micrometer-metrics / context-propagation

Context Propagation API
Apache License 2.0
74 stars 21 forks source link

Propagation doesn't work when using a Future #218

Closed ceremo closed 4 months ago

ceremo commented 4 months ago

Hi,

when I create a Mono from a Future, ThreadLocals are not propagated, it seems that only occurs when I use a Future. I created an example in a test included here.

Thanks for your time.

chemicL commented 4 months ago

Hey, @ceremo ! Thanks for the report. This belongs to reactor-core. The demo is based around it. Context-propagation library is not the source of the confusion.

What you observe is actually expected for the Future case. That is because the Context has nothing in it and we do restore ThreadLocal values in case of foreign execution sources, such as Futures based on the current Subscriber's Context. In this case you're looking for the contextCapture() operator at the end of your chain because you set some ThreadLocal values and require them to appear in the reactive pipeline's Context.

In case of the Callable case, what you see is unspecified behaviour. Because you didn't capture anything into the Context and the mechanism for automatic propagation uses Scheduler wrapping with propagation of current ThreadLocal values it happens that the value gets propagated through that mechanism. Another combination of sources can restore the state from Context.

In summary, this is not a specified behaviour. You do need the contextCapture() operator if you subscribe to a pipeline and expect currently set ThreadLocal values to be propagated. The other option is to directly store the value into the Context using contextWrite() operator under the key of the accessor.