refactor(http): resolve each request once, in the core that already routes it

Both adapters routed every request themselves, and then handle() routed it
again from the same inputs — a four-route app walked its table 2.5 times
per request. Neither side was wrong: an adapter must know the route to
decide whether to read a body, and the core must know it to dispatch.

The cause was the shape of the handoff. NeutralRequest carried an
already-parsed body, so producing one was the adapter's problem, and every
policy that depends on the matched route came with it — these four chains
were written out in server.ts and web.ts character for character:

    matched.def.maxBodyBytes   ?? opts?.limits?.maxBodyBytes ?? 1_000_000
    matched.def.bodyDuplicates ?? opts?.bodyDuplicates       ?? 'last'
    matched.def.maxParts       ?? opts?.limits?.maxParts     ?? 1000
    opts?.limits?.maxBodyBytes ?? 1_000_000

A fifth knob, or one changed default, meant editing both or letting the
runtimes quietly disagree about limits.

Handing over the ability to read rather than the result moves the decision
to where the route is already known. What stays in an adapter is what
genuinely differs between runtimes: getting bytes in, putting bytes out.
Enforcement stays with the reader too, because Node aborts an oversized
upload as chunks arrive while a fetch runtime can only measure what
arrayBuffer() already resolved — passing the limit in preserves that.
413/400/501 keep their exact current shape, Node's connection: close
included; it now has the test it never had.

Measured through app.fetch, both versions in one process, interleaved:
40 routes with the match declared last, 3.89 -> 3.58 us (-8.2%). One
route, where there is no second scan to save, is unchanged.

The first cut of this was 13% SLOWER, and the reason is worth recording:
a per-request closure for the reader plus the error-context object it
captured cost 250 ns, and the async frames around a body that did not
exist cost another 215 ns — together more than the duplicate scan the
whole change removes. The reader is now built once per server and takes
the runtime's request as an argument, and a bodiless request touches no
promise on this path at all.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-08-16 23:46:57 -05:00
1 parent 0c9f8a545e
commit a4bb3c02d6
5 files changed
+262 -201

No files matched your search

