Commit 05531f7a authored by Tim Neutkens's avatar Tim Neutkens

Fix compression emitter accumulation

parent fc8bcc2b
......@@ -51,6 +51,24 @@ function createMockResponse(opts: { backpressureAfter: number }) {
return mock as typeof mock & ServerResponse
}
function createCompressionPatchedMockResponse(opts: {
backpressureAfter: number
}) {
const mock = createMockResponse(opts)
const gzip = new EventEmitter()
const originalOn = mock.on.bind(mock)
mock.on = ((event: string, listener: (...args: any[]) => void) => {
if (event === 'drain') {
gzip.on('drain', listener)
return mock
}
return originalOn(event, listener)
}) as typeof mock.on
return { mock, gzip }
}
describe('pipeNodeReadableToResponse', () => {
// Regression test for the backpressure + disconnect hang.
//
......@@ -93,4 +111,25 @@ describe('pipeNodeReadableToResponse', () => {
expect(result).toBe('resolved')
})
it('does not accumulate gzip drain listeners when drain is proxied by compression', async () => {
const readable = Readable.from(
Array.from({ length: 20 }, (_, i) => Buffer.from(`chunk-${i}`))
)
const { mock: res, gzip } = createCompressionPatchedMockResponse({
backpressureAfter: 1,
})
const pipePromise = pipeNodeReadableToResponse(readable, res as any)
const interval = setInterval(() => {
gzip.emit('drain')
}, 1)
await pipePromise
clearInterval(interval)
// A single long-lived drain listener is expected for this response.
expect(gzip.listenerCount('drain')).toBeLessThanOrEqual(1)
})
})
......@@ -163,6 +163,20 @@ export async function pipeNodeReadableToResponse(
let started = false
const finished = new DetachedPromise<void>()
let pendingDrainCallback: ((error?: Error | null) => void) | null = null
// Use a single drain listener for the entire response.
//
// The compression middleware proxies `res.on('drain', listener)` to an
// internal Gzip stream. Repeated `res.once('drain', callback)` calls can
// accumulate wrappers on that Gzip stream because `once` removal targets
// `res`, not the proxied emitter.
const onDrain = () => {
const callback = pendingDrainCallback
pendingDrainCallback = null
callback?.()
}
res.on('drain', onDrain)
const { Writable: NodeWritable } =
require('node:stream') as typeof import('node:stream')
......@@ -210,7 +224,7 @@ export async function pipeNodeReadableToResponse(
}
if (!ok) {
res.once('drain', callback)
pendingDrainCallback = callback
} else {
callback()
}
......@@ -290,6 +304,7 @@ export async function pipeNodeReadableToResponse(
await finished.promise
res.off('close', onClose)
res.off('drain', onDrain)
} catch (err: any) {
if (isAbortError(err)) return
throw new Error('failed to pipe node readable to response', {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment