Improve WebClient observations handling of CANCEL signal
Prior to this commit, `WebClient` observations would be recorded as
aborted (with tags "outcome":"UNKNOWN", "status":"CLIENT_ERROR")
for use cases like this:
```
Flux<String> result = client.get()
.uri("/path")
.retrieve()
.bodyToFlux(String.class)
.take(1);
```
This is due to operators like `take` or `next` that consume *some*
`onNext` signals and then cancels the subscription before completion.
This means the subscriber is only partially interested in the response
and we should not count this as a client error.
This commit ensures that observations are only recorded as aborted if
the response was not published at the time the CANCEL signal was
received.
The code snippet above will now publish observations with
"outcome":"SUCCESS" and "status":"200" tags, for example.
Closes gh-30070
This commit is contained in:
@@ -26,6 +26,7 @@ import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntPredicate;
|
||||
@@ -37,6 +38,7 @@ import io.micrometer.observation.contextpropagation.ObservationThreadLocalAccess
|
||||
import org.reactivestreams.Publisher;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.publisher.SignalType;
|
||||
import reactor.util.context.Context;
|
||||
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
@@ -455,13 +457,16 @@ class DefaultWebClient implements WebClient {
|
||||
if (this.contextModifier != null) {
|
||||
responseMono = responseMono.contextWrite(this.contextModifier);
|
||||
}
|
||||
final AtomicBoolean responseReceived = new AtomicBoolean();
|
||||
return responseMono
|
||||
.doOnNext(response -> responseReceived.set(true))
|
||||
.doOnError(observationContext::setError)
|
||||
.doOnCancel(() -> {
|
||||
observationContext.setAborted(true);
|
||||
.doFinally(signalType -> {
|
||||
if (signalType == SignalType.CANCEL && !responseReceived.get()) {
|
||||
observationContext.setAborted(true);
|
||||
}
|
||||
observation.stop();
|
||||
})
|
||||
.doOnTerminate(observation::stop)
|
||||
.contextWrite(context -> context.put(ObservationThreadLocalAccessor.KEY, observation));
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user