From 8965246318c27b1ebcc16d1b1d64e6772f2ae3b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 06:12:15 +0000 Subject: [PATCH 01/21] fix(functions): end a response the handler leaves open, as deployed functions do A handler that returned without ending its response hung under launch:functions:serve (Azure and GCP answer 504 CF005 after the timeout). Deployed AWS functions (lambda-node-bridge's finalizeResponse) end it as soon as the handler returns or its promise settles, with the status and headers it set, and leave a response whose headers were already sent for the handler to end. Do the same. Anything the handler writes after that (end, write, writeHead, setHeader, and so send, json and redirect through them) is ignored with one warn: line, so a late answer cannot crash serve with ERR_HTTP_HEADERS_SENT. --- AGENTS.md | 6 +++ src/functions/cloud-functions.test.ts | 75 +++++++++++++++++++++++++++ src/functions/cloud-functions.ts | 28 ++++++++++ 3 files changed, 109 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index d40e523..7cfd3f5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -547,6 +547,12 @@ The approved differences from V1 are these, and only these: `res.redirect(url)` with a 302 and a body, treat `res.send(404)` as a 404 status and an invalid one such as `res.send(42)` as a 500, and honour the two-argument forms of `res.send` and `res.json`. + A handler that returns (or whose promise settles) without ending its response is ended for it + at once with the status and headers it set, as AWS's `finalizeResponse` does (CL-8970); a + response whose headers were already sent is left for the handler to end. Anything the handler + writes after that is ignored with one `warn:` line instead of crashing serve, so a callback that + answers after the handler returned gets an empty response, exactly as on AWS. Azure and GCP (V1) + answer a handler that never ends its response with 504 CF005 after the timeout. - **A function that reaches a file outside `functions/` is warned about, not refused**, naming the function file that crosses the boundary. - **Errors name the user's file.** A function that fails to bundle or load stops serve with diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 93663cd..2834d70 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -622,6 +622,81 @@ describe('CloudFunctions serve routing', () => { expect(loggedErrors).toEqual([]); }); + it('ends a response the handler leaves open as soon as the handler finishes, keeping its status and headers, as deployed functions do', async () => { + writeFunctionFile( + 'open.js', + 'export default function open(request, response) { response.statusCode = 201; response.setHeader("cache-control", "max-age=5"); }', + ); + writeFunctionFile('bare.js', 'export default function bare() {}'); + writeFunctionFile( + 'awaited.js', + 'export default async function awaited(request, response) { await new Promise((done) => setTimeout(done, 20)); response.statusCode = 202; }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const open = await sendRequest(port, '/open'); + const bare = await sendRequest(port, '/bare'); + const awaited = await sendRequest(port, '/awaited'); + + expect(open).toMatchObject({ status: 201, body: '', cacheControl: 'max-age=5', contentType: undefined }); + expect(bare).toMatchObject({ status: 200, body: '', cacheControl: 'no-store', contentType: undefined }); + expect(awaited).toMatchObject({ status: 202, body: '' }); + expect(loggedErrors).toEqual([]); + }, 4000); + + it.each([ + ['send', 'response.status(500).send("late")'], + ['json', 'response.json({ late: true })'], + ['end', 'response.end("late")'], + ['write', 'response.write("late")'], + ['writeHead', 'response.writeHead(500)'], + ['setHeader', 'response.setHeader("x-late", "yes")'], + ['redirect', 'response.redirect("/elsewhere")'], + ])('ignores a late %s after the handler finished, warns once, and keeps serving, where deployed functions have already answered', async (_method, lateCall) => { + writeFunctionFile( + 'late.js', + `export default function late(request, response) { setTimeout(() => { ${lateCall}; ${lateCall}; globalThis.lateDone = true; }, 50); }`, + ); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send(String(globalThis.lateDone)); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const late = await sendRequest(port, '/late'); + await new Promise((done) => setTimeout(done, 150)); + const next = await sendRequest(port, '/next'); + + expect(late).toMatchObject({ status: 200, body: '' }); + expect(next).toMatchObject({ status: 200, body: 'true' }); + expect(loggedLines.filter((line) => line.startsWith('warn: /late'))).toEqual([ + 'warn: /late answered after its handler returned. Deployed functions have already ended the response by then, so this answer was ignored.', + ]); + expect(loggedErrors).toEqual([]); + delete (globalThis as Record).lateDone; + }, 4000); + + it('leaves a response the handler has started streaming open for the handler to end, as deployed functions do', async () => { + writeFunctionFile( + 'stream.js', + 'export default function stream(request, response) { response.write("part"); globalThis.openStream = response; }', + ); + writeFunctionFile( + 'finish.js', + 'export default function finish(request, response) { globalThis.openStream.end("ial"); response.send("done"); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const stream = sendRequest(port, '/stream'); + await new Promise((done) => setTimeout(done, 300)); + const finish = await sendRequest(port, '/finish'); + + expect(await stream).toMatchObject({ status: 200, body: 'partial' }); + expect(finish).toMatchObject({ status: 200, body: 'done' }); + expect(loggedErrors).toEqual([]); + delete (globalThis as Record).openStream; + }, 4000); + it('answers res.redirect(url) with a bare 307 and the location exactly as given, as deployed functions do', async () => { writeFunctionFile('go.js', 'export default function go(request, response) { response.redirect("/target?from=a b"); }'); const port = await freePort(); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 35a7363..f59d228 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -182,6 +182,33 @@ function sendLikeDeployedFunctions(_request: Request, response: Response, next: next(); } +const LATE_ANSWER_METHODS = ['end', 'write', 'writeHead', 'setHeader'] as const; + +function ignoreLateAnswers(response: Response, route: string): void { + let warned = false; + const ignore = (): Response => { + if (!warned) { + warned = true; + const warning = + `warn: ${route} answered after its handler returned. ` + + 'Deployed functions have already ended the response by then, so this answer was ignored.'; + console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); + } + return response; + }; + LATE_ANSWER_METHODS.forEach((method) => { + (response as unknown as Record)[method] = ignore; + }); +} + +function endLikeDeployedFunctions(response: Response, route: string): void { + if (response.writableEnded || response.headersSent) { + return; + } + response.end(); + ignoreLateAnswers(response, route); +} + export function answerRequestError( error: Error & { status?: number; type?: string }, _request: Request, @@ -307,6 +334,7 @@ export class CloudFunctions { app.all(cloudFunctionResource.apiResourceURI, async (request: Request, response: Response) => { try { await cloudFunctionResource.handler(request, response); + endLikeDeployedFunctions(response, cloudFunctionResource.apiResourceURI); } catch (error) { console.error(error); response.status(500).send(); From 18aada4b5fdcbefe73f9b7d5d3236cbaa7a45ce4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 06:12:44 +0000 Subject: [PATCH 02/21] chore: refresh .talismanrc checksums for cloud-functions.test.ts and AGENTS.md Test code and prose; no credentials. --- .talismanrc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.talismanrc b/.talismanrc index 8e8cadf..0cfe735 100644 --- a/.talismanrc +++ b/.talismanrc @@ -240,7 +240,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: d9ece4c45007c65054469efcd50de93573c756ad9664a6a2d7658db021a5078c + checksum: ab39826370a45880e65ac5b77ec8ed31a34a36c733062b3c523bb8fa1cb2bc90 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\\)`" @@ -287,7 +287,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 038f5cd182e1fd0105e6e10dde7f5068a0c15883222450f72ea3904890a56c0c - filename: src/functions/cloud-functions.test.ts - checksum: ca4e03b4ae6d4e39fe5ad654f781b002deb37f2f30ebf58c27feeb162696c562 + checksum: 730ae7ae514ab97fac1ffe63222ae5157326a4132c80138dd99785a4db451cd3 - filename: src/functions/function.errors.ts checksum: a24194bef73c8db8c28b8ac104955f2f22abdc8c8d0608fa36a39032055bda57 - filename: src/transport/proxy.test.ts From e99ef53e47c0bad71a4be373d8e3642ba68596fe Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 06:21:59 +0000 Subject: [PATCH 03/21] fix(functions): guard every late header call and let a file send finish Review follow-ups for ending an open response like deployed functions: - A late res.sendStatus(204), res.status(205).send() or a direct removeHeader/appendHeader/setHeaders call still reached Node's header methods after the forced end and threw ERR_HTTP_HEADERS_SENT. Ignore those too. - res.sendFile and res.download finish asynchronously, so the forced end cut them to an empty 200 with no warning. A response they are sending is now left for them to end. - The warning names the requested URL instead of the route pattern. - Tests poll instead of sleeping and clean their globals in afterEach. --- AGENTS.md | 10 +++-- src/functions/cloud-functions.test.ts | 59 ++++++++++++++++++++++++--- src/functions/cloud-functions.ts | 35 ++++++++++++---- 3 files changed, 87 insertions(+), 17 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7cfd3f5..f14cc6c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -549,10 +549,12 @@ The approved differences from V1 are these, and only these: and `res.json`. A handler that returns (or whose promise settles) without ending its response is ended for it at once with the status and headers it set, as AWS's `finalizeResponse` does (CL-8970); a - response whose headers were already sent is left for the handler to end. Anything the handler - writes after that is ignored with one `warn:` line instead of crashing serve, so a callback that - answers after the handler returned gets an empty response, exactly as on AWS. Azure and GCP (V1) - answer a handler that never ends its response with 504 CF005 after the timeout. + response whose headers were already sent, or that `res.sendFile`/`res.download` is still + sending, is left for the handler to end. Anything the handler writes after that is ignored with + one `warn:` line naming the requested URL instead of crashing serve, so a callback that answers + after the handler returned gets an empty response, exactly as on AWS. Azure and GCP (V1) still + deliver such a late answer as written, and answer a handler that never ends its response with + 504 CF005 after the timeout. - **A function that reaches a file outside `functions/` is warned about, not refused**, naming the function file that crosses the boundary. - **Errors name the user's file.** A function that fails to bundle or load stops serve with diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 2834d70..b23b84c 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -31,6 +31,12 @@ let loggedLines: string[]; let loggedErrors: unknown[]; let exitCodes: (number | undefined)[]; +async function eventually(isDone: () => boolean): Promise { + for (let attempt = 0; attempt < 200 && !isDone(); attempt += 1) { + await new Promise((done) => setTimeout(done, 10)); + } +} + function writeProjectFile(relativePath: string, source: string): void { const absolutePath = join(workspace, relativePath); mkdirSync(dirname(absolutePath), { recursive: true }); @@ -118,6 +124,8 @@ afterEach(async () => { ); rmSync(workspace, { recursive: true, force: true }); jest.restoreAllMocks(); + delete (globalThis as Record).openStream; + delete (globalThis as Record).lateDone; }); function toDataURL(source: string): string { @@ -653,6 +661,11 @@ describe('CloudFunctions serve routing', () => { ['writeHead', 'response.writeHead(500)'], ['setHeader', 'response.setHeader("x-late", "yes")'], ['redirect', 'response.redirect("/elsewhere")'], + ['sendStatus', 'response.sendStatus(204)'], + ['send with a 205 status', 'response.status(205).send()'], + ['removeHeader', 'response.removeHeader("x-late")'], + ['appendHeader', 'response.appendHeader("x-late", "yes")'], + ['setHeaders', 'response.setHeaders(new Map([["x-late", "yes"]]))'], ])('ignores a late %s after the handler finished, warns once, and keeps serving, where deployed functions have already answered', async (_method, lateCall) => { writeFunctionFile( 'late.js', @@ -662,17 +675,16 @@ describe('CloudFunctions serve routing', () => { const port = await freePort(); await new CloudFunctions(workspace).serve(port); - const late = await sendRequest(port, '/late'); - await new Promise((done) => setTimeout(done, 150)); + const late = await sendRequest(port, '/late?from=table'); + await eventually(() => (globalThis as Record).lateDone === true); const next = await sendRequest(port, '/next'); expect(late).toMatchObject({ status: 200, body: '' }); expect(next).toMatchObject({ status: 200, body: 'true' }); expect(loggedLines.filter((line) => line.startsWith('warn: /late'))).toEqual([ - 'warn: /late answered after its handler returned. Deployed functions have already ended the response by then, so this answer was ignored.', + 'warn: /late?from=table answered after its handler returned. Deployed functions have already ended the response by then, so this answer was ignored.', ]); expect(loggedErrors).toEqual([]); - delete (globalThis as Record).lateDone; }, 4000); it('leaves a response the handler has started streaming open for the handler to end, as deployed functions do', async () => { @@ -688,13 +700,48 @@ describe('CloudFunctions serve routing', () => { await new CloudFunctions(workspace).serve(port); const stream = sendRequest(port, '/stream'); - await new Promise((done) => setTimeout(done, 300)); + await eventually(() => (globalThis as Record).openStream !== undefined); const finish = await sendRequest(port, '/finish'); expect(await stream).toMatchObject({ status: 200, body: 'partial' }); expect(finish).toMatchObject({ status: 200, body: 'done' }); expect(loggedErrors).toEqual([]); - delete (globalThis as Record).openStream; + }, 4000); + + it.each([ + ['sendFile', 'response.sendFile(process.env.LAUNCH_TEST_PAGE)'], + ['download', 'response.download(process.env.LAUNCH_TEST_PAGE)'], + ])('lets a file the handler starts sending with res.%s finish after the handler returns', async (_method, call) => { + writeProjectFile('page.html', '

page

'); + process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); + writeFunctionFile('file.js', `export default function file(request, response) { ${call}; }`); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const file = await sendRequest(port, '/file'); + + expect(file).toMatchObject({ status: 200, body: '

page

' }); + expect(loggedLines.filter((line) => line.startsWith('warn:'))).toEqual([]); + expect(loggedErrors).toEqual([]); + delete process.env.LAUNCH_TEST_PAGE; + }, 4000); + + it('ends a response the handler started writing and then threw on, logs the error, and keeps serving', async () => { + writeFunctionFile( + 'broken.js', + 'export default async function broken(request, response) { response.write("part"); throw new Error("boom"); }', + ); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const broken = await sendRequest(port, '/broken'); + const next = await sendRequest(port, '/next'); + + expect(broken).toMatchObject({ status: 200, body: 'part' }); + expect(next).toMatchObject({ status: 200, body: 'alive' }); + expect(loggedErrors).toHaveLength(1); + expect((loggedErrors[0] as Error).message).toBe('boom'); }, 4000); it('answers res.redirect(url) with a bare 307 and the location exactly as given, as deployed functions do', async () => { diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index f59d228..21f7569 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -182,15 +182,35 @@ function sendLikeDeployedFunctions(_request: Request, response: Response, next: next(); } -const LATE_ANSWER_METHODS = ['end', 'write', 'writeHead', 'setHeader'] as const; +const LATE_ANSWER_METHODS = [ + 'end', + 'write', + 'writeHead', + 'setHeader', + 'removeHeader', + 'appendHeader', + 'setHeaders', +] as const; +const FILE_ANSWER_METHODS = ['sendFile', 'download'] as const; +const sendingFile = new WeakSet(); + +function trackFileAnswers(response: Response): void { + FILE_ANSWER_METHODS.forEach((method) => { + const answer = response[method].bind(response) as (...args: unknown[]) => void; + (response as unknown as Record)[method] = (...args: unknown[]): void => { + sendingFile.add(response); + answer(...args); + }; + }); +} -function ignoreLateAnswers(response: Response, route: string): void { +function ignoreLateAnswers(response: Response, requestedUrl: string): void { let warned = false; const ignore = (): Response => { if (!warned) { warned = true; const warning = - `warn: ${route} answered after its handler returned. ` + + `warn: ${requestedUrl} answered after its handler returned. ` + 'Deployed functions have already ended the response by then, so this answer was ignored.'; console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); } @@ -201,12 +221,12 @@ function ignoreLateAnswers(response: Response, route: string): void { }); } -function endLikeDeployedFunctions(response: Response, route: string): void { - if (response.writableEnded || response.headersSent) { +function endLikeDeployedFunctions(response: Response, requestedUrl: string): void { + if (response.writableEnded || response.headersSent || sendingFile.has(response)) { return; } response.end(); - ignoreLateAnswers(response, route); + ignoreLateAnswers(response, requestedUrl); } export function answerRequestError( @@ -333,8 +353,9 @@ export class CloudFunctions { cloudFunctionResources.forEach((cloudFunctionResource) => { app.all(cloudFunctionResource.apiResourceURI, async (request: Request, response: Response) => { try { + trackFileAnswers(response); await cloudFunctionResource.handler(request, response); - endLikeDeployedFunctions(response, cloudFunctionResource.apiResourceURI); + endLikeDeployedFunctions(response, request.originalUrl); } catch (error) { console.error(error); response.status(500).send(); From b8727978018247ffb164500b3e219905dca34ff9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 06:22:19 +0000 Subject: [PATCH 04/21] chore: refresh .talismanrc checksums for cloud-functions.test.ts and AGENTS.md Test code and prose; no credentials. --- .talismanrc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.talismanrc b/.talismanrc index 0cfe735..a26b992 100644 --- a/.talismanrc +++ b/.talismanrc @@ -240,7 +240,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: ab39826370a45880e65ac5b77ec8ed31a34a36c733062b3c523bb8fa1cb2bc90 + checksum: 1c52c901fd040e147442bb04c2c038637ac8ce43ad079b7143dc28c01c73e7e5 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\\)`" @@ -287,7 +287,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 038f5cd182e1fd0105e6e10dde7f5068a0c15883222450f72ea3904890a56c0c - filename: src/functions/cloud-functions.test.ts - checksum: 730ae7ae514ab97fac1ffe63222ae5157326a4132c80138dd99785a4db451cd3 + checksum: ec39f60280e4586ebd473b02c54f214287bc314922460f010e58ead0ccfcd608 - filename: src/functions/function.errors.ts checksum: a24194bef73c8db8c28b8ac104955f2f22abdc8c8d0608fa36a39032055bda57 - filename: src/transport/proxy.test.ts From a55dfae4d8242970c96ca26458ab9fc6d5647a2e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 06:41:17 +0000 Subject: [PATCH 05/21] fix(functions): settle file sends and guard every ended response Second review follow-ups for ending an open response like deployed functions: - A file send is marked only once res.sendFile/download/sendfile returned without throwing, and a callback-style send clears its mark when it settles; if the response is still open then, it is ended as AWS would. Before, a send that threw, or whose callback only set a status, left the request hanging, and the lowercase res.sendfile was cut short. - Once a response has ended for any reason (forced end, the 500 path, or the handler itself), later end/write/header/file calls are ignored with one warning instead of crashing serve. A callback passed to them gets ERR_STREAM_ALREADY_FINISHED on the next tick, and write returns false. - The warning now says the response was changed, not answered, so it also fits header-only calls. - AGENTS.md: the deployment agent's 2.x upgrade drops late answers on Azure and GCP; tests clean LAUNCH_TEST_PAGE in afterEach. --- AGENTS.md | 13 +++- src/functions/cloud-functions.test.ts | 73 +++++++++++++++++++- src/functions/cloud-functions.ts | 99 +++++++++++++++++++-------- 3 files changed, 151 insertions(+), 34 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f14cc6c..b3ad449 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -550,9 +550,12 @@ The approved differences from V1 are these, and only these: A handler that returns (or whose promise settles) without ending its response is ended for it at once with the status and headers it set, as AWS's `finalizeResponse` does (CL-8970); a response whose headers were already sent, or that `res.sendFile`/`res.download` is still - sending, is left for the handler to end. Anything the handler writes after that is ignored with - one `warn:` line naming the requested URL instead of crashing serve, so a callback that answers - after the handler returned gets an empty response, exactly as on AWS. Azure and GCP (V1) still + sending, is left for the handler to end; a file send that throws, or whose callback leaves the + response open, is ended the same way once it settles. Once a response has ended, for whatever + reason, any later change to it (`end`, `write`, header calls, a file send, and so `send`, `json` + and `redirect`) is ignored with one `warn:` line naming the requested URL instead of crashing + serve; a callback passed to it gets `ERR_STREAM_ALREADY_FINISHED`, as Node does. So a callback + that answers after the handler returned gets an empty response, exactly as on AWS. Azure and GCP (V1) still deliver such a late answer as written, and answer a handler that never ends its response with 504 CF005 after the timeout. - **A function that reaches a file outside `functions/` is warned about, not refused**, naming @@ -1092,6 +1095,10 @@ and the agent would then wait forever for a port that never opens. Never replace 2.x build without changing `SERVER_COMMAND` to `launch:functions:serve` in the same change. The same applies to any customer `package.json` script that runs `launch:functions`: it is a release-note line for 2.0, and the umbrella `@contentstack/cli` must keep pinning `cli-launch@^1` until 2.0 is GA. +Moving Azure and GCP to 2.x also changes how their functions answer: 2.x serve ends a response the +handler leaves open as AWS does (CL-8970), so a handler that answers from a callback after it +returned, which those clouds deliver today, gets an empty response instead. Say so in the agent's +release notes. **`this.dataDir`.** `LaunchCommand` already computed the data directory to find `.cs-launch.json`; it now exposes it, because `projects:create` has to zip that same directory and `--data-dir` is a diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index b23b84c..d6be5d0 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -126,6 +126,8 @@ afterEach(async () => { jest.restoreAllMocks(); delete (globalThis as Record).openStream; delete (globalThis as Record).lateDone; + delete (globalThis as Record).lateResult; + delete process.env.LAUNCH_TEST_PAGE; }); function toDataURL(source: string): string { @@ -666,7 +668,12 @@ describe('CloudFunctions serve routing', () => { ['removeHeader', 'response.removeHeader("x-late")'], ['appendHeader', 'response.appendHeader("x-late", "yes")'], ['setHeaders', 'response.setHeaders(new Map([["x-late", "yes"]]))'], + ['sendFile', 'response.sendFile(process.env.LAUNCH_TEST_PAGE)'], + ['download', 'response.download(process.env.LAUNCH_TEST_PAGE)'], + ['sendfile', 'response.sendfile(process.env.LAUNCH_TEST_PAGE)'], ])('ignores a late %s after the handler finished, warns once, and keeps serving, where deployed functions have already answered', async (_method, lateCall) => { + writeProjectFile('page.html', '

page

'); + process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); writeFunctionFile( 'late.js', `export default function late(request, response) { setTimeout(() => { ${lateCall}; ${lateCall}; globalThis.lateDone = true; }, 50); }`, @@ -682,7 +689,7 @@ describe('CloudFunctions serve routing', () => { expect(late).toMatchObject({ status: 200, body: '' }); expect(next).toMatchObject({ status: 200, body: 'true' }); expect(loggedLines.filter((line) => line.startsWith('warn: /late'))).toEqual([ - 'warn: /late?from=table answered after its handler returned. Deployed functions have already ended the response by then, so this answer was ignored.', + 'warn: /late?from=table changed its response after it had been ended. The change was ignored; deployed functions end the response when the handler returns.', ]); expect(loggedErrors).toEqual([]); }, 4000); @@ -711,6 +718,7 @@ describe('CloudFunctions serve routing', () => { it.each([ ['sendFile', 'response.sendFile(process.env.LAUNCH_TEST_PAGE)'], ['download', 'response.download(process.env.LAUNCH_TEST_PAGE)'], + ['sendfile', 'response.sendfile(process.env.LAUNCH_TEST_PAGE)'], ])('lets a file the handler starts sending with res.%s finish after the handler returns', async (_method, call) => { writeProjectFile('page.html', '

page

'); process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); @@ -723,7 +731,68 @@ describe('CloudFunctions serve routing', () => { expect(file).toMatchObject({ status: 200, body: '

page

' }); expect(loggedLines.filter((line) => line.startsWith('warn:'))).toEqual([]); expect(loggedErrors).toEqual([]); - delete process.env.LAUNCH_TEST_PAGE; + }, 4000); + + it('ends a response like deployed functions when a file send throws or its callback leaves the response open', async () => { + writeProjectFile('page.html', '

page

'); + process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); + writeFunctionFile( + 'relative.js', + 'export default function relative(request, response) { try { response.sendFile("page.html"); } catch { response.status(400); } }', + ); + writeFunctionFile( + 'missing.js', + 'export default function missing(request, response) { response.sendFile(`${process.env.LAUNCH_TEST_PAGE}.missing`, (error) => { if (error) { response.status(404); } }); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const relative = await sendRequest(port, '/relative'); + const missing = await sendRequest(port, '/missing'); + + expect(relative).toMatchObject({ status: 400, body: '' }); + expect(missing).toMatchObject({ status: 404, body: '' }); + expect(loggedErrors).toEqual([]); + }, 4000); + + it('calls the callback of a late end or write with an error, as Node does, and a late write returns false', async () => { + writeFunctionFile( + 'late.js', + 'export default function late(request, response) { setTimeout(() => { const wrote = response.write("x", (error) => { globalThis.lateResult = { ...globalThis.lateResult, wrote, writeError: error.code }; }); response.end("y", (error) => { globalThis.lateResult = { ...globalThis.lateResult, endError: error.code }; globalThis.lateDone = true; }); }, 20); }', + ); + writeFunctionFile('next.js', 'export default function next(request, response) { response.json(globalThis.lateResult); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + await sendRequest(port, '/late'); + await eventually(() => (globalThis as Record).lateDone === true); + const next = await sendRequest(port, '/next'); + + expect(JSON.parse(next.body)).toEqual({ + wrote: false, + writeError: 'ERR_STREAM_ALREADY_FINISHED', + endError: 'ERR_STREAM_ALREADY_FINISHED', + }); + }, 4000); + + it.each([ + ['threw after starting a late answer', 'setTimeout(() => { response.send("again"); globalThis.lateDone = true; }, 20); throw new Error("boom");', 500], + ['ended the response and answered again later', 'response.send("ok"); setTimeout(() => { response.send("again"); globalThis.lateDone = true; }, 20);', 200], + ])('keeps serving and warns once when a handler that %s', async (_case, body, status) => { + writeFunctionFile('twice.js', `export default async function twice(request, response) { ${body} }`); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const twice = await sendRequest(port, '/twice'); + await eventually(() => (globalThis as Record).lateDone === true); + const next = await sendRequest(port, '/next'); + + expect(twice.status).toBe(status); + expect(next).toMatchObject({ status: 200, body: 'alive' }); + expect(loggedLines.filter((line) => line.startsWith('warn: /twice'))).toEqual([ + 'warn: /twice changed its response after it had been ended. The change was ignored; deployed functions end the response when the handler returns.', + ]); }, 4000); it('ends a response the handler started writing and then threw on, logs the error, and keeps serving', async () => { diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 21f7569..a054068 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -182,7 +182,8 @@ function sendLikeDeployedFunctions(_request: Request, response: Response, next: next(); } -const LATE_ANSWER_METHODS = [ +const FILE_ANSWER_METHODS = ['sendFile', 'download', 'sendfile'] as const; +const LATE_CHANGE_METHODS = [ 'end', 'write', 'writeHead', @@ -190,43 +191,82 @@ const LATE_ANSWER_METHODS = [ 'removeHeader', 'appendHeader', 'setHeaders', + ...FILE_ANSWER_METHODS, ] as const; -const FILE_ANSWER_METHODS = ['sendFile', 'download'] as const; -const sendingFile = new WeakSet(); -function trackFileAnswers(response: Response): void { - FILE_ANSWER_METHODS.forEach((method) => { - const answer = response[method].bind(response) as (...args: unknown[]) => void; - (response as unknown as Record)[method] = (...args: unknown[]): void => { - sendingFile.add(response); - answer(...args); - }; - }); +interface Answering { + requestedUrl: string; + handlerReturned: boolean; + filesInFlight: number; + ignoringLateChanges: boolean; } -function ignoreLateAnswers(response: Response, requestedUrl: string): void { +function alreadyFinished(): NodeJS.ErrnoException { + return Object.assign(new Error('The response was already ended.'), { code: 'ERR_STREAM_ALREADY_FINISHED' }); +} + +function ignoreLateChanges(response: Response, answering: Answering): void { + if (answering.ignoringLateChanges) { + return; + } + answering.ignoringLateChanges = true; let warned = false; - const ignore = (): Response => { - if (!warned) { - warned = true; - const warning = - `warn: ${requestedUrl} answered after its handler returned. ` + - 'Deployed functions have already ended the response by then, so this answer was ignored.'; - console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); - } - return response; - }; - LATE_ANSWER_METHODS.forEach((method) => { - (response as unknown as Record)[method] = ignore; + LATE_CHANGE_METHODS.forEach((method) => { + (response as unknown as Record)[method] = (...args: unknown[]): unknown => { + if (!warned) { + warned = true; + const warning = + `warn: ${answering.requestedUrl} changed its response after it had been ended. ` + + 'The change was ignored; deployed functions end the response when the handler returns.'; + console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); + } + const callback = args[args.length - 1]; + if (typeof callback === 'function') { + process.nextTick(callback, alreadyFinished()); + } + return method === 'write' ? false : response; + }; }); } -function endLikeDeployedFunctions(response: Response, requestedUrl: string): void { - if (response.writableEnded || response.headersSent || sendingFile.has(response)) { +function endLikeDeployedFunctions(response: Response, answering: Answering): void { + if (!answering.handlerReturned || answering.filesInFlight > 0) { + return; + } + if (response.writableEnded) { + ignoreLateChanges(response, answering); + return; + } + if (response.headersSent) { return; } response.end(); - ignoreLateAnswers(response, requestedUrl); + ignoreLateChanges(response, answering); +} + +function trackAnswering(response: Response, requestedUrl: string): Answering { + const answering: Answering = { requestedUrl, handlerReturned: false, filesInFlight: 0, ignoringLateChanges: false }; + FILE_ANSWER_METHODS.forEach((method) => { + const sendFile = response[method].bind(response) as (...args: unknown[]) => void; + (response as unknown as Record)[method] = (...args: unknown[]): void => { + const callback = args[args.length - 1]; + if (typeof callback !== 'function') { + sendFile(...args); + answering.filesInFlight += 1; + return; + } + sendFile(...args.slice(0, -1), (error: unknown) => { + answering.filesInFlight -= 1; + try { + callback(error); + } finally { + endLikeDeployedFunctions(response, answering); + } + }); + answering.filesInFlight += 1; + }; + }); + return answering; } export function answerRequestError( @@ -352,14 +392,15 @@ export class CloudFunctions { private applyAppRouter(cloudFunctionResources: CloudFunctionResource[], app: Express): void { cloudFunctionResources.forEach((cloudFunctionResource) => { app.all(cloudFunctionResource.apiResourceURI, async (request: Request, response: Response) => { + const answering = trackAnswering(response, request.originalUrl); try { - trackFileAnswers(response); await cloudFunctionResource.handler(request, response); - endLikeDeployedFunctions(response, request.originalUrl); } catch (error) { console.error(error); response.status(500).send(); } + answering.handlerReturned = true; + endLikeDeployedFunctions(response, answering); }); }); } From 6662391435685e229b3c26ac8367ea7d5bfcdd8d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 06:41:38 +0000 Subject: [PATCH 06/21] chore: refresh .talismanrc checksums for cloud-functions.test.ts and AGENTS.md Test code and prose; no credentials. --- .talismanrc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.talismanrc b/.talismanrc index a26b992..656c1ca 100644 --- a/.talismanrc +++ b/.talismanrc @@ -240,7 +240,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: 1c52c901fd040e147442bb04c2c038637ac8ce43ad079b7143dc28c01c73e7e5 + checksum: 9adebd401e13faf06ef6eb72f780c79a22b458135b28ba5a606652db57c62dbf 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\\)`" @@ -287,7 +287,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 038f5cd182e1fd0105e6e10dde7f5068a0c15883222450f72ea3904890a56c0c - filename: src/functions/cloud-functions.test.ts - checksum: ec39f60280e4586ebd473b02c54f214287bc314922460f010e58ead0ccfcd608 + checksum: 32ade7b1e394bf084a4f54cfdb7c2cc679c626c90a4391887b122640dcd21df7 - filename: src/functions/function.errors.ts checksum: a24194bef73c8db8c28b8ac104955f2f22abdc8c8d0608fa36a39032055bda57 - filename: src/transport/proxy.test.ts From 088dcc24fc2d2bbc022618c692bb1acceda9d341 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:12:47 +0000 Subject: [PATCH 07/21] fix(functions): guard every finished response and close piped sources Final review follow-ups for ending an open response like deployed AWS functions: - Install the late-change guard when the response finishes, whatever ended it, so a late header change after a callback-less file send can no longer crash serve (and the guard's repeat branch is covered). - Destroy a stream piped into a response that serve ends for the handler, so serve no longer keeps its file descriptor open. - A late write's callback gets ERR_STREAM_WRITE_AFTER_END, as Node does; end keeps ERR_STREAM_ALREADY_FINISHED. - The warning says deployed AWS functions, since Azure and GCP (V1) still deliver late answers. --- AGENTS.md | 6 ++-- src/functions/cloud-functions.test.ts | 47 +++++++++++++++++++++++++-- src/functions/cloud-functions.ts | 28 +++++++++++++--- 3 files changed, 71 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b3ad449..fe2710c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -554,8 +554,10 @@ The approved differences from V1 are these, and only these: response open, is ended the same way once it settles. Once a response has ended, for whatever reason, any later change to it (`end`, `write`, header calls, a file send, and so `send`, `json` and `redirect`) is ignored with one `warn:` line naming the requested URL instead of crashing - serve; a callback passed to it gets `ERR_STREAM_ALREADY_FINISHED`, as Node does. So a callback - that answers after the handler returned gets an empty response, exactly as on AWS. Azure and GCP (V1) still + serve; a callback passed to it gets `ERR_STREAM_WRITE_AFTER_END` (`write`) or + `ERR_STREAM_ALREADY_FINISHED`, as Node does. A stream piped into a response serve ends this way + is destroyed, so serve does not keep it open. So a callback that answers after the handler + returned gets an empty response, exactly as on AWS. Azure and GCP (V1) still deliver such a late answer as written, and answer a handler that never ends its response with 504 CF005 after the timeout. - **A function that reaches a file outside `functions/` is warned about, not refused**, naming diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index d6be5d0..5fea105 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -127,6 +127,7 @@ afterEach(async () => { delete (globalThis as Record).openStream; delete (globalThis as Record).lateDone; delete (globalThis as Record).lateResult; + delete (globalThis as Record).piped; delete process.env.LAUNCH_TEST_PAGE; }); @@ -689,7 +690,7 @@ describe('CloudFunctions serve routing', () => { expect(late).toMatchObject({ status: 200, body: '' }); expect(next).toMatchObject({ status: 200, body: 'true' }); expect(loggedLines.filter((line) => line.startsWith('warn: /late'))).toEqual([ - 'warn: /late?from=table changed its response after it had been ended. The change was ignored; deployed functions end the response when the handler returns.', + 'warn: /late?from=table changed its response after it had been ended. The change was ignored; deployed AWS functions end the response when the handler returns.', ]); expect(loggedErrors).toEqual([]); }, 4000); @@ -733,6 +734,46 @@ describe('CloudFunctions serve routing', () => { expect(loggedErrors).toEqual([]); }, 4000); + it('ignores a late change after a file send without a callback has finished, warns once, and keeps serving', async () => { + writeProjectFile('page.html', '

page

'); + process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); + writeFunctionFile( + 'file.js', + 'export default function file(request, response) { response.sendFile(process.env.LAUNCH_TEST_PAGE); setTimeout(() => { response.setHeader("x-late", "yes"); globalThis.lateDone = true; }, 100); }', + ); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const file = await sendRequest(port, '/file'); + await eventually(() => (globalThis as Record).lateDone === true); + const next = await sendRequest(port, '/next'); + + expect(file).toMatchObject({ status: 200, body: '

page

' }); + expect(next).toMatchObject({ status: 200, body: 'alive' }); + expect(loggedLines.filter((line) => line.startsWith('warn: /file'))).toEqual([ + 'warn: /file changed its response after it had been ended. The change was ignored; deployed AWS functions end the response when the handler returns.', + ]); + }, 4000); + + it('closes a stream piped into a response it ends for the handler, so serve does not keep it open', async () => { + writeProjectFile('page.html', '

page

'); + process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); + writeFunctionFile( + 'piped.js', + 'import { createReadStream } from "node:fs"; export default function piped(request, response) { globalThis.piped = createReadStream(process.env.LAUNCH_TEST_PAGE); globalThis.piped.pipe(response); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const piped = await sendRequest(port, '/piped'); + const source = (globalThis as Record).piped as { destroyed: boolean }; + await eventually(() => source.destroyed); + + expect(piped).toMatchObject({ status: 200, body: '' }); + expect(source.destroyed).toBe(true); + }, 4000); + it('ends a response like deployed functions when a file send throws or its callback leaves the response open', async () => { writeProjectFile('page.html', '

page

'); process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); @@ -770,7 +811,7 @@ describe('CloudFunctions serve routing', () => { expect(JSON.parse(next.body)).toEqual({ wrote: false, - writeError: 'ERR_STREAM_ALREADY_FINISHED', + writeError: 'ERR_STREAM_WRITE_AFTER_END', endError: 'ERR_STREAM_ALREADY_FINISHED', }); }, 4000); @@ -791,7 +832,7 @@ describe('CloudFunctions serve routing', () => { expect(twice.status).toBe(status); expect(next).toMatchObject({ status: 200, body: 'alive' }); expect(loggedLines.filter((line) => line.startsWith('warn: /twice'))).toEqual([ - 'warn: /twice changed its response after it had been ended. The change was ignored; deployed functions end the response when the handler returns.', + 'warn: /twice changed its response after it had been ended. The change was ignored; deployed AWS functions end the response when the handler returns.', ]); }, 4000); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index a054068..0f83e1b 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -1,3 +1,4 @@ +import type { Readable } from 'node:stream'; import { parse as parseCookieHeader } from 'cookie'; import dotenv from 'dotenv'; import type { @@ -199,10 +200,12 @@ interface Answering { handlerReturned: boolean; filesInFlight: number; ignoringLateChanges: boolean; + pipedSources: Set; } -function alreadyFinished(): NodeJS.ErrnoException { - return Object.assign(new Error('The response was already ended.'), { code: 'ERR_STREAM_ALREADY_FINISHED' }); +function alreadyFinished(method: string): NodeJS.ErrnoException { + const code = method === 'write' ? 'ERR_STREAM_WRITE_AFTER_END' : 'ERR_STREAM_ALREADY_FINISHED'; + return Object.assign(new Error('The response was already ended.'), { code }); } function ignoreLateChanges(response: Response, answering: Answering): void { @@ -217,12 +220,12 @@ function ignoreLateChanges(response: Response, answering: Answering): void { warned = true; const warning = `warn: ${answering.requestedUrl} changed its response after it had been ended. ` + - 'The change was ignored; deployed functions end the response when the handler returns.'; + 'The change was ignored; deployed AWS functions end the response when the handler returns.'; console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); } const callback = args[args.length - 1]; if (typeof callback === 'function') { - process.nextTick(callback, alreadyFinished()); + process.nextTick(callback, alreadyFinished(method)); } return method === 'write' ? false : response; }; @@ -241,11 +244,26 @@ function endLikeDeployedFunctions(response: Response, answering: Answering): voi return; } response.end(); + answering.pipedSources.forEach((source) => { + source.destroy(); + }); ignoreLateChanges(response, answering); } function trackAnswering(response: Response, requestedUrl: string): Answering { - const answering: Answering = { requestedUrl, handlerReturned: false, filesInFlight: 0, ignoringLateChanges: false }; + const answering: Answering = { + requestedUrl, + handlerReturned: false, + filesInFlight: 0, + ignoringLateChanges: false, + pipedSources: new Set(), + }; + response.on('pipe', (source: Readable) => { + answering.pipedSources.add(source); + }); + response.once('finish', () => { + ignoreLateChanges(response, answering); + }); FILE_ANSWER_METHODS.forEach((method) => { const sendFile = response[method].bind(response) as (...args: unknown[]) => void; (response as unknown as Record)[method] = (...args: unknown[]): void => { From 5b11fbe0e43c379225a5c3bfd8931fb2fa72246a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:13:21 +0000 Subject: [PATCH 08/21] chore: refresh .talismanrc checksums for cloud-functions.test.ts and AGENTS.md Test code and prose; no credentials. --- .talismanrc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.talismanrc b/.talismanrc index 656c1ca..7c08ecf 100644 --- a/.talismanrc +++ b/.talismanrc @@ -240,7 +240,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: 9adebd401e13faf06ef6eb72f780c79a22b458135b28ba5a606652db57c62dbf + checksum: f34b000d5c634c9d6fae712e79808700c9a85730610720ecb9390ed7ad2300a0 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\\)`" @@ -287,7 +287,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 038f5cd182e1fd0105e6e10dde7f5068a0c15883222450f72ea3904890a56c0c - filename: src/functions/cloud-functions.test.ts - checksum: 32ade7b1e394bf084a4f54cfdb7c2cc679c626c90a4391887b122640dcd21df7 + checksum: eb3b936375906292df092ec1b6f55371f5ec0fdda1a066bc9263789d52c94d4d - filename: src/functions/function.errors.ts checksum: a24194bef73c8db8c28b8ac104955f2f22abdc8c8d0608fa36a39032055bda57 - filename: src/transport/proxy.test.ts From fa7735d8c5a625ad8ee3cd6bfc5b6284d389f916 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:11:28 +0000 Subject: [PATCH 09/21] fix(functions): guard late changes from the start and survive an invalid status Review follow-ups on #314: - Wrap the late-change methods when the request starts, passing calls through until the response has ended, so a write or end between end() and 'finish' (for example res.end('a'); res.write('b')) is ignored with the warning instead of crashing serve. - If ending the response for the handler throws (an invalid status or status message), log the error and answer 500 instead of an unhandled rejection that stopped serve. - Serve's own 500 for a handler that throws is sent only if the response has not ended, so it no longer triggers a false late-change warning. - A stream piped into a response that serve ended, or that had already ended, is unpiped, and only a file stream is destroyed; a stream the function owns, such as a shared PassThrough, is left open. - Only methods that exist are wrapped (Express 5 has no res.sendfile). - The late-change test after a file send waits for 'finish' instead of a fixed timer. --- AGENTS.md | 10 +- src/functions/cloud-functions.test.ts | 104 ++++++++++++++++++++- src/functions/cloud-functions.ts | 129 ++++++++++++++++---------- 3 files changed, 191 insertions(+), 52 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fe2710c..0d73e14 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -555,9 +555,13 @@ The approved differences from V1 are these, and only these: reason, any later change to it (`end`, `write`, header calls, a file send, and so `send`, `json` and `redirect`) is ignored with one `warn:` line naming the requested URL instead of crashing serve; a callback passed to it gets `ERR_STREAM_WRITE_AFTER_END` (`write`) or - `ERR_STREAM_ALREADY_FINISHED`, as Node does. A stream piped into a response serve ends this way - is destroyed, so serve does not keep it open. So a callback that answers after the handler - returned gets an empty response, exactly as on AWS. Azure and GCP (V1) still + `ERR_STREAM_ALREADY_FINISHED`, as Node does. A stream piped into a response serve ends this way, + or into one that has already ended, is unpiped, and a file stream among them is destroyed, so + serve does not keep its file descriptor open; a stream the function owns otherwise is left + alone. An invalid status on a response serve ends for the handler is logged and answered 500. + So a callback that answers after the handler returned gets an empty response, exactly as on AWS. + Because serve wraps `res.sendFile`/`download`/`sendfile` to track them, Express's deprecation + warning for the lowercase `res.sendfile` names serve's file, not the function's. Azure and GCP (V1) still deliver such a late answer as written, and answer a handler that never ends its response with 504 CF005 after the timeout. - **A function that reaches a file outside `functions/` is warned about, not refused**, naming diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 5fea105..0446440 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -8,6 +8,8 @@ import os, { tmpdir } from 'os'; import { dirname, join, win32 } from 'path'; import { pathToFileURL } from 'url'; +import express from 'express'; + import { answerRequestError, CloudFunctions, functionFilesImporting, isOutsideDirectory, listenFailure } from './cloud-functions'; import { PortInUseError } from './function.errors'; import * as loader from './load-data-url'; @@ -128,6 +130,7 @@ afterEach(async () => { delete (globalThis as Record).lateDone; delete (globalThis as Record).lateResult; delete (globalThis as Record).piped; + delete (globalThis as Record).hub; delete process.env.LAUNCH_TEST_PAGE; }); @@ -739,7 +742,7 @@ describe('CloudFunctions serve routing', () => { process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); writeFunctionFile( 'file.js', - 'export default function file(request, response) { response.sendFile(process.env.LAUNCH_TEST_PAGE); setTimeout(() => { response.setHeader("x-late", "yes"); globalThis.lateDone = true; }, 100); }', + 'export default function file(request, response) { response.sendFile(process.env.LAUNCH_TEST_PAGE); response.on("finish", () => setImmediate(() => { response.setHeader("x-late", "yes"); globalThis.lateDone = true; })); }', ); writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); const port = await freePort(); @@ -774,6 +777,105 @@ describe('CloudFunctions serve routing', () => { expect(source.destroyed).toBe(true); }, 4000); + it('ignores a change made in the same tick right after the handler ended the response, warns once, and keeps serving', async () => { + writeFunctionFile( + 'sameTick.js', + 'export default function sameTick(request, response) { response.end("a"); response.write("b"); response.end("c"); }', + ); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const sameTick = await sendRequest(port, '/sameTick'); + const next = await sendRequest(port, '/next'); + + expect(sameTick).toMatchObject({ status: 200, body: 'a' }); + expect(next).toMatchObject({ status: 200, body: 'alive' }); + expect(loggedLines.filter((line) => line.startsWith('warn: /sameTick'))).toEqual([ + 'warn: /sameTick changed its response after it had been ended. The change was ignored; deployed AWS functions end the response when the handler returns.', + ]); + expect(loggedErrors).toEqual([]); + }, 4000); + + it('answers 500 and keeps serving when the response it ends for the handler has an invalid status', async () => { + writeFunctionFile('invalid.js', 'export default function invalid(request, response) { response.status(Number("abc")); }'); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const invalid = await sendRequest(port, '/invalid'); + const next = await sendRequest(port, '/next'); + + expect(invalid).toMatchObject({ status: 500, body: '' }); + expect(next).toMatchObject({ status: 200, body: 'alive' }); + expect(loggedErrors).toHaveLength(1); + expect((loggedErrors[0] as NodeJS.ErrnoException).code).toBe('ERR_HTTP_INVALID_STATUS_CODE'); + }, 4000); + + it('logs an error thrown after the handler already answered without a 500 or a late-change warning', async () => { + writeFunctionFile( + 'answered.js', + 'export default async function answered(request, response) { response.send("ok"); await new Promise((done) => setTimeout(done, 10)); throw new Error("boom"); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const answered = await sendRequest(port, '/answered'); + await eventually(() => loggedErrors.length > 0); + + expect(answered).toMatchObject({ status: 200, body: 'ok' }); + expect(loggedLines.filter((line) => line.startsWith('warn:'))).toEqual([]); + expect(loggedErrors).toHaveLength(1); + expect((loggedErrors[0] as Error).message).toBe('boom'); + }, 4000); + + it('releases a file stream piped into a response after it was ended, and leaves a stream the function owns open', async () => { + writeProjectFile('page.html', '

page

'); + process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); + writeFunctionFile( + 'latePipe.js', + 'import { createReadStream } from "node:fs"; export default function latePipe(request, response) { setTimeout(() => { globalThis.piped = createReadStream(process.env.LAUNCH_TEST_PAGE); globalThis.piped.pipe(response); globalThis.lateDone = true; }, 20); }', + ); + writeFunctionFile( + 'hub.js', + 'import { PassThrough } from "node:stream"; globalThis.hub = globalThis.hub ?? new PassThrough(); export default function hub(request, response) { globalThis.hub.pipe(response); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const latePipe = await sendRequest(port, '/latePipe'); + await eventually(() => (globalThis as Record).lateDone === true); + const source = (globalThis as Record).piped as { destroyed: boolean }; + await eventually(() => source.destroyed); + const hub = await sendRequest(port, '/hub'); + const hubStream = (globalThis as Record).hub as { destroyed: boolean }; + + expect(latePipe).toMatchObject({ status: 200, body: '' }); + expect(source.destroyed).toBe(true); + expect(hub).toMatchObject({ status: 200, body: '' }); + expect(hubStream.destroyed).toBe(false); + }, 4000); + + it('serves and ends responses on an Express without res.sendfile, as Express 5 ships', async () => { + const expressResponse = express.response as unknown as Record; + const sendfile = expressResponse.sendfile; + delete expressResponse.sendfile; + writeFunctionFile( + 'modern.js', + 'export default function modern(request, response) { response.statusCode = 202; }', + ); + const port = await freePort(); + + try { + await new CloudFunctions(workspace).serve(port); + const modern = await sendRequest(port, '/modern'); + + expect(modern).toMatchObject({ status: 202, body: '' }); + } finally { + expressResponse.sendfile = sendfile; + } + }, 4000); + it('ends a response like deployed functions when a file send throws or its callback leaves the response open', async () => { writeProjectFile('page.html', '

page

'); process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 0f83e1b..df40f48 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -8,7 +8,7 @@ import type { } from 'express'; import express from 'express'; import type { Express } from 'express-serve-static-core'; -import { existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs'; +import { ReadStream, existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs'; import type { Server } from 'http'; import { isBuiltin } from 'module'; import type { AddressInfo } from 'net'; @@ -199,30 +199,47 @@ interface Answering { requestedUrl: string; handlerReturned: boolean; filesInFlight: number; - ignoringLateChanges: boolean; + warned: boolean; pipedSources: Set; } +type ResponseMethods = Record; + function alreadyFinished(method: string): NodeJS.ErrnoException { const code = method === 'write' ? 'ERR_STREAM_WRITE_AFTER_END' : 'ERR_STREAM_ALREADY_FINISHED'; return Object.assign(new Error('The response was already ended.'), { code }); } -function ignoreLateChanges(response: Response, answering: Answering): void { - if (answering.ignoringLateChanges) { +function warnLateChange(answering: Answering): void { + if (answering.warned) { return; } - answering.ignoringLateChanges = true; - let warned = false; + answering.warned = true; + const warning = + `warn: ${answering.requestedUrl} changed its response after it had been ended. ` + + 'The change was ignored; deployed AWS functions end the response when the handler returns.'; + console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); +} + +function release(source: Readable, response: Response): void { + source.unpipe(response); + if (source instanceof ReadStream) { + source.destroy(); + } +} + +function guardLateChanges(response: Response, answering: Answering): void { + const methods = response as unknown as ResponseMethods; LATE_CHANGE_METHODS.forEach((method) => { - (response as unknown as Record)[method] = (...args: unknown[]): unknown => { - if (!warned) { - warned = true; - const warning = - `warn: ${answering.requestedUrl} changed its response after it had been ended. ` + - 'The change was ignored; deployed AWS functions end the response when the handler returns.'; - console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); + if (typeof methods[method] !== 'function') { + return; + } + const change = (methods[method] as (...args: unknown[]) => unknown).bind(response); + methods[method] = (...args: unknown[]): unknown => { + if (!response.writableEnded) { + return change(...args); } + warnLateChange(answering); const callback = args[args.length - 1]; if (typeof callback === 'function') { process.nextTick(callback, alreadyFinished(method)); @@ -232,41 +249,14 @@ function ignoreLateChanges(response: Response, answering: Answering): void { }); } -function endLikeDeployedFunctions(response: Response, answering: Answering): void { - if (!answering.handlerReturned || answering.filesInFlight > 0) { - return; - } - if (response.writableEnded) { - ignoreLateChanges(response, answering); - return; - } - if (response.headersSent) { - return; - } - response.end(); - answering.pipedSources.forEach((source) => { - source.destroy(); - }); - ignoreLateChanges(response, answering); -} - -function trackAnswering(response: Response, requestedUrl: string): Answering { - const answering: Answering = { - requestedUrl, - handlerReturned: false, - filesInFlight: 0, - ignoringLateChanges: false, - pipedSources: new Set(), - }; - response.on('pipe', (source: Readable) => { - answering.pipedSources.add(source); - }); - response.once('finish', () => { - ignoreLateChanges(response, answering); - }); +function trackFileAnswers(response: Response, answering: Answering): void { + const methods = response as unknown as ResponseMethods; FILE_ANSWER_METHODS.forEach((method) => { - const sendFile = response[method].bind(response) as (...args: unknown[]) => void; - (response as unknown as Record)[method] = (...args: unknown[]): void => { + if (typeof methods[method] !== 'function') { + return; + } + const sendFile = (methods[method] as (...args: unknown[]) => void).bind(response); + methods[method] = (...args: unknown[]): void => { const callback = args[args.length - 1]; if (typeof callback !== 'function') { sendFile(...args); @@ -284,6 +274,47 @@ function trackAnswering(response: Response, requestedUrl: string): Answering { answering.filesInFlight += 1; }; }); +} + +function endLikeDeployedFunctions(response: Response, answering: Answering): void { + if ( + !answering.handlerReturned || + answering.filesInFlight > 0 || + response.writableEnded || + response.headersSent + ) { + return; + } + try { + response.end(); + } catch (error) { + console.error(error); + response.statusCode = 500; + response.statusMessage = ''; + response.end(); + } + answering.pipedSources.forEach((source) => { + release(source, response); + }); +} + +function trackAnswering(response: Response, requestedUrl: string): Answering { + const answering: Answering = { + requestedUrl, + handlerReturned: false, + filesInFlight: 0, + warned: false, + pipedSources: new Set(), + }; + response.on('pipe', (source: Readable) => { + if (response.writableEnded) { + release(source, response); + return; + } + answering.pipedSources.add(source); + }); + trackFileAnswers(response, answering); + guardLateChanges(response, answering); return answering; } @@ -415,7 +446,9 @@ export class CloudFunctions { await cloudFunctionResource.handler(request, response); } catch (error) { console.error(error); - response.status(500).send(); + if (!response.writableEnded) { + response.status(500).send(); + } } answering.handlerReturned = true; endLikeDeployedFunctions(response, answering); From 9b95f1fb74be79a3bc475c83c38297fdc4410724 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:11:55 +0000 Subject: [PATCH 10/21] chore: refresh .talismanrc checksums for cloud-functions.test.ts and AGENTS.md Test code and prose; no credentials. --- .talismanrc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.talismanrc b/.talismanrc index 7c08ecf..25e2bbd 100644 --- a/.talismanrc +++ b/.talismanrc @@ -240,7 +240,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: f34b000d5c634c9d6fae712e79808700c9a85730610720ecb9390ed7ad2300a0 + checksum: d4429d6badbb37d3f972b9a5ad8c59344f23331df62bba758915c231cf10fc1b 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\\)`" @@ -287,7 +287,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 038f5cd182e1fd0105e6e10dde7f5068a0c15883222450f72ea3904890a56c0c - filename: src/functions/cloud-functions.test.ts - checksum: eb3b936375906292df092ec1b6f55371f5ec0fdda1a066bc9263789d52c94d4d + checksum: 60011f04b1107b56faed924c0c92e458dfeac185d20a994469b9217ec5dc503f - filename: src/functions/function.errors.ts checksum: a24194bef73c8db8c28b8ac104955f2f22abdc8c8d0608fa36a39032055bda57 - filename: src/transport/proxy.test.ts From d51666537ab8c1774c33a7675f5ca5736963ae69 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:22:52 +0000 Subject: [PATCH 11/21] fix(functions): release piped streams on close and never crash answering 500 Review follow-ups on #314: - An end() with no body on an ended response passes through to Node's own no-op, so res.json(data).end() no longer logs a late-change warning. - Streams piped into a response are released when it closes, whoever ended it, and a stream piped into an already-ended one is released at once. Each is unpiped and destroyed unless it still feeds another destination: an upstream response, web stream or child stdout no longer leaks, a file stream also piped to a cache file is not cut short, and a stream piped late is not left flowing with no reader. - Serve's 500 (a handler that throws, or a failed auto-end) resets the status message and drops the connection if even that end throws, so an invalid status message or a content-length mismatch no longer crashes serve. - .talismanrc: refreshed the checksum for cloud-functions.test.ts (inline test functions, no credentials). --- .talismanrc | 2 +- AGENTS.md | 17 ++-- src/functions/cloud-functions.test.ts | 113 +++++++++++++++++++++++++- src/functions/cloud-functions.ts | 46 ++++++++--- 4 files changed, 154 insertions(+), 24 deletions(-) diff --git a/.talismanrc b/.talismanrc index 25e2bbd..aab2012 100644 --- a/.talismanrc +++ b/.talismanrc @@ -287,7 +287,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 038f5cd182e1fd0105e6e10dde7f5068a0c15883222450f72ea3904890a56c0c - filename: src/functions/cloud-functions.test.ts - checksum: 60011f04b1107b56faed924c0c92e458dfeac185d20a994469b9217ec5dc503f + checksum: b24b70a25789e42eeb7503f50257ef23d5c873bae8463adf1a79a896cb483e69 - filename: src/functions/function.errors.ts checksum: a24194bef73c8db8c28b8ac104955f2f22abdc8c8d0608fa36a39032055bda57 - filename: src/transport/proxy.test.ts diff --git a/AGENTS.md b/AGENTS.md index 0d73e14..d1dd226 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -552,13 +552,16 @@ The approved differences from V1 are these, and only these: response whose headers were already sent, or that `res.sendFile`/`res.download` is still sending, is left for the handler to end; a file send that throws, or whose callback leaves the response open, is ended the same way once it settles. Once a response has ended, for whatever - reason, any later change to it (`end`, `write`, header calls, a file send, and so `send`, `json` - and `redirect`) is ignored with one `warn:` line naming the requested URL instead of crashing - serve; a callback passed to it gets `ERR_STREAM_WRITE_AFTER_END` (`write`) or - `ERR_STREAM_ALREADY_FINISHED`, as Node does. A stream piped into a response serve ends this way, - or into one that has already ended, is unpiped, and a file stream among them is destroyed, so - serve does not keep its file descriptor open; a stream the function owns otherwise is left - alone. An invalid status on a response serve ends for the handler is logged and answered 500. + reason, any later change to it (`end` with a body, `write`, header calls, a file send, and so + `send`, `json` and `redirect`) is ignored with one `warn:` line naming the requested URL instead + of crashing serve; a callback passed to it gets `ERR_STREAM_WRITE_AFTER_END` (`write`) or + `ERR_STREAM_ALREADY_FINISHED`, as Node does. An `end()` with no body is Node's own no-op and is + not warned about (`res.json(data).end()`). Once a response closes, or when a stream is piped + into one that has already ended, every stream piped into it is unpiped, and destroyed unless it + still feeds another destination, so serve keeps no file descriptor, upstream socket or child + process open; a shared stream piped elsewhere too keeps flowing there. If ending the response + for the handler fails (an invalid status, a content-length mismatch), or a handler throws, serve + logs the error and answers a plain 500, dropping the connection if even that cannot be sent. So a callback that answers after the handler returned gets an empty response, exactly as on AWS. Because serve wraps `res.sendFile`/`download`/`sendfile` to track them, Express's deprecation warning for the lowercase `res.sendfile` names serve's file, not the function's. Azure and GCP (V1) still diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 0446440..08db0d9 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -131,6 +131,7 @@ afterEach(async () => { delete (globalThis as Record).lateResult; delete (globalThis as Record).piped; delete (globalThis as Record).hub; + delete (globalThis as Record).received; delete process.env.LAUNCH_TEST_PAGE; }); @@ -829,7 +830,7 @@ describe('CloudFunctions serve routing', () => { expect((loggedErrors[0] as Error).message).toBe('boom'); }, 4000); - it('releases a file stream piped into a response after it was ended, and leaves a stream the function owns open', async () => { + it('releases a file stream piped into a response after it was ended, and leaves a stream that still feeds another destination flowing', async () => { writeProjectFile('page.html', '

page

'); process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); writeFunctionFile( @@ -838,7 +839,7 @@ describe('CloudFunctions serve routing', () => { ); writeFunctionFile( 'hub.js', - 'import { PassThrough } from "node:stream"; globalThis.hub = globalThis.hub ?? new PassThrough(); export default function hub(request, response) { globalThis.hub.pipe(response); }', + 'import { PassThrough, Writable } from "node:stream"; globalThis.received = globalThis.received ?? []; globalThis.hub = globalThis.hub ?? new PassThrough(); if (globalThis.hub.listenerCount("data") === 0) { globalThis.hub.pipe(new Writable({ write(chunk, encoding, done) { globalThis.received.push(String(chunk)); done(); } })); } export default function hub(request, response) { setTimeout(() => globalThis.hub.pipe(response), 20); }', ); const port = await freePort(); @@ -848,7 +849,10 @@ describe('CloudFunctions serve routing', () => { const source = (globalThis as Record).piped as { destroyed: boolean }; await eventually(() => source.destroyed); const hub = await sendRequest(port, '/hub'); - const hubStream = (globalThis as Record).hub as { destroyed: boolean }; + await new Promise((done) => setTimeout(done, 50)); + const hubStream = (globalThis as Record).hub as { destroyed: boolean; write: (chunk: string) => void }; + hubStream.write('after'); + await eventually(() => ((globalThis as Record).received as string[]).includes('after')); expect(latePipe).toMatchObject({ status: 200, body: '' }); expect(source.destroyed).toBe(true); @@ -856,6 +860,109 @@ describe('CloudFunctions serve routing', () => { expect(hubStream.destroyed).toBe(false); }, 4000); + it('destroys a stream piped into a response it ends when nothing else reads it, and spares one that still feeds another destination', async () => { + writeFunctionFile( + 'proxy.js', + 'import { PassThrough } from "node:stream"; export default function proxy(request, response) { globalThis.piped = new PassThrough(); globalThis.piped.pipe(response); }', + ); + writeFunctionFile('shared.js', 'import { PassThrough, Writable } from "node:stream"; globalThis.received = globalThis.received ?? []; globalThis.hub = globalThis.hub ?? new PassThrough(); if (globalThis.hub.listenerCount("data") === 0) { globalThis.hub.pipe(new Writable({ write(chunk, encoding, done) { globalThis.received.push(String(chunk)); done(); } })); } export default function shared(request, response) { globalThis.hub.pipe(response); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const proxy = await sendRequest(port, '/proxy'); + const shared = await sendRequest(port, '/shared'); + const upstream = (globalThis as Record).piped as { destroyed: boolean }; + const hubStream = (globalThis as Record).hub as { destroyed: boolean; write: (chunk: string) => void }; + hubStream.write('after'); + await eventually(() => ((globalThis as Record).received as string[]).includes('after')); + + expect(proxy).toMatchObject({ status: 200, body: '' }); + expect(upstream.destroyed).toBe(true); + expect(shared).toMatchObject({ status: 200, body: '' }); + expect(hubStream.destroyed).toBe(false); + }, 4000); + + it('releases a file stream the handler piped when the handler ended the response itself', async () => { + writeProjectFile('page.html', '

page

'); + process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); + writeFunctionFile( + 'pipeThenEnd.js', + 'import { createReadStream } from "node:fs"; export default function pipeThenEnd(request, response) { globalThis.piped = createReadStream(process.env.LAUNCH_TEST_PAGE); globalThis.piped.pipe(response); response.end("done"); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const pipeThenEnd = await sendRequest(port, '/pipeThenEnd'); + const source = (globalThis as Record).piped as { destroyed: boolean }; + await eventually(() => source.destroyed); + + expect(pipeThenEnd).toMatchObject({ status: 200, body: 'done' }); + expect(source.destroyed).toBe(true); + }, 4000); + + it('answers with the request body when the handler pipes the request into its response', async () => { + writeFunctionFile('echo.js', 'export default function echo(request, response) { request.pipe(response); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const echo = await sendRequest(port, '/echo', { method: 'POST', headers: { 'content-type': 'image/png' }, body: 'pixels' }); + + expect(echo).toMatchObject({ status: 200, body: 'pixels' }); + }, 4000); + + it('passes a no-op end on an ended response through without a late-change warning', async () => { + writeFunctionFile( + 'noopEnd.js', + 'export default function noopEnd(request, response) { response.status(200).json({ ok: true }).end(); response.end(); response.end(() => { globalThis.lateDone = true; }); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const noopEnd = await sendRequest(port, '/noopEnd'); + await eventually(() => (globalThis as Record).lateDone === true); + + expect(noopEnd).toMatchObject({ status: 200, body: '{"ok":true}' }); + expect(loggedLines.filter((line) => line.startsWith('warn:'))).toEqual([]); + expect(loggedErrors).toEqual([]); + }, 4000); + + it('answers 500 and keeps serving when a handler that set an invalid status message throws', async () => { + writeFunctionFile( + 'badThrow.js', + 'export default function badThrow(request, response) { response.statusMessage = "Done \u2713"; throw new Error("boom"); }', + ); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const badThrow = await sendRequest(port, '/badThrow'); + const next = await sendRequest(port, '/next'); + + expect(badThrow).toMatchObject({ status: 500, body: '' }); + expect(next).toMatchObject({ status: 200, body: 'alive' }); + expect((loggedErrors[0] as Error).message).toBe('boom'); + }, 4000); + + it('drops the connection and keeps serving when ending the response for the handler fails twice', async () => { + writeFunctionFile( + 'mismatch.js', + 'export default function mismatch(request, response) { response.strictContentLength = true; response.setHeader("content-length", "5"); }', + ); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const mismatch = await sendRequest(port, '/mismatch').catch((error: NodeJS.ErrnoException) => error.code); + const next = await sendRequest(port, '/next'); + + expect(mismatch).toBe('ECONNRESET'); + expect(next).toMatchObject({ status: 200, body: 'alive' }); + expect(loggedErrors.map((error) => (error as NodeJS.ErrnoException).code)).toEqual([ + 'ERR_HTTP_CONTENT_LENGTH_MISMATCH', + 'ERR_HTTP_CONTENT_LENGTH_MISMATCH', + ]); + }, 4000); + it('serves and ends responses on an Express without res.sendfile, as Express 5 ships', async () => { const expressResponse = express.response as unknown as Record; const sendfile = expressResponse.sendfile; diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index df40f48..6ad7738 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -8,7 +8,7 @@ import type { } from 'express'; import express from 'express'; import type { Express } from 'express-serve-static-core'; -import { ReadStream, existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs'; +import { existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs'; import type { Server } from 'http'; import { isBuiltin } from 'module'; import type { AddressInfo } from 'net'; @@ -221,13 +221,33 @@ function warnLateChange(answering: Answering): void { console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); } +function remainingPipes(source: Readable): number { + return (source as unknown as { _readableState: { pipes: unknown[] } })._readableState.pipes.length; +} + function release(source: Readable, response: Response): void { source.unpipe(response); - if (source instanceof ReadStream) { + if (remainingPipes(source) === 0) { source.destroy(); } } +function isNoOpEnd(method: string, args: unknown[]): boolean { + const chunk = args[0]; + return method === 'end' && (typeof chunk === 'function' || !chunk); +} + +function answerServerError(response: Response): void { + response.statusCode = 500; + response.statusMessage = ''; + try { + response.end(); + } catch (error) { + console.error(error); + response.destroy(); + } +} + function guardLateChanges(response: Response, answering: Answering): void { const methods = response as unknown as ResponseMethods; LATE_CHANGE_METHODS.forEach((method) => { @@ -236,7 +256,7 @@ function guardLateChanges(response: Response, answering: Answering): void { } const change = (methods[method] as (...args: unknown[]) => unknown).bind(response); methods[method] = (...args: unknown[]): unknown => { - if (!response.writableEnded) { + if (!response.writableEnded || isNoOpEnd(method, args)) { return change(...args); } warnLateChange(answering); @@ -289,18 +309,13 @@ function endLikeDeployedFunctions(response: Response, answering: Answering): voi response.end(); } catch (error) { console.error(error); - response.statusCode = 500; - response.statusMessage = ''; - response.end(); + answerServerError(response); } - answering.pipedSources.forEach((source) => { - release(source, response); - }); } -function trackAnswering(response: Response, requestedUrl: string): Answering { +function trackAnswering(request: Request, response: Response): Answering { const answering: Answering = { - requestedUrl, + requestedUrl: request.originalUrl, handlerReturned: false, filesInFlight: 0, warned: false, @@ -313,6 +328,11 @@ function trackAnswering(response: Response, requestedUrl: string): Answering { } answering.pipedSources.add(source); }); + response.once('close', () => { + answering.pipedSources.forEach((source) => { + release(source, response); + }); + }); trackFileAnswers(response, answering); guardLateChanges(response, answering); return answering; @@ -441,13 +461,13 @@ export class CloudFunctions { private applyAppRouter(cloudFunctionResources: CloudFunctionResource[], app: Express): void { cloudFunctionResources.forEach((cloudFunctionResource) => { app.all(cloudFunctionResource.apiResourceURI, async (request: Request, response: Response) => { - const answering = trackAnswering(response, request.originalUrl); + const answering = trackAnswering(request, response); try { await cloudFunctionResource.handler(request, response); } catch (error) { console.error(error); if (!response.writableEnded) { - response.status(500).send(); + answerServerError(response); } } answering.handlerReturned = true; From 9d63bfa0ae250d1119b0b0c5c11e6f9889665429 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:23:27 +0000 Subject: [PATCH 12/21] chore: refresh .talismanrc checksum for AGENTS.md Prose; no credentials. --- .talismanrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.talismanrc b/.talismanrc index aab2012..301e5e2 100644 --- a/.talismanrc +++ b/.talismanrc @@ -240,7 +240,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: d4429d6badbb37d3f972b9a5ad8c59344f23331df62bba758915c231cf10fc1b + checksum: a4ba620e7e1e3eb55f2cdc536e395c1e0f6fb8bf7d3b7ccb2c1532df82c28e73 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\\)`" From 27a2f351821dc8a8ce4277c9718d411bd6c06468 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:50:35 +0000 Subject: [PATCH 13/21] fix(functions): release only what serve owns, and never crash on a foreign stream Review follow-ups on #314 (Dhruv, 9d63bfa): - A piped source is unpiped only if it has unpipe(), so a legacy Stream.pipe source (request, through, event-stream) no longer crashes serve when its response closes. - Only a file stream (fs.ReadStream) is destroyed, and only on the next turn when nothing reads it any more (no 'data' or 'readable' listener, which every pipe() adds). This drops the internal _readableState read that crashed on readable-stream v2/v3 sources, keeps a function-owned stream (an SSE PassThrough, a child's stdout) alive across requests, and lets a late tee or async iterator keep reading the file. - A stream piped after the client disconnected is released too. - Serve's 500 drops the headers the failed handler had set (a stale content-length or set-cookie) when they were not sent yet. - A late end() with a body gives its callback ERR_STREAM_WRITE_AFTER_END, as Node does. - .talismanrc: refreshed the checksum for AGENTS.md (prose, no credentials). --- .talismanrc | 2 +- AGENTS.md | 18 ++-- src/functions/cloud-functions.test.ts | 114 +++++++++++++++++++++++++- src/functions/cloud-functions.ts | 24 ++++-- 4 files changed, 139 insertions(+), 19 deletions(-) diff --git a/.talismanrc b/.talismanrc index 301e5e2..188b0ba 100644 --- a/.talismanrc +++ b/.talismanrc @@ -240,7 +240,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: a4ba620e7e1e3eb55f2cdc536e395c1e0f6fb8bf7d3b7ccb2c1532df82c28e73 + checksum: d4e594dd66506cded5d4e36b52cc5dd918b2bf7800991f14e41d33c4837a72fe 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\\)`" diff --git a/AGENTS.md b/AGENTS.md index d1dd226..5408a25 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -554,14 +554,16 @@ The approved differences from V1 are these, and only these: response open, is ended the same way once it settles. Once a response has ended, for whatever reason, any later change to it (`end` with a body, `write`, header calls, a file send, and so `send`, `json` and `redirect`) is ignored with one `warn:` line naming the requested URL instead - of crashing serve; a callback passed to it gets `ERR_STREAM_WRITE_AFTER_END` (`write`) or - `ERR_STREAM_ALREADY_FINISHED`, as Node does. An `end()` with no body is Node's own no-op and is - not warned about (`res.json(data).end()`). Once a response closes, or when a stream is piped - into one that has already ended, every stream piped into it is unpiped, and destroyed unless it - still feeds another destination, so serve keeps no file descriptor, upstream socket or child - process open; a shared stream piped elsewhere too keeps flowing there. If ending the response - for the handler fails (an invalid status, a content-length mismatch), or a handler throws, serve - logs the error and answers a plain 500, dropping the connection if even that cannot be sent. + of crashing serve; a callback passed to it gets `ERR_STREAM_WRITE_AFTER_END` (`write`, or `end` + with a body) or `ERR_STREAM_ALREADY_FINISHED`, as Node does. An `end()` with no body is Node's own + no-op and is not warned about (`res.json(data).end()`). Once a response closes, or when a stream + is piped into one that has already ended or whose client has gone, each stream piped into it is + unpiped (if it can be); a file stream (`fs.ReadStream`) is then destroyed unless something else + still reads it, so serve keeps no file descriptor open. Any other stream (an upstream response, a + shared `PassThrough`, a child's stdout) is the function's to close, as on AWS. If ending the + response for the handler fails (an invalid status, a content-length mismatch), or a handler + throws before its headers were sent, serve logs the error and answers a 500 without the headers + the handler had set, dropping the connection if even that cannot be sent. So a callback that answers after the handler returned gets an empty response, exactly as on AWS. Because serve wraps `res.sendFile`/`download`/`sendfile` to track them, Express's deprecation warning for the lowercase `res.sendfile` names serve's file, not the function's. Azure and GCP (V1) still diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 08db0d9..f13b792 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -132,6 +132,8 @@ afterEach(async () => { delete (globalThis as Record).piped; delete (globalThis as Record).hub; delete (globalThis as Record).received; + delete (globalThis as Record).ReadableV3; + delete (globalThis as Record).iterated; delete process.env.LAUNCH_TEST_PAGE; }); @@ -860,7 +862,7 @@ describe('CloudFunctions serve routing', () => { expect(hubStream.destroyed).toBe(false); }, 4000); - it('destroys a stream piped into a response it ends when nothing else reads it, and spares one that still feeds another destination', async () => { + it('leaves a stream that is not a file stream to the function after unpiping it, and spares one that still feeds another destination', async () => { writeFunctionFile( 'proxy.js', 'import { PassThrough } from "node:stream"; export default function proxy(request, response) { globalThis.piped = new PassThrough(); globalThis.piped.pipe(response); }', @@ -877,11 +879,117 @@ describe('CloudFunctions serve routing', () => { await eventually(() => ((globalThis as Record).received as string[]).includes('after')); expect(proxy).toMatchObject({ status: 200, body: '' }); - expect(upstream.destroyed).toBe(true); + expect(upstream.destroyed).toBe(false); expect(shared).toMatchObject({ status: 200, body: '' }); expect(hubStream.destroyed).toBe(false); }, 4000); + it('keeps serving when the handler pipes a legacy stream or a readable-stream v3 stream into its response', async () => { + (globalThis as Record).ReadableV3 = (jest.requireActual('readable-stream') as { Readable: unknown }).Readable; + writeFunctionFile( + 'legacy.js', + 'import { Stream } from "node:stream"; export default function legacy(request, response) { new Stream().pipe(response); response.end("legacy"); }', + ); + writeFunctionFile( + 'modernish.js', + 'export default function modernish(request, response) { new globalThis.ReadableV3({ read() {} }).pipe(response); response.end("v3"); }', + ); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const legacy = await sendRequest(port, '/legacy'); + const modernish = await sendRequest(port, '/modernish'); + await new Promise((done) => setTimeout(done, 20)); + const next = await sendRequest(port, '/next'); + + expect(legacy).toMatchObject({ status: 200, body: 'legacy' }); + expect(modernish).toMatchObject({ status: 200, body: 'v3' }); + expect(next).toMatchObject({ status: 200, body: 'alive' }); + expect(loggedErrors).toEqual([]); + }, 4000); + + it('lets a file stream piped late into an ended response keep feeding another destination or reader', async () => { + writeProjectFile('page.html', '

page

'); + process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); + writeFunctionFile( + 'tee.js', + 'import { createReadStream } from "node:fs"; import { Writable } from "node:stream"; export default function tee(request, response) { setTimeout(() => { globalThis.received = []; const file = createReadStream(process.env.LAUNCH_TEST_PAGE); file.pipe(response); file.pipe(new Writable({ write(chunk, encoding, done) { globalThis.received.push(String(chunk)); done(); } })); }, 20); }', + ); + writeFunctionFile( + 'reader.js', + 'import { createReadStream } from "node:fs"; export default function reader(request, response) { setTimeout(() => { globalThis.lateResult = []; const file = createReadStream(process.env.LAUNCH_TEST_PAGE); file.on("data", (chunk) => globalThis.lateResult.push(String(chunk))); file.pipe(response); }, 20); }', + ); + writeFunctionFile( + 'iterator.js', + 'import { createReadStream } from "node:fs"; export default function iterator(request, response) { setTimeout(async () => { globalThis.iterated = []; const file = createReadStream(process.env.LAUNCH_TEST_PAGE); file.pipe(response); try { for await (const chunk of file) { globalThis.iterated.push(String(chunk)); } } catch { globalThis.iterated.push("destroyed"); } globalThis.lateDone = true; }, 20); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + await sendRequest(port, '/tee'); + await eventually(() => ((globalThis as Record).received as string[] | undefined)?.join('') === '

page

'); + await sendRequest(port, '/reader'); + await eventually(() => ((globalThis as Record).lateResult as string[] | undefined)?.join('') === '

page

'); + + await sendRequest(port, '/iterator'); + await eventually(() => (globalThis as Record).lateDone === true); + + expect(((globalThis as Record).received as string[]).join('')).toBe('

page

'); + expect(((globalThis as Record).lateResult as string[]).join('')).toBe('

page

'); + expect(((globalThis as Record).iterated as string[]).join('')).toBe('

page

'); + }, 4000); + + it('releases a file stream piped after the client disconnected', async () => { + writeProjectFile('page.html', '

page

'); + process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); + writeFunctionFile( + 'gone.js', + 'import { createReadStream } from "node:fs"; export default async function gone(request, response) { await new Promise((done) => setTimeout(done, 100)); globalThis.piped = createReadStream(process.env.LAUNCH_TEST_PAGE); globalThis.piped.pipe(response); globalThis.lateDone = true; }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + await new Promise((resolve) => { + const clientRequest = httpRequest({ host: '127.0.0.1', port, path: '/gone' }); + clientRequest.on('error', () => resolve()); + clientRequest.end(); + setTimeout(() => clientRequest.destroy(), 30); + }); + await eventually(() => (globalThis as Record).lateDone === true); + const source = (globalThis as Record).piped as { destroyed: boolean }; + await eventually(() => source.destroyed); + + expect(source.destroyed).toBe(true); + }, 4000); + + it('answers its 500 without the headers the failed handler had set', async () => { + writeFunctionFile( + 'stale.js', + 'export default function stale(request, response) { response.setHeader("content-length", "5"); response.setHeader("set-cookie", "a=1"); throw new Error("boom"); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const stale = await new Promise<{ status: number; headers: Record; body: string }>((resolve, reject) => { + httpRequest({ host: '127.0.0.1', port, path: '/stale' }, (response) => { + let body = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + body += chunk; + }); + response.on('end', () => resolve({ status: response.statusCode as number, headers: response.headers, body })); + }) + .on('error', reject) + .end(); + }); + + expect(stale.status).toBe(500); + expect(stale.body).toBe(''); + expect(stale.headers['set-cookie']).toBeUndefined(); + expect(stale.headers['content-length']).not.toBe('5'); + }, 4000); + it('releases a file stream the handler piped when the handler ended the response itself', async () => { writeProjectFile('page.html', '

page

'); process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); @@ -1021,7 +1129,7 @@ describe('CloudFunctions serve routing', () => { expect(JSON.parse(next.body)).toEqual({ wrote: false, writeError: 'ERR_STREAM_WRITE_AFTER_END', - endError: 'ERR_STREAM_ALREADY_FINISHED', + endError: 'ERR_STREAM_WRITE_AFTER_END', }); }, 4000); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 6ad7738..aea32d8 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -8,7 +8,7 @@ import type { } from 'express'; import express from 'express'; import type { Express } from 'express-serve-static-core'; -import { existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs'; +import { ReadStream, existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs'; import type { Server } from 'http'; import { isBuiltin } from 'module'; import type { AddressInfo } from 'net'; @@ -206,7 +206,7 @@ interface Answering { type ResponseMethods = Record; function alreadyFinished(method: string): NodeJS.ErrnoException { - const code = method === 'write' ? 'ERR_STREAM_WRITE_AFTER_END' : 'ERR_STREAM_ALREADY_FINISHED'; + const code = method === 'write' || method === 'end' ? 'ERR_STREAM_WRITE_AFTER_END' : 'ERR_STREAM_ALREADY_FINISHED'; return Object.assign(new Error('The response was already ended.'), { code }); } @@ -221,14 +221,21 @@ function warnLateChange(answering: Answering): void { console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); } -function remainingPipes(source: Readable): number { - return (source as unknown as { _readableState: { pipes: unknown[] } })._readableState.pipes.length; +function hasNoReader(file: ReadStream): boolean { + return file.listenerCount('data') === 0 && file.listenerCount('readable') === 0; } function release(source: Readable, response: Response): void { + if (typeof source.unpipe !== 'function') { + return; + } source.unpipe(response); - if (remainingPipes(source) === 0) { - source.destroy(); + if (source instanceof ReadStream) { + setImmediate(() => { + if (!source.destroyed && hasNoReader(source)) { + source.destroy(); + } + }); } } @@ -238,6 +245,9 @@ function isNoOpEnd(method: string, args: unknown[]): boolean { } function answerServerError(response: Response): void { + if (!response.headersSent) { + response.getHeaderNames().forEach((name) => response.removeHeader(name)); + } response.statusCode = 500; response.statusMessage = ''; try { @@ -322,7 +332,7 @@ function trackAnswering(request: Request, response: Response): Answering { pipedSources: new Set(), }; response.on('pipe', (source: Readable) => { - if (response.writableEnded) { + if (response.writableEnded || response.destroyed) { release(source, response); return; } From 2c08689e550c7ed35baeb89458872d3669fe0814 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:51:11 +0000 Subject: [PATCH 14/21] chore: refresh .talismanrc checksum for cloud-functions.test.ts Test code; no credentials. --- .talismanrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.talismanrc b/.talismanrc index 188b0ba..9bbdb60 100644 --- a/.talismanrc +++ b/.talismanrc @@ -287,7 +287,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 038f5cd182e1fd0105e6e10dde7f5068a0c15883222450f72ea3904890a56c0c - filename: src/functions/cloud-functions.test.ts - checksum: b24b70a25789e42eeb7503f50257ef23d5c873bae8463adf1a79a896cb483e69 + checksum: 4ecfc8deb42597cda166c7156720901c12665c1439495b4f3b35b942db4fda49 - filename: src/functions/function.errors.ts checksum: a24194bef73c8db8c28b8ac104955f2f22abdc8c8d0608fa36a39032055bda57 - filename: src/transport/proxy.test.ts From f6f8ddd163d15c0578da3c514588d9ebdc8c4b44 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:15:21 +0000 Subject: [PATCH 15/21] fix(functions): drain a released stream instead of leaving it paused Review follow-ups on #314 (Dhruv, 2c08689): - After unpiping a source, serve settles it on the next turn: a file stream nothing else reads is destroyed as before; any other stream not read through 'readable' is resumed, so it drains and finishes. A file stream with a side 'data' reader, a gzip transform feeding the response (and the file behind it), a child's stdout or an upstream body no longer stay paused holding a descriptor, socket or child, and the close path now leaves a stream in the same flowing state as the late-pipe path. Serve still never destroys a stream the function owns. - Serve's 500 restores its cache-control: no-store default after dropping the failed handler's headers. - The readable-stream v2/v3 test builds that shape inline instead of relying on a hoisted, undeclared package. --- AGENTS.md | 14 ++++---- src/functions/cloud-functions.test.ts | 49 ++++++++++++++++++++++++--- src/functions/cloud-functions.ts | 22 +++++++----- 3 files changed, 65 insertions(+), 20 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5408a25..3494182 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -558,12 +558,14 @@ The approved differences from V1 are these, and only these: with a body) or `ERR_STREAM_ALREADY_FINISHED`, as Node does. An `end()` with no body is Node's own no-op and is not warned about (`res.json(data).end()`). Once a response closes, or when a stream is piped into one that has already ended or whose client has gone, each stream piped into it is - unpiped (if it can be); a file stream (`fs.ReadStream`) is then destroyed unless something else - still reads it, so serve keeps no file descriptor open. Any other stream (an upstream response, a - shared `PassThrough`, a child's stdout) is the function's to close, as on AWS. If ending the - response for the handler fails (an invalid status, a content-length mismatch), or a handler - throws before its headers were sent, serve logs the error and answers a 500 without the headers - the handler had set, dropping the connection if even that cannot be sent. + unpiped (if it can be). On the next turn a file stream (`fs.ReadStream`) that nothing else reads + is destroyed, and any other stream not read through `'readable'` is resumed, so it drains and + finishes as it would on AWS (a side `'data'` reader, a transform feeding the response, a child's + stdout, an upstream body) instead of holding a file descriptor, socket or child open; serve never + destroys a stream the function owns. If ending the response for the handler fails (an invalid + status, a content-length mismatch), or a handler throws before its headers were sent, serve logs + the error and answers a `cache-control: no-store` 500 without the headers the handler had set, + dropping the connection if even that cannot be sent. So a callback that answers after the handler returned gets an empty response, exactly as on AWS. Because serve wraps `res.sendFile`/`download`/`sendfile` to track them, Express's deprecation warning for the lowercase `res.sendfile` names serve's file, not the function's. Azure and GCP (V1) still diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index f13b792..2c7b119 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -1,4 +1,4 @@ -import { randomUUID } from 'crypto'; +import { randomBytes, randomUUID } from 'crypto'; import fs, { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'fs'; import type { Server } from 'http'; import { createServer } from 'http'; @@ -132,7 +132,6 @@ afterEach(async () => { delete (globalThis as Record).piped; delete (globalThis as Record).hub; delete (globalThis as Record).received; - delete (globalThis as Record).ReadableV3; delete (globalThis as Record).iterated; delete process.env.LAUNCH_TEST_PAGE; }); @@ -878,21 +877,23 @@ describe('CloudFunctions serve routing', () => { hubStream.write('after'); await eventually(() => ((globalThis as Record).received as string[]).includes('after')); + await new Promise((done) => setTimeout(done, 50)); + expect(proxy).toMatchObject({ status: 200, body: '' }); expect(upstream.destroyed).toBe(false); + expect((upstream as unknown as { readableFlowing: boolean | null }).readableFlowing).toBe(true); expect(shared).toMatchObject({ status: 200, body: '' }); expect(hubStream.destroyed).toBe(false); }, 4000); - it('keeps serving when the handler pipes a legacy stream or a readable-stream v3 stream into its response', async () => { - (globalThis as Record).ReadableV3 = (jest.requireActual('readable-stream') as { Readable: unknown }).Readable; + it('keeps serving when the handler pipes a legacy stream, or one shaped like readable-stream v2/v3, into its response', async () => { writeFunctionFile( 'legacy.js', 'import { Stream } from "node:stream"; export default function legacy(request, response) { new Stream().pipe(response); response.end("legacy"); }', ); writeFunctionFile( 'modernish.js', - 'export default function modernish(request, response) { new globalThis.ReadableV3({ read() {} }).pipe(response); response.end("v3"); }', + 'import { Stream } from "node:stream"; export default function modernish(request, response) { const source = new Stream(); source.unpipe = () => source; source._readableState = { pipes: null, pipesCount: 0 }; source.pipe(response); response.end("v3"); }', ); writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); const port = await freePort(); @@ -940,6 +941,43 @@ describe('CloudFunctions serve routing', () => { expect(((globalThis as Record).iterated as string[]).join('')).toBe('

page

'); }, 4000); + it('lets a file stream with a side reader finish and close once its response closes', async () => { + writeProjectFile('page.html', '

page

'); + process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); + writeFunctionFile( + 'sideReader.js', + 'import { createReadStream } from "node:fs"; export default function sideReader(request, response) { globalThis.lateResult = []; globalThis.piped = createReadStream(process.env.LAUNCH_TEST_PAGE); globalThis.piped.on("data", (chunk) => globalThis.lateResult.push(String(chunk))); globalThis.piped.pipe(response); response.end("done"); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const sideReader = await sendRequest(port, '/sideReader'); + const source = (globalThis as Record).piped as { destroyed: boolean }; + await eventually(() => source.destroyed); + + expect(sideReader).toMatchObject({ status: 200, body: 'done' }); + expect(((globalThis as Record).lateResult as string[]).join('')).toBe('

page

'); + expect(source.destroyed).toBe(true); + }, 4000); + + it('drains a transform it unpiped, so the file stream feeding it finishes and closes', async () => { + writeFileSync(join(workspace, 'big.bin'), randomBytes(1024 * 1024)); + process.env.LAUNCH_TEST_PAGE = join(workspace, 'big.bin'); + writeFunctionFile( + 'zipped.js', + 'import { createReadStream } from "node:fs"; import { createGzip } from "node:zlib"; export default function zipped(request, response) { globalThis.piped = createReadStream(process.env.LAUNCH_TEST_PAGE); globalThis.piped.pipe(createGzip()).pipe(response); response.end("done"); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const zipped = await sendRequest(port, '/zipped'); + const source = (globalThis as Record).piped as { destroyed: boolean }; + await eventually(() => source.destroyed); + + expect(zipped).toMatchObject({ status: 200, body: 'done' }); + expect(source.destroyed).toBe(true); + }, 4000); + it('releases a file stream piped after the client disconnected', async () => { writeProjectFile('page.html', '

page

'); process.env.LAUNCH_TEST_PAGE = join(workspace, 'page.html'); @@ -988,6 +1026,7 @@ describe('CloudFunctions serve routing', () => { expect(stale.body).toBe(''); expect(stale.headers['set-cookie']).toBeUndefined(); expect(stale.headers['content-length']).not.toBe('5'); + expect(stale.headers['cache-control']).toBe('no-store'); }, 4000); it('releases a file stream the handler piped when the handler ended the response itself', async () => { diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index aea32d8..4de38bb 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -221,8 +221,17 @@ function warnLateChange(answering: Answering): void { console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); } -function hasNoReader(file: ReadStream): boolean { - return file.listenerCount('data') === 0 && file.listenerCount('readable') === 0; +function settleReleased(source: Readable): void { + if (source.listenerCount('readable') > 0) { + return; + } + if (source instanceof ReadStream && source.listenerCount('data') === 0) { + source.destroy(); + return; + } + if (typeof source.resume === 'function') { + source.resume(); + } } function release(source: Readable, response: Response): void { @@ -230,13 +239,7 @@ function release(source: Readable, response: Response): void { return; } source.unpipe(response); - if (source instanceof ReadStream) { - setImmediate(() => { - if (!source.destroyed && hasNoReader(source)) { - source.destroy(); - } - }); - } + setImmediate(() => settleReleased(source)); } function isNoOpEnd(method: string, args: unknown[]): boolean { @@ -247,6 +250,7 @@ function isNoOpEnd(method: string, args: unknown[]): boolean { function answerServerError(response: Response): void { if (!response.headersSent) { response.getHeaderNames().forEach((name) => response.removeHeader(name)); + response.setHeader('cache-control', 'no-store'); } response.statusCode = 500; response.statusMessage = ''; From ed948bacd3f4db91a5124cdbfa7d09f8bedc81d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:15:53 +0000 Subject: [PATCH 16/21] chore: refresh .talismanrc checksums for cloud-functions.test.ts and AGENTS.md Test code and prose; no credentials. --- .talismanrc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.talismanrc b/.talismanrc index 9bbdb60..f94f008 100644 --- a/.talismanrc +++ b/.talismanrc @@ -240,7 +240,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: d4e594dd66506cded5d4e36b52cc5dd918b2bf7800991f14e41d33c4837a72fe + checksum: 682bf14598b3f679daa9693faf34ecfbfdd5de6ce733ec2b82d3af2a5cddbabc 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\\)`" @@ -287,7 +287,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 038f5cd182e1fd0105e6e10dde7f5068a0c15883222450f72ea3904890a56c0c - filename: src/functions/cloud-functions.test.ts - checksum: 4ecfc8deb42597cda166c7156720901c12665c1439495b4f3b35b942db4fda49 + checksum: fc0fdeb281fcc60fa2379d8e11993b9f91acd239c87851ed6ff672231e4cebd5 - filename: src/functions/function.errors.ts checksum: a24194bef73c8db8c28b8ac104955f2f22abdc8c8d0608fa36a39032055bda57 - filename: src/transport/proxy.test.ts From 4b128ee593f6eba9224e1f0c3f50fb303e27b5ae Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:51:57 +0000 Subject: [PATCH 17/21] fix(functions): resume a released stream only for a reader it still has Review follow-ups on #314 (Dhruv, ed948ba): - A released stream is resumed only when it still has a 'data' reader, so that reader gets the rest; a stream nothing reads is left paused, as Node leaves it after an unpipe. Resuming every released stream could spin serve on an endless synchronous producer and drained a queue the function reuses across requests. - A released source without listenerCount (a stream-like object) is left alone instead of throwing from setImmediate, and one without resume is never resumed. - Tests: the released-PassThrough test now expects it paused and buffering; an endless producer no longer blocks the next request; a non-core stream with a reader is resumed through its own resume; and two stream-like objects without listenerCount or resume keep serve up. The gzip drain test is dropped with the behaviour it pinned. - AGENTS.md states the rule and its limit: only a file stream nothing reads is closed for the function; anything else it leaves paused stays open until the function closes it. --- AGENTS.md | 15 +++++----- src/functions/cloud-functions.test.ts | 40 +++++++++++++++++---------- src/functions/cloud-functions.ts | 7 +++-- 3 files changed, 37 insertions(+), 25 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3494182..ef23d4c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -559,13 +559,14 @@ The approved differences from V1 are these, and only these: no-op and is not warned about (`res.json(data).end()`). Once a response closes, or when a stream is piped into one that has already ended or whose client has gone, each stream piped into it is unpiped (if it can be). On the next turn a file stream (`fs.ReadStream`) that nothing else reads - is destroyed, and any other stream not read through `'readable'` is resumed, so it drains and - finishes as it would on AWS (a side `'data'` reader, a transform feeding the response, a child's - stdout, an upstream body) instead of holding a file descriptor, socket or child open; serve never - destroys a stream the function owns. If ending the response for the handler fails (an invalid - status, a content-length mismatch), or a handler throws before its headers were sent, serve logs - the error and answers a `cache-control: no-store` 500 without the headers the handler had set, - dropping the connection if even that cannot be sent. + is destroyed, so it does not keep its file descriptor open; that is the one kind of stream serve + closes for the function. A stream that still has a `'data'` reader is resumed so that reader gets + the rest. Any other stream is left paused, as Node leaves it after an unpipe, for the function to + resume or close: a file stream behind a transform (for example gzip), a child's stdout or an + upstream body then stays open until the function closes it. If ending the response for the + handler fails (an invalid status, a content-length mismatch), or a handler throws before its + headers were sent, serve logs the error and answers a `cache-control: no-store` 500 without the + headers the handler had set, dropping the connection if even that cannot be sent. So a callback that answers after the handler returned gets an empty response, exactly as on AWS. Because serve wraps `res.sendFile`/`download`/`sendfile` to track them, Express's deprecation warning for the lowercase `res.sendfile` names serve's file, not the function's. Azure and GCP (V1) still diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 2c7b119..5dd250f 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -1,4 +1,4 @@ -import { randomBytes, randomUUID } from 'crypto'; +import { randomUUID } from 'crypto'; import fs, { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'fs'; import type { Server } from 'http'; import { createServer } from 'http'; @@ -861,7 +861,7 @@ describe('CloudFunctions serve routing', () => { expect(hubStream.destroyed).toBe(false); }, 4000); - it('leaves a stream that is not a file stream to the function after unpiping it, and spares one that still feeds another destination', async () => { + it('leaves a released stream that nothing reads paused for the function, and spares one that still feeds another destination', async () => { writeFunctionFile( 'proxy.js', 'import { PassThrough } from "node:stream"; export default function proxy(request, response) { globalThis.piped = new PassThrough(); globalThis.piped.pipe(response); }', @@ -878,22 +878,28 @@ describe('CloudFunctions serve routing', () => { await eventually(() => ((globalThis as Record).received as string[]).includes('after')); await new Promise((done) => setTimeout(done, 50)); + (upstream as unknown as { write: (chunk: string) => void }).write('kept'); expect(proxy).toMatchObject({ status: 200, body: '' }); expect(upstream.destroyed).toBe(false); - expect((upstream as unknown as { readableFlowing: boolean | null }).readableFlowing).toBe(true); + expect((upstream as unknown as { readableFlowing: boolean | null }).readableFlowing).toBe(false); + expect((upstream as unknown as { readableLength: number }).readableLength).toBe(4); expect(shared).toMatchObject({ status: 200, body: '' }); expect(hubStream.destroyed).toBe(false); }, 4000); - it('keeps serving when the handler pipes a legacy stream, or one shaped like readable-stream v2/v3, into its response', async () => { + it('keeps serving when the handler pipes a legacy stream, a non-core stream or a stream-like object into its response', async () => { writeFunctionFile( 'legacy.js', 'import { Stream } from "node:stream"; export default function legacy(request, response) { new Stream().pipe(response); response.end("legacy"); }', ); writeFunctionFile( 'modernish.js', - 'import { Stream } from "node:stream"; export default function modernish(request, response) { const source = new Stream(); source.unpipe = () => source; source._readableState = { pipes: null, pipesCount: 0 }; source.pipe(response); response.end("v3"); }', + 'import { Stream } from "node:stream"; export default function modernish(request, response) { const source = new Stream(); source.unpipe = () => source; source.resume = () => { globalThis.lateResult = "resumed"; }; source.on("data", () => {}); source.pipe(response); response.end("v3"); }', + ); + writeFunctionFile( + 'foreign.js', + 'export default function foreign(request, response) { response.emit("pipe", { unpipe() {} }); response.emit("pipe", { unpipe() {}, listenerCount(event) { return event === "data" ? 1 : 0; } }); response.end("foreign"); }', ); writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); const port = await freePort(); @@ -901,11 +907,15 @@ describe('CloudFunctions serve routing', () => { await new CloudFunctions(workspace).serve(port); const legacy = await sendRequest(port, '/legacy'); const modernish = await sendRequest(port, '/modernish'); + await eventually(() => (globalThis as Record).lateResult === 'resumed'); + const foreign = await sendRequest(port, '/foreign'); await new Promise((done) => setTimeout(done, 20)); const next = await sendRequest(port, '/next'); expect(legacy).toMatchObject({ status: 200, body: 'legacy' }); expect(modernish).toMatchObject({ status: 200, body: 'v3' }); + expect((globalThis as Record).lateResult).toBe('resumed'); + expect(foreign).toMatchObject({ status: 200, body: 'foreign' }); expect(next).toMatchObject({ status: 200, body: 'alive' }); expect(loggedErrors).toEqual([]); }, 4000); @@ -960,22 +970,22 @@ describe('CloudFunctions serve routing', () => { expect(source.destroyed).toBe(true); }, 4000); - it('drains a transform it unpiped, so the file stream feeding it finishes and closes', async () => { - writeFileSync(join(workspace, 'big.bin'), randomBytes(1024 * 1024)); - process.env.LAUNCH_TEST_PAGE = join(workspace, 'big.bin'); + it('keeps serving after it releases an endless stream that nothing reads', async () => { writeFunctionFile( - 'zipped.js', - 'import { createReadStream } from "node:fs"; import { createGzip } from "node:zlib"; export default function zipped(request, response) { globalThis.piped = createReadStream(process.env.LAUNCH_TEST_PAGE); globalThis.piped.pipe(createGzip()).pipe(response); response.end("done"); }', + 'endless.js', + 'import { Readable } from "node:stream"; export default function endless(request, response) { globalThis.piped = new Readable({ read() { this.push(Buffer.alloc(1024)); } }); globalThis.piped.pipe(response); response.end("done"); }', ); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); const port = await freePort(); await new CloudFunctions(workspace).serve(port); - const zipped = await sendRequest(port, '/zipped'); - const source = (globalThis as Record).piped as { destroyed: boolean }; - await eventually(() => source.destroyed); + const endless = await sendRequest(port, '/endless'); + await new Promise((done) => setTimeout(done, 50)); + const next = await sendRequest(port, '/next'); - expect(zipped).toMatchObject({ status: 200, body: 'done' }); - expect(source.destroyed).toBe(true); + expect(endless).toMatchObject({ status: 200, body: 'done' }); + expect(next).toMatchObject({ status: 200, body: 'alive' }); + expect((globalThis as Record).piped as { destroyed: boolean }).toMatchObject({ destroyed: false }); }, 4000); it('releases a file stream piped after the client disconnected', async () => { diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 4de38bb..0e6b766 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -222,14 +222,15 @@ function warnLateChange(answering: Answering): void { } function settleReleased(source: Readable): void { - if (source.listenerCount('readable') > 0) { + if (typeof source.listenerCount !== 'function' || source.listenerCount('readable') > 0) { return; } - if (source instanceof ReadStream && source.listenerCount('data') === 0) { + const read = source.listenerCount('data') > 0; + if (source instanceof ReadStream && !read) { source.destroy(); return; } - if (typeof source.resume === 'function') { + if (read && typeof source.resume === 'function') { source.resume(); } } From c30e51b88fa1651f7dc8d86a0b6fb11f4b78b67a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:52:30 +0000 Subject: [PATCH 18/21] chore: refresh .talismanrc checksums for cloud-functions.test.ts and AGENTS.md Test code and prose; no credentials. --- .talismanrc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.talismanrc b/.talismanrc index f94f008..0e8fc63 100644 --- a/.talismanrc +++ b/.talismanrc @@ -240,7 +240,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: 682bf14598b3f679daa9693faf34ecfbfdd5de6ce733ec2b82d3af2a5cddbabc + checksum: 02e965efd6f44f24a5592f879daa5cd9e10eb6ed6e928418308643395d352aae 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\\)`" @@ -287,7 +287,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 038f5cd182e1fd0105e6e10dde7f5068a0c15883222450f72ea3904890a56c0c - filename: src/functions/cloud-functions.test.ts - checksum: fc0fdeb281fcc60fa2379d8e11993b9f91acd239c87851ed6ff672231e4cebd5 + checksum: 7ab207d85499c0487f1ab3d080bccd9b86de72242328c260ee160788c48e42fe - filename: src/functions/function.errors.ts checksum: a24194bef73c8db8c28b8ac104955f2f22abdc8c8d0608fa36a39032055bda57 - filename: src/transport/proxy.test.ts From c225c9df1d1d6cfad732257d3217ab3d9d643443 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:23:44 +0000 Subject: [PATCH 19/21] fix(functions): drain a released request body, and release a late pipe after pipe() returns Review follow-ups on #314 (Dhruv, c30e51b): - A request or upstream body (http.IncomingMessage) that serve releases is drained. A handler that pipes its request into its response and returns before a large body arrives no longer stalls the upload and the keep-alive connection: Node does not dump a request pipe() already consumed, so leaving it paused hung the next request on that socket. - A stream piped into an already-ended response is released on the next tick, after pipe() has called resume() itself, so it ends up paused like one released on close instead of flowing with no reader. - The endless-producer test caps its producer and asserts it stayed paused, so a regression fails the test instead of hanging the run. - AGENTS.md describes the drained bodies and that both paths leave any other stream paused. - .talismanrc: refreshed the checksums for cloud-functions.test.ts and AGENTS.md (test code and prose, no credentials). --- .talismanrc | 4 +- AGENTS.md | 13 +++--- src/functions/cloud-functions.test.ts | 67 +++++++++++++++++++++++++-- src/functions/cloud-functions.ts | 7 ++- 4 files changed, 79 insertions(+), 12 deletions(-) diff --git a/.talismanrc b/.talismanrc index 0e8fc63..14b3233 100644 --- a/.talismanrc +++ b/.talismanrc @@ -240,7 +240,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: 02e965efd6f44f24a5592f879daa5cd9e10eb6ed6e928418308643395d352aae + checksum: b278cb3dddec26aec4fae9a6897de34bf6aa1f284946efe2d0252c33bca30b44 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\\)`" @@ -287,7 +287,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 038f5cd182e1fd0105e6e10dde7f5068a0c15883222450f72ea3904890a56c0c - filename: src/functions/cloud-functions.test.ts - checksum: 7ab207d85499c0487f1ab3d080bccd9b86de72242328c260ee160788c48e42fe + checksum: 7a9226b7f7e029734b33a1c4461373415e8be27f22274c7ee7c5bdd65b5e18cc - filename: src/functions/function.errors.ts checksum: a24194bef73c8db8c28b8ac104955f2f22abdc8c8d0608fa36a39032055bda57 - filename: src/transport/proxy.test.ts diff --git a/AGENTS.md b/AGENTS.md index ef23d4c..ce18a66 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -558,12 +558,13 @@ The approved differences from V1 are these, and only these: with a body) or `ERR_STREAM_ALREADY_FINISHED`, as Node does. An `end()` with no body is Node's own no-op and is not warned about (`res.json(data).end()`). Once a response closes, or when a stream is piped into one that has already ended or whose client has gone, each stream piped into it is - unpiped (if it can be). On the next turn a file stream (`fs.ReadStream`) that nothing else reads - is destroyed, so it does not keep its file descriptor open; that is the one kind of stream serve - closes for the function. A stream that still has a `'data'` reader is resumed so that reader gets - the rest. Any other stream is left paused, as Node leaves it after an unpipe, for the function to - resume or close: a file stream behind a transform (for example gzip), a child's stdout or an - upstream body then stays open until the function closes it. If ending the response for the + unpiped (if it can be) once `pipe()` has returned. On the next turn a request or upstream body + (`http.IncomingMessage`) is drained, so its connection is freed; a file stream (`fs.ReadStream`) + that nothing else reads is destroyed, so it does not keep its file descriptor open; and a stream + that still has a `'data'` reader is resumed so that reader gets the rest. Any other stream is left + paused, as Node leaves it after an unpipe, for the function to resume or close: a file stream + behind a transform (for example gzip) or a child's stdout then stays open until the function + closes it. If ending the response for the handler fails (an invalid status, a content-length mismatch), or a handler throws before its headers were sent, serve logs the error and answers a `cache-control: no-store` 500 without the headers the handler had set, dropping the connection if even that cannot be sent. diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index 5dd250f..ed432b1 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -2,7 +2,7 @@ import { randomUUID } from 'crypto'; import fs, { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'fs'; import type { Server } from 'http'; import { createServer } from 'http'; -import { request as httpRequest } from 'http'; +import { Agent, request as httpRequest } from 'http'; import type { AddressInfo } from 'net'; import os, { tmpdir } from 'os'; import { dirname, join, win32 } from 'path'; @@ -970,10 +970,70 @@ describe('CloudFunctions serve routing', () => { expect(source.destroyed).toBe(true); }, 4000); + it('leaves a stream piped into an already-ended response paused, as on close', async () => { + writeFunctionFile( + 'lateQueue.js', + 'import { PassThrough } from "node:stream"; export default function lateQueue(request, response) { response.end("done"); setTimeout(() => { globalThis.piped = new PassThrough(); globalThis.piped.pipe(response); globalThis.lateDone = true; }, 20); }', + ); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + const lateQueue = await sendRequest(port, '/lateQueue'); + await eventually(() => (globalThis as Record).lateDone === true); + await new Promise((done) => setTimeout(done, 20)); + const queue = (globalThis as Record).piped as { readableFlowing: boolean | null; readableLength: number; write: (chunk: string) => void }; + queue.write('kept'); + + expect(lateQueue).toMatchObject({ status: 200, body: 'done' }); + expect(queue.readableFlowing).toBe(false); + expect(queue.readableLength).toBe(4); + }, 4000); + + it('drains a request body piped into a response it ends, so the keep-alive connection answers the next request', async () => { + writeFunctionFile('echoLate.js', 'export default function echoLate(request, response) { request.pipe(response); }'); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + const agent = new Agent({ keepAlive: true, maxSockets: 1 }); + + try { + await new CloudFunctions(workspace).serve(port); + const echoLate = new Promise((resolve, reject) => { + const clientRequest = httpRequest( + { host: '127.0.0.1', port, path: '/echoLate', method: 'POST', agent, headers: { 'content-type': 'image/png', 'content-length': String(1024 * 1024) } }, + (response) => { + response.resume(); + response.on('end', () => resolve(response.statusCode as number)); + }, + ); + clientRequest.on('error', reject); + clientRequest.flushHeaders(); + setTimeout(() => clientRequest.end(Buffer.alloc(1024 * 1024)), 100); + }); + const next = new Promise((resolve, reject) => { + httpRequest({ host: '127.0.0.1', port, path: '/next', agent }, (response) => { + let body = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + body += chunk; + }); + response.on('end', () => resolve(body)); + }) + .on('error', reject) + .end(); + }); + const answered = await Promise.race([next, new Promise((resolve) => setTimeout(() => resolve('no answer'), 1500))]); + + expect(await echoLate).toBe(200); + expect(answered).toBe('alive'); + } finally { + agent.destroy(); + } + }, 4000); + it('keeps serving after it releases an endless stream that nothing reads', async () => { writeFunctionFile( 'endless.js', - 'import { Readable } from "node:stream"; export default function endless(request, response) { globalThis.piped = new Readable({ read() { this.push(Buffer.alloc(1024)); } }); globalThis.piped.pipe(response); response.end("done"); }', + 'import { Readable } from "node:stream"; export default function endless(request, response) { globalThis.lateResult = 0; globalThis.piped = new Readable({ read() { globalThis.lateResult += 1; this.push(globalThis.lateResult > 10000 ? null : Buffer.alloc(1024)); } }); globalThis.piped.pipe(response); response.end("done"); }', ); writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); const port = await freePort(); @@ -985,7 +1045,8 @@ describe('CloudFunctions serve routing', () => { expect(endless).toMatchObject({ status: 200, body: 'done' }); expect(next).toMatchObject({ status: 200, body: 'alive' }); - expect((globalThis as Record).piped as { destroyed: boolean }).toMatchObject({ destroyed: false }); + expect((globalThis as Record).piped as { destroyed: boolean }).toMatchObject({ destroyed: false, readableFlowing: false }); + expect((globalThis as Record).lateResult).toBeLessThan(100); }, 4000); it('releases a file stream piped after the client disconnected', async () => { diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 0e6b766..7a93ddf 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -9,6 +9,7 @@ import type { import express from 'express'; import type { Express } from 'express-serve-static-core'; import { ReadStream, existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs'; +import { IncomingMessage } from 'http'; import type { Server } from 'http'; import { isBuiltin } from 'module'; import type { AddressInfo } from 'net'; @@ -222,6 +223,10 @@ function warnLateChange(answering: Answering): void { } function settleReleased(source: Readable): void { + if (source instanceof IncomingMessage) { + source.resume(); + return; + } if (typeof source.listenerCount !== 'function' || source.listenerCount('readable') > 0) { return; } @@ -338,7 +343,7 @@ function trackAnswering(request: Request, response: Response): Answering { }; response.on('pipe', (source: Readable) => { if (response.writableEnded || response.destroyed) { - release(source, response); + process.nextTick(() => release(source, response)); return; } answering.pipedSources.add(source); From 294fd07a8ca95e75cac5ed56b5916b2841772421 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:54:15 +0000 Subject: [PATCH 20/21] fix(functions): drain only the exchange's request, and unpipe a late pipe at once Review follow-ups on #314 (Dhruv, c225c9d): - Only this exchange's own request body is drained on release, as Node would dump it. An upstream body (a live feed, an SSE relay) piped into the response is left paused like any other stream instead of being read at full speed after the client has gone. - A stream piped into an already-ended response is unpiped inside the 'pipe' event again, so a shared hub's next write does not reach the ended response and log a false late-change warning, and a throwing unpipe surfaces in the caller's pipe() as on v2-dev. To undo pipe()'s own resume, the source is paused from a one-shot 'resume' listener (removed on the next turn); a reader it still has is resumed by the settle step, as on close. An endless producer piped late no longer spins. - AGENTS.md names only the request as drained and lists a request piped through a transform among the streams left to the function. - .talismanrc: refreshed the checksum for cloud-functions.test.ts (test code, no credentials). --- .talismanrc | 2 +- AGENTS.md | 21 ++++---- src/functions/cloud-functions.test.ts | 73 +++++++++++++++++++++++++++ src/functions/cloud-functions.ts | 27 +++++++--- 4 files changed, 105 insertions(+), 18 deletions(-) diff --git a/.talismanrc b/.talismanrc index 14b3233..426d8f7 100644 --- a/.talismanrc +++ b/.talismanrc @@ -287,7 +287,7 @@ fileignoreconfig: - filename: test/integration/projects-list-command.test.ts checksum: 038f5cd182e1fd0105e6e10dde7f5068a0c15883222450f72ea3904890a56c0c - filename: src/functions/cloud-functions.test.ts - checksum: 7a9226b7f7e029734b33a1c4461373415e8be27f22274c7ee7c5bdd65b5e18cc + checksum: 126ebc9a778b18a0601e5c11cbf1b6441a5989b558bb276ae640cbc7b33fe712 - filename: src/functions/function.errors.ts checksum: a24194bef73c8db8c28b8ac104955f2f22abdc8c8d0608fa36a39032055bda57 - filename: src/transport/proxy.test.ts diff --git a/AGENTS.md b/AGENTS.md index ce18a66..f53e021 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -558,16 +558,17 @@ The approved differences from V1 are these, and only these: with a body) or `ERR_STREAM_ALREADY_FINISHED`, as Node does. An `end()` with no body is Node's own no-op and is not warned about (`res.json(data).end()`). Once a response closes, or when a stream is piped into one that has already ended or whose client has gone, each stream piped into it is - unpiped (if it can be) once `pipe()` has returned. On the next turn a request or upstream body - (`http.IncomingMessage`) is drained, so its connection is freed; a file stream (`fs.ReadStream`) - that nothing else reads is destroyed, so it does not keep its file descriptor open; and a stream - that still has a `'data'` reader is resumed so that reader gets the rest. Any other stream is left - paused, as Node leaves it after an unpipe, for the function to resume or close: a file stream - behind a transform (for example gzip) or a child's stdout then stays open until the function - closes it. If ending the response for the - handler fails (an invalid status, a content-length mismatch), or a handler throws before its - headers were sent, serve logs the error and answers a `cache-control: no-store` 500 without the - headers the handler had set, dropping the connection if even that cannot be sent. + unpiped (if it can be). On the next turn the exchange's own request body is drained, as Node + would dump it, so the connection can serve its next request; a file stream (`fs.ReadStream`) that + nothing else reads is destroyed, so it does not keep its file descriptor open; and a stream that + still has a `'data'` reader is resumed so that reader gets the rest. Any other stream is left + paused, as Node leaves it after an unpipe (a stream piped into an already-ended response is + paused again after `pipe()` resumes it), for the function to resume or close: a file stream or + the request behind a transform (for example gzip), a child's stdout or an upstream body then + stays open, or stalls that keep-alive connection, until the function closes it. If ending the + response for the handler fails (an invalid status, a content-length mismatch), or a handler throws + before its headers were sent, serve logs the error and answers a `cache-control: no-store` 500 + without the headers the handler had set, dropping the connection if even that cannot be sent. So a callback that answers after the handler returned gets an empty response, exactly as on AWS. Because serve wraps `res.sendFile`/`download`/`sendfile` to track them, Express's deprecation warning for the lowercase `res.sendfile` names serve's file, not the function's. Azure and GCP (V1) still diff --git a/src/functions/cloud-functions.test.ts b/src/functions/cloud-functions.test.ts index ed432b1..e6fd507 100644 --- a/src/functions/cloud-functions.test.ts +++ b/src/functions/cloud-functions.test.ts @@ -134,6 +134,7 @@ afterEach(async () => { delete (globalThis as Record).received; delete (globalThis as Record).iterated; delete process.env.LAUNCH_TEST_PAGE; + delete process.env.LAUNCH_TEST_UPSTREAM; }); function toDataURL(source: string): string { @@ -901,10 +902,16 @@ describe('CloudFunctions serve routing', () => { 'foreign.js', 'export default function foreign(request, response) { response.emit("pipe", { unpipe() {} }); response.emit("pipe", { unpipe() {}, listenerCount(event) { return event === "data" ? 1 : 0; } }); response.end("foreign"); }', ); + writeFunctionFile( + 'lateForeign.js', + 'export default function lateForeign(request, response) { response.end("late"); setTimeout(() => { response.emit("pipe", { unpipe() {} }); response.emit("pipe", { unpipe() {}, once(event, listener) { listener(); }, removeListener() {} }); response.emit("pipe", { unpipe() {}, once(event, listener) { listener(); }, removeListener() {}, listenerCount() { return 0; } }); response.emit("pipe", { unpipe() {}, once(event, listener) { listener(); }, removeListener() {}, pause() {} }); response.emit("pipe", { unpipe() {}, pause() {} }); globalThis.lateDone = true; }, 20); }', + ); writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); const port = await freePort(); await new CloudFunctions(workspace).serve(port); + const lateForeign = await sendRequest(port, '/lateForeign'); + await eventually(() => (globalThis as Record).lateDone === true); const legacy = await sendRequest(port, '/legacy'); const modernish = await sendRequest(port, '/modernish'); await eventually(() => (globalThis as Record).lateResult === 'resumed'); @@ -916,6 +923,7 @@ describe('CloudFunctions serve routing', () => { expect(modernish).toMatchObject({ status: 200, body: 'v3' }); expect((globalThis as Record).lateResult).toBe('resumed'); expect(foreign).toMatchObject({ status: 200, body: 'foreign' }); + expect(lateForeign).toMatchObject({ status: 200, body: 'late' }); expect(next).toMatchObject({ status: 200, body: 'alive' }); expect(loggedErrors).toEqual([]); }, 4000); @@ -989,6 +997,71 @@ describe('CloudFunctions serve routing', () => { expect(queue.readableLength).toBe(4); }, 4000); + it('releases a stream piped into an already-ended response at once, so a shared hub writes nothing to it, and re-pauses an endless one', async () => { + writeFunctionFile( + 'lateHub.js', + 'import { PassThrough, Writable } from "node:stream"; export default function lateHub(request, response) { response.end("done"); setTimeout(() => { globalThis.received = []; globalThis.hub = new PassThrough(); globalThis.hub.pipe(new Writable({ write(chunk, encoding, done) { globalThis.received.push(String(chunk)); done(); } })); globalThis.hub.pipe(response); globalThis.hub.write("x"); globalThis.lateDone = true; }, 20); }', + ); + writeFunctionFile( + 'lateEndless.js', + 'import { Readable } from "node:stream"; export default function lateEndless(request, response) { response.end("done"); setTimeout(() => { globalThis.lateResult = 0; globalThis.piped = new Readable({ read() { globalThis.lateResult += 1; this.push(globalThis.lateResult > 10000 ? null : Buffer.alloc(1024)); } }); globalThis.piped.pipe(response); }, 20); }', + ); + writeFunctionFile( + 'lateFlowing.js', + 'import { PassThrough, Writable } from "node:stream"; export default function lateFlowing(request, response) { response.end("done"); const sink = new Writable({ write(chunk, encoding, done) { done(); } }); globalThis.openStream = new PassThrough(); globalThis.openStream.pipe(sink); setTimeout(() => { globalThis.openStream.pipe(response); setTimeout(() => { globalThis.openStream.unpipe(sink); globalThis.openStream.resume(); globalThis.lateDone = true; }, 30); }, 20); }', + ); + writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); + const port = await freePort(); + + await new CloudFunctions(workspace).serve(port); + await sendRequest(port, '/lateFlowing'); + await eventually(() => (globalThis as Record).lateDone === true); + await new Promise((done) => setTimeout(done, 10)); + const ownResume = ((globalThis as Record).openStream as { readableFlowing: boolean | null }).readableFlowing; + await sendRequest(port, '/lateHub'); + await eventually(() => ((globalThis as Record).received as string[] | undefined)?.includes('x') === true); + await new Promise((done) => setTimeout(done, 20)); + ((globalThis as Record).hub as { write: (chunk: string) => void }).write('y'); + await eventually(() => ((globalThis as Record).received as string[]).includes('y')); + await sendRequest(port, '/lateEndless'); + await new Promise((done) => setTimeout(done, 80)); + const next = await sendRequest(port, '/next'); + + expect(ownResume).toBe(true); + expect((globalThis as Record).received).toEqual(['x', 'y']); + expect(loggedLines.filter((line) => line.startsWith('warn: /lateHub'))).toEqual([]); + expect(next).toMatchObject({ status: 200, body: 'alive' }); + expect((globalThis as Record).piped as { readableFlowing: boolean | null }).toMatchObject({ readableFlowing: false }); + expect((globalThis as Record).lateResult).toBeLessThan(100); + }, 4000); + + it('drains only the request of the exchange, and leaves an upstream body piped into the response paused', async () => { + const upstream = createServer((_request, upstreamResponse) => { + upstreamResponse.write('a'); + }); + await new Promise((resolve) => upstream.listen(0, '127.0.0.1', () => resolve())); + process.env.LAUNCH_TEST_UPSTREAM = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}/`; + writeFunctionFile( + 'relay.js', + 'import http from "node:http"; export default function relay(request, response) { response.end("done"); http.get(process.env.LAUNCH_TEST_UPSTREAM, (upstreamBody) => { globalThis.piped = upstreamBody; upstreamBody.pipe(response); globalThis.lateDone = true; }); }', + ); + const port = await freePort(); + + try { + await new CloudFunctions(workspace).serve(port); + const relay = await sendRequest(port, '/relay'); + await eventually(() => (globalThis as Record).lateDone === true); + await new Promise((done) => setTimeout(done, 50)); + + expect(relay).toMatchObject({ status: 200, body: 'done' }); + expect((globalThis as Record).piped as { readableFlowing: boolean | null }).toMatchObject({ readableFlowing: false }); + } finally { + ((globalThis as Record).piped as { destroy?: () => void } | undefined)?.destroy?.(); + upstream.closeAllConnections(); + await new Promise((resolve) => upstream.close(() => resolve())); + } + }, 4000); + it('drains a request body piped into a response it ends, so the keep-alive connection answers the next request', async () => { writeFunctionFile('echoLate.js', 'export default function echoLate(request, response) { request.pipe(response); }'); writeFunctionFile('next.js', 'export default function next(request, response) { response.send("alive"); }'); diff --git a/src/functions/cloud-functions.ts b/src/functions/cloud-functions.ts index 7a93ddf..fa53d01 100755 --- a/src/functions/cloud-functions.ts +++ b/src/functions/cloud-functions.ts @@ -9,7 +9,6 @@ import type { import express from 'express'; import type { Express } from 'express-serve-static-core'; import { ReadStream, existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs'; -import { IncomingMessage } from 'http'; import type { Server } from 'http'; import { isBuiltin } from 'module'; import type { AddressInfo } from 'net'; @@ -197,6 +196,7 @@ const LATE_CHANGE_METHODS = [ ] as const; interface Answering { + request: Readable; requestedUrl: string; handlerReturned: boolean; filesInFlight: number; @@ -222,8 +222,8 @@ function warnLateChange(answering: Answering): void { console.log(styled(warning, 'yellow', process.stdout.isTTY === true)); } -function settleReleased(source: Readable): void { - if (source instanceof IncomingMessage) { +function settleReleased(source: Readable, request: Readable): void { + if (source === request) { source.resume(); return; } @@ -240,12 +240,23 @@ function settleReleased(source: Readable): void { } } -function release(source: Readable, response: Response): void { +function pauseOnResume(source: Readable): void { + if (typeof source.once !== 'function' || typeof source.pause !== 'function') { + return; + } + const pause = (): void => { + source.pause(); + }; + source.once('resume', pause); + setImmediate(() => source.removeListener('resume', pause)); +} + +function release(source: Readable, response: Response, request: Readable): void { if (typeof source.unpipe !== 'function') { return; } source.unpipe(response); - setImmediate(() => settleReleased(source)); + setImmediate(() => settleReleased(source, request)); } function isNoOpEnd(method: string, args: unknown[]): boolean { @@ -335,6 +346,7 @@ function endLikeDeployedFunctions(response: Response, answering: Answering): voi function trackAnswering(request: Request, response: Response): Answering { const answering: Answering = { + request, requestedUrl: request.originalUrl, handlerReturned: false, filesInFlight: 0, @@ -343,14 +355,15 @@ function trackAnswering(request: Request, response: Response): Answering { }; response.on('pipe', (source: Readable) => { if (response.writableEnded || response.destroyed) { - process.nextTick(() => release(source, response)); + release(source, response, request); + pauseOnResume(source); return; } answering.pipedSources.add(source); }); response.once('close', () => { answering.pipedSources.forEach((source) => { - release(source, response); + release(source, response, request); }); }); trackFileAnswers(response, answering); From 738037a9952f3cea33321eafb812d4d27115a84b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:54:46 +0000 Subject: [PATCH 21/21] chore: refresh .talismanrc checksum for AGENTS.md Prose; no credentials. --- .talismanrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.talismanrc b/.talismanrc index 426d8f7..95561ee 100644 --- a/.talismanrc +++ b/.talismanrc @@ -240,7 +240,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: b278cb3dddec26aec4fae9a6897de34bf6aa1f284946efe2d0252c33bca30b44 + checksum: f21023b4c3d85ca532cf5956577f0ebaf340bf99d353b0ee1ce1f0a43a9acf92 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\\)`"