fix(hub): don't crash when an SSE client disconnects while gzip output is buffered (#2314)

compressSseResponse pauses zlib when the client falls behind, so a large
event can leave compressed output parked in zlib's readable buffer. pull()
calls gzip.resume(), which flows that buffer on a later tick. If the client
disconnects in between, cancel() closes the stream and destroys zlib, but
the pending flow still emits 'data' and controller.enqueue() throws
"Invalid state: Controller is already closed". The throw happens inside a
zlib event handler, so nothing catches it and the hub process exits.

Track when the stream has finished (closed, errored or cancelled) and stop
touching the controller after that.

via [HAPI](https://hapi.run)

Co-authored-by: HAPI <noreply@hapi.run>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
anantheparty
2026-11-09 12:05:40 +08:00
committed by GitHub
co-authored by HAPI Claude Opus 5.5
parent 38b6540bed
commit eb84dfa0d9
2 changed files with 52 additions and 0 deletions
+35
View File
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'bun:test'
import { randomBytes } from 'node:crypto'
import zlib from 'node:zlib'
import { acceptsGzip, compressSseResponse } from './sseCompression'
@@ -161,6 +162,40 @@ describe('compressSseResponse cleanup', () => {
expect(rejections).toEqual([])
})
it('does not throw when the client cancels while zlib still holds output', async () => {
// A large event leaves compressed output parked in zlib while the
// consumer is behind. pull() switches zlib back to flowing; if the
// client disconnects before that flow runs, the late 'data' event
// must not enqueue into the closed stream. Uncaught, that error
// takes the whole hub down.
const payload = randomBytes(96 * 1024).toString('base64')
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode(`data: {"pad":"${payload}"}\n\n`))
}
})
const result = compressSseResponse(
new Response(body, { headers: { 'Content-Type': 'text/event-stream' } }),
'gzip'
)
const errors: unknown[] = []
const onError = (error: unknown) => errors.push(error)
process.on('uncaughtException', onError)
try {
const reader = result.body!.getReader()
await reader.read()
await new Promise((resolve) => setTimeout(resolve, 20))
void reader.read()
await reader.cancel('client gone')
await new Promise((resolve) => setTimeout(resolve, 50))
} finally {
process.off('uncaughtException', onError)
}
expect(errors).toEqual([])
})
})
describe('compressSseResponse content negotiation', () => {
+17
View File
@@ -67,6 +67,11 @@ export function compressSseResponse(response: Response, acceptEncoding: string |
// reader, which is the whole lifetime of the connection.
const reader = source.getReader()
let resumeRead: (() => void) | null = null
// Set once the stream is closed, errored or cancelled. zlib can still emit
// output it buffered while the client was behind (pull() resumes it on a
// later tick), and touching a closed controller throws from inside the
// zlib event handler, which nothing catches.
let finished = false
const compressed = new ReadableStream<Uint8Array>({
start(controller) {
@@ -84,15 +89,26 @@ export function compressSseResponse(response: Response, acceptEncoding: string |
}
gzip.on('data', (chunk: Buffer) => {
if (finished) {
return
}
controller.enqueue(new Uint8Array(chunk))
if ((controller.desiredSize ?? 1) <= 0) {
gzip.pause()
}
})
gzip.on('end', () => {
if (finished) {
return
}
finished = true
controller.close()
})
gzip.on('error', (error) => {
if (finished) {
return
}
finished = true
controller.error(error)
})
@@ -123,6 +139,7 @@ export function compressSseResponse(response: Response, acceptEncoding: string |
resume?.()
},
cancel(reason) {
finished = true
gzip.destroy()
resumeRead?.()
resumeRead = null