Add the sse-websocket module
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
package com.ankurm.ssews;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.context.request.async.DeferredResult;
|
||||
import org.springframework.web.servlet.AsyncHandlerInterceptor;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* Answers "how long does my SSE stream actually get?" without waiting for it to happen.
|
||||
*
|
||||
* <p>The chain is: {@code SseEmitter}'s own constructor argument, else
|
||||
* {@code spring.mvc.async.request-timeout}, else whatever the servlet container defaults to.
|
||||
* Only the last one is invisible.
|
||||
*
|
||||
* <p>Reading it needs a little care. Inside the handler method {@code isAsyncStarted()} is still
|
||||
* {@code false} — Spring starts async processing <em>after</em> the method returns, once
|
||||
* it sees the return type. The first place the real {@code AsyncContext} exists is
|
||||
* {@link AsyncHandlerInterceptor#afterConcurrentHandlingStarted}, so that is where the timeout
|
||||
* is captured.
|
||||
*/
|
||||
@RestController
|
||||
public class AsyncTimeoutProbe {
|
||||
|
||||
static final AtomicReference<Object> LAST_TIMEOUT = new AtomicReference<>("<not captured>");
|
||||
|
||||
private final String configured;
|
||||
|
||||
AsyncTimeoutProbe(@Value("${spring.mvc.async.request-timeout:<unset>}") String configured) {
|
||||
this.configured = configured;
|
||||
}
|
||||
|
||||
/** Start async, so the interceptor below can read the effective timeout, then answer. */
|
||||
@GetMapping("/diag/async-start")
|
||||
public DeferredResult<String> start() {
|
||||
DeferredResult<String> result = new DeferredResult<>();
|
||||
result.setResult("started");
|
||||
return result;
|
||||
}
|
||||
|
||||
@GetMapping("/diag/async-timeout")
|
||||
public Map<String, Object> asyncTimeout(HttpServletRequest request) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("spring.mvc.async.request-timeout", configured);
|
||||
m.put("servletContainer", request.getServletContext().getServerInfo());
|
||||
m.put("effectiveAsyncTimeoutMs", LAST_TIMEOUT.get());
|
||||
return m;
|
||||
}
|
||||
|
||||
@Component
|
||||
static class CaptureAsyncTimeout implements AsyncHandlerInterceptor {
|
||||
|
||||
@Override
|
||||
public void afterConcurrentHandlingStarted(HttpServletRequest request,
|
||||
HttpServletResponse response, Object handler) {
|
||||
if (request.isAsyncStarted()) {
|
||||
LAST_TIMEOUT.set(request.getAsyncContext().getTimeout());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class RegisterInterceptor implements WebMvcConfigurer {
|
||||
|
||||
private final CaptureAsyncTimeout interceptor;
|
||||
|
||||
RegisterInterceptor(CaptureAsyncTimeout interceptor) {
|
||||
this.interceptor = interceptor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(interceptor);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.ankurm.ssews;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.time.Instant;
|
||||
|
||||
import org.springframework.messaging.handler.annotation.MessageMapping;
|
||||
import org.springframework.messaging.handler.annotation.Payload;
|
||||
import org.springframework.messaging.handler.annotation.SendTo;
|
||||
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
|
||||
import org.springframework.messaging.simp.SimpMessageType;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
/**
|
||||
* The chat. Three handlers, each demonstrating a different routing rule.
|
||||
*
|
||||
* @see <a href="../../../../../docs/04-stomp.md">docs/04-stomp.md</a>
|
||||
*/
|
||||
@Controller
|
||||
public class ChatController {
|
||||
|
||||
private final SimpMessagingTemplate template;
|
||||
|
||||
ChatController(SimpMessagingTemplate template) {
|
||||
this.template = template;
|
||||
}
|
||||
|
||||
/** Explicit fan-out destination. Client SENDs to /app/chat.send, subscribers get /topic/room. */
|
||||
@MessageMapping("/chat.send")
|
||||
@SendTo("/topic/room")
|
||||
public ChatMessage send(@Payload ChatMessage in, SimpMessageHeaderAccessor headers) {
|
||||
String from = in.from() == null ? headers.getSessionId() : in.from();
|
||||
return new ChatMessage(from, in.text(), Instant.now());
|
||||
}
|
||||
|
||||
/**
|
||||
* No {@code @SendTo}. The return value still goes somewhere: the default destination is the
|
||||
* broker prefix plus the mapping, i.e. {@code /topic/chat.echo}. That default is why a
|
||||
* handler you thought was private is readable by anyone who guesses the path.
|
||||
*/
|
||||
@MessageMapping("/chat.echo")
|
||||
public ChatMessage echo(@Payload ChatMessage in) {
|
||||
return new ChatMessage("echo", in.text(), Instant.now());
|
||||
}
|
||||
|
||||
/**
|
||||
* Point-to-point. Sent to one session's private destination; every other subscriber to
|
||||
* /user/queue/whisper gets nothing, because the broker rewrote the destination per session.
|
||||
*
|
||||
* <p>The three extra lines are not optional and their absence is silent. With no
|
||||
* authenticated {@link Principal} the "user" is the STOMP session id, and
|
||||
* {@code DefaultUserDestinationResolver} can only turn a session id into a real destination
|
||||
* if the message also <em>carries</em> that session id in its headers. Call the two-argument
|
||||
* {@code convertAndSendToUser(sessionId, dest, payload)} instead and the message is resolved
|
||||
* against a user registry that has never heard of that name: no exception, no log line, no
|
||||
* delivery. {@code setLeaveMutable(true)} is required too — without it the accessor is
|
||||
* immutable by the time the resolver looks, and the session id is lost again.
|
||||
*/
|
||||
@MessageMapping("/chat.whisper")
|
||||
public void whisper(@Payload ChatMessage in, SimpMessageHeaderAccessor headers, Principal principal) {
|
||||
String targetSessionId = in.from();
|
||||
SimpMessageHeaderAccessor out = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
|
||||
out.setSessionId(targetSessionId);
|
||||
out.setLeaveMutable(true);
|
||||
template.convertAndSendToUser(targetSessionId, "/queue/whisper",
|
||||
new ChatMessage(principal == null ? headers.getSessionId() : principal.getName(),
|
||||
in.text(), Instant.now()),
|
||||
out.getMessageHeaders());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.ankurm.ssews;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/** A single chat line, carried as the STOMP frame body. */
|
||||
public record ChatMessage(String from, String text, Instant at) {
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.ankurm.ssews;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
/**
|
||||
* The live dashboard, and four smaller endpoints that exist only so the article can quote a
|
||||
* transcript rather than assert a behaviour.
|
||||
*
|
||||
* @see <a href="../../../../../docs/02-sse-lifecycle.md">docs/02-sse-lifecycle.md</a>
|
||||
*/
|
||||
@RestController
|
||||
public class DashboardSseController {
|
||||
|
||||
private final EmitterRegistry registry;
|
||||
private final AtomicLong seq = new AtomicLong();
|
||||
|
||||
DashboardSseController(EmitterRegistry registry) {
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* The dashboard stream. Subscribers get whatever the scheduled broadcaster pushes.
|
||||
*
|
||||
* <p>{@code Long.MAX_VALUE} disables the async timeout for this handler. That is the right
|
||||
* call for a stream that is supposed to stay open, and it is also the line that turns a
|
||||
* leaked emitter into a permanent leak — which is why {@link EmitterRegistry} removes
|
||||
* on all three callbacks.
|
||||
*/
|
||||
@GetMapping(path = "/sse/metrics", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter metrics() {
|
||||
return registry.register(UUID.randomUUID().toString(), new SseEmitter(Long.MAX_VALUE));
|
||||
}
|
||||
|
||||
/**
|
||||
* Three events and a close, written from the request thread, so a curl transcript shows the
|
||||
* exact wire format: field names, the blank-line record separator, and where {@code retry}
|
||||
* and {@code id} land.
|
||||
*/
|
||||
@GetMapping(path = "/sse/raw", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter raw() throws IOException {
|
||||
SseEmitter emitter = new SseEmitter(10_000L);
|
||||
emitter.send(SseEmitter.event().comment("stream open"));
|
||||
emitter.send(SseEmitter.event()
|
||||
.id("1").name("metric").reconnectTime(3000)
|
||||
.data(new MetricSnapshot(1, "node-a", 0.42, 512, Instant.parse("2026-09-03T10:00:00Z")),
|
||||
MediaType.APPLICATION_JSON));
|
||||
// Multi-line data is split into several data: lines by the SSE spec, and the browser
|
||||
// rejoins them with "\n". Worth seeing once.
|
||||
emitter.send(SseEmitter.event().id("2").name("note").data("line one\nline two"));
|
||||
emitter.complete();
|
||||
return emitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the same record twice: once with an explicit JSON media type and once with none.
|
||||
* The difference is the whole of {@code docs/03-the-payload.md}.
|
||||
*/
|
||||
@GetMapping(path = "/sse/payload", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter payload() throws IOException {
|
||||
SseEmitter emitter = new SseEmitter(10_000L);
|
||||
MetricSnapshot snap =
|
||||
new MetricSnapshot(7, "node-a", 0.42, 512, Instant.parse("2026-09-03T10:00:00Z"));
|
||||
emitter.send(SseEmitter.event().name("with-json").data(snap, MediaType.APPLICATION_JSON));
|
||||
emitter.send(SseEmitter.event().name("no-media-type").data(snap));
|
||||
// The same two calls for a String payload, where the answer is different: a String is
|
||||
// written by StringHttpMessageConverter unless a JSON media type forces Jackson, and
|
||||
// Jackson then quotes and escapes it.
|
||||
emitter.send(SseEmitter.event().name("string-plain").data("{\"already\":\"json\"}"));
|
||||
emitter.send(SseEmitter.event().name("string-json")
|
||||
.data("{\"already\":\"json\"}", MediaType.APPLICATION_JSON));
|
||||
emitter.complete();
|
||||
return emitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a stream, writes one event, then never writes again. With a short timeout this shows
|
||||
* what a client actually observes when the async request times out mid-stream.
|
||||
*/
|
||||
@GetMapping(path = "/sse/silent", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter silent(@RequestParam(defaultValue = "1500") long timeoutMs) throws IOException {
|
||||
SseEmitter emitter = registry.register(UUID.randomUUID().toString(), new SseEmitter(timeoutMs));
|
||||
emitter.send(SseEmitter.event().name("hello").data("then silence"));
|
||||
return emitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Echoes the {@code Last-Event-ID} request header. The browser sends it automatically on
|
||||
* reconnect; the server is expected to replay from there, and almost nothing does.
|
||||
*/
|
||||
@GetMapping(path = "/sse/resume", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter resume(@RequestHeader(name = "Last-Event-ID", required = false) String lastEventId)
|
||||
throws IOException {
|
||||
SseEmitter emitter = new SseEmitter(10_000L);
|
||||
long from = lastEventId == null ? 0 : Long.parseLong(lastEventId);
|
||||
emitter.send(SseEmitter.event().name("resumed")
|
||||
.data("Last-Event-ID=" + lastEventId + " -> replaying from " + (from + 1)));
|
||||
for (long i = from + 1; i <= from + 2; i++) {
|
||||
emitter.send(SseEmitter.event().id(Long.toString(i)).name("metric").data("event " + i));
|
||||
}
|
||||
emitter.complete();
|
||||
return emitter;
|
||||
}
|
||||
|
||||
long nextSeq() {
|
||||
return seq.incrementAndGet();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.ankurm.ssews;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import jakarta.servlet.ServletContext;
|
||||
import jakarta.websocket.server.ServerContainer;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.messaging.simp.user.SimpUserRegistry;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* Prints the runtime state that is otherwise invisible: how many SSE streams are open, how many
|
||||
* writes discovered a dead one, and how many WebSocket sessions the broker believes it has.
|
||||
*
|
||||
* <p>Delete this before shipping. It is here because "the emitter map is leaking" and "the
|
||||
* broker still thinks that user is connected" are both conditions you cannot see from the
|
||||
* outside, and both are much easier to argue about with a number in front of you.
|
||||
*/
|
||||
@RestController
|
||||
public class DiagnosticsController {
|
||||
|
||||
private final EmitterRegistry registry;
|
||||
private final SimpUserRegistry userRegistry;
|
||||
private final List<HttpMessageConverter<?>> converters;
|
||||
private final String asyncTimeout;
|
||||
private final String tomcatMaxThreads;
|
||||
|
||||
DiagnosticsController(EmitterRegistry registry,
|
||||
SimpUserRegistry userRegistry,
|
||||
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter adapter,
|
||||
@Value("${spring.mvc.async.request-timeout:<unset>}") String asyncTimeout,
|
||||
@Value("${server.tomcat.threads.max:<unset>}") String tomcatMaxThreads) {
|
||||
this.registry = registry;
|
||||
this.userRegistry = userRegistry;
|
||||
this.converters = adapter.getMessageConverters();
|
||||
this.asyncTimeout = asyncTimeout;
|
||||
this.tomcatMaxThreads = tomcatMaxThreads;
|
||||
}
|
||||
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
ServletContext servletContext;
|
||||
|
||||
@GetMapping("/diag")
|
||||
public Map<String, Object> diag() {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("sse.open", registry.open());
|
||||
m.put("sse.opened", registry.opened());
|
||||
m.put("sse.completed", registry.completed());
|
||||
m.put("sse.timedOut", registry.timedOut());
|
||||
m.put("sse.errored", registry.errored());
|
||||
m.put("sse.sendsOk", registry.sendsOk());
|
||||
m.put("sse.sendsFailed", registry.sendsFailed());
|
||||
m.put("ws.users", userRegistry.getUserCount());
|
||||
m.put("config.spring.mvc.async.request-timeout", asyncTimeout);
|
||||
m.put("config.server.tomcat.threads.max", tomcatMaxThreads);
|
||||
// The order that decides what SseEmitter.send(data, mediaType) actually does: the first
|
||||
// converter whose canWrite(type, mediaType) returns true wins, and the media type you
|
||||
// passed is only a filter, never a preference.
|
||||
m.put("http.messageConverters",
|
||||
converters.stream().map(c -> c.getClass().getSimpleName()).toList());
|
||||
|
||||
// The number that actually decides how big a STOMP frame can be. It belongs to the
|
||||
// servlet container, not to Spring, and Spring's own messageSizeLimit never sees a
|
||||
// frame the container refused to assemble.
|
||||
Object sc = servletContext.getAttribute("jakarta.websocket.server.ServerContainer");
|
||||
if (sc instanceof ServerContainer container) {
|
||||
m.put("ws.container.defaultMaxTextMessageBufferSize",
|
||||
container.getDefaultMaxTextMessageBufferSize());
|
||||
m.put("ws.container.defaultMaxBinaryMessageBufferSize",
|
||||
container.getDefaultMaxBinaryMessageBufferSize());
|
||||
m.put("ws.container.defaultMaxSessionIdleTimeout",
|
||||
container.getDefaultMaxSessionIdleTimeout());
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.ankurm.ssews;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
/**
|
||||
* The piece every SSE tutorial leaves out: something that owns the open emitters and removes
|
||||
* them again.
|
||||
*
|
||||
* <p>An {@link SseEmitter} is not a subscription. Nothing in Spring keeps a list of them, and
|
||||
* nothing tells you when one dies — you find out on the next write, as an
|
||||
* {@link IOException} thrown from {@code send()} on whichever thread happened to be
|
||||
* broadcasting. If that thread is a scheduler thread and the exception escapes, the schedule
|
||||
* stops and the whole dashboard silently freezes for everyone.
|
||||
*
|
||||
* <p>The counters here are exposed by {@link DiagnosticsController} so the article can quote
|
||||
* real numbers for "how many streams were open, and how many writes discovered a dead one".
|
||||
*
|
||||
* @see <a href="../../../../../docs/02-sse-lifecycle.md">docs/02-sse-lifecycle.md</a>
|
||||
*/
|
||||
@Component
|
||||
public class EmitterRegistry {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(EmitterRegistry.class);
|
||||
|
||||
private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();
|
||||
|
||||
private final AtomicLong opened = new AtomicLong();
|
||||
private final AtomicLong completed = new AtomicLong();
|
||||
private final AtomicLong timedOut = new AtomicLong();
|
||||
private final AtomicLong errored = new AtomicLong();
|
||||
private final AtomicLong sendsOk = new AtomicLong();
|
||||
private final AtomicLong sendsFailed = new AtomicLong();
|
||||
|
||||
public SseEmitter register(String id, SseEmitter emitter) {
|
||||
emitters.put(id, emitter);
|
||||
opened.incrementAndGet();
|
||||
|
||||
// All three callbacks must remove the emitter. Registering only onCompletion is the
|
||||
// most common variant of this bug: a timed-out emitter is never completed by the
|
||||
// client, so it stays in the map for ever and every broadcast keeps paying for it.
|
||||
emitter.onCompletion(() -> { emitters.remove(id); completed.incrementAndGet(); });
|
||||
emitter.onTimeout(() -> {
|
||||
emitters.remove(id);
|
||||
timedOut.incrementAndGet();
|
||||
// Spring completes the async request on timeout, but call complete() so the
|
||||
// onCompletion callback semantics stay consistent for our own bookkeeping.
|
||||
emitter.complete();
|
||||
});
|
||||
emitter.onError(t -> { emitters.remove(id); errored.incrementAndGet(); });
|
||||
return emitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcast to everyone, dropping the streams that turn out to be gone.
|
||||
*
|
||||
* <p>The try/catch is not defensive programming; it is the only way a dead client is
|
||||
* detected. Note also that this is where SSE's cost lives: one serialise-and-write per
|
||||
* open stream, on the calling thread.
|
||||
*/
|
||||
public int broadcast(String eventName, MetricSnapshot payload) {
|
||||
int delivered = 0;
|
||||
for (Map.Entry<String, SseEmitter> e : emitters.entrySet()) {
|
||||
try {
|
||||
e.getValue().send(SseEmitter.event()
|
||||
.id(Long.toString(payload.seq()))
|
||||
.name(eventName)
|
||||
.reconnectTime(3000)
|
||||
.data(payload, org.springframework.http.MediaType.APPLICATION_JSON));
|
||||
sendsOk.incrementAndGet();
|
||||
delivered++;
|
||||
}
|
||||
catch (IOException | IllegalStateException ex) {
|
||||
// IOException -> the socket is gone (client closed the tab, proxy reaped it).
|
||||
// IllegalState -> the emitter already completed or timed out on another thread.
|
||||
sendsFailed.incrementAndGet();
|
||||
emitters.remove(e.getKey());
|
||||
log.debug("dropping emitter {}: {}", e.getKey(), ex.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
return delivered;
|
||||
}
|
||||
|
||||
public int open() { return emitters.size(); }
|
||||
public long opened() { return opened.get(); }
|
||||
public long completed() { return completed.get(); }
|
||||
public long timedOut() { return timedOut.get(); }
|
||||
public long errored() { return errored.get(); }
|
||||
public long sendsOk() { return sendsOk.get(); }
|
||||
public long sendsFailed() { return sendsFailed.get(); }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.ankurm.ssews;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* One row of the live dashboard.
|
||||
*
|
||||
* <p>{@link Instant} is here on purpose: it is the field that fails to serialise if the wrong
|
||||
* converter is chosen for the SSE payload, which is what {@code SseDataConversionTest} pins.
|
||||
*
|
||||
* @see <a href="../../../../../docs/03-the-payload.md">docs/03-the-payload.md</a>
|
||||
*/
|
||||
public record MetricSnapshot(long seq, String host, double cpu, long heapMb, Instant at) {
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.ankurm.ssews;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Pushes one snapshot to every open dashboard stream on a fixed schedule.
|
||||
*
|
||||
* <p>Fan-out happens on the scheduler thread, which is the shape almost every SSE dashboard
|
||||
* ends up with and also its first scaling limit: 1 000 open streams means 1 000
|
||||
* serialise-and-write calls in a row on one thread, every tick.
|
||||
* {@code docs/06-choosing.md} has the measurement.
|
||||
*/
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "dashboard.broadcast.enabled", havingValue = "true", matchIfMissing = true)
|
||||
public class MetricsBroadcaster {
|
||||
|
||||
private final EmitterRegistry registry;
|
||||
private final AtomicLong seq = new AtomicLong();
|
||||
|
||||
MetricsBroadcaster(EmitterRegistry registry) {
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
@Scheduled(fixedRateString = "${dashboard.broadcast.interval-ms:500}")
|
||||
public void tick() {
|
||||
if (registry.open() == 0) {
|
||||
return;
|
||||
}
|
||||
registry.broadcast("metric", new MetricSnapshot(
|
||||
seq.incrementAndGet(),
|
||||
"node-a",
|
||||
Math.round(ThreadLocalRandom.current().nextDouble() * 10000) / 10000.0,
|
||||
256 + ThreadLocalRandom.current().nextInt(256),
|
||||
Instant.now()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.ankurm.ssews;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.socket.messaging.SessionConnectedEvent;
|
||||
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
|
||||
import org.springframework.web.socket.messaging.SessionSubscribeEvent;
|
||||
|
||||
/**
|
||||
* Presence, and the reason people reach for STOMP over SSE in the first place: the server knows
|
||||
* who is connected, who subscribed to what, and when they left.
|
||||
*
|
||||
* <p>SSE has no equivalent. There is no disconnect event — only a write that fails later.
|
||||
*/
|
||||
@Component
|
||||
public class PresenceListener {
|
||||
|
||||
private final List<String> log = new CopyOnWriteArrayList<>();
|
||||
|
||||
@EventListener
|
||||
public void onConnected(SessionConnectedEvent e) {
|
||||
log.add("CONNECTED " + StompHeaderAccessor.wrap(e.getMessage()).getSessionId());
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void onSubscribe(SessionSubscribeEvent e) {
|
||||
StompHeaderAccessor h = StompHeaderAccessor.wrap(e.getMessage());
|
||||
log.add("SUBSCRIBE " + h.getSessionId() + " -> " + h.getDestination());
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void onDisconnect(SessionDisconnectEvent e) {
|
||||
log.add("DISCONNECT " + e.getSessionId() + " status=" + e.getCloseStatus());
|
||||
}
|
||||
|
||||
public List<String> events() {
|
||||
return List.copyOf(log);
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
log.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.ankurm.ssews;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
/**
|
||||
* Both halves of the article in one application: a Server-Sent Events dashboard under
|
||||
* {@code /sse/**} and a STOMP-over-WebSocket chat under {@code /ws}.
|
||||
*
|
||||
* <p>They coexist deliberately. The point of the companion article is that they are not
|
||||
* competitors so much as different answers to "who needs to talk", and running them side by
|
||||
* side makes the asymmetry visible: the SSE endpoints are plain MVC handler methods with a
|
||||
* return type, while the chat needs a broker, a message-converter stack and a session registry.
|
||||
*
|
||||
* @see <a href="../../../../../docs/01-two-protocols.md">docs/01-two-protocols.md</a>
|
||||
*/
|
||||
@SpringBootApplication
|
||||
@EnableScheduling
|
||||
public class SseWebSocketApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SseWebSocketApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.ankurm.ssews;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;
|
||||
|
||||
/**
|
||||
* The other half of the message size limit — the half that is not in Spring.
|
||||
*
|
||||
* <p>{@code WebSocketTransportRegistration.setMessageSizeLimit(64 * 1024)} is not the limit that
|
||||
* bites first. Spring's {@code SubProtocolWebSocketHandler} does not support partial messages,
|
||||
* so the servlet container has to buffer each WebSocket text message whole before handing it
|
||||
* over — and Tomcat's buffer defaults to <strong>8 192 bytes</strong>. Cross that and
|
||||
* Tomcat closes the connection with WebSocket status <strong>1009</strong> before Spring ever
|
||||
* sees the frame, so raising Spring's limit alone changes nothing.
|
||||
*
|
||||
* <p>Active under the {@code bigframes} profile so the companion test can show both behaviours
|
||||
* from one build.
|
||||
*
|
||||
* @see <a href="../../../../../docs/05-limits.md">docs/05-limits.md</a>
|
||||
*/
|
||||
@Configuration
|
||||
@Profile("bigframes")
|
||||
public class WebSocketBufferConfig {
|
||||
|
||||
@Bean
|
||||
public ServletServerContainerFactoryBean createWebSocketContainer(
|
||||
@org.springframework.beans.factory.annotation.Value("${ws.buffer-bytes:262144}") int bytes) {
|
||||
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
|
||||
container.setMaxTextMessageBufferSize(bytes);
|
||||
container.setMaxBinaryMessageBufferSize(bytes);
|
||||
return container;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.ankurm.ssews;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
|
||||
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
|
||||
|
||||
/**
|
||||
* Four lines of configuration that decide more than they look like they do.
|
||||
*
|
||||
* @see <a href="../../../../../docs/04-stomp.md">docs/04-stomp.md</a>
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebSocketMessageBroker
|
||||
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
|
||||
@Override
|
||||
public void registerStompEndpoints(StompEndpointRegistry registry) {
|
||||
// No setAllowedOrigins call at all. The handshake then permits same-origin requests
|
||||
// only -- and "same origin" is decided from the Origin header, which a non-browser
|
||||
// client does not send, so curl and the Java client are allowed while a page on
|
||||
// another site is not. Add setAllowedOriginPatterns("https://app.example.com") for a
|
||||
// real cross-origin front end; setAllowedOrigins("*") is rejected outright when
|
||||
// credentials are allowed.
|
||||
registry.addEndpoint("/ws");
|
||||
|
||||
// The SockJS variant is a SECOND endpoint on its own path. Registering .withSockJS()
|
||||
// on the same path does not give you both: SockJS wraps the URL in /{server}/{session}
|
||||
// and a plain WebSocket client pointed at it fails the handshake.
|
||||
registry.addEndpoint("/ws-sockjs").withSockJS();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureMessageBroker(MessageBrokerRegistry registry) {
|
||||
// The simple broker. In-memory, single JVM, no persistence, no acknowledgement, and it
|
||||
// drops everything on restart. enableStompBrokerRelay(..) swaps in RabbitMQ or ActiveMQ
|
||||
// without touching a controller -- see ../rabbitmq for the broker side.
|
||||
registry.enableSimpleBroker("/topic", "/queue");
|
||||
|
||||
// Destinations a CLIENT sends to. /app/chat.send is routed to @MessageMapping; anything
|
||||
// starting with /topic or /queue goes straight to the broker and is NEVER seen by a
|
||||
// controller. Getting this backwards produces a message that vanishes with no error.
|
||||
registry.setApplicationDestinationPrefixes("/app");
|
||||
|
||||
// The prefix a client subscribes under for messages addressed to it alone. The client
|
||||
// subscribes to /user/queue/whisper; the broker rewrites that to a session-scoped
|
||||
// destination that no other session can subscribe to.
|
||||
registry.setUserDestinationPrefix("/user");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
|
||||
// Defaults, restated so the numbers are visible in one place rather than discovered
|
||||
// when a 70 KB frame disappears. WebSocketTransportRegistration's own defaults are
|
||||
// 64 KB for both; see WebSocketLimitsTest for what exceeding them looks like.
|
||||
registration.setMessageSizeLimit(64 * 1024);
|
||||
registration.setSendBufferSizeLimit(512 * 1024);
|
||||
registration.setSendTimeLimit(20_000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
spring:
|
||||
application:
|
||||
name: sse-websocket
|
||||
# spring.mvc.async.request-timeout is deliberately ABSENT, not set to blank. When it is
|
||||
# absent Spring never calls AsyncContext.setTimeout(..), so the servlet container's own
|
||||
# default applies. /diag/async-timeout reports what that turns out to be on this container;
|
||||
# an SseEmitter constructor argument overrides both.
|
||||
|
||||
server:
|
||||
port: 8080
|
||||
|
||||
dashboard:
|
||||
broadcast:
|
||||
enabled: true
|
||||
interval-ms: 500
|
||||
|
||||
logging:
|
||||
level:
|
||||
org.springframework.web.socket: INFO
|
||||
Reference in New Issue
Block a user