-
Notifications
You must be signed in to change notification settings - Fork 1k
Improve context propagation for brave integration #6139
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 13 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
5eafb19
minimal impl
jrhee17 6f5a662
cleanup
jrhee17 f2f0d90
Merge branch 'main' into feat/brave-prop
jrhee17 a525b8a
Merge branch 'main' into feat/brave-prop
jrhee17 23eeedb
add propagation logic to executors
jrhee17 46833c4
address comments by @minwoox and @trustin
jrhee17 933912a
minor nits
jrhee17 f737fea
warn when a different context is set
jrhee17 4598cc8
use object equality for checking trace context equality
jrhee17 2ab56cb
address comment by @minwoox
jrhee17 3296dcb
Merge remote-tracking branch 'origin/main' into feat/brave-prop
jrhee17 835d38d
lint
jrhee17 39ecbe8
Merge branch 'main' into feat/brave-prop
jrhee17 b7dee51
address comment by @ikhoon
jrhee17 fafd081
Merge branch 'main' into feat/brave-prop
jrhee17 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -16,21 +16,13 @@ | |
|
|
||
| package com.linecorp.armeria.common.brave; | ||
|
|
||
| import static com.linecorp.armeria.internal.common.brave.TraceContextUtil.setTraceContext; | ||
| import static com.linecorp.armeria.internal.common.brave.TraceContextUtil.traceContext; | ||
|
|
||
| import java.util.List; | ||
| import java.util.function.Function; | ||
| import java.util.function.Supplier; | ||
| import java.util.regex.Pattern; | ||
|
|
||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import com.linecorp.armeria.client.brave.BraveClient; | ||
| import com.linecorp.armeria.common.RequestContext; | ||
| import com.linecorp.armeria.common.annotation.Nullable; | ||
| import com.linecorp.armeria.common.annotation.UnstableApi; | ||
| import com.linecorp.armeria.internal.common.brave.InternalTraceContextUtil; | ||
| import com.linecorp.armeria.internal.common.brave.TraceContextUtil; | ||
| import com.linecorp.armeria.server.brave.BraveService; | ||
|
|
||
|
|
@@ -92,65 +84,45 @@ public static RequestContextCurrentTraceContextBuilder builder() { | |
| * > } | ||
| * > }); | ||
| * }</pre> | ||
| * | ||
| * @deprecated This setting has no effect. | ||
| */ | ||
| @Deprecated | ||
| public static void setCurrentThreadNotRequestThread(boolean value) { | ||
| if (value) { | ||
| THREAD_NOT_REQUEST_THREAD.set(true); | ||
| } else { | ||
| THREAD_NOT_REQUEST_THREAD.remove(); | ||
| } | ||
| } | ||
|
|
||
| private static final RequestContextCurrentTraceContext DEFAULT = builder().build(); | ||
|
|
||
| private static final Logger logger = LoggerFactory.getLogger(RequestContextCurrentTraceContext.class); | ||
|
|
||
| // Thread-local for storing TraceContext when invoking callbacks off the request thread. | ||
| private static final ThreadLocal<TraceContext> THREAD_LOCAL_CONTEXT = new ThreadLocal<>(); | ||
|
|
||
| private static final ThreadLocal<Boolean> THREAD_NOT_REQUEST_THREAD = new ThreadLocal<>(); | ||
|
|
||
| private static final Scope INITIAL_REQUEST_SCOPE = new Scope() { | ||
| private static final Scope NOOP_SCOPE = new Scope() { | ||
| @Override | ||
| public void close() { | ||
| // Don't remove the outer-most context (client or server request) | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "InitialRequestScope"; | ||
| return "ArmeriaNoopScope"; | ||
| } | ||
| }; | ||
|
|
||
| private final List<Pattern> nonRequestThreadPatterns; | ||
| private final boolean scopeDecoratorAdded; | ||
|
|
||
| RequestContextCurrentTraceContext(CurrentTraceContext.Builder builder, | ||
| List<Pattern> nonRequestThreadPatterns, boolean scopeDecoratorAdded) { | ||
| RequestContextCurrentTraceContext(CurrentTraceContext.Builder builder, boolean scopeDecoratorAdded) { | ||
| super(builder); | ||
|
|
||
| this.nonRequestThreadPatterns = nonRequestThreadPatterns; | ||
| this.scopeDecoratorAdded = scopeDecoratorAdded; | ||
| } | ||
|
|
||
| @Override | ||
| @Nullable | ||
| public TraceContext get() { | ||
| final RequestContext ctx = getRequestContextOrWarnOnce(); | ||
| if (ctx == null) { | ||
| return THREAD_LOCAL_CONTEXT.get(); | ||
| final TraceContext traceContext = InternalTraceContextUtil.get(); | ||
| if (traceContext != null) { | ||
| return traceContext; | ||
| } | ||
|
|
||
| if (ctx.eventLoop().inEventLoop()) { | ||
| return traceContext(ctx); | ||
| } else { | ||
| final TraceContext threadLocalContext = THREAD_LOCAL_CONTEXT.get(); | ||
| if (threadLocalContext != null) { | ||
| return threadLocalContext; | ||
| } | ||
| // First span on a non-request thread will use the request's TraceContext as a parent. | ||
| return traceContext(ctx); | ||
| final RequestContext ctx = RequestContext.currentOrNull(); | ||
| if (ctx == null) { | ||
| return null; | ||
| } | ||
| return traceContext(ctx); | ||
| } | ||
|
|
||
| @Override | ||
|
|
@@ -160,16 +132,27 @@ public Scope newScope(@Nullable TraceContext currentSpan) { | |
| return Scope.NOOP; | ||
| } | ||
|
|
||
| final RequestContext ctx = getRequestContextOrWarnOnce(); | ||
| final TraceContext threadPrev = InternalTraceContextUtil.get(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can't we short-circuit when |
||
| if (threadPrev == currentSpan) { | ||
| // a custom noop scope is used to avoid special behavior in built-in scope decorators | ||
| return decorateScope(currentSpan, NOOP_SCOPE); | ||
| } | ||
|
|
||
| InternalTraceContextUtil.set(currentSpan); | ||
|
|
||
| class ThreadLocalContextScope implements Scope { | ||
| @Override | ||
| public void close() { | ||
| InternalTraceContextUtil.set(threadPrev); | ||
| } | ||
|
|
||
| if (ctx != null && ctx.eventLoop().inEventLoop()) { | ||
| return createScopeForRequestThread(ctx, currentSpan); | ||
| } else { | ||
| // The RequestContext is the canonical thread-local storage for the thread processing the request. | ||
| // However, when creating spans on other threads (e.g., a thread-pool), we must use separate | ||
| // thread-local storage to prevent threads from replacing the same trace context. | ||
| return createScopeForNonRequestThread(currentSpan); | ||
| @Override | ||
| public String toString() { | ||
| return "ThreadLocalScope"; | ||
| } | ||
| } | ||
|
|
||
| return decorateScope(currentSpan, new ThreadLocalContextScope()); | ||
| } | ||
|
|
||
| @UnstableApi | ||
|
|
@@ -190,104 +173,4 @@ public Scope decorateScope(@Nullable TraceContext context, Scope scope) { | |
| public boolean scopeDecoratorAdded() { | ||
| return scopeDecoratorAdded; | ||
| } | ||
|
|
||
| private Scope createScopeForRequestThread(RequestContext ctx, @Nullable TraceContext currentSpan) { | ||
| final TraceContext previous = traceContext(ctx); | ||
| setTraceContext(ctx, currentSpan); | ||
|
|
||
| // Don't remove the outer-most context (client or server request) | ||
| if (previous == null) { | ||
| return decorateScope(currentSpan, INITIAL_REQUEST_SCOPE); | ||
| } | ||
|
|
||
| // Removes sub-spans (i.e. local spans) from the current context when Brave's scope does. | ||
| // If an asynchronous sub-span, it may still complete later. | ||
| class RequestContextTraceContextScope implements Scope { | ||
| @Override | ||
| public void close() { | ||
| // re-lookup the attribute to avoid holding a reference to the request if this scope is leaked | ||
| final RequestContext ctx = getRequestContextOrWarnOnce(); | ||
| if (ctx != null) { | ||
| setTraceContext(ctx, previous); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "RequestContextTraceContextScope"; | ||
| } | ||
| } | ||
|
|
||
| return decorateScope(currentSpan, new RequestContextTraceContextScope()); | ||
| } | ||
|
|
||
| private Scope createScopeForNonRequestThread(@Nullable TraceContext currentSpan) { | ||
| final TraceContext previous = THREAD_LOCAL_CONTEXT.get(); | ||
| THREAD_LOCAL_CONTEXT.set(currentSpan); | ||
| class ThreadLocalScope implements Scope { | ||
| @Override | ||
| public void close() { | ||
| THREAD_LOCAL_CONTEXT.set(previous); | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "ThreadLocalScope"; | ||
| } | ||
| } | ||
|
|
||
| return decorateScope(currentSpan, new ThreadLocalScope()); | ||
| } | ||
|
|
||
| /** | ||
| * Armeria code should always have a request context available, and this won't work without it. | ||
| */ | ||
| @Nullable | ||
| private RequestContext getRequestContextOrWarnOnce() { | ||
| if (Boolean.TRUE.equals(THREAD_NOT_REQUEST_THREAD.get())) { | ||
| return null; | ||
| } | ||
| if (!nonRequestThreadPatterns.isEmpty()) { | ||
| final String threadName = Thread.currentThread().getName(); | ||
| for (Pattern pattern : nonRequestThreadPatterns) { | ||
| if (pattern.matcher(threadName).find()) { | ||
| // A matched thread will match forever, so it's worth avoiding this regex match on every | ||
| // time the thread is used by saving into the ThreadLocal. | ||
| setCurrentThreadNotRequestThread(true); | ||
| return null; | ||
| } | ||
| } | ||
| } | ||
| return RequestContext.mapCurrent(Function.identity(), LogRequestContextWarningOnce.INSTANCE); | ||
| } | ||
|
|
||
| private enum LogRequestContextWarningOnce implements Supplier<RequestContext> { | ||
|
|
||
| INSTANCE; | ||
|
|
||
| @Override | ||
| @Nullable | ||
| public RequestContext get() { | ||
| ClassLoaderHack.loadMe(); | ||
| return null; | ||
| } | ||
|
|
||
| /** | ||
| * This won't be referenced until {@link #get()} is called. If there's only one classloader, the | ||
| * initializer will only be called once. | ||
| */ | ||
| private static final class ClassLoaderHack { | ||
| static void loadMe() {} | ||
|
|
||
| static { | ||
| logger.warn("Attempted to propagate trace context, but no request context available. " + | ||
| "Did you forget to use RequestContext.makeContextAware()?", | ||
| new NoRequestContextException()); | ||
| } | ||
| } | ||
|
|
||
| private static final class NoRequestContextException extends RuntimeException { | ||
| private static final long serialVersionUID = 2804189311774982052L; | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
52 changes: 52 additions & 0 deletions
52
...ain/java/com/linecorp/armeria/internal/common/brave/BraveThreadLocalAccessorProvider.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| /* | ||
| * Copyright 2025 LINE Corporation | ||
| * | ||
| * LINE Corporation licenses this file to you under the Apache License, | ||
| * version 2.0 (the "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at: | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
| * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
| * License for the specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
|
|
||
| package com.linecorp.armeria.internal.common.brave; | ||
|
|
||
| import com.linecorp.armeria.common.annotation.Nullable; | ||
| import com.linecorp.armeria.internal.common.context.ThreadLocalAccessorProvider; | ||
|
|
||
| import brave.propagation.TraceContext; | ||
| import io.micrometer.context.ThreadLocalAccessor; | ||
|
|
||
| public final class BraveThreadLocalAccessorProvider implements ThreadLocalAccessorProvider { | ||
|
|
||
| @Override | ||
| public ThreadLocalAccessor<?> threadLocalAccessor() { | ||
| return new ThreadLocalAccessor<Object>() { | ||
| @Override | ||
| public Object key() { | ||
| return BraveThreadLocalAccessorProvider.class; | ||
| } | ||
|
|
||
| @Nullable | ||
| @Override | ||
| public Object getValue() { | ||
| return InternalTraceContextUtil.get(); | ||
| } | ||
|
|
||
| @Override | ||
| public void setValue(Object o) { | ||
| InternalTraceContextUtil.set((TraceContext) o); | ||
| } | ||
|
|
||
| @Override | ||
| public void setValue() { | ||
| InternalTraceContextUtil.set(null); | ||
| } | ||
| }; | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because a span is fixed to a
RequestContext, how about leaving a warning log if aRequestContexthas aTraceContextalready? I've seen internal customers who have used this API.Also, I think we can remove
@NullablefromsetTraceContextmethod.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm unsure if leaving a log level with
WARNlevel is a good idea since it is a valid behavior to do so. e.g. UsingTraceContextPropagation#inject(span1) withBraveClient(span2) will also overwrite the span wherespan2.parent == span1.What do you think of leaving a trace level log so that we can guide users if there is unexpected behavior?
Alternatively, I can also add a static field guard so that the log is left only once if you feel strongly of this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah, that's valid situtation. IIUC, in that case, the same
TraceContextcan be set to aRequestContext. Is it right? If so, can't we add a warning log if it tries to set a differentTraceContext?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It would help if you could explain why users using this API is a bad idea. If users were setting the
TraceContextmanually before this change, couldn't they continue using it this way after this change as well?Just to be clear are you suggesting that a warning log is printed once guarded by a static variable? or every time a different context is set?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just to be clear, the following scenario yields different spans:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've imagined some of this situation. Please let me know if this doesn't make sense:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I still maintain that
Anyways, I've updated to always leave a warning log as you requested. PTAL when you have time
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since it's a valid scenario, could you change to log just one time?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry for chiming in late.
prevTraceContextcould be the server's context where the client is used. The logging could cause confusion despite correct usage.Should we use
ctx.ownAttr(TRACE_CONTEXT_KEY)to check the duplicate context?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good point, done