Skip to content

Commit db5b4d2

Browse files
feat(设备接入): 补齐设备诊断链路追踪 (#761)
* feat(设备接入): 补齐设备诊断链路追踪 透传设备消息追踪上下文并补充响应和透传处理 span。 支持协议 Monitor 在同步及响应式上下文中切换,并补充聚焦测试。 * test(协议组件): 覆盖监控上下文异常恢复 * docs(设备接入): 回填链路追踪交付信息 * fix(链路追踪): 补齐响应式日志上下文传播 通过 OpenTelemetry ContextStorageProvider 与 Micrometer ThreadLocalAccessor 共享上下文,并开启 Reactor 自动传播,修复协议诊断日志和系统日志缺少 traceId 的问题。 --------- Co-authored-by: zhou-hao <zh.sqy@qq.com>
1 parent f0b621b commit db5b4d2

18 files changed

Lines changed: 1399 additions & 5 deletions

File tree

jetlinks-components/common-component/src/main/java/org/jetlinks/community/configuration/CommonConfiguration.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
import org.springframework.beans.BeansException;
6262
import org.springframework.beans.factory.ObjectProvider;
6363
import org.springframework.beans.factory.config.BeanPostProcessor;
64+
import org.springframework.beans.factory.InitializingBean;
6465
import org.springframework.boot.autoconfigure.AutoConfiguration;
6566
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
6667
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
@@ -84,7 +85,7 @@
8485
@AutoConfiguration
8586
@SuppressWarnings("all")
8687
@EnableConfigurationProperties({ConfigScopeProperties.class})
87-
public class CommonConfiguration {
88+
public class CommonConfiguration implements InitializingBean {
8889

8990
static {
9091
InternalAggregationSupports.register();
@@ -205,6 +206,13 @@ public <T> T convert(Class<T> type, Object value) {
205206
});
206207
}
207208

209+
@Override
210+
public void afterPropertiesSet() {
211+
// Restore all registered thread-local contexts around Reactor operators. OpenTelemetry
212+
// and protocol Monitor accessors are responsible for restoring their previous values.
213+
Hooks.enableAutomaticContextPropagation();
214+
}
215+
208216
@Bean
209217
public ApplicationContextAware staticBeanRegister() {
210218

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
/*
2+
* Copyright 2026 JetLinks https://www.jetlinks.cn
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.jetlinks.community.tracing;
17+
18+
import io.micrometer.context.ThreadLocalAccessor;
19+
import io.netty.util.concurrent.FastThreadLocal;
20+
import io.opentelemetry.context.Context;
21+
import io.opentelemetry.context.ContextStorage;
22+
import io.opentelemetry.context.ContextStorageProvider;
23+
import io.opentelemetry.context.Scope;
24+
import lombok.extern.slf4j.Slf4j;
25+
26+
import javax.annotation.Nonnull;
27+
import javax.annotation.Nullable;
28+
29+
/**
30+
* Bridges OpenTelemetry context storage with Micrometer context propagation.
31+
*
32+
* <p>Both SPIs operate on the same {@link FastThreadLocal}, allowing Reactor to restore the
33+
* OpenTelemetry {@link Context} before invoking an operator and to restore the previous context
34+
* after the signal. This provider only propagates existing contexts and never creates spans.</p>
35+
*
36+
* @see ContextStorageProvider
37+
* @see ThreadLocalAccessor
38+
* @since 2.12
39+
*/
40+
@Slf4j
41+
public class ThreadLocalContextStorageProvider
42+
implements ContextStorageProvider, ThreadLocalAccessor<Context> {
43+
44+
private static final FastThreadLocal<Context> CONTEXT_STORAGE = new FastThreadLocal<>();
45+
46+
private static final ContextStorage STORAGE = new ThreadLocalContextStorage();
47+
48+
@Override
49+
public ContextStorage get() {
50+
return STORAGE;
51+
}
52+
53+
@Override
54+
@Nonnull
55+
public Object key() {
56+
return Context.class;
57+
}
58+
59+
@Override
60+
@Nullable
61+
public Context getValue() {
62+
return CONTEXT_STORAGE.getIfExists();
63+
}
64+
65+
@Override
66+
public void setValue(@Nonnull Context value) {
67+
CONTEXT_STORAGE.set(value);
68+
}
69+
70+
@Override
71+
public void setValue() {
72+
CONTEXT_STORAGE.remove();
73+
}
74+
75+
private static final class ThreadLocalContextStorage implements ContextStorage {
76+
77+
@Override
78+
public Scope attach(Context toAttach) {
79+
if (toAttach == null) {
80+
return NoopScope.INSTANCE;
81+
}
82+
83+
Context previous = current();
84+
if (toAttach == previous) {
85+
return NoopScope.INSTANCE;
86+
}
87+
88+
CONTEXT_STORAGE.set(toAttach);
89+
return new RestoringScope(previous, toAttach);
90+
}
91+
92+
@Override
93+
@Nullable
94+
public Context current() {
95+
return CONTEXT_STORAGE.getIfExists();
96+
}
97+
}
98+
99+
private static final class RestoringScope implements Scope {
100+
101+
@Nullable
102+
private final Context previous;
103+
104+
private final Context attached;
105+
106+
private boolean closed;
107+
108+
private RestoringScope(@Nullable Context previous, Context attached) {
109+
this.previous = previous;
110+
this.attached = attached;
111+
}
112+
113+
@Override
114+
public void close() {
115+
if (closed) {
116+
return;
117+
}
118+
// Only the matching scope may restore the context; out-of-order close would corrupt
119+
// a nested span and must leave the active context untouched.
120+
if (CONTEXT_STORAGE.getIfExists() != attached) {
121+
log.warn("Trying to close a scope which does not represent the current context. Ignoring the call.");
122+
return;
123+
}
124+
closed = true;
125+
if (previous == null) {
126+
CONTEXT_STORAGE.remove();
127+
} else {
128+
CONTEXT_STORAGE.set(previous);
129+
}
130+
}
131+
}
132+
133+
private enum NoopScope implements Scope {
134+
INSTANCE;
135+
136+
@Override
137+
public void close() {
138+
}
139+
}
140+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
org.jetlinks.community.tracing.ThreadLocalContextStorageProvider
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
org.jetlinks.community.tracing.ThreadLocalContextStorageProvider
Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
/*
2+
* Copyright 2026 JetLinks https://www.jetlinks.cn
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.jetlinks.community.tracing;
17+
18+
import io.micrometer.context.ThreadLocalAccessor;
19+
import io.opentelemetry.api.trace.Span;
20+
import io.opentelemetry.api.trace.SpanContext;
21+
import io.opentelemetry.api.trace.TraceFlags;
22+
import io.opentelemetry.api.trace.TraceState;
23+
import io.opentelemetry.context.Context;
24+
import io.opentelemetry.context.ContextStorage;
25+
import io.opentelemetry.context.ContextStorageProvider;
26+
import io.opentelemetry.context.Scope;
27+
import org.jetlinks.community.configuration.CommonConfiguration;
28+
import org.jetlinks.community.log.LogRecord;
29+
import org.junit.jupiter.api.AfterAll;
30+
import org.junit.jupiter.api.AfterEach;
31+
import org.junit.jupiter.api.BeforeAll;
32+
import org.junit.jupiter.api.Test;
33+
import reactor.core.publisher.Flux;
34+
import reactor.core.publisher.Hooks;
35+
import reactor.core.publisher.Mono;
36+
import reactor.core.scheduler.Scheduler;
37+
import reactor.core.scheduler.Schedulers;
38+
import reactor.test.StepVerifier;
39+
40+
import java.util.ServiceLoader;
41+
42+
import static org.junit.jupiter.api.Assertions.assertEquals;
43+
import static org.junit.jupiter.api.Assertions.assertFalse;
44+
import static org.junit.jupiter.api.Assertions.assertNull;
45+
import static org.junit.jupiter.api.Assertions.assertTrue;
46+
47+
class TraceContextPropagationTest {
48+
49+
private static final String TRACE_ID = "0123456789abcdef0123456789abcdef";
50+
51+
private static final String SPAN_ID = "0123456789abcdef";
52+
53+
@BeforeAll
54+
static void enableAutomaticContextPropagation() {
55+
new CommonConfiguration().afterPropertiesSet();
56+
}
57+
58+
@AfterAll
59+
static void disableAutomaticContextPropagation() {
60+
Hooks.disableAutomaticContextPropagation();
61+
}
62+
63+
@AfterEach
64+
void clearCurrentContext() {
65+
new ThreadLocalContextStorageProvider().setValue();
66+
}
67+
68+
@Test
69+
void shouldRegisterOpenTelemetryAndMicrometerProviders() {
70+
assertTrue(ServiceLoader
71+
.load(ContextStorageProvider.class)
72+
.stream()
73+
.anyMatch(provider -> provider.type() == ThreadLocalContextStorageProvider.class));
74+
assertTrue(ServiceLoader
75+
.load(ThreadLocalAccessor.class)
76+
.stream()
77+
.anyMatch(provider -> provider.type() == ThreadLocalContextStorageProvider.class));
78+
}
79+
80+
@Test
81+
void shouldRestoreNestedScopes() {
82+
Span outer = span(TRACE_ID, SPAN_ID);
83+
Span inner = span("fedcba9876543210fedcba9876543210", "fedcba9876543210");
84+
85+
assertFalse(Span.current().getSpanContext().isValid());
86+
try (Scope ignored = outer.makeCurrent()) {
87+
assertEquals(outer.getSpanContext(), Span.current().getSpanContext());
88+
try (Scope nested = inner.makeCurrent()) {
89+
assertEquals(inner.getSpanContext(), Span.current().getSpanContext());
90+
}
91+
assertEquals(outer.getSpanContext(), Span.current().getSpanContext());
92+
}
93+
assertFalse(Span.current().getSpanContext().isValid());
94+
}
95+
96+
@Test
97+
void shouldProtectScopeRestorationFromInvalidCloseOrder() {
98+
ThreadLocalContextStorageProvider provider = new ThreadLocalContextStorageProvider();
99+
ContextStorage storage = provider.get();
100+
Context outer = Context.root().with(span(TRACE_ID, SPAN_ID));
101+
Context inner = Context.root().with(span(
102+
"fedcba9876543210fedcba9876543210",
103+
"fedcba9876543210"
104+
));
105+
106+
try (Scope ignored = storage.attach(null)) {
107+
assertNull(storage.current());
108+
}
109+
110+
Scope outerScope = storage.attach(outer);
111+
try (Scope ignored = storage.attach(outer)) {
112+
assertEquals(outer, storage.current());
113+
}
114+
Scope innerScope = storage.attach(inner);
115+
116+
outerScope.close();
117+
assertEquals(inner, storage.current());
118+
119+
innerScope.close();
120+
assertEquals(outer, storage.current());
121+
122+
outerScope.close();
123+
outerScope.close();
124+
assertNull(storage.current());
125+
}
126+
127+
@Test
128+
void shouldAttachTraceIdToLogRecordAcrossSchedulerAndClearContext() {
129+
Scheduler scheduler = Schedulers.newSingle("trace-context-test");
130+
Context traceContext = Context.root().with(span(TRACE_ID, SPAN_ID));
131+
try {
132+
Mono<String> tracedLog = Mono
133+
.just("decoded")
134+
.publishOn(scheduler)
135+
.map(ignored -> new LogRecord().getTraceId())
136+
.contextWrite(context -> context.put(Context.class, traceContext));
137+
138+
Mono<Boolean> contextCleared = Mono
139+
.fromSupplier(() -> Span.current().getSpanContext().isValid())
140+
.subscribeOn(scheduler);
141+
142+
StepVerifier
143+
.create(tracedLog.concatWith(contextCleared.map(String::valueOf)))
144+
.expectNext(TRACE_ID, "false")
145+
.verifyComplete();
146+
} finally {
147+
scheduler.dispose();
148+
}
149+
}
150+
151+
@Test
152+
void shouldClearContextAfterError() {
153+
Scheduler scheduler = Schedulers.newSingle("trace-context-error-test");
154+
Context traceContext = Context.root().with(span(TRACE_ID, SPAN_ID));
155+
try {
156+
Mono<String> failed = Mono
157+
.just("decoded")
158+
.publishOn(scheduler)
159+
.<String>flatMap(ignored -> {
160+
assertEquals(TRACE_ID, Span.current().getSpanContext().getTraceId());
161+
return Mono.error(new IllegalStateException("expected failure"));
162+
})
163+
.contextWrite(context -> context.put(Context.class, traceContext));
164+
165+
StepVerifier
166+
.create(failed.onErrorResume(ignored -> Mono
167+
.fromSupplier(() -> String.valueOf(Span.current().getSpanContext().isValid()))
168+
.subscribeOn(scheduler)))
169+
.expectNext("false")
170+
.verifyComplete();
171+
} finally {
172+
scheduler.dispose();
173+
}
174+
}
175+
176+
@Test
177+
void shouldClearContextAfterCancellation() {
178+
Scheduler scheduler = Schedulers.newSingle("trace-context-cancel-test");
179+
Context traceContext = Context.root().with(span(TRACE_ID, SPAN_ID));
180+
try {
181+
Flux<String> cancellable = Mono
182+
.just("ready")
183+
.publishOn(scheduler)
184+
.map(ignored -> Span.current().getSpanContext().getTraceId())
185+
.concatWith(Mono.never())
186+
.contextWrite(context -> context.put(Context.class, traceContext));
187+
188+
StepVerifier
189+
.create(cancellable)
190+
.expectNext(TRACE_ID)
191+
.thenCancel()
192+
.verify();
193+
194+
StepVerifier
195+
.create(Mono
196+
.fromSupplier(() -> Span.current().getSpanContext().isValid())
197+
.subscribeOn(scheduler))
198+
.expectNext(false)
199+
.verifyComplete();
200+
} finally {
201+
scheduler.dispose();
202+
}
203+
}
204+
205+
private static Span span(String traceId, String spanId) {
206+
return Span.wrap(SpanContext.create(
207+
traceId,
208+
spanId,
209+
TraceFlags.getSampled(),
210+
TraceState.getDefault()
211+
));
212+
}
213+
}

0 commit comments

Comments
 (0)