0

Using spring-boot-starter-parent 3.0.6 with

  • spring-boot-starter-webflux
  • spring-boot-starter-security
  • micrometer-tracing
  • micrometer-tracing-bridge-otel

I also use Hooks.enableAutomaticContextPropagation(); in my main @SpringBootApplication class;

having a simple filter that should just inject current trace ID to the response:

package some.controller;

import io.micrometer.tracing.Span;
import io.micrometer.tracing.Tracer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.UUID;

@Slf4j
@Component
public class AddResponseHeaderWebFilter implements WebFilter, Ordered {

    private final Tracer tracer;

    public AddResponseHeaderWebFilter(
        final Tracer tracer
    ) {
        this.tracer = tracer;
    }

    @SuppressWarnings("NullableProblems")
    @Override
    public Mono<Void> filter(final ServerWebExchange exchange, final WebFilterChain chain) {
        return chain.filter(withCallback(exchange));
    }

    private ServerWebExchange withCallback(final ServerWebExchange exchange) {
        exchange
            .getResponse()
            .beforeCommit(() -> {
                HttpHeaders httpHeaders = exchange.getResponse().getHeaders();

                httpHeaders.add("trace-id", callId());

                return Mono.empty();
            });

        return exchange;
    }

    private static String fallbackValue() {
        String fallbackValue = UUID.randomUUID().toString();
        log.warn("Could not use trace ID; generated dummy UUID for tracking purposes: {}", fallbackValue);

        return fallbackValue;
    }

    private String callId() {
        Span currentSpan = this.tracer.currentSpan();

        return currentSpan == null
            ? fallbackValue()
            : currentSpan.context().traceId();
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

}

it works well if my controller returns Mono<List<Object>> or Mono<Object> but always falls into "fallback" when controller returns Flux<Object>;

is it a known limitation (it did work in SB 2.7.x with Sleuth though) or some additional configuration / code change is needed?

note: for Flux<Object> responses, I see 'transfer-encoding: chunked' header is added

asceta
  • 272
  • 1
  • 4
  • 10

0 Answers0