Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,17 @@ export function writeFromReadableStreamDefaultReader(
writable: Writable,
currentReadPromise?: Promise<ReadableStreamReadResult<Uint8Array>> | undefined
) {
const handleError = () => {
// ignore the error
const cancel = (error?: unknown) => {
reader.cancel(error).catch(() => {})
}

writable.on('error', handleError)
writable.on('close', cancel)
writable.on('error', cancel)
;(currentReadPromise ?? reader.read()).then(flow, handleStreamError)

return reader.closed.finally(() => {
writable.off('error', handleError)
writable.off('close', cancel)
writable.off('error', cancel)
})

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down
10 changes: 6 additions & 4 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,15 @@ describe('buildOutgoingHttpHeaders', () => {
})

describe('writeFromReadableStream', () => {
it('should handle client disconnection gracefully without canceling stream', async () => {
it('should handle client disconnection', async () => {
let enqueueCalled = false
let cancelCalled = false
let enqueueTimeout: NodeJS.Timeout | undefined

// Create test ReadableStream
const stream = new ReadableStream({
start(controller) {
setTimeout(() => {
enqueueTimeout = setTimeout(() => {
try {
controller.enqueue(new TextEncoder().encode('test'))
enqueueCalled = true
Expand All @@ -97,6 +98,7 @@ describe('writeFromReadableStream', () => {
},
cancel() {
cancelCalled = true
clearTimeout(enqueueTimeout)
},
})

Expand All @@ -110,8 +112,8 @@ describe('writeFromReadableStream', () => {

await writeFromReadableStream(stream, writable)

expect(enqueueCalled).toBe(true) // enqueue should succeed
expect(cancelCalled).toBe(false) // cancel should not be called
expect(enqueueCalled).toBe(false) // enqueue should not be called
expect(cancelCalled).toBe(true) // cancel should be called
})
})

Expand Down
Loading