Skip to content

Commit d1c8abb

Browse files
committed
Stop server observation on async completion only
Prior to this commit, `ServerHttpObservationFilter` stopped the observation in both `AsyncListener.onTimeout` and `onComplete`. As per the Servlet specification, `onTimeout` is not terminal: the container then performs an error dispatch, which sets the final response status, and always completes the async context afterwards. Stopping the observation in `onTimeout` recorded the request before that status was known and stopped it a second time in `onComplete`. This commit stops the observation in `onComplete` only. Closes gh-37627
1 parent 522ca1e commit d1c8abb

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ public void onStartAsync(AsyncEvent event) {
198198

199199
@Override
200200
public void onTimeout(AsyncEvent event) {
201-
this.currentObservation.stop();
201+
// The container must perform an error dispatch after.
202202
}
203203

204204
@Override

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,24 @@ void shouldCloseObservationAfterAsyncError() throws Exception {
182182
assertThatHttpObservation().hasLowCardinalityKeyValue("exception", "IllegalStateException").hasBeenStopped();
183183
}
184184

185+
@Test
186+
void shouldNotCloseObservationOnAsyncTimeout() throws Exception {
187+
this.request.setAsyncSupported(true);
188+
this.request.startAsync();
189+
this.filter.doFilter(this.request, this.response, this.mockFilterChain);
190+
MockAsyncContext asyncContext = (MockAsyncContext) this.request.getAsyncContext();
191+
for (AsyncListener listener : asyncContext.getListeners()) {
192+
listener.onTimeout(new AsyncEvent(asyncContext));
193+
}
194+
assertThat(this.observationRegistry).hasObservationWithNameEqualTo("http.server.requests").that()
195+
.isNotStopped();
196+
197+
// error dispatch sets the final status before the container completes the request
198+
this.response.setStatus(503);
199+
asyncContext.complete();
200+
assertThatHttpObservation().hasLowCardinalityKeyValue("status", "503").hasBeenStopped();
201+
}
202+
185203
@Test
186204
void shouldNotCloseObservationDuringAsyncDispatch() throws Exception {
187205
this.mockFilterChain = new MockFilterChain(new ScopeCheckingServlet(this.observationRegistry));

0 commit comments

Comments
 (0)