Node 18 and Node 20 are end-of-life and receive no security patches, so supporting them before RC.1 would mean promising a runtime nobody can patch. Node 22 is the oldest line still maintained. engines.node moves to >=22, @types/node to ^22, the tsup target to node22, and CI's build job from Node 18 to 22, so every workflow now runs Node 22 only. The docs, the bug report example and the comments that stated 18 as the floor follow. The node:crypto fallback in the HTTP core existed only for Node 18, which lacked the global crypto; it goes with its regression test, which said as much. The ws fallback for the WebSocket client stays: Node 22 has the global, but it can still be switched off with a flag. Moving off Node 18 and 20 also unblocks vitest 4, which the remaining dev audit advisories need. BREAKING CHANGE: Node 18 and Node 20 are no longer supported. The minimum is Node 22. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
424 lines
16 KiB
TypeScript
424 lines
16 KiB
TypeScript
// src/http/core.ts — runtime-neutral request handling core, shared by the Node adapter and (later) app.fetch.
|
|
import { HttpError, NotFound } from '../signals';
|
|
import { renderError } from '../transformers';
|
|
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';
|
|
|
|
/**
|
|
* `randomUUID` from the web-standard global, which every supported runtime exposes without a flag:
|
|
* Node (the `engines` floor is 22; the global arrived unflagged in 19), Deno, Bun and workerd.
|
|
*
|
|
* Node 18 lacked it, and this used to fall back to `node:crypto` there. That fallback went with the
|
|
* Node 18 floor.
|
|
*/
|
|
const randomUUID = (): string => crypto.randomUUID();
|
|
|
|
/**
|
|
* 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>;
|
|
/** 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;
|
|
traceId?: string;
|
|
}
|
|
|
|
// Module scope, not a local inside `correlateRequest`. Declared there it was a closure allocated
|
|
// on every single request, which measured at 0.16 us against a ~4.4 us one — 45% of the whole
|
|
// observability overhead, for a helper that captures nothing.
|
|
const first = (value: string | string[] | undefined): string | undefined => (Array.isArray(value) ? value[0] : value);
|
|
|
|
/**
|
|
* 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. 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
|
|
* untouched: core implements no propagation spec, and W3C Trace Context belongs to the exporter.
|
|
*/
|
|
export function correlateRequest(headers: Record<string, string | string[] | undefined>): {
|
|
requestId: string;
|
|
traceId?: string;
|
|
} {
|
|
const incoming = first(headers['x-request-id'])?.trim();
|
|
const traceId = first(headers.traceparent)?.trim();
|
|
|
|
// `randomUUID` is not the lazy choice here, it is the measured one. Every supported runtime
|
|
// already batches entropy behind it, so the obvious "faster" replacements are not:
|
|
//
|
|
// crypto.randomUUID() 76 ns
|
|
// batched getRandomValues + hex, 12 bytes 50 ns cross-runtime, saves 0.26% of a request
|
|
// batched + Buffer.toString('hex') 49 ns Node-only, so it cannot be used here
|
|
// uint32 -> toString(36) from a pool 114 ns
|
|
// Math.random() x2 -> base36 265 ns 3.5x SLOWER; string work dominates
|
|
// getRandomValues per call, unbatched 472 ns
|
|
//
|
|
// The only cross-runtime win is 26 ns, against ~10.19 us for a real socketed request. A hand-
|
|
// rolled entropy pool is not worth 0.26%. A lazy getter is separately useless: the adapters and
|
|
// the payload builders both spread this object, and the first spread materialises it.
|
|
return { requestId: incoming || randomUUID(), traceId: traceId || undefined };
|
|
}
|
|
|
|
/** 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;
|
|
/** 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 {
|
|
injected: Record<string, string>;
|
|
outcome: NeutralOutcome;
|
|
}
|
|
|
|
/** {@link handle}'s result for a CORS preflight: the caller must answer with 204 + these headers. */
|
|
export interface Preflight {
|
|
preflight: Record<string, string>;
|
|
}
|
|
|
|
/**
|
|
* Computes the security + CORS headers that get injected into every response for a request — the same
|
|
* authoritative set {@link handle} applies to its outcomes. Shared with `buildFetch` (src/http/web.ts)
|
|
* so early-failure responses (413/400/501, before a route even matches) carry the same headers Node's
|
|
* `patchResponseHeaders` would have installed up-front.
|
|
*/
|
|
export function computeInjected(
|
|
opts: HttpOptions | undefined,
|
|
req: { secure: boolean; headers: Record<string, string | string[] | undefined> },
|
|
): Record<string, string> {
|
|
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) };
|
|
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req, opts.logger));
|
|
return injected;
|
|
}
|
|
|
|
function errorOutcome(
|
|
error: unknown,
|
|
req: NeutralRequest,
|
|
injected: Record<string, string>,
|
|
opts: HttpOptions | undefined,
|
|
headers: Record<string, string> = {},
|
|
): HandleResult {
|
|
const rendered = renderError(error, req, opts?.onError, opts?.logger);
|
|
return {
|
|
injected,
|
|
outcome: {
|
|
kind: 'buffered',
|
|
status: rendered.status,
|
|
headers: { ...rendered.headers, ...headers },
|
|
body: req.method === 'HEAD' ? '' : rendered.body,
|
|
},
|
|
};
|
|
}
|
|
|
|
async function unmatchedOutcome(
|
|
routes: RouteDef[],
|
|
opts: HttpOptions | undefined,
|
|
req: NeutralRequest,
|
|
path: string,
|
|
injected: Record<string, string>,
|
|
): Promise<HandleResult> {
|
|
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
|
|
const hit = await opts.static(path);
|
|
|
|
if (hit) {
|
|
return {
|
|
injected,
|
|
outcome: {
|
|
kind: 'buffered',
|
|
status: 200,
|
|
headers: { 'content-type': hit.contentType },
|
|
body: req.method === 'HEAD' ? '' : hit.body,
|
|
},
|
|
};
|
|
}
|
|
}
|
|
|
|
const allow = allowedMethods(routes, path);
|
|
|
|
if (req.method === 'OPTIONS' && allow.length) {
|
|
return {
|
|
injected,
|
|
outcome: { kind: 'buffered', status: 204, headers: { allow: allow.join(', ') }, body: '' },
|
|
};
|
|
}
|
|
|
|
const error = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found');
|
|
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
|
|
}
|
|
|
|
/**
|
|
* The `route` reported for a request no route matched.
|
|
*
|
|
* A bounded value rather than an empty field, and deliberately unlike any pattern a user can
|
|
* declare — a route pattern starts with `/`, so this cannot collide with one. It aggregates as a
|
|
* single series where the concrete path would produce one per distinct URL.
|
|
*/
|
|
export const UNMATCHED_ROUTE = '<unmatched>';
|
|
|
|
/** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */
|
|
interface Trace {
|
|
route?: string;
|
|
}
|
|
|
|
/**
|
|
* Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405,
|
|
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
|
|
* caller (a Node adapter, a fetch adapter, …) reads/writes the actual request/response.
|
|
*
|
|
* Wraps {@link dispatch} with the request-level lifecycle events. `request:end` fires when the handler
|
|
* returns, **not** when a stream it produced finishes: a route that returns an `AsyncIterable` is done
|
|
* here in milliseconds while its connection may live for hours, and ending the span at close would put
|
|
* hour-long SSE connections and 2 ms buffered replies in one latency distribution, ruining both.
|
|
* `stream:open`/`stream:close` already describe the connection, and now carry the same `requestId`.
|
|
*/
|
|
export function handle(
|
|
routes: RouteDef[],
|
|
opts: HttpOptions | undefined,
|
|
req: NeutralRequest,
|
|
injected?: Record<string, string>,
|
|
): Promise<HandleResult | Preflight> {
|
|
const bus = opts?.bus;
|
|
|
|
// Deliberately not `async`. Wrapping `dispatch` in a second async frame costs a promise and two
|
|
// microtask ticks per request — measured at 0.43 us, an order of magnitude more than the four
|
|
// Map lookups this branch avoids. An unobserved app returns dispatch's own promise untouched.
|
|
if (
|
|
bus === undefined ||
|
|
!(
|
|
bus.hasListeners('request:start') ||
|
|
bus.hasListeners('request:end') ||
|
|
bus.hasListeners('route:matched') ||
|
|
bus.hasListeners('route:unmatched')
|
|
)
|
|
) {
|
|
return dispatch(routes, opts, req, undefined, undefined, injected);
|
|
}
|
|
|
|
return observedDispatch(routes, opts, req, bus, injected);
|
|
}
|
|
|
|
/**
|
|
* Whether anything is listening for the request pair — the one check both adapters need before
|
|
* paying for a `performance.now()` on a request they are about to refuse.
|
|
*/
|
|
export function watchingRequests(bus: Bus | undefined): bus is Bus {
|
|
return bus !== undefined && (bus.hasListeners('request:start') || bus.hasListeners('request:end'));
|
|
}
|
|
|
|
/**
|
|
* Emits the lifecycle pair for a request shed before routing.
|
|
*
|
|
* A shed request never reaches {@link handle}, so `observedDispatch` — the emitter every other
|
|
* terminal path goes through — never sees it, and an adapter that emitted only `request:end` would
|
|
* be the first thing in the tree to break the pairing {@link LifecycleEvent} guarantees. Both
|
|
* events are emitted here, in order, so a consumer that opens per-`requestId` state on
|
|
* `request:start` and closes it on `request:end` does not start leaking half-open entries the first
|
|
* time a server sheds — under load, which is when it can least afford them.
|
|
*
|
|
* Each event keeps its own listener guard: the pairing is a promise to a subscriber of *both*, and
|
|
* costs nothing for a subscriber of one.
|
|
*/
|
|
export function emitShedPair(
|
|
bus: Bus,
|
|
req: { method: string; url: string; requestId?: string; traceId?: string },
|
|
startedAt: number,
|
|
): void {
|
|
const name = `${req.method} ${req.url}`;
|
|
|
|
if (bus.hasListeners('request:start'))
|
|
bus.emit('request:start', { name, method: req.method, requestId: req.requestId, traceId: req.traceId });
|
|
|
|
if (bus.hasListeners('request:end'))
|
|
bus.emit('request:end', {
|
|
name,
|
|
method: req.method,
|
|
status: 503,
|
|
durationMs: performance.now() - startedAt,
|
|
requestId: req.requestId,
|
|
traceId: req.traceId,
|
|
});
|
|
}
|
|
|
|
async function observedDispatch(
|
|
routes: RouteDef[],
|
|
opts: HttpOptions | undefined,
|
|
req: NeutralRequest,
|
|
bus: Bus,
|
|
injected?: Record<string, string>,
|
|
): Promise<HandleResult | Preflight> {
|
|
const watchingEnd = bus.hasListeners('request:end');
|
|
const startedAt = watchingEnd ? performance.now() : 0;
|
|
const trace: Trace = {};
|
|
|
|
if (bus.hasListeners('request:start'))
|
|
bus.emit('request:start', {
|
|
name: `${req.method} ${req.url}`,
|
|
method: req.method,
|
|
requestId: req.requestId,
|
|
traceId: req.traceId,
|
|
});
|
|
|
|
const result = await dispatch(routes, opts, req, bus, trace, injected);
|
|
|
|
if (watchingEnd) {
|
|
// A preflight is a 204 the router never routed; a stream has no status of its own and is a 200
|
|
// by the time anything is piped.
|
|
const status = 'preflight' in result ? 204 : result.outcome.kind === 'buffered' ? result.outcome.status : 200;
|
|
bus.emit('request:end', {
|
|
name: trace.route ?? `${req.method} ${req.url}`,
|
|
method: req.method,
|
|
route: trace.route,
|
|
status,
|
|
durationMs: performance.now() - startedAt,
|
|
requestId: req.requestId,
|
|
traceId: req.traceId,
|
|
});
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
async function dispatch(
|
|
routes: RouteDef[],
|
|
opts: HttpOptions | undefined,
|
|
req: NeutralRequest,
|
|
bus: Bus | undefined,
|
|
trace: Trace | undefined,
|
|
precomputed?: Record<string, string>,
|
|
): Promise<HandleResult | Preflight> {
|
|
// Both adapters compute this before routing, because a response written above `handle()` — a
|
|
// shed 503, a 413 from the body reader — has to carry the same headers as one written below it.
|
|
// Recomputing here would run `security` and, worse, the `origins` predicate a second time for
|
|
// one request. `computeInjected` stays as the fallback for callers that have nothing yet.
|
|
const injected = precomputed ?? computeInjected(opts, req);
|
|
let path: string;
|
|
|
|
try {
|
|
path = normalizeRequestPath(req.url.split('?')[0]);
|
|
} catch {
|
|
return errorOutcome(new HttpError(400, 'Bad Request'), req, injected, opts);
|
|
}
|
|
|
|
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
|
return { preflight: corsPreflightHeaders(opts.cors, req, injected) };
|
|
}
|
|
|
|
const matched = resolveRoute(routes, req.method, path);
|
|
|
|
if (!matched) {
|
|
// `name` here is the path that arrived, and it is the one value in this payload that must never
|
|
// become a metric label: a matched route's path is bounded by the route table, an unmatched one
|
|
// is bounded by nothing at all, and a scanner walking /aaa, /aab, /aac is a memory leak with a
|
|
// metrics backend attached. So the event carries a bounded `route` as well, and so does the
|
|
// `request:end` that follows it, rather than leaving every consumer to invent the same fallback
|
|
// and some of them to get it wrong.
|
|
if (trace) trace.route = UNMATCHED_ROUTE;
|
|
|
|
if (bus?.hasListeners('route:unmatched'))
|
|
bus.emit('route:unmatched', {
|
|
name: `${req.method} ${path}`,
|
|
route: UNMATCHED_ROUTE,
|
|
method: req.method,
|
|
requestId: req.requestId,
|
|
traceId: req.traceId,
|
|
});
|
|
|
|
return unmatchedOutcome(routes, opts, req, path, injected);
|
|
}
|
|
|
|
if (trace) trace.route = matched.def.pattern;
|
|
|
|
if (bus?.hasListeners('route:matched'))
|
|
bus.emit('route:matched', {
|
|
name: matched.def.pattern,
|
|
route: matched.def.pattern,
|
|
method: req.method,
|
|
transport: matched.def.transport,
|
|
requestId: req.requestId,
|
|
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 {
|
|
result = await matched.def.handler({
|
|
method: req.method,
|
|
url: req.url,
|
|
headers: req.headers,
|
|
params: matched.params,
|
|
query: parseQuery(req.url),
|
|
body: acquired.body,
|
|
protocol: req.secure ? 'https' : 'http',
|
|
ip: req.ip,
|
|
requestId: req.requestId,
|
|
traceId: req.traceId,
|
|
});
|
|
} catch (error) {
|
|
result = renderError(error, req, opts?.onError, opts?.logger);
|
|
}
|
|
|
|
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,
|
|
route: matched.def.pattern,
|
|
},
|
|
};
|
|
}
|
|
|
|
return {
|
|
injected,
|
|
outcome: {
|
|
kind: 'buffered',
|
|
status: result.status,
|
|
headers: result.headers,
|
|
body: req.method === 'HEAD' ? '' : result.body,
|
|
},
|
|
};
|
|
}
|