Skip to content

Commit f93fda2

Browse files
committed
Guard against no-op observation
Update `ServerHttpObservationFilter` to check if the `Observation` is a no-op before adding the `ServerRequestObservationContext`. Prior to this commit, if the `Observation` is a no-op then the context type added with the `CURRENT_OBSERVATION_CONTEXT_ATTRIBUTE` would not be a `ServerRequestObservationContext`. This would mean that `findObservationContext` would throw a `ClassCastException`. Fixes gh-29356
1 parent 0889e47 commit f93fda2

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

spring-web/src/main/java/org/springframework/web/filter/ServerHttpObservationFilter.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,9 @@ private Observation createOrFetchObservation(HttpServletRequest request, HttpSer
130130
observation = ServerHttpObservationDocumentation.HTTP_REQUESTS.observation(this.observationConvention,
131131
DEFAULT_OBSERVATION_CONVENTION, () -> context, this.observationRegistry).start();
132132
request.setAttribute(CURRENT_OBSERVATION_ATTRIBUTE, observation);
133-
request.setAttribute(CURRENT_OBSERVATION_CONTEXT_ATTRIBUTE, observation.getContext());
133+
if (!observation.isNoop()) {
134+
request.setAttribute(CURRENT_OBSERVATION_CONTEXT_ATTRIBUTE, observation.getContext());
135+
}
134136
}
135137
return observation;
136138
}

spring-web/src/test/java/org/springframework/web/filter/ServerHttpObservationFilterTests.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
package org.springframework.web.filter;
1818

19+
import io.micrometer.observation.ObservationRegistry;
1920
import io.micrometer.observation.tck.TestObservationRegistry;
2021
import io.micrometer.observation.tck.TestObservationRegistryAssert;
2122
import jakarta.servlet.RequestDispatcher;
@@ -33,6 +34,7 @@
3334

3435
/**
3536
* Tests for {@link ServerHttpObservationFilter}.
37+
*
3638
* @author Brian Clozel
3739
*/
3840
class ServerHttpObservationFilterTests {
@@ -61,6 +63,16 @@ void filterShouldFillObservationContext() throws Exception {
6163
assertThatHttpObservation().hasLowCardinalityKeyValue("outcome", "SUCCESS");
6264
}
6365

66+
@Test
67+
void filterShouldAcceptNoOpObservationContext() throws Exception {
68+
ServerHttpObservationFilter filter = new ServerHttpObservationFilter(ObservationRegistry.NOOP);
69+
filter.doFilter(this.request, this.response, this.mockFilterChain);
70+
71+
ServerRequestObservationContext context = (ServerRequestObservationContext) this.request
72+
.getAttribute(ServerHttpObservationFilter.CURRENT_OBSERVATION_CONTEXT_ATTRIBUTE);
73+
assertThat(context).isNull();
74+
}
75+
6476
@Test
6577
void filterShouldUseThrownException() throws Exception {
6678
IllegalArgumentException customError = new IllegalArgumentException("custom error");

0 commit comments

Comments
 (0)