perf(http): resolve ctx.ip on first read instead of on every request
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 23s
CI / runtimes (deno) (pull_request) Successful in 34s

Every Bun request called server.requestIP() for ctx.ip (#116), a native
call that builds an object, whether anything read the address or not. On
Mac that measured 7-11% of a small request; recording the server in the
peer map instead costs nothing.

The neutral request now carries a resolver rather than an address. The
handler request and the pipeline seed expose ctx.ip as an accessor that
resolves once on first read, and a step may still assign it. runPipeline
uses the seed it is given instead of spreading it, which would have
evaluated the accessor; both callers build the seed fresh per request.

Inside a stream body ctx.ip is '' unless a step or the handler read it
before the stream was returned: the body runs after the response has
started, when the socket may be gone.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-28 14:31:20 -05:00
1 parent 109297ca4c
commit b86cd605c4
9 files changed
+283 -57

No files matched your search

+35 -10
View File
@@ -1722,6 +1722,40 @@ function createRouteTable(buildLocal: () => RouteDef[]): {
};
}
/**
* The context every HTTP pipeline starts from: what the providers gave, then the request's own keys.
* `ctx.ip` reads and writes through to `ctx.req.ip`, which resolves on first read. A class so the
* accessor sits on the prototype: a literal with an accessor is a slow object, and every step and
* handler read of every key paid for it.
*/
class HttpSeed {
[key: string]: unknown;
req: Parameters<RouteDef['handler']>[0];
params: Record<string, string>;
query: Record<string, string>;
body: unknown;
headers: Record<string, string | string[] | undefined>;
protocol: 'http' | 'https';
constructor(provided: Record<string, unknown>, req: Parameters<RouteDef['handler']>[0]) {
Object.assign(this, provided);
this.req = req;
this.params = req.params;
this.query = req.query;
this.body = req.body;
this.headers = req.headers;
this.protocol = req.protocol;
}
get ip(): string {
return this.req.ip;
}
set ip(value: string) {
this.req.ip = value;
}
}
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline. */
function buildHttpRoutes(routePlans: RoutePlan[], deps: PipelineDeps): RouteDef[] {
const { providedSeed, planSteps, bus, onError, logger } = deps;
@@ -1754,16 +1788,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], deps: PipelineDeps): RouteDef[
method: plan.method,
transport: plan.transport,
},
seed: {
...provided,
req,
params: req.params,
query: req.query,
body: req.body,
headers: req.headers,
protocol: req.protocol,
ip: req.ip,
},
seed: new HttpSeed(provided, req),
});
},
}));
+3 -2
View File
@@ -127,8 +127,9 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
return new Response('WebSocket upgrade failed', { status: 400 });
}
// The same object goes to `app.fetch`, which is what lets it find the peer again.
setPeer(request, server.requestIP(request)?.address ?? '');
// The same object goes to `app.fetch`, which is what lets it find the peer again. The server,
// not its answer: `requestIP` runs only if something reads `ctx.ip` (see `peer.ts`).
setPeer(request, server);
return app.fetch(request);
},
websocket: {
+77 -20
View File
@@ -9,7 +9,7 @@ import { acquireBody, type BodyReader } from './body';
import { bodyEtag, findHeader, isNotModified, notModifiedHeaders, staticEtag } from './conditional';
import type { StaticHit } from '../views';
import type { Encoding } from './compression';
import type { RouteDef, HttpOptions } from './types';
import type { RouteDef, HttpOptions, MatchedRoute } from './types';
import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus';
@@ -41,7 +41,11 @@ export interface NeutralRequest {
/** The runtime's own request object, passed back to {@link readBody} untouched and never inspected here. */
source: unknown;
secure: boolean;
ip: string;
/**
* The client address, resolved only when something reads `ctx.ip`. A function of `source` rather
* than a closure, so an adapter passes one module-level function and allocates nothing per request.
*/
resolveIp: (source: unknown, opts: HttpOptions | undefined) => string;
requestId: string;
traceId?: string;
}
@@ -358,6 +362,76 @@ async function observedDispatch(
return result;
}
/**
* The request a route handler receives.
*
* `ip` is resolved on its first read and kept. Most routes never read it, and on Bun resolving it
* is a native call. A step may assign it, as it may any key. The accessor is on the prototype rather
* than in an object literal: a literal with an accessor is a slow object in V8 and JSC, and every
* read of every key paid for it, which cost Node and Deno 15-24%.
*/
class RouteRequest {
method: string;
url: string;
headers: NeutralRequest['headers'];
query: Record<string, string>;
protocol: 'http' | 'https';
requestId: string;
traceId: string | undefined;
private resolved: string | undefined = undefined;
constructor(
private readonly req: NeutralRequest,
private readonly opts: HttpOptions | undefined,
public params: Record<string, string>,
public body: unknown,
) {
this.method = req.method;
this.url = req.url;
this.headers = req.headers;
this.query = parseQuery(req.url);
this.protocol = req.secure ? 'https' : 'http';
this.requestId = req.requestId;
this.traceId = req.traceId;
}
get ip(): string {
return (this.resolved ??= this.req.resolveIp(this.req.source, this.opts));
}
set ip(value: string) {
this.resolved = value;
}
/**
* A stream body runs after the response has started, when the socket the address would come
* from may already be gone, so once a stream is returned an address nothing has read yet is `''`.
*/
seal(): void {
this.resolved ??= '';
}
}
/** Runs the matched route's handler, turning a throw into the standard error envelope. */
async function runHandler(
matched: MatchedRoute,
req: NeutralRequest,
body: unknown,
opts: HttpOptions | undefined,
): Promise<PipelineResult> {
const request = new RouteRequest(req, opts, matched.params, body);
let result: PipelineResult;
try {
result = await matched.def.handler(request);
} catch (error) {
result = renderError(error, req, opts?.onError, opts?.logger);
}
if (isStreamResult(result)) request.seal();
return result;
}
async function dispatch(
routes: RouteDef[],
opts: HttpOptions | undefined,
@@ -428,24 +502,7 @@ async function dispatch(
// 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);
}
const result = await runHandler(matched, req, acquired.body, opts);
if (isStreamResult(result)) {
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
+18 -6
View File
@@ -12,18 +12,30 @@
// with no shared chunk, so each carries its own copy of this one: a module-private map in
// `@green-tea/core/bun` would record peers that `app.fetch` from `@green-tea/core` never sees. An app
// that loads core both as ESM and as CommonJS has the same split.
//
// Bun records its server rather than an address. `server.requestIP()` is a native call that builds
// an object, and making it on every request measured 7–11% on Bun; recording the server is free, and
// the address is asked for only when something reads `ctx.ip`. Deno hands the address over already
// resolved, so it records the string.
const KEY = Symbol.for('@green-tea/core:peer');
const registry = globalThis as { [KEY]?: WeakMap<Request, string> };
const peers = (registry[KEY] ??= new WeakMap<Request, string>());
/** Records `ip` as the peer of `request`. An empty address — a unix socket has none — is not recorded. */
export function setPeer(request: Request, ip: string): void {
if (ip) peers.set(request, ip);
/** Names a request's socket peer on demand: Bun's server. */
export interface PeerSource {
requestIP(request: Request): { address: string } | null;
}
const registry = globalThis as { [KEY]?: WeakMap<Request, string | PeerSource> };
const peers = (registry[KEY] ??= new WeakMap<Request, string | PeerSource>());
/** Records the peer of `request`. An empty address — a unix socket has none — is not recorded. */
export function setPeer(request: Request, peer: string | PeerSource): void {
if (peer) peers.set(request, peer);
}
/** The peer an adapter recorded for `request`, or `''` when none did. */
export function peerOf(request: Request): string {
return peers.get(request) ?? '';
const peer = peers.get(request);
return typeof peer === 'object' ? (peer.requestIP(request)?.address ?? '') : (peer ?? '');
}
// The client address a runtime adapter read from a header its platform's proxy sets — today only the
+6 -1
View File
@@ -45,6 +45,11 @@ function errorRequest(req: http.IncomingMessage): ErrorRequest {
* @param meshControl Optional mesh gateway hook for a reserved upgrade path.
* @param opts Limits, TLS, security, CORS, and body-parsing options.
*/
/** `ctx.ip` on Node, for `NeutralRequest.resolveIp`: the forwarded hop under `trustProxy`, else the socket peer. */
function nodeIp(source: unknown, opts: HttpOptions | undefined): string {
return deriveIp(source as http.IncomingMessage, opts?.trustProxy ?? false);
}
export function createHttpServer(
routes: RouteTable,
wsRoutes: WsRouteDef[] = [],
@@ -174,7 +179,7 @@ function createRequestHandler(cfg: HandlerConfig) {
readBody,
source: req,
secure,
ip: deriveIp(req, trustProxy),
resolveIp: nodeIp,
},
injected,
);
+17 -12
View File
@@ -245,12 +245,24 @@ function outcomeToResponse(
}
/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */
function forwardedFor(headers: Record<string, string>, opts: HttpOptions | undefined): string {
function forwardedFor(request: Request, opts: HttpOptions | undefined): string {
if (!opts?.trustProxy) return '';
return String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim();
return (request.headers.get('x-forwarded-for') ?? '').split(',')[0].trim();
}
/**
* `ctx.ip` on the fetch path, for `NeutralRequest.resolveIp`. Mirrors Node's `deriveIp`
* (src/http/request.ts): only trust `x-forwarded-for` when the proxy is trusted, and take its first
* hop, because an untrusted XFF is client-spoofable. Otherwise the socket peer, which only the Deno
* and Bun adapters can supply; a bare `app.fetch` has none, so there the answer is still ''. Ahead of
* both, under `trustProxy` only: the address the edge adapter read from `cf-connecting-ip`.
* Cloudflare sets that header itself, while XFF can carry hops the client supplied, so on the edge
* it wins (CARD-23).
*/
function fetchIp(source: unknown, opts: HttpOptions | undefined): string {
const request = source as Request;
return trustedProxyClient(request, opts?.trustProxy) || forwardedFor(request, opts) || peerOf(request);
}
/**
@@ -324,14 +336,7 @@ export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) {
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.
// Otherwise the socket peer, which only the Deno and Bun adapters can supply; a bare
// `app.fetch` has none, so there the answer is still ''.
// Ahead of both, under `trustProxy` only: the address the edge adapter read from
// `cf-connecting-ip`. Cloudflare sets that header itself, while XFF can carry hops the
// client supplied, so on the edge it wins (CARD-23).
ip: trustedProxyClient(request, opts?.trustProxy) || forwardedFor(headers, opts) || peerOf(request),
resolveIp: fetchIp,
},
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
// one call per request.
+3 -1
View File
@@ -120,7 +120,9 @@ export async function runPipeline(args: {
}): Promise<PipelineResult> {
const { steps, handler, transformer, seed, bus, transport, onError, logger, correlation = {} } = args;
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
let context: any = { ...seed };
// The seed itself, not a copy. Both callers build it fresh per request, and a spread would evaluate
// `ctx.ip`'s accessor, resolving on every request the address most routes never read.
let context: any = seed;
try {
context = await runSteps(steps, context, bus, correlation);