From 635c91100cd4cdb1d3e05b98e6be750fc2e432d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 11:25:48 +0000 Subject: [PATCH 1/2] fix(functions): keep the raw request body and leave req.body undefined, as deployed functions do Deployed AWS functions (lambda-node-bridge) hand the function a real request stream that still holds the body, and a req.body parsed from the same bytes: undefined with no content type, JSON, a Buffer for octet-stream, querystring for urlencoded, the string for text/plain, and undefined for any other type. Serve used Express's body parsers, which read the stream, so a function reading it (a webhook signature check) got nothing, one waiting for 'end' on a text/plain body hung, and req.body was {} with no body or an unknown type. Serve now reads the body once, up to the 6mb cap, and puts the bytes back into the request stream with unshift before 'end' is emitted, then sets req.body by the bridge's rules. A request with no body is not touched. next() runs on the next tick, so a handler that pipes the request and returns still starts flowing before serve ends the response, as before. Kept from gap 1: a malformed JSON body is a bare 400, and a body over the cap a bare 413; the rest of an oversized body is drained so a keep-alive connection answers its next request. A client that drops the connection mid-body is answered as a request error without the function running. AGENTS.md describes the change, and the .talismanrc checksums of the two touched files are refreshed. --- .talismanrc | 4 +- AGENTS.md | 10 +- src/functions/cloud-functions.test.ts | 149 ++++++++++++++++++++++++++ src/functions/cloud-functions.ts | 91 +++++++++++++++- 4 files changed, 244 insertions(+), 10 deletions(-) diff --git a/.talismanrc b/.talismanrc index 68a2edd..9916a61 100644 --- a/.talismanrc +++ b/.talismanrc @@ -239,7 +239,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: 990c5f77386440b38417ad3277d8cf6afdff910a12d21884e8773b449f8f0ab7 + checksum: c257cb1ecfeafbd880e51525dd34a6f4f2585b1f434b593a46a6679de3d96611 allowed_patterns: - "Do not add an exemption to a guard to make a new file pass" - "passes its own error wording to `client.request\\(req, MESSAGES\\)`" @@ -286,7 +286,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 6709766943430b80aad2d7200102d936a92321e86c41f66d6a60a5baf82a81bf - filename: src/functions/cloud-functions.test.ts - checksum: b4ea493e2e58fae9bdd9a7d890eb6bfb0a66eaa20c3afbd2dea989e82cdb56a5 + checksum: 92369cb15e359d46a99f1ba03236e6ef411313333ae68940d70ef0838d69dfab - filename: src/functions/function.errors.ts checksum: cad477cf24c97bf3395427235ca1de0f305369d05d61c21a83435654df2269e3 - filename: src/transport/proxy.test.ts diff --git a/AGENTS.md b/AGENTS.md index 11af16a..ba73723 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -534,7 +534,11 @@ The approved differences from V1 are these, and only these: - **Requests match AWS deployed functions** (`lambda-node-bridge/cf-sv-with-helpers.ts` in `contentfly-deployment-agent`), as agreed with CL-8791's reporter. JSON and urlencoded bodies are parsed, `text/plain` arrives as the raw string, `application/octet-stream` as a - Buffer, all up to Lambda's 6mb cap. `request.cookies` is the parsed `Cookie` header, or `{}`. + Buffer, all up to Lambda's 6mb cap; a request with no body, or a body of any other type, leaves + `request.body` undefined (CL-8970). Serve reads the body once before the function runs and puts + it back into the request stream, so a function can still read the raw stream (`for await`, + `'data'`/`'end'`, `pipe`, a webhook signature check) as well as `request.body` (CL-8970). + `request.cookies` is the parsed `Cookie` header, or `{}`. `request.query` also holds the path parameters, which win over a query value of the same name (`/items/abc?id=zzz` → `{ id: 'abc' }`), as on AWS (CL-8970); Azure and GCP (V1) keep them only in `request.params`. The query string and an urlencoded body are parsed flat with Node's @@ -545,8 +549,8 @@ The approved differences from V1 are these, and only these: instead of Express's HTML page. Deployed, such a request never reaches the function and nginx answers it with its own 404 page. The project `.env` is loaded before the functions are bundled. Azure and GCP still run the - vendored V1 server, which leaves text and octet-stream bodies unparsed; locally a handler - that reads the raw request stream for those two types gets an empty stream. + vendored V1 server, which leaves text and octet-stream bodies unparsed, gives `request.body` as + `{}` when there is none, and leaves an empty request stream for a JSON or urlencoded body. `res.redirect(url)` answers a bare 307 with the location as given (CL-8970). `res.send` takes one argument, as on AWS and Vercel (CL-8970, chosen by the ticket owner): a number is sent as JSON with the current status (`res.send(42)` → `42`, diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 15fd712..aaec017 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -130,6 +130,7 @@ afterEach(async () => { jest.restoreAllMocks(); delete (globalThis as Record).openStream; delete (globalThis as Record).lateDone; + delete (globalThis as Record).bodyRan; delete (globalThis as Record).lateResult; delete (globalThis as Record).piped; delete (globalThis as Record).hub; @@ -435,6 +436,106 @@ describe('CloudFunctions serve routing', () => { expect(JSON.parse(response.body)).toEqual({ length: data.length }); }); + it.each([ + ['a GET', { method: 'GET' }], + ['an empty JSON POST', { method: 'POST', headers: { 'content-type': 'application/json', 'content-length': '0' } }], + ['an empty chunked JSON POST', { method: 'POST', headers: { 'content-type': 'application/json', 'transfer-encoding': 'chunked' } }], + ])('hands the handler an undefined body for %s with no body, as deployed functions do', async (_label, options) => { + writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ type: typeof request.body }); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/body', options); + + expect(response.status).toBe(200); + expect(JSON.parse(response.body)).toEqual({ type: 'undefined' }); + }); + + it('hands the handler an undefined body for a content type deployed functions do not parse', async () => { + writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ type: typeof request.body }); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/body', { method: 'POST', headers: { 'content-type': 'application/xml' }, body: '' }); + + expect(JSON.parse(response.body)).toEqual({ type: 'undefined' }); + }); + + it.each([ + ['application/json', '{"event":"push"}', { event: 'push' }], + ['text/plain', 'hello', 'hello'], + ])('keeps a %s body in the request stream as well as in request.body, as deployed functions do', async (contentType, body, parsed) => { + writeFunctionFile( + 'raw.js', + [ + 'export default async function raw(request, response) {', + ' const chunks = [];', + ' for await (const chunk of request) { chunks.push(chunk); }', + ' response.json({ raw: Buffer.concat(chunks).toString(), body: request.body });', + '}', + ].join('\n'), + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/raw', { method: 'POST', headers: { 'content-type': contentType }, body }); + + expect(JSON.parse(response.body)).toEqual({ raw: body, body: parsed }); + }); + + it('lets a handler that waits for the end event read a text/plain body instead of hanging', async () => { + writeFunctionFile( + 'events.js', + [ + 'export default async function events(request, response) {', + ' let bytes = 0;', + ' await new Promise((resolve, reject) => {', + ' request.on("data", (chunk) => { bytes += chunk.length; });', + ' request.on("end", resolve);', + ' request.on("error", reject);', + ' });', + ' response.json({ bytes });', + '}', + ].join('\n'), + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/events', { method: 'POST', headers: { 'content-type': 'text/plain' }, body: 'hello' }); + + expect(JSON.parse(response.body)).toEqual({ bytes: 5 }); + }, 4000); + + it('answers the next request on a keep-alive connection when the handler leaves the body unread', async () => { + writeFunctionFile('ignore.js', 'export default function ignore(request, response) { response.send("ignored"); }'); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + const agent = new Agent({ keepAlive: true, maxSockets: 1 }); + const send = (path: string, body?: Buffer): Promise => + new Promise((resolve, reject) => { + const headers = body ? { 'content-type': 'text/plain', 'content-length': String(body.length) } : {}; + httpRequest({ host: '127.0.0.1', port, path, method: body ? 'POST' : 'GET', agent, headers }, (response) => { + let text = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + text += chunk; + }); + response.on('end', () => resolve(text)); + }) + .on('error', reject) + .end(body); + }); + + try { + await new CloudFunctions(workspace).serve(port); + + expect(await send('/ignore', Buffer.alloc(1024 * 1024, 'a'))).toBe('ignored'); + expect(await Promise.race([send('/next'), new Promise((resolve) => setTimeout(() => resolve('no answer'), 1500))])).toBe('alive'); + } finally { + agent.destroy(); + } + }); + it('hands a text/plain body to the handler as the raw string', async () => { writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ body: request.body }); }'); const port = await freePort(); @@ -1625,6 +1726,54 @@ describe('CloudFunctions serve routing', () => { expect(loggedErrors).toEqual(['Request rejected before the function ran: 413 entity.too.large']); }); + it('keeps serving after a client drops its connection in the middle of sending a body', async () => { + writeFunctionFile('body.js', 'export default function body(request, response) { globalThis.bodyRan = true; response.json({ body: request.body }); }'); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const socket = connect(port, '127.0.0.1'); + await new Promise((resolve) => socket.once('connect', () => resolve())); + socket.write('POST /body HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: text/plain\r\nContent-Length: 100\r\n\r\nonly ten b'); + await new Promise((resolve) => setTimeout(resolve, 100)); + socket.destroy(); + await eventually(() => loggedErrors.length > 0); + + expect((await sendRequest(port, '/next')).body).toBe('alive'); + expect((globalThis as Record).bodyRan).toBeUndefined(); + expect(loggedErrors).toEqual(['Request rejected before the function ran: 500 Error']); + }); + + it('answers the next request on a keep-alive connection after refusing a body over the payload limit', async () => { + writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ body: request.body }); }'); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + const agent = new Agent({ keepAlive: true, maxSockets: 1 }); + const send = (path: string, body?: Buffer): Promise => + new Promise((resolve, reject) => { + const headers = body ? { 'content-type': 'text/plain', 'content-length': String(body.length) } : {}; + httpRequest({ host: '127.0.0.1', port, path, method: body ? 'POST' : 'GET', agent, headers }, (response) => { + let text = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + text += chunk; + }); + response.on('end', () => resolve(`${response.statusCode} ${text}`)); + }) + .on('error', reject) + .end(body); + }); + + try { + await new CloudFunctions(workspace).serve(port); + + expect(await send('/body', Buffer.alloc(7 * 1024 * 1024, 'x'))).toBe('413 '); + expect(await Promise.race([send('/next'), new Promise((resolve) => setTimeout(() => resolve('no answer'), 2000))])).toBe('200 alive'); + } finally { + agent.destroy(); + } + }); + it('answers a request error that carries no status with a bare 500', () => { const end = jest.fn(); const status = jest.fn(() => ({ end })); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 54b887e..f36f20e 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -14,6 +14,7 @@ import { isBuiltin } from 'module'; import type { AddressInfo } from 'net'; import { tmpdir } from 'os'; import path from 'path'; +import { parse as parseQueryString } from 'querystring'; import type { Plugin, RollupLog } from 'rollup'; import { fileURLToPath, pathToFileURL } from 'url'; @@ -37,7 +38,7 @@ import type { CloudFunctionResource } from './types'; type CloudFunctionHandler = CloudFunctionResource['handler']; -const DEPLOYED_PAYLOAD_LIMIT = '6mb'; +const DEPLOYED_PAYLOAD_LIMIT_BYTES = 6 * 1024 * 1024; const DEPLOYED_REDIRECT_STATUS = 307; const INVALID_REDIRECT_MESSAGE = "Invalid redirect arguments. Please use a single argument URL, e.g. res.redirect('/destination') " + @@ -404,10 +405,90 @@ function applyRequestMiddleware(app: Express): void { app.use(attachCookies); app.use(redirectLikeDeployedFunctions); app.use(sendLikeDeployedFunctions); - app.use(express.json({ limit: DEPLOYED_PAYLOAD_LIMIT })); - app.use(express.urlencoded({ extended: false, limit: DEPLOYED_PAYLOAD_LIMIT })); - app.use(express.text({ limit: DEPLOYED_PAYLOAD_LIMIT })); - app.use(express.raw({ limit: DEPLOYED_PAYLOAD_LIMIT })); + app.use(readBodyLikeDeployedFunctions); +} + +function requestError(status: number, type: string, message: string): Error & { status: number; type: string } { + return Object.assign(new Error(message), { status, type }); +} + +function hasBody(request: Request): boolean { + return request.headers['transfer-encoding'] !== undefined || Number(request.headers['content-length']) > 0; +} + +function bufferBody(request: Request): Promise { + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + let size = 0; + const settle = (): void => { + request.off('readable', read); + request.off('error', fail); + }; + const fail = (error: Error): void => { + settle(); + reject(error); + }; + const read = (): void => { + let chunk: Buffer | null; + while ((chunk = request.read() as Buffer | null) !== null) { + size += chunk.length; + if (size > DEPLOYED_PAYLOAD_LIMIT_BYTES) { + settle(); + request.resume(); + reject(requestError(413, 'entity.too.large', 'request entity too large')); + return; + } + chunks.push(chunk); + } + if (request.complete) { + settle(); + const body = Buffer.concat(chunks); + if (body.length > 0) { + request.unshift(body); + } + resolve(body); + } + }; + request.on('readable', read); + request.once('error', fail); + }); +} + +function parseBody(request: Request, body: Buffer): unknown { + if (body.length === 0) { + return undefined; + } + if (request.is('json')) { + try { + return JSON.parse(body.toString()); + } catch { + throw requestError(400, 'entity.parse.failed', 'invalid json'); + } + } + if (request.is('application/octet-stream')) { + return body; + } + if (request.is('urlencoded')) { + return parseQueryString(body.toString()); + } + if (request.is('text/plain')) { + return body.toString(); + } + return undefined; +} + +function readBodyLikeDeployedFunctions(request: Request, _response: Response, next: NextFunction): void { + if (!hasBody(request)) { + request.body = undefined; + next(); + return; + } + bufferBody(request) + .then((body) => parseBody(request, body)) + .then((parsed) => { + request.body = parsed; + process.nextTick(next); + }, next); } import { loadDataURL } from './load-data-url'; From 55c8c9290be1f79f020a4e17aa573f01c22e66a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 12:38:28 +0000 Subject: [PATCH 2/2] fix(functions): drain an unread body, keep an empty one open and log a hang-up as 400 Three review findings on the body handling. A client that hangs up mid-body is now rejected as a 400 request.aborted, as body-parser logged it, instead of a 500 server error. An empty chunked body no longer hangs a function that waits for the request's 'end' event. Serve waits one turn for the body to arrive and, when the request is already complete with nothing buffered, hands it to the function without reading it to the end, so 'end' still fires for the function. A body the function leaves unread is drained once its response finishes, as Node's own dump would, so the request still ends and closes. Reading the body marks the request as consumed, which stopped Node from doing it. This also covers the 400 bad-JSON path. AGENTS.md describes the change, and the .talismanrc checksums of the two touched files are refreshed. --- .talismanrc | 4 +- AGENTS.md | 5 +- src/functions/cloud-functions.test.ts | 95 ++++++++++++++++++++++++++- src/functions/cloud-functions.ts | 38 ++++++++--- 4 files changed, 129 insertions(+), 13 deletions(-) diff --git a/.talismanrc b/.talismanrc index 9916a61..c44539a 100644 --- a/.talismanrc +++ b/.talismanrc @@ -239,7 +239,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: c257cb1ecfeafbd880e51525dd34a6f4f2585b1f434b593a46a6679de3d96611 + checksum: 5e00b7347fb405145f6b1059ef533ff5b58ef5b4e4f2af5fab3b5dd9424529c4 allowed_patterns: - "Do not add an exemption to a guard to make a new file pass" - "passes its own error wording to `client.request\\(req, MESSAGES\\)`" @@ -286,7 +286,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 6709766943430b80aad2d7200102d936a92321e86c41f66d6a60a5baf82a81bf - filename: src/functions/cloud-functions.test.ts - checksum: 92369cb15e359d46a99f1ba03236e6ef411313333ae68940d70ef0838d69dfab + checksum: ae6261584e816fb4839b8ae52b3d6b80db2ab26b12b6f0c3cc3f9f555a6cc521 - filename: src/functions/function.errors.ts checksum: cad477cf24c97bf3395427235ca1de0f305369d05d61c21a83435654df2269e3 - filename: src/transport/proxy.test.ts diff --git a/AGENTS.md b/AGENTS.md index ba73723..ed255f9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -537,7 +537,10 @@ The approved differences from V1 are these, and only these: Buffer, all up to Lambda's 6mb cap; a request with no body, or a body of any other type, leaves `request.body` undefined (CL-8970). Serve reads the body once before the function runs and puts it back into the request stream, so a function can still read the raw stream (`for await`, - `'data'`/`'end'`, `pipe`, a webhook signature check) as well as `request.body` (CL-8970). + `'data'`/`'end'`, `pipe`, a webhook signature check) as well as `request.body` (CL-8970). A + body the function leaves unread is drained once its response finishes, as Node does, so the + request still ends and closes; a client that hangs up mid-body is logged as a 400 + `request.aborted`, as body-parser logged it (CL-8970). `request.cookies` is the parsed `Cookie` header, or `{}`. `request.query` also holds the path parameters, which win over a query value of the same name (`/items/abc?id=zzz` → `{ id: 'abc' }`), as on AWS (CL-8970); Azure and GCP (V1) keep them only diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index aaec017..91ede49 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -131,6 +131,8 @@ afterEach(async () => { delete (globalThis as Record).openStream; delete (globalThis as Record).lateDone; delete (globalThis as Record).bodyRan; + delete (globalThis as Record).requestEnded; + delete (globalThis as Record).requestClosed; delete (globalThis as Record).lateResult; delete (globalThis as Record).piped; delete (globalThis as Record).hub; @@ -506,6 +508,97 @@ describe('CloudFunctions serve routing', () => { expect(JSON.parse(response.body)).toEqual({ bytes: 5 }); }, 4000); + it('hands the handler an undefined body for an empty chunked JSON body whose end arrives after its headers', async () => { + writeFunctionFile('body.js', 'export default function body(request, response) { response.json({ type: typeof request.body }); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const socket = connect(port, '127.0.0.1'); + const answer = new Promise((resolve) => { + let raw = ''; + socket.on('data', (chunk) => { + raw += chunk; + }); + socket.on('end', () => resolve(raw)); + }); + await new Promise((resolve) => socket.once('connect', () => resolve())); + socket.write('POST /body HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n'); + await new Promise((resolve) => setTimeout(resolve, 50)); + socket.write('0\r\n\r\n'); + const raw = await answer; + + expect(raw.split('\r\n')[0]).toBe('HTTP/1.1 200 OK'); + expect(raw.split('\r\n\r\n')[1]).toBe('{"type":"undefined"}'); + }); + + it('lets a handler that waits for the end event answer an empty chunked body of a type serve does not parse', async () => { + writeFunctionFile( + 'events.js', + [ + 'export default async function events(request, response) {', + ' let bytes = 0;', + ' await new Promise((resolve, reject) => {', + ' request.on("data", (chunk) => { bytes += chunk.length; });', + ' request.on("end", resolve);', + ' request.on("error", reject);', + ' });', + ' response.json({ bytes, type: typeof request.body });', + '}', + ].join('\n'), + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const response = await sendRequest(port, '/events', { + method: 'POST', + headers: { 'content-type': 'application/xml', 'transfer-encoding': 'chunked' }, + }); + + expect(JSON.parse(response.body)).toEqual({ bytes: 0, type: 'undefined' }); + }, 4000); + + it('ends and closes a request whose large body the handler leaves unread once its response is sent on a keep-alive connection, as Node does', async () => { + writeFunctionFile( + 'unread.js', + [ + 'export default function unread(request, response) {', + ' request.on("end", () => { globalThis.requestEnded = true; });', + ' request.on("close", () => { globalThis.requestClosed = true; });', + ' response.send("ok");', + '}', + ].join('\n'), + ); + const port = await freePort(); + + const agent = new Agent({ keepAlive: true, maxSockets: 1 }); + + try { + await new CloudFunctions(workspace).serve(port); + const body = await new Promise((resolve, reject) => { + httpRequest( + { host: '127.0.0.1', port, path: '/unread', method: 'POST', agent, headers: { 'content-type': 'text/plain', 'content-length': String(1024 * 1024) } }, + (response) => { + let text = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + text += chunk; + }); + response.on('end', () => resolve(text)); + }, + ) + .on('error', reject) + .end(Buffer.alloc(1024 * 1024, 'a')); + }); + await eventually(() => (globalThis as Record).requestClosed === true); + + expect(body).toBe('ok'); + expect((globalThis as Record).requestEnded).toBe(true); + expect((globalThis as Record).requestClosed).toBe(true); + } finally { + agent.destroy(); + } + }); + it('answers the next request on a keep-alive connection when the handler leaves the body unread', async () => { writeFunctionFile('ignore.js', 'export default function ignore(request, response) { response.send("ignored"); }'); writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); @@ -1741,7 +1834,7 @@ describe('CloudFunctions serve routing', () => { expect((await sendRequest(port, '/next')).body).toBe('alive'); expect((globalThis as Record).bodyRan).toBeUndefined(); - expect(loggedErrors).toEqual(['Request rejected before the function ran: 500 Error']); + expect(loggedErrors).toEqual(['Request rejected before the function ran: 400 request.aborted']); }); it('answers the next request on a keep-alive connection after refusing a body over the payload limit', async () => { diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index f36f20e..b566482 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -424,9 +424,9 @@ function bufferBody(request: Request): Promise { request.off('readable', read); request.off('error', fail); }; - const fail = (error: Error): void => { + const fail = (): void => { settle(); - reject(error); + reject(requestError(400, 'request.aborted', 'request aborted')); }; const read = (): void => { let chunk: Buffer | null; @@ -477,18 +477,38 @@ function parseBody(request: Request, body: Buffer): unknown { return undefined; } -function readBodyLikeDeployedFunctions(request: Request, _response: Response, next: NextFunction): void { +/** + * Reading the body marks the request as consumed, so Node no longer dumps it when the response finishes. Drain + * what the function left unread, as Node would, so its 'end' and 'close' events still fire. + */ +function drainUnreadBody(request: Request): void { + if (!request.readableEnded && request.listenerCount('data') === 0 && request.listenerCount('readable') === 0) { + request.resume(); + } +} + +function readBodyLikeDeployedFunctions(request: Request, response: Response, next: NextFunction): void { if (!hasBody(request)) { request.body = undefined; next(); return; } - bufferBody(request) - .then((body) => parseBody(request, body)) - .then((parsed) => { - request.body = parsed; - process.nextTick(next); - }, next); + setImmediate(() => { + if (request.complete && request.readableLength === 0) { + request.body = undefined; + next(); + return; + } + bufferBody(request) + .then((body) => { + response.once('finish', () => drainUnreadBody(request)); + return parseBody(request, body); + }) + .then((parsed) => { + request.body = parsed; + process.nextTick(next); + }, next); + }); } import { loadDataURL } from './load-data-url';