Skip to content

Commit c9fed25

Browse files
victorcuenaclaude
andcommitted
CAP-1150: Stream text/event-stream responses instead of buffering them
OpenApiValidationFilter wraps every validated response in a ContentCachingResponseWrapper, which keeps the body (and ignores flushes) until the request completes. For Server-Sent Events this means the client receives every event at once, at the end, even though event-stream bodies are never validated (only JSON, XML and HTML are). The response wrapper now writes and flushes straight through once the content type is text/event-stream, and keeps caching every other response. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6d8c3c7 commit c9fed25

5 files changed

Lines changed: 168 additions & 1 deletion

File tree

‎spring-boot-starter/spring-boot-starter-web/src/main/java/com/getyourguide/openapi/validation/factory/ContentCachingWrapperFactory.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.getyourguide.openapi.validation.factory;
22

3+
import com.getyourguide.openapi.validation.filter.EventStreamAwareContentCachingResponseWrapper;
34
import com.getyourguide.openapi.validation.filter.MultiReadContentCachingRequestWrapper;
45
import jakarta.servlet.http.HttpServletRequest;
56
import jakarta.servlet.http.HttpServletResponse;
@@ -22,7 +23,7 @@ public ContentCachingResponseWrapper buildContentCachingResponseWrapper(HttpServ
2223
return cachingResponse;
2324
}
2425

25-
return new ContentCachingResponseWrapper(response);
26+
return new EventStreamAwareContentCachingResponseWrapper(response);
2627
}
2728

