fix(sse): wait for the pump before returning

When a client disconnected, the handler stopped its pump and returned at
once, while the pump could still be writing an event or a heartbeat to
the response. net/http does not allow a write to a response after
ServeHTTP has returned. The handler now waits for the pump to exit; a
pump blocked in a write returns once the connection is gone.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
This commit is contained in:
Aleksei Sviridkin committed 2026-11-13 12:35:06 +03:00
1 parent 86da6c7a5b
commit 40d340a3fc
2 files changed
+64

No files matched your search

+1
View File
@@ -222,6 +222,7 @@ func (s *Server) handleStream(w http.ResponseWriter, r *http.Request) {
case <-pumped:
}
c.stop()
<-pumped
}
// stop ends the client's pump. Shutdown and the client's own handler both
+63
View File
@@ -181,3 +181,66 @@ func TestShutdownEndsOpenStreams(t *testing.T) {
t.Fatal("Shutdown left the stream open")
}
}
// blockingWriter holds every write after the first until release is closed.
type blockingWriter struct {
streamWriter
writing chan struct{}
release chan struct{}
returned chan struct{}
}
func (w *blockingWriter) Write(p []byte) (int, error) {
if w.String() == "" {
return w.streamWriter.Write(p)
}
select {
case w.writing <- struct{}{}:
default:
}
<-w.release
return w.streamWriter.Write(p)
}
// The handler does not return while its pump is still writing: net/http does
// not allow a write to a response after ServeHTTP has returned.
func TestStreamWaitsForPumpBeforeReturning(t *testing.T) {
s := newTestServer(time.Hour)
w := &blockingWriter{
streamWriter: streamWriter{header: http.Header{}, okWrites: 100},
writing: make(chan struct{}, 1),
release: make(chan struct{}),
returned: make(chan struct{}),
}
ctx, cancel := context.WithCancel(context.Background())
r := httptest.NewRequest(http.MethodGet, "/stream", nil).WithContext(ctx)
go func() {
s.handleStream(w, r)
close(w.returned)
}()
deadline := time.Now().Add(time.Second)
for len(s.snapshotClients()) == 0 && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
// Straight onto the client's queue, which only the pump reads: Publish
// would also set latest, which the handler itself may still write.
s.snapshotClients()[0].ch <- "event"
select {
case <-w.writing:
case <-time.After(time.Second):
t.Fatal("the pump never wrote the event")
}
cancel()
select {
case <-w.returned:
close(w.release)
t.Fatal("the handler returned while its pump was writing")
case <-time.After(100 * time.Millisecond):
}
close(w.release)
select {
case <-w.returned:
case <-time.After(time.Second):
t.Fatal("the handler did not return once its pump finished")
}
}