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),
});
},
}));