Search code examples
spring-cloud-sleuth

Spring Cloud Sleuth: Initialise baggage item


I already have this Java Configuration:

@Configuration
public class FAPIAutoConfiguration {

    private static final String INTERACTION_ID = "x-fapi-interaction-id";
    
    private final BaggageField fapiBaggageField = BaggageField.create(INTERACTION_ID);

    @Bean
    BaggagePropagationCustomizer baggagePropagationCustomizer() {
        return builder -> builder.add(SingleBaggageField.
            remote(fapiBaggageField));
    }

    @Bean
    CorrelationScopeCustomizer correlationScopeCustomizer() {
        return builder -> builder.add(SingleCorrelationField.create(fapiBaggageField));
    }
}

And the propagation in a Webflux application works, but I would like to know what is the best way to initialize the baggage if it is not present in the request headers. I mean, if the header is missing, generate a value and propagate this one.


Solution

  • I ended up adding a TracingCustomizer to the above configuration to fill the value when is missing in that context.

        @Bean
        TracingCustomizer tracingCustomizer(UniqueIdGenerator generator) {
            return builder -> builder.addSpanHandler(new SpanHandler() {
                @Override
                public boolean begin(TraceContext context, MutableSpan span, TraceContext parent) {
                    var value = fapiBaggageField.getValue(context);
                    if (value == null) {
                        fapiBaggageField.updateValue(context, generator.next());
                    }
                    return super.begin(context, span, parent);
                }
            });
        }
    

    I do not know if this is the best option yet