+135
View File
@@ -0,0 +1,135 @@
// src/http/body.ts — runtime-neutral body acquisition: limit resolution, parsing, and the failure
// envelope. The one part that is genuinely runtime-specific — getting the bytes — is supplied by
// the caller as a {@link BodyReader}.
import { HttpError, isHttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers';
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
import type { MatchedRoute, HttpOptions } from './types';
/** A ready-to-send error response produced while acquiring the request body. */
export interface BodyFailure {
fail: { status: number; headers: Record<string, string>; body: string };
}
/** A value, or a promise of one. Readers that have nothing to await return the value directly. */
export type MaybePromise<T> = T | Promise<T>;
/** True for the native promises both adapters' readers return; no cross-realm thenables reach here. */
function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
return value instanceof Promise;
}
/**
* Reads the raw request body, enforcing `limit`.
*
* The adapter owns this and nothing else about the body, because enforcement is the one place the
* runtimes legitimately differ: Node checks the running total as chunks arrive and can abort a
* 10 GB upload after 1 MB, while a fetch runtime has only `request.arrayBuffer()` and can check
* `byteLength` after the fact. Passing the limit *in*, rather than measuring the returned buffer
* here, is what keeps Node's incremental abort — measuring afterwards would force it to buffer
* without bound first.
*
* The failure branch is opaque on purpose: Node answers an over-limit request with
* `connection: close`, so the rest of the upload does not keep arriving on a kept-alive socket.
* That header means nothing on the fetch side, and is a forbidden response header on some
* runtimes, so the adapter that needs it is the one that attaches it.
*
* `source` is the runtime's own request object, handed straight back untouched. It exists so the
* reader can be built **once per server** instead of once per request: a closure capturing the
* request measured at 250 ns per request together with the error-context object it captured —
* more than the duplicate route resolution this whole indirection removes.
*/
export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ bytes: Buffer | undefined } | BodyFailure>;
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
type ParseResult = { body: unknown } | { error: string; status?: number };
/**
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
*/
export async function parseRequestBody(
buf: Buffer | undefined,
contentType: string,
duplicates: 'array' | 'last',
maxParts: number,
): Promise<ParseResult> {
if (buf !== undefined && contentType.includes('application/json')) {
try {
return { body: JSON.parse(buf.toString('utf8')) };
} catch {
return { error: 'Invalid JSON body' };
}
}
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
}
if (buf !== undefined && contentType.includes('multipart/form-data')) {
const boundary = extractBoundary(contentType);
if (!boundary) return { error: 'Invalid multipart body' };
try {
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
} catch (error) {
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
if (isHttpError(error)) return { error: error.message, status: error.status };
return { error: 'Invalid multipart body' };
}
}
const text = buf?.toString('utf8');
return { body: text === '' ? undefined : text };
}
/**
* Resolves the body limits for a matched route, reads it through `read`, and parses it.
*
* The four `route ?? server ?? default` chains below used to be written out in both adapters,
* character for character, because each adapter had to route the request itself in order to know
* whether to read a body — and so ended up owning every policy that depends on the matched route.
* Adding a fifth knob, or changing one default, meant changing it in two places or letting the
* runtimes quietly disagree about limits.
*/
export function acquireBody(
read: BodyReader,
source: unknown,
matched: MatchedRoute,
opts: HttpOptions | undefined,
req: ErrorRequest,
): MaybePromise<{ body: unknown } | BodyFailure> {
const limit = matched.def.maxBodyBytes ?? opts?.limits?.maxBodyBytes ?? 1_000_000;
const acquired = read(source, limit);
// Deliberately not `async`. A request with no body — every GET, which is most of them — resolves
// this whole path without a single promise, and an `async` wrapper here would allocate one
// regardless. Same reason `handle()` is not async.
return isPromise(acquired)
? acquired.then((settled) => parseAcquired(settled, matched, opts, req))
: parseAcquired(acquired, matched, opts, req);
}
function parseAcquired(
acquired: { bytes: Buffer | undefined } | BodyFailure,
matched: MatchedRoute,
opts: HttpOptions | undefined,
req: ErrorRequest,
): MaybePromise<{ body: unknown } | BodyFailure> {
if ('fail' in acquired) return acquired;
// `parseRequestBody(undefined, …)` answers `{ body: undefined }` for every content type, so
// there is nothing to parse and nothing to await. Skipping it is what keeps a bodiless request
// off the promise path entirely.
if (acquired.bytes === undefined) return { body: undefined };
const contentType = String(req.headers['content-type'] ?? '');
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) =>
'error' in parsed
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError) }
: { body: parsed.body },
);
}
+50 -11
View File
@@ -5,6 +5,7 @@ import { isStreamResult, type PipelineResult } from '../pipeline';
import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security';
import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
import { pickEncoder } from './stream';
import { acquireBody, type BodyReader } from './body';
import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus';
@@ -16,12 +17,24 @@ import type { Bus } from '../bus';
// have without a compatibility flag.
declare const crypto: { randomUUID(): string };
/** A runtime-neutral inbound request: body already parsed by the caller's ingress (Node stream, fetch Request, …). */
/**
* A runtime-neutral inbound request.
*
* The body arrives as a {@link BodyReader} rather than a value, and that is the whole reason this
* core resolves each request exactly once. When the adapter had to hand over an already-parsed
* body, it first had to route the request itself — a body is only read for a request that reaches
* a handler — so both the adapter and `dispatch` resolved the same route from the same inputs, and
* a four-route app walked its table two and a half times per request. Handing over the *ability*
* to read instead of the result moves that decision here, where the route is known anyway.
*/
export interface NeutralRequest {
method: string;
url: string; // path + query, e.g. "/users/9?x=1"
headers: Record<string, string | string[] | undefined>;
body: unknown; // already-parsed body
/** Called only once a route matches, so an unmatched request still never reads a body. */
readBody: BodyReader;
/** The runtime's own request object, passed back to {@link readBody} untouched and never inspected here. */
source: unknown;
secure: boolean;
ip: string;
requestId: string;
@@ -36,10 +49,10 @@ const first = (value: string | string[] | undefined): string | undefined => (Arr
/**
* Derives a request's identity from its headers, for the adapters to stamp on a `NeutralRequest`.
*
* **Called by the adapters, not by {@link handle}**, and the placement is the point. Both adapters
* read and size-check the body before they reach `handle()` (`server.ts`, `web.ts`), so a `413` is
* answered without `handle()` ever seeing the request. Generating identity in here would leave
* precisely the failures an operator most wants to correlate with nothing to correlate them by.
* **Called by the adapters, not by {@link handle}**, and the placement is the point. An adapter's
* `BodyReader` renders its own `413` (`server.ts`, `web.ts`) without `handle()` ever producing it,
* so identity has to exist before the read starts. Generating it in here would leave precisely the
* failures an operator most wants to correlate with nothing to correlate them by.
*
* An `x-request-id` from a gateway is adopted rather than replaced — a service behind a proxy must
* not open a second identity for a request that already has one. `traceparent` is carried through
@@ -71,7 +84,14 @@ export function correlateRequest(headers: Record<string, string | string[] | und
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
export type NeutralOutcome =
| { kind: 'buffered'; status: number; headers: Record<string, string>; body: string | Buffer }
| { kind: 'stream'; headers: Record<string, string>; stream: AsyncIterable<unknown>; encoder: StreamEncoder };
| {
kind: 'stream';
headers: Record<string, string>;
stream: AsyncIterable<unknown>;
encoder: StreamEncoder;
/** The matched route's pattern, for naming the stream lifecycle events. */
route: string;
};
/** {@link handle}'s result for a normal (non-preflight) request. */
export interface HandleResult {
@@ -106,7 +126,7 @@ function errorOutcome(
opts: HttpOptions | undefined,
headers: Record<string, string> = {},
): HandleResult {
const rendered = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
const rendered = renderError(error, req, opts?.onError);
return {
injected,
outcome: {
@@ -279,6 +299,16 @@ async function dispatch(
traceId: req.traceId,
});
// `req` is passed straight through as the error context: a `NeutralRequest` already has the
// `method`/`url`/`headers` an `ErrorRequest` is, so copying those three fields into a fresh
// object per request bought nothing.
const acquired = await acquireBody(req.readBody, req.source, matched, opts, req);
// The adapter rendered this one itself (a 413 it had to answer while reading), or `acquireBody`
// did (a malformed or unsupported body). Either way it is already the standard envelope, and the
// caller merges `injected` into it exactly as it does for every other outcome.
if ('fail' in acquired) return { injected, outcome: { kind: 'buffered', ...acquired.fail } };
let result: PipelineResult;
try {
@@ -288,19 +318,28 @@ async function dispatch(
headers: req.headers,
params: matched.params,
query: parseQuery(req.url),
body: req.body,
body: acquired.body,
protocol: req.secure ? 'https' : 'http',
ip: req.ip,
requestId: req.requestId,
traceId: req.traceId,
});
} catch (error) {
result = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
result = renderError(error, req, opts?.onError);
}
if (isStreamResult(result)) {
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } };
return {
injected,
outcome: {
kind: 'stream',
headers: encoder.headers,
stream: result.stream,
encoder,
route: matched.def.pattern,
},
};
}
return {
+36 -116
View File
@@ -1,29 +1,23 @@
import type http from 'http';
import type https from 'https';
import { renderError, type ErrorRequest } from '../transformers';
import { isHttpError, HttpError } from '../signals';
import type { Bus } from '../bus';
import { buildSecurityHeaders, resolveCors } from '../security';
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
import { normalizeRequestPath, resolveRoute } from './router';
import { readBody, deriveSecure, deriveIp } from './request';
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream';
import { attachWs } from './ws';
import { mergeInjectedHeaders } from './headers';
import { handle, correlateRequest } from './core';
import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types';
import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
interface HandlerConfig {
routes: RouteDef[];
bus?: Bus;
opts?: HttpOptions;
maxBody: number;
trustProxy: boolean;
}
/** A ready-to-send error response produced while acquiring the request body. */
type BodyFailure = { fail: { status: number; headers: Record<string, string>; body: string } };
/** Builds the {@link ErrorRequest} handed to a user error renderer. */
function errorRequest(req: http.IncomingMessage): ErrorRequest {
return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers };
@@ -44,9 +38,8 @@ export function createHttpServer(
meshControl?: MeshControl,
opts?: HttpOptions,
): http.Server {
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
const trustProxy = opts?.trustProxy ?? false;
const handler = createRequestHandler({ routes, bus, opts, maxBody, trustProxy });
const handler = createRequestHandler({ routes, bus, opts, trustProxy });
// Node http/https are loaded lazily so importing createApp stays edge/workerd-safe
// (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen().
@@ -70,18 +63,18 @@ export function createHttpServer(
/**
* Builds the request listener: a thin Node adapter around the runtime-neutral {@link handle} core.
* Reads the body (Node-specific), delegates security/CORS/routing/error-rendering to `handle()`,
* then writes the result to `res` (buffered or streamed). The security-header monkeypatch is
* installed here — and stays the single source of truth for merging headers into every response —
* so `handle()`'s own `injected` is intentionally unused by this adapter.
* Describes the request, supplies the {@link BodyReader} the core calls once a route matches, then
* writes the result to `res` (buffered or streamed). Routing, body parsing, limits and error
* rendering all live in the core. The security-header monkeypatch is installed here — and stays the
* single source of truth for merging headers into every response — so `handle()`'s own `injected`
* is intentionally unused by this adapter.
*/
function createRequestHandler(cfg: HandlerConfig) {
const { routes, bus, opts, maxBody, trustProxy } = cfg;
const { routes, bus, opts, trustProxy } = cfg;
// Built once per server, not once per request — see `BodyReader`.
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
const url = req.url ?? '/';
const path = url.split('?')[0];
const method = req.method ?? 'GET';
// Install the security-header patch BEFORE any routing/response so every path
// (200, 404, error, stream) writes headers through the same patched writeHead.
const secure = deriveSecure(req, trustProxy);
@@ -94,37 +87,13 @@ function createRequestHandler(cfg: HandlerConfig) {
// by reference at writeHead time, so keys added here still land on every response.
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
// Mirror handle()'s own preflight/route-match decision here, so we only read the body
// (below) for a request that actually reaches a route handler — matching prior behaviour.
const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']);
let matched: ReturnType<typeof resolveRoute>;
try {
matched = isPreflight ? undefined : resolveRoute(routes, method, normalizeRequestPath(path));
} catch {
matched = undefined; // handle() owns the standard 400 envelope and injected headers
}
let body: unknown;
if (matched) {
const acquired = await acquireBody(req, matched, opts, maxBody);
if ('fail' in acquired) {
res.writeHead(acquired.fail.status, acquired.fail.headers);
res.end(acquired.fail.body);
return;
}
body = acquired.body;
}
const result = await handle(routes, opts, {
...correlation,
method,
url,
method: req.method ?? 'GET',
url: req.url ?? '/',
headers: req.headers,
body,
readBody,
source: req,
secure,
ip: deriveIp(req, trustProxy),
});
@@ -136,7 +105,7 @@ function createRequestHandler(cfg: HandlerConfig) {
}
if (result.outcome.kind === 'stream') {
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, matched?.def.pattern, opts?.streams);
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, result.outcome.route, opts?.streams);
return;
}
@@ -145,34 +114,27 @@ function createRequestHandler(cfg: HandlerConfig) {
};
}
/** Reads and parses the request body, returning `{ body }` or a ready-to-send `{ fail }` error response. */
async function acquireBody(
req: http.IncomingMessage,
matched: MatchedRoute,
/**
* The Node half of body acquisition: bytes off the socket, and the over-limit answer.
*
* `readBody` enforces the limit against the running total as chunks arrive, so an oversized upload
* is rejected without being buffered. `connection: close` on that response is load-bearing — it
* stops the remainder of the upload from continuing to arrive on a kept-alive socket.
*/
function readRequestBytes(
source: unknown,
limit: number,
opts: HttpOptions | undefined,
maxBody: number,
): Promise<{ body: unknown } | BodyFailure> {
let buf: Buffer | undefined;
const bodyLimit = matched.def.maxBodyBytes ?? maxBody; // per-route override falls back to the server default
): Promise<{ bytes: Buffer | undefined } | BodyFailure> {
const req = source as http.IncomingMessage;
try {
buf = await readBody(req, bodyLimit);
} catch (error) {
const rendered = renderError(error, errorRequest(req), opts?.onError);
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
}
const contentType = String(req.headers['content-type'] ?? '');
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts);
if ('error' in parsed) {
const rendered = renderError(new HttpError(parsed.status ?? 400, parsed.error), errorRequest(req), opts?.onError);
return { fail: rendered };
}
return { body: parsed.body };
return readBodyBytes(req, limit).then(
(bytes) => ({ bytes }),
(error: unknown) => {
const rendered = renderError(error, errorRequest(req), opts?.onError);
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
},
);
}
/**
@@ -189,45 +151,3 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record<string,
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
};
}
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
type ParseResult = { body: unknown } | { error: string; status?: number };
/**
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
*/
export async function parseRequestBody(
buf: Buffer | undefined,
contentType: string,
duplicates: 'array' | 'last',
maxParts: number,
): Promise<ParseResult> {
if (buf !== undefined && contentType.includes('application/json')) {
try {
return { body: JSON.parse(buf.toString('utf8')) };
} catch {
return { error: 'Invalid JSON body' };
}
}
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
}
if (buf !== undefined && contentType.includes('multipart/form-data')) {
const boundary = extractBoundary(contentType);
if (!boundary) return { error: 'Invalid multipart body' };
try {
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
} catch (error) {
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
if (isHttpError(error)) return { error: error.message, status: error.status };
return { error: 'Invalid multipart body' };
}
}
const text = buf?.toString('utf8');
return { body: text === '' ? undefined : text };
}
+37 -74
View File
@@ -1,11 +1,10 @@
import type { StreamEncoder } from '../encoders';
import { handle, computeInjected, correlateRequest, type HandleResult } from './core';
import { mergeInjectedHeaders } from './headers';
import { parseRequestBody } from './server';
import { normalizeRequestPath, resolveRoute } from './router';
import type { BodyFailure, BodyReader, MaybePromise } from './body';
import { HttpError } from '../signals';
import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers';
import type { RouteDef, HttpOptions, MatchedRoute } from './types';
import { renderError, type ErrorRequest } from '../transformers';
import type { RouteDef, HttpOptions } from './types';
/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */
export function asReadableStream(source: AsyncIterable<unknown>, encoder: StreamEncoder): ReadableStream<Uint8Array> {
@@ -44,60 +43,36 @@ function headersToRecord(headers: Headers): Record<string, string> {
}
/**
* Turns a rendered error (or any {status, headers, body}) into a web `Response`, merging in the
* authoritative `injected` security/CORS headers — mirrors the Node adapter, where
* `patchResponseHeaders` installs these before body acquisition even runs, so early failures
* (413/400/501) carry them too.
* The fetch half of body acquisition: bytes out of the `Request`, and the over-limit answer.
*
* Unlike Node, there is no incremental read to abort — `arrayBuffer()` resolves with the whole body
* or not at all, so the limit can only be checked once the bytes are already in memory. That
* difference is exactly why the limit is passed in rather than applied by the shared core.
*/
function errorResponse(rendered: ErrorResponse, injected: Record<string, string>): Response {
const headers = mergeInjectedHeaders(rendered.headers, injected);
return new Response(rendered.body, { status: rendered.status, headers });
}
/**
* Reads and parses a matched request's body (enforcing `maxBodyBytes` → 413), mirroring the Node
* adapter's `acquireBody`. Returns `{ body }` on success, or a ready-to-send `{ response }` on failure.
*/
async function acquireFetchBody(
request: Request,
matched: MatchedRoute,
headers: Record<string, string>,
path: string,
maxBody: number,
function readFetchBytes(
source: unknown,
limit: number,
opts: HttpOptions | undefined,
injected: Record<string, string>,
): Promise<{ body: unknown } | { response: Response }> {
const errReq: ErrorRequest = { method: request.method, url: path, headers };
let buf: Buffer | undefined;
): MaybePromise<{ bytes: Buffer | undefined } | BodyFailure> {
const request = source as Request;
// Not `async`: a bodiless request answers without allocating a promise at all.
if (!request.body) return { bytes: undefined };
if (request.body) {
const arrayBuffer = await request.arrayBuffer();
const bodyLimit = matched.def.maxBodyBytes ?? maxBody;
if (arrayBuffer.byteLength > bodyLimit) {
return {
response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError), injected),
return request.arrayBuffer().then((arrayBuffer) => {
if (arrayBuffer.byteLength > limit) {
// Rebuilt here rather than captured per request: only an over-limit body ever needs it, and
// a `url`/`headers` pair captured up-front cost more than the work it saved.
const url = new URL(request.url);
const errReq: ErrorRequest = {
method: request.method,
url: url.pathname + url.search,
headers: headersToRecord(request.headers),
};
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError) };
}
buf = arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer);
}
const contentType = headers['content-type'] ?? '';
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts);
if ('error' in parsed) {
return {
response: errorResponse(
renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError),
injected,
),
};
}
return { body: parsed.body };
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
});
}
/**
@@ -144,11 +119,14 @@ function outcomeToResponse(result: HandleResult): Response {
/**
* Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses:
* reads the body (enforcing `maxBodyBytes` → 413), parses it by content type, runs it through the
* runtime-neutral {@link handle}, and converts the outcome to a `Response` (buffered or streamed).
* describes the request for the runtime-neutral {@link handle}, supplies the {@link BodyReader} it
* calls once a route matches, and converts the outcome to a `Response` (buffered or streamed).
* Routing, body parsing, limits and error rendering all live in the core; this file is the part
* that knows how to get bytes out of a `Request` and how to put them into a `Response`.
*/
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
// Built once per server, not once per request — see `BodyReader`.
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
return async (request: Request): Promise<Response> => {
const url = new URL(request.url);
@@ -156,33 +134,18 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
const headers = headersToRecord(request.headers);
// Derived before the body is read, so a 413 rejected below still carries an identity.
const correlation = correlateRequest(headers);
let matched: ReturnType<typeof resolveRoute>;
try {
matched = resolveRoute(routes, request.method, normalizeRequestPath(url.pathname));
} catch {
matched = undefined; // handle() renders the shared 400 response without reading a body
}
const secure = url.protocol === 'https:';
// Computed up-front from the same inputs `handle()` uses, so early-failure responses (413/400/501,
// before a route handler even runs) carry the same security/CORS headers Node's writeHead patch
// would have installed before body acquisition.
// Computed up-front from the same inputs `handle()` uses, so a preflight — the one response
// this adapter builds itself — carries the same security/CORS headers every other one does.
const injected = computeInjected(opts, { secure, headers });
let body: unknown;
if (matched) {
const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts, injected);
if ('response' in acquired) return acquired.response;
body = acquired.body;
}
const result = await handle(routes, opts, {
...correlation,
method: request.method,
url: path,
headers,
body,
readBody,
source: request,
secure,
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is
// trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket
+4
View File
@@ -112,6 +112,10 @@ describe('request hardening', () => {
const res = await fetch(`${getUrl(server)}/echo`, { method: 'POST', body: 'x'.repeat(1000) });
expect(res.status).toBe(413);
expect(ran).toBe(false);
// Load-bearing, not cosmetic: without it the rest of the upload keeps arriving on a
// kept-alive socket after the response. Node-only — `Connection` is a forbidden response
// header on the fetch side, which is why the adapter attaches it rather than the shared core.
expect(res.headers.get('connection')).toBe('close');
server.close();
});