Skip to content

fix: Skip content-length assignment when transfer-encoding is chunked. #271

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 12, 2025
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
63 changes: 33 additions & 30 deletions src/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ const responseViaCache = async (
header = buildOutgoingHttpHeaders(header)
}

// in `responseViaCache`, if body is not stream, Transfer-Encoding is considered not chunked
if (typeof body === 'string') {
header['Content-Length'] = Buffer.byteLength(body)
} else if (body instanceof Uint8Array) {
Expand Down Expand Up @@ -131,43 +132,45 @@ const responseViaResponseObject = async (
let done = false
let currentReadPromise: Promise<ReadableStreamReadResult<Uint8Array>> | undefined = undefined

// In the case of synchronous responses, usually a maximum of two (or three in special cases) readings is done
let maxReadCount = 2
for (let i = 0; i < maxReadCount; i++) {
currentReadPromise ||= reader.read()
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
console.error(e)
done = true
})
if (!chunk) {
if (i === 1 && resHeaderRecord['transfer-encoding'] !== 'chunked') {
// 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)]) )
await new Promise((resolve) => setTimeout(resolve))
maxReadCount = 3
continue
if (resHeaderRecord['transfer-encoding'] !== 'chunked') {
// In the case of synchronous responses, usually a maximum of two (or three in special cases) readings is done
let maxReadCount = 2
for (let i = 0; i < maxReadCount; i++) {
currentReadPromise ||= reader.read()
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
console.error(e)
done = true
})
if (!chunk) {
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)]) )
await new Promise((resolve) => setTimeout(resolve))
maxReadCount = 3
continue
}

// Error occurred or currentReadPromise is not yet resolved.
// If an error occurs, immediately break the loop.
// If currentReadPromise is not yet resolved, pass it to writeFromReadableStreamDefaultReader.
break
}
currentReadPromise = undefined

// Error occurred or currentReadPromise is not yet resolved.
// If an error occurs, immediately break the loop.
// If currentReadPromise is not yet resolved, pass it to writeFromReadableStreamDefaultReader.
break
if (chunk.value) {
values.push(chunk.value)
}
if (chunk.done) {
done = true
break
}
}
currentReadPromise = undefined

if (chunk.value) {
values.push(chunk.value)
}
if (chunk.done) {
done = true
break
if (done && !('content-length' in resHeaderRecord)) {
resHeaderRecord['content-length'] = values.reduce((acc, value) => acc + value.length, 0)
}
}

if (done && !('content-length' in resHeaderRecord)) {
resHeaderRecord['content-length'] = values.reduce((acc, value) => acc + value.length, 0)
}

outgoing.writeHead(res.status, resHeaderRecord)
values.forEach((value) => {
;(outgoing as Writable).write(value)
Expand Down
22 changes: 22 additions & 0 deletions test/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@

it('Should return 200 response - POST /partially-consumed', async () => {
const buffer = Buffer.alloc(1024 * 10) // large buffer
const res = await new Promise<any>((resolve, reject) => {

Check warning on line 70 in test/server.test.ts

View workflow job for this annotation

GitHub Actions / ci (24.x)

Unexpected any. Specify a different type

Check warning on line 70 in test/server.test.ts

View workflow job for this annotation

GitHub Actions / ci (18.x)

Unexpected any. Specify a different type

Check warning on line 70 in test/server.test.ts

View workflow job for this annotation

GitHub Actions / ci (20.x)

Unexpected any. Specify a different type

Check warning on line 70 in test/server.test.ts

View workflow job for this annotation

GitHub Actions / ci (22.x)

Unexpected any. Specify a different type
const req = request(server)
.post('/partially-consumed')
.set('Content-Length', buffer.length.toString())
Expand All @@ -88,7 +88,7 @@

it('Should return 200 response - POST /partially-consumed-and-cancelled', async () => {
const buffer = Buffer.alloc(1) // A large buffer will not make the test go far, so keep it small because it won't go far.
const res = await new Promise<any>((resolve, reject) => {

Check warning on line 91 in test/server.test.ts

View workflow job for this annotation

GitHub Actions / ci (24.x)

Unexpected any. Specify a different type

Check warning on line 91 in test/server.test.ts

View workflow job for this annotation

GitHub Actions / ci (18.x)

Unexpected any. Specify a different type

Check warning on line 91 in test/server.test.ts

View workflow job for this annotation

GitHub Actions / ci (20.x)

Unexpected any. Specify a different type

Check warning on line 91 in test/server.test.ts

View workflow job for this annotation

GitHub Actions / ci (22.x)

Unexpected any. Specify a different type
const req = request(server)
.post('/partially-consumed-and-cancelled')
.set('Content-Length', buffer.length.toString())
Expand Down Expand Up @@ -185,6 +185,20 @@
})
return new Response(stream)
})
app.get('/readable-stream-with-transfer-encoding', () => {
const stream = new ReadableStream({
async start(controller) {
controller.enqueue('Hello!') // send one chunk synchronously
controller.close()
},
})
return new Response(stream, {
headers: {
'content-type': 'text/plain; charset=UTF-8',
'transfer-encoding': 'chunked',
},
})
})
const eventStreamPromise = new Promise<void>((resolve) => {
resolveEventStreamPromise = resolve
})
Expand Down Expand Up @@ -295,6 +309,14 @@
expect(expectedChunks.length).toBe(0) // all chunks are received
})

it('Should return 200 response - GET /readable-stream-with-transfer-encoding', async () => {
const res = await request(server).get('/readable-stream-with-transfer-encoding')
expect(res.status).toBe(200)
expect(res.headers['content-type']).toMatch('text/plain; charset=UTF-8')
expect(res.headers['transfer-encoding']).toBe('chunked')
expect(res.headers['content-length']).toBeUndefined()
})

it('Should return 200 response - GET /event-stream', async () => {
const expectedChunks = ['data: First!\n\n', 'data: Second!\n\n']
const resPromise = request(server)
Expand Down
Loading