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:
5 files changed
+262
-201
No files matched your search
+37
-74
@@ -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
|
||||
|
||||
Reference in new issue
Block a user