2829
@Nullable
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.getyourguide.openapi.validation.filter;
2+
3+
import jakarta.servlet.ServletOutputStream;
4+
import jakarta.servlet.http.HttpServletResponse;
5+
import java.io.IOException;
6+
import java.io.PrintWriter;
7+
import java.util.Locale;
8+
import org.springframework.http.MediaType;
9+
import org.springframework.web.util.ContentCachingResponseWrapper;
10+
11+
/**
12+
* Caches the response body for validation, except for Server-Sent Events: a {@code text/event-stream}
13+
* response is written and flushed straight through so each event reaches the client as it is sent.
14+
* Its body is never validated anyway, as only JSON, XML and HTML responses are.
15+
*/
16+
public class EventStreamAwareContentCachingResponseWrapper extends ContentCachingResponseWrapper {
17+
18+
public EventStreamAwareContentCachingResponseWrapper(HttpServletResponse response) {
19+
super(response);
20+
}
21+
22+
@Override
23+
public ServletOutputStream getOutputStream() throws IOException {
24+
return isEventStream() ? getResponse().getOutputStream() : super.getOutputStream();
25+
}
26+
27+
@Override
28+
public PrintWriter getWriter() throws IOException {
29+
return isEventStream() ? getResponse().getWriter() : super.getWriter();
30+
}
31+
32+
@Override
33+
public void flushBuffer() throws IOException {
34+
if (isEventStream()) {
35+
getResponse().flushBuffer();
36+
} else {
37+
super.flushBuffer();
38+
}
39+
}
40+
41+
private boolean isEventStream() {
42+
var contentType = getContentType();
43+
return contentType != null
44+
&& contentType.toLowerCase(Locale.ROOT).startsWith(MediaType.TEXT_EVENT_STREAM_VALUE);
45+
}
46+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.getyourguide.openapi.validation.filter;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertFalse;
5+
import static org.junit.jupiter.api.Assertions.assertTrue;
6+
7+
import java.io.IOException;
8+
import java.nio.charset.StandardCharsets;
9+
import org.junit.jupiter.api.Test;
10+
import org.springframework.mock.web.MockHttpServletResponse;
11+
12+
class EventStreamAwareContentCachingResponseWrapperTest {
13+
14+
private final MockHttpServletResponse response = new MockHttpServletResponse();
15+
private final EventStreamAwareContentCachingResponseWrapper wrapper =
16+
new EventStreamAwareContentCachingResponseWrapper(response);
17+
18+
@Test
19+
public void whenJsonResponseThenBodyIsCachedUntilCopied() throws IOException {
20+
wrapper.setContentType("application/json");
21+
wrapper.getOutputStream().write("{}".getBytes(StandardCharsets.UTF_8));
22+
wrapper.flushBuffer();
23+
24+
assertEquals("", response.getContentAsString());
25+
assertFalse(response.isCommitted());
26+
assertEquals("{}", new String(wrapper.getContentAsByteArray(), StandardCharsets.UTF_8));
27+
28+
wrapper.copyBodyToResponse();
29+
30+
assertEquals("{}", response.getContentAsString());
31+
}
32+
33+
@Test
34+
public void whenEventStreamThenEachWriteAndFlushReachesTheResponse() throws IOException {
35+
wrapper.setContentType("text/event-stream;charset=UTF-8");
36+
wrapper.getOutputStream().write("data: first\n\n".getBytes(StandardCharsets.UTF_8));
37+
wrapper.flushBuffer();
38+
39+
assertEquals("data: first\n\n", response.getContentAsString());
40+
assertTrue(response.isCommitted());
41+
assertEquals(0, wrapper.getContentSize());
42+
}
43+
44+
@Test
45+
public void whenEventStreamWrittenThroughWriterThenItReachesTheResponse() throws IOException {
46+
wrapper.setContentType("TEXT/EVENT-STREAM");
47+
wrapper.getWriter().write("data: first\n\n");
48+
wrapper.getWriter().flush();
49+
50+
assertEquals("data: first\n\n", response.getContentAsString());
51+
assertEquals(0, wrapper.getContentSize());
52+
}
53+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.getyourguide.openapi.validation.integration;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
5+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
6+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
7+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
8+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
9+
10+
import com.getyourguide.openapi.validation.integration.controller.EventStreamController;
11+
import org.junit.jupiter.api.Test;
12+
import org.junit.jupiter.api.extension.ExtendWith;
13+
import org.springframework.beans.factory.annotation.Autowired;
14+
import org.springframework.boot.test.context.SpringBootTest;
15+
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
16+
import org.springframework.http.MediaType;
17+
import org.springframework.test.context.junit.jupiter.SpringExtension;
18+
import org.springframework.test.web.servlet.MockMvc;
19+
20+
@SpringBootTest
21+
@AutoConfigureMockMvc
22+
@ExtendWith(SpringExtension.class)
23+
public class EventStreamIntegrationTest {
24+
25+
@Autowired
26+
private MockMvc mockMvc;
27+
28+
@Test
29+
public void whenEventStreamThenEventsReachTheClientBeforeTheStreamCompletes() throws Exception {
30+
var result = mockMvc.perform(get("/sse").accept(MediaType.TEXT_EVENT_STREAM))
31+
.andExpect(request().asyncStarted())
32+
.andReturn();
33+
34+
assertEquals("data:first\n\n", result.getResponse().getContentAsString());
35+
36+
var emitter = EventStreamController.CURRENT.get();
37+
emitter.send("second");
38+
emitter.complete();
39+
40+
mockMvc.perform(asyncDispatch(result))
41+
.andExpectAll(
42+
status().isOk(),
43+
content().string("data:first\n\ndata:second\n\n")
44+
);
45+
}
46+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.getyourguide.openapi.validation.integration.controller;
2+
3+
import java.io.IOException;
4+
import java.util.concurrent.atomic.AtomicReference;
5+
import org.springframework.http.MediaType;
6+
import org.springframework.web.bind.annotation.GetMapping;
7+
import org.springframework.web.bind.annotation.RestController;
8+
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
9+
10+
@RestController
11+
public class EventStreamController {
12+
public static final AtomicReference<SseEmitter> CURRENT = new AtomicReference<>();
13+
14+
@GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
15+
public SseEmitter stream() throws IOException {
16+
var emitter = new SseEmitter(10_000L);
17+
emitter.send("first");
18+
CURRENT.set(emitter);
19+
return emitter;
20+
}
21+
}

0 commit comments

Comments
 (0)