From 8b67b1a46c31e6b47c2f0fad54183aaebcd30954 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Mon, 26 Oct 2026 08:02:03 -0500 Subject: [PATCH 1/4] perf(http): trim per-request work on the Node path Profiling the validate (POST) bench route against 4d1639f showed the loss since then spread over several small costs on the Node request path rather than one regression. This removes the ones that do not change behaviour: - readBody reads with data/end/error/close listeners instead of `for await`, whose async iterator costs a promise and a microtask per chunk. It keeps the iterator's semantics: the running total enforces the limit, an over-limit body destroys the request as leaving the loop did, an error or a close before `end` rejects (the latter with ERR_STREAM_PREMATURE_CLOSE), and the declared-length 413 is still a rejection rather than a synchronous throw. A single chunk is returned without Buffer.concat. - writeResult is no longer async. A buffered response without compression is written synchronously and returns nothing to await; only a stream or a compressed body returns a promise, which serve awaits, so a failure still reaches failSafe. The compression request object is not built when compression is off. - declaresOverLimit compares the number first and runs its /^\d+$/ shape test only when the length is over the limit. The `serve().catch(failSafe)` wrapper stays: it is the #108 guarantee, and handle() is asynchronous, so there is no synchronous path to skip. Local A/B against 74faa55 (5 s x 4 rounds, macOS, indicative only): validate (POST) +4.6%. test/read-body.test.ts pins readBody's semantics: joining, empty body, 413 with destroy, declared-length 413, stream error and premature close. Signed-off-by: Diego Resendez --- CHANGELOG.md | 7 +++++ src/http/body.ts | 4 ++- src/http/request.ts | 59 +++++++++++++++++++++++++++++++++++------- src/http/server.ts | 44 ++++++++++++++++++------------- test/read-body.test.ts | 48 ++++++++++++++++++++++++++++++++++ 5 files changed, 133 insertions(+), 29 deletions(-) create mode 100644 test/read-body.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index e1d7d7d..fcea17c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -272,6 +272,13 @@ npm treats versions as semver and semver forbids leading zeros. introspection routes (`devGraph`, `devOpenapi`) now sit before remote routes in that table, so in the one case where a teapot exports the same path at the same specificity, the dev route wins. +- **The Node request path does less per request.** A JSON `POST` reads its body with stream + listeners instead of `for await`, which cost a promise and a microtask per chunk; the response is + written without an `async` wrapper when nothing needs awaiting, and without building the + compression request when compression is off; the `content-length` limit check runs its shape test + only for a body that would be refused. Behaviour is unchanged: the same `413`s, the same + rejection when a client goes away mid-body. + ### Deprecated - **The `Headers` type** (D19). Import `RequestHeaders` instead: same type, a name that does not diff --git a/src/http/body.ts b/src/http/body.ts index 0808d46..0a3f59c 100644 --- a/src/http/body.ts +++ b/src/http/body.ts @@ -46,7 +46,9 @@ export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ byte * and the running total still enforces the limit on whatever actually arrives. */ export function declaresOverLimit(contentLength: string | null | undefined, limit: number): boolean { - return contentLength != null && /^\d+$/.test(contentLength) && Number(contentLength) > limit; + // The numeric test first: nearly every request is under the limit, so the shape check below runs + // only for the rare one that would be refused. + return contentLength != null && Number(contentLength) > limit && /^\d+$/.test(contentLength); } /** diff --git a/src/http/request.ts b/src/http/request.ts index 9834d59..67a0b21 100644 --- a/src/http/request.ts +++ b/src/http/request.ts @@ -3,21 +3,60 @@ import { HttpError } from '../signals'; import { declaresOverLimit } from './body'; /** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */ -export async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise { +export function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise { // A declared length over the limit is refused without waiting for the first chunk, which could // otherwise sit until the request timeout. The fetch adapter makes the same check. - if (declaresOverLimit(req.headers['content-length'], maxBodyBytes)) throw new HttpError(413, 'Payload Too Large'); + if (declaresOverLimit(req.headers['content-length'], maxBodyBytes)) + return Promise.reject(new HttpError(413, 'Payload Too Large')); - const chunks: Buffer[] = []; - let total = 0; + // Listeners rather than `for await`: the async iterator costs a promise and a microtask per chunk, + // which a JSON POST pays on every request. The semantics are the iterator's: the running total + // still enforces the limit, an over-limit body destroys the request as leaving the loop did, and a + // stream that errors or closes before `end` rejects. + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + let total = 0; - for await (const chunk of req) { - total += (chunk as Buffer).length; - if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large'); - chunks.push(chunk as Buffer); - } + const settle = (): void => { + req.off('data', onData); + req.off('end', onEnd); + req.off('error', onError); + req.off('close', onClose); + }; - return chunks.length === 0 ? undefined : Buffer.concat(chunks); + const onData = (chunk: Buffer): void => { + total += chunk.length; + + if (total <= maxBodyBytes) { + chunks.push(chunk); + return; + } + + settle(); + req.destroy(); + reject(new HttpError(413, 'Payload Too Large')); + }; + + const onEnd = (): void => { + settle(); + resolve(chunks.length === 0 ? undefined : chunks.length === 1 ? chunks[0] : Buffer.concat(chunks)); + }; + + const onError = (err: Error): void => { + settle(); + reject(err); + }; + + const onClose = (): void => { + settle(); + reject(Object.assign(new Error('Premature close'), { code: 'ERR_STREAM_PREMATURE_CLOSE' })); + }; + + req.on('data', onData); + req.on('end', onEnd); + req.on('error', onError); + req.on('close', onClose); + }); } /** Returns the first comma-separated token of a header value (handles array-valued headers). */ diff --git a/src/http/server.ts b/src/http/server.ts index 29c0283..499966d 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -15,6 +15,7 @@ import { watchingRequests, type HandleResult, type Preflight, + type NeutralOutcome, } from './core'; import type { BodyFailure, BodyReader } from './body'; import type { RouteTable, WsRouteDef, MeshControl, HttpOptions } from './types'; @@ -184,44 +185,51 @@ function createRequestHandler(cfg: HandlerConfig) { } } - await writeResult(req, res, result, { opts, bus, correlation }); + const written = writeResult(req, res, result, { opts, bus, correlation }); + if (written) await written; } } /** * Writes what `handle()` produced: a preflight, or an outcome after `compressOutcome` (CARD-16). * Module scope rather than inside `serve`, whose closure would charge every branch here again. + * + * Deliberately not `async`, like `handle()`: a buffered response without compression is written + * synchronously and returns nothing to await, so the common request allocates no promise here. + * Only a stream, or a compressed body, returns one. */ -async function writeResult( +function writeResult( req: http.IncomingMessage, res: http.ServerResponse, result: HandleResult | Preflight, ctx: { opts: HttpOptions | undefined; bus: Bus | undefined; correlation: Correlation }, -): Promise { - const { opts, bus, correlation } = ctx; - +): Promise | undefined { if ('preflight' in result) { res.writeHead(204, result.preflight); res.end(); - return; + return undefined; } - // Not awaited unless compression actually returned a promise: an app without it keeps the - // synchronous write it had. - const decided = compressOutcome( - opts?.compression, - { method: req.method ?? 'GET', headers: req.headers }, - result.outcome, - ); - const outcome = decided instanceof Promise ? await decided : decided; + const compression = ctx.opts?.compression; + if (!compression) return writeOutcome(res, result.outcome, ctx); - if (outcome.kind === 'stream') { - await pipeStream(res, outcome, bus, opts?.streams, correlation); - return; - } + const decided = compressOutcome(compression, { method: req.method ?? 'GET', headers: req.headers }, result.outcome); + return decided instanceof Promise + ? decided.then((outcome) => writeOutcome(res, outcome, ctx)) + : writeOutcome(res, decided, ctx); +} + +/** Pipes a stream (returning its promise) or writes a buffered outcome in one go (returning nothing). */ +function writeOutcome( + res: http.ServerResponse, + outcome: NeutralOutcome, + ctx: { opts: HttpOptions | undefined; bus: Bus | undefined; correlation: Correlation }, +): Promise | undefined { + if (outcome.kind === 'stream') return pipeStream(res, outcome, ctx.bus, ctx.opts?.streams, ctx.correlation); res.writeHead(outcome.status, outcome.headers); res.end(outcome.body); + return undefined; } /** diff --git a/test/read-body.test.ts b/test/read-body.test.ts new file mode 100644 index 0000000..927762d --- /dev/null +++ b/test/read-body.test.ts @@ -0,0 +1,48 @@ +// readBody reads with listeners instead of `for await`; these pin the iterator's semantics it keeps. +import { describe, expect, it } from 'vitest'; +import { PassThrough } from 'node:stream'; +import type http from 'node:http'; +import { readBody } from '../src/http/request'; + +const request = (headers: Record = {}) => + Object.assign(new PassThrough(), { headers }) as unknown as http.IncomingMessage & PassThrough; + +describe('readBody', () => { + it('joins every chunk, and answers undefined for an empty body', async () => { + const req = request(); + const read = readBody(req, 100); + req.write('ab'); + req.end('cd'); + expect((await read)?.toString()).toBe('abcd'); + + const empty = request(); + const none = readBody(empty, 100); + empty.end(); + expect(await none).toBeUndefined(); + }); + + it('a body over the limit rejects 413 and destroys the request', async () => { + const req = request(); + const read = readBody(req, 3); + req.write('abcd'); + await expect(read).rejects.toMatchObject({ status: 413 }); + expect(req.destroyed).toBe(true); + }); + + it('a declared content-length over the limit rejects without reading', async () => { + await expect(readBody(request({ 'content-length': '10' }), 3)).rejects.toMatchObject({ status: 413 }); + }); + + it('a stream error or a close before end rejects', async () => { + const failing = request(); + const read = readBody(failing, 100); + failing.destroy(new Error('boom')); + await expect(read).rejects.toThrow('boom'); + + const closed = request(); + const cut = readBody(closed, 100); + closed.write('ab'); + closed.destroy(); + await expect(cut).rejects.toMatchObject({ code: 'ERR_STREAM_PREMATURE_CLOSE' }); + }); +}); From 704622cf656096403bfb51be8479b6dc84998935 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Mon, 26 Oct 2026 13:23:55 -0500 Subject: [PATCH 2/4] bench(compare): add compression cases to the A/B harness The A/B harness had no case with compression on, so a change to the response write path was measured only on its uncompressed branch. Add an 8 KB JSON response uncompressed, identity-negotiated, gzip and br, plus a small response under the threshold with compression enabled. Signed-off-by: Diego Resendez --- bench/compare.ts | 9 +++++++++ bench/servers/compare.ts | 7 +++++++ 2 files changed, 16 insertions(+) diff --git a/bench/compare.ts b/bench/compare.ts index 4b0d46a..4af6ff3 100644 --- a/bench/compare.ts +++ b/bench/compare.ts @@ -75,6 +75,15 @@ const CASES: Case[] = [ // all-static, so it takes the full scan rather than the early exit a literal path gets. { name: 'param, 50 routes', path: '/users/42', env: { GT_ROUTES: '50' } }, { name: 'param, 200 routes', path: '/users/42', env: { GT_ROUTES: '200' } }, + // Compression (CARD-16). `json 8KB uncompressed` is the same response uncompressed, so each compressed case + // has its own baseline in the table. `hello + compression` sits under the threshold: the cost of + // deciding not to encode, which is what most small responses pay once compression is on. Without + // `accept-encoding`, the 8 KB case measures negotiation alone. + { name: 'json 8KB uncompressed', path: '/big' }, + { name: 'hello + compression', path: '/hello', env: { GT_COMPRESS: '1' }, headers: { 'accept-encoding': 'gzip, br' } }, + { name: 'json 8KB + compression, identity', path: '/big', env: { GT_COMPRESS: '1' } }, + { name: 'json 8KB + gzip', path: '/big', env: { GT_COMPRESS: '1' }, headers: { 'accept-encoding': 'gzip' } }, + { name: 'json 8KB + br', path: '/big', env: { GT_COMPRESS: '1' }, headers: { 'accept-encoding': 'br' } }, ]; const ONLY = process.env.AB_ONLY; diff --git a/bench/servers/compare.ts b/bench/servers/compare.ts index 4ba044b..e8f4ac5 100644 --- a/bench/servers/compare.ts +++ b/bench/servers/compare.ts @@ -18,12 +18,17 @@ function makeStep(n: number) { } const steps = [1, 2, 3, 4, 5].map(makeStep); +// ~8 KB of JSON: well over the 1024-byte compression threshold, and repetitive the way list +// responses are, so the encoders do real work rather than bailing out on incompressible input. +const BIG = Array.from({ length: 120 }, (_, i) => ({ id: i, name: `user ${i}`, email: `user${i}@example.com`, active: i % 2 === 0 })); + @Route('/') class Bench { @Get('/hello') hello() { return { hello: 'world' }; } @Get('/users/:id') user(@param('id') id: string) { return { id }; } @Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; } @Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; } + @Get('/big') big() { return BIG; } @Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; } // Reads the counter without resetting it — the read itself carries no Origin, so it cannot // change what it reports. @@ -68,10 +73,12 @@ const cors = } : undefined; +// Only passed when asked for, so the file still boots against a revision without compression. const app = createApp({ modules: [BenchModule], security: process.env.GT_SECURE === '1', ...(cors ? { cors } : {}), + ...(process.env.GT_COMPRESS === '1' ? { compression: true } : {}), }); async function main() { From 88be9b1cb27f3462e7f8208c8cca68f80812af4b Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Mon, 26 Oct 2026 22:48:15 -0500 Subject: [PATCH 3/4] perf(http): skip the body stream for a request without a body On Node every request goes through readBody, GET included. Subscribing listeners to an empty request stream measured ~4% slower than the old async iterator on an 8 KB GET response, in both orders on jarvis. A request with no Transfer-Encoding and no or a zero Content-Length has no body (RFC 9112 6.3), so resolve undefined without touching the stream. Node drains the unread request when the response ends. Signed-off-by: Diego Resendez --- src/http/request.ts | 11 +++++++++-- test/read-body.test.ts | 11 ++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/http/request.ts b/src/http/request.ts index 67a0b21..a3c0333 100644 --- a/src/http/request.ts +++ b/src/http/request.ts @@ -6,8 +6,15 @@ import { declaresOverLimit } from './body'; export function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise { // A declared length over the limit is refused without waiting for the first chunk, which could // otherwise sit until the request timeout. The fetch adapter makes the same check. - if (declaresOverLimit(req.headers['content-length'], maxBodyBytes)) - return Promise.reject(new HttpError(413, 'Payload Too Large')); + const contentLength = req.headers['content-length']; + if (declaresOverLimit(contentLength, maxBodyBytes)) return Promise.reject(new HttpError(413, 'Payload Too Large')); + + // No `Transfer-Encoding` and no (or a zero) `Content-Length` is a request without a body (RFC 9112 + // §6.3) — every GET. Node's parser has already finished it, so there is nothing to wait for, and + // subscribing to the stream anyway measured ~4% on an 8 KB GET response. Node drains the unread + // request itself when the response ends. + if (req.headers['transfer-encoding'] === undefined && (contentLength === undefined || contentLength === '0')) + return Promise.resolve(undefined); // Listeners rather than `for await`: the async iterator costs a promise and a microtask per chunk, // which a JSON POST pays on every request. The semantics are the iterator's: the running total diff --git a/test/read-body.test.ts b/test/read-body.test.ts index 927762d..411ee8c 100644 --- a/test/read-body.test.ts +++ b/test/read-body.test.ts @@ -4,7 +4,8 @@ import { PassThrough } from 'node:stream'; import type http from 'node:http'; import { readBody } from '../src/http/request'; -const request = (headers: Record = {}) => +// Chunked by default: a request with neither header has no body and never touches the stream. +const request = (headers: Record = { 'transfer-encoding': 'chunked' }) => Object.assign(new PassThrough(), { headers }) as unknown as http.IncomingMessage & PassThrough; describe('readBody', () => { @@ -21,6 +22,14 @@ describe('readBody', () => { expect(await none).toBeUndefined(); }); + it('a request without a body resolves undefined without subscribing to the stream', async () => { + for (const headers of [{}, { 'content-length': '0' }] as Record[]) { + const req = request(headers); + expect(await readBody(req, 100)).toBeUndefined(); + expect(req.listenerCount('data')).toBe(0); + } + }); + it('a body over the limit rejects 413 and destroys the request', async () => { const req = request(); const read = readBody(req, 3); From d626fadbfdd8f07405bf8e89a4f2e1a0430d3cbc Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 27 Oct 2026 00:31:50 -0500 Subject: [PATCH 4/4] docs(changelog): note the bodiless-request fast path Signed-off-by: Diego Resendez --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fcea17c..ca24875 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -272,7 +272,9 @@ npm treats versions as semver and semver forbids leading zeros. introspection routes (`devGraph`, `devOpenapi`) now sit before remote routes in that table, so in the one case where a teapot exports the same path at the same specificity, the dev route wins. -- **The Node request path does less per request.** A JSON `POST` reads its body with stream +- **The Node request path does less per request.** A request without a body (no + `Transfer-Encoding`, no or a zero `Content-Length`, RFC 9112 §6.3), which is every `GET`, no + longer touches the request stream at all. A JSON `POST` reads its body with stream listeners instead of `for await`, which cost a promise and a microtask per chunk; the response is written without an `async` wrapper when nothing needs awaiting, and without building the compression request when compression is off; the `content-length` limit check runs its shape test