Skip to content
Open
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: 8 additions & 2 deletions src/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,7 @@ const responseViaResponseObject = async (

const values: Uint8Array[] = []
let done = false
let readError: unknown
let currentReadPromise: Promise<ReadableStreamReadResult<Uint8Array>> | undefined = undefined

if (resHeaderRecord['transfer-encoding'] !== 'chunked') {
Expand All @@ -364,10 +365,15 @@ const responseViaResponseObject = async (
for (let i = 0; i < maxReadCount; i++) {
currentReadPromise ||= reader.read()
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
console.error(e)
done = true
// An errored body must not be answered as a complete, empty 200:
// record the error and keep `done` false so the streaming path
// below tears the connection down instead.
readError = e
})
if (!chunk) {
if (readError) {
break
}
if (i === 1) {
// XXX: In Node.js v24, some response bodies are not read all the way through until the next task queue,
// so wait a moment and retry. (e.g. new Blob([new Uint8Array(contents)]) )
Expand Down
22 changes: 22 additions & 0 deletions test/listener.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ import { GlobalRequest, Request as LightweightRequest, RequestError } from '../s
import { GlobalResponse, Response as LightweightResponse } from '../src/response'
import { requestServer } from './helpers/request'

// The `overrideGlobalObjects` block further down mutates globalThis.Response, so capture the
// native constructor here for tests that need it.
const NativeResponse = Response

const withTimeout = async <T>(promise: Promise<T>, message: string): Promise<T> => {
let timeoutId: ReturnType<typeof setTimeout> | undefined

Expand Down Expand Up @@ -725,3 +729,21 @@ describe('overrideGlobalObjects', () => {
})
})
})

describe('Response body stream erroring before the first chunk', () => {
it('Should cut the connection rather than return a complete empty 200 with overrideGlobalObjects: false', async () => {
const requestListener = getRequestListener(
() =>
new NativeResponse(
new ReadableStream({
start(controller) {
controller.error(new Error('failed'))
},
}),
),
{ overrideGlobalObjects: false }
)
const server = createServer(requestListener)
await expect(requestServer(server, { method: 'GET', path: '/' })).rejects.toThrow('aborted')
})
})