perf(http): trim per-request work on the Node path
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 19s
CI / build (pull_request) Successful in 28s
CI / runtimes (edge) (pull_request) Successful in 23s
CI / runtimes (deno) (pull_request) Successful in 32s

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 <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-26 08:02:03 -05:00
1 parent 74faa55f41
commit 8b67b1a46c
5 files changed
+133 -29

No files matched your search

+49 -10
View File
@@ -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<Buffer | undefined> {
export function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
// 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<Buffer | undefined>((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). */