From b86cd605c41e18ed29a6899d82652d66152c0387 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 28 Oct 2026 08:16:56 -0500 Subject: [PATCH] perf(http): resolve ctx.ip on first read instead of on every request 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 --- CHANGELOG.md | 27 ++++++++++++ src/app/index.ts | 45 +++++++++++++++----- src/bun.ts | 5 ++- src/http/core.ts | 97 +++++++++++++++++++++++++++++++++--------- src/http/peer.ts | 24 ++++++++--- src/http/server.ts | 7 +++- src/http/web.ts | 29 +++++++------ src/pipeline.ts | 4 +- test/fetch.test.ts | 102 ++++++++++++++++++++++++++++++++++++++++++--- 9 files changed, 283 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d326975..f9c4280 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -272,6 +272,33 @@ npm treats versions as semver and semver forbids leading zeros. introspection routes (`devGraph`, `devOpenapi`) now sit before remote routes in that table, so in the one case where a teapot exports the same path at the same specificity, the dev route wins. +- **`ctx.ip` is resolved when it is read, not on every request.** The client address is now + worked out the first time a step, a handler or a plugin such as rate-limit reads `ctx.ip`, and + kept for the rest of the request. A route that never reads it pays nothing. The rules are + unchanged: the first `x-forwarded-for` hop under `trustProxy`, otherwise the socket peer. What + the address costs to resolve depends on the runtime: + + | Runtime | Where the address comes from | Cost when read | + | --- | --- | --- | + | Node | `req.socket.remoteAddress`, cached by Node per connection | negligible | + | Deno | `info.remoteAddr`, handed over by `Deno.serve` | negligible | + | Bun | `server.requestIP()`, a native call per request | 7–11% of a small request | + | edge | the `cf-connecting-ip` header, under `trustProxy` | negligible | + + The Bun figure is what reading the address costs on every request. Before this change every Bun + request paid it, whether anything read `ctx.ip` or not. Behind a proxy that sets + `x-forwarded-for`, `trustProxy: true` takes the address from the header on every runtime and + never asks the socket. + + Measured against the previous commit, on a Ryzen 3700X with 4 pinned cores, 15 cases including + gzip and brotli: Bun is 3–11% faster on every case that never reads `ctx.ip`; a `POST` gains + about 1%, because the body read dominates it. Node and Deno are unchanged, within ±4%. + + **Inside a stream body `ctx.ip` is `''`** unless a step or the handler read it before returning + the stream. The body runs after the response has started, when the socket the address would come + from may already be gone. A route that needs the address in a stream reads it first, as + rate-limit already does. + - **The Node request path does less per request.** A request without a body (no `Transfer-Encoding`, no or a zero `Content-Length`, RFC 9112 §6.3), which is every `GET`, no longer touches the request stream at all. A JSON `POST` reads its body with stream diff --git a/src/app/index.ts b/src/app/index.ts index c15428a..c819014 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -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[0]; + params: Record; + query: Record; + body: unknown; + headers: Record; + protocol: 'http' | 'https'; + + constructor(provided: Record, req: Parameters[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), }); }, })); diff --git a/src/bun.ts b/src/bun.ts index 8f40f1d..905b666 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -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: { diff --git a/src/http/core.ts b/src/http/core.ts index 52b7604..ba58236 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -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; + 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, + 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 { + 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 ?? '')); diff --git a/src/http/peer.ts b/src/http/peer.ts index 84f68e7..1e165c4 100644 --- a/src/http/peer.ts +++ b/src/http/peer.ts @@ -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 }; -const peers = (registry[KEY] ??= new WeakMap()); -/** 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 }; +const peers = (registry[KEY] ??= new WeakMap()); + +/** 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 diff --git a/src/http/server.ts b/src/http/server.ts index 499966d..db2c81b 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -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, ); diff --git a/src/http/web.ts b/src/http/web.ts index 2de1e28..639b35d 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -245,12 +245,24 @@ function outcomeToResponse( } /** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */ -function forwardedFor(headers: Record, 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. diff --git a/src/pipeline.ts b/src/pipeline.ts index fccc9cc..8dd31ad 100644 --- a/src/pipeline.ts +++ b/src/pipeline.ts @@ -120,7 +120,9 @@ export async function runPipeline(args: { }): Promise { 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); diff --git a/test/fetch.test.ts b/test/fetch.test.ts index 144295e..4d49b19 100644 --- a/test/fetch.test.ts +++ b/test/fetch.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi } from 'vitest'; -import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index'; +import { createApp, Provider, Step, Route, Get, Post, Sse, Module, needs, body, ctx } from '../src/index'; import { countingStream } from './helpers/counting-stream'; import { setPeer } from '../src/http/peer'; @@ -153,7 +153,7 @@ describe('app.fetch trustProxy gates x-forwarded-for', () => { expect(copy.peerOf(request)).toBe('192.0.2.1'); }); - it('T8: only the adapter\'s own Request carries the peer — a copy of it does not', async () => { + it("T8: only the adapter's own Request carries the peer — a copy of it does not", async () => { const original = new Request('http://x/ip/whoami'); setPeer(original, '127.0.0.1'); @@ -163,6 +163,100 @@ describe('app.fetch trustProxy gates x-forwarded-for', () => { }); }); +// `ctx.ip` resolves on its first read. A peer recorded as a resolver, as Bun records its server, is +// asked only when something reads the address, at most once per request, and not from inside a +// stream body, which runs after the response has started. +@Route('/lazy') +class LazyIpCtl { + @Get('/none') none() { + return { ok: true }; + } + @Get('/twice') twice(@ctx() c: any) { + return { ip: c.ip, again: c.ip }; + } + @Sse('/stream') stream(@ctx() c: any) { + return (async function* () { + yield c.ip === '' ? 'empty' : c.ip; + })(); + } +} +@Module({ mountpoint: '/', controllers: [LazyIpCtl] }) +class LazyIpModule {} + +@Step({ provides: 'seen' }) +class SeesIp { + run(c: any) { + return { seen: c.ip }; + } +} +@Route('/early') +class EarlyIpCtl { + @Sse('/stream') stream(@needs('seen') seen: string, @ctx() c: any) { + return (async function* () { + yield `${seen}|${c.ip}`; + })(); + } +} +@Module({ mountpoint: '/', steps: [SeesIp], controllers: [EarlyIpCtl] }) +class EarlyIpModule {} + +@Step({ provides: 'ip' }) +class AssignsIp { + run() { + return { ip: '198.51.100.1' }; + } +} +@Route('/assigned') +class AssignedIpCtl { + @Get('/') whoami(@needs('ip') ip: string, @ctx() c: any) { + return { ip, ctx: c.ip }; + } +} +@Module({ mountpoint: '/', steps: [AssignsIp], controllers: [AssignedIpCtl] }) +class AssignedIpModule {} + +describe('ctx.ip is resolved only when read', () => { + const resolver = () => { + const source = { calls: 0, requestIP: () => (source.calls++, { address: '203.0.113.9' }) }; + return source; + }; + const via = async (app: ReturnType, path: string) => { + const request = new Request(`http://x${path}`); + const peer = resolver(); + setPeer(request, peer); + const res = await app.fetch(request); + return { text: await res.text(), calls: peer.calls }; + }; + + it('a route that never reads ctx.ip never asks for the peer', async () => { + expect((await via(createApp({ modules: [LazyIpModule] }), '/lazy/none')).calls).toBe(0); + }); + + it('reading ctx.ip twice asks once', async () => { + const { text, calls } = await via(createApp({ modules: [LazyIpModule] }), '/lazy/twice'); + expect(JSON.parse(text)).toEqual({ ip: '203.0.113.9', again: '203.0.113.9' }); + expect(calls).toBe(1); + }); + + it('inside a stream body ctx.ip is empty, and the peer is never asked', async () => { + const { text, calls } = await via(createApp({ modules: [LazyIpModule] }), '/lazy/stream'); + expect(text).toContain('data: "empty"'); + expect(calls).toBe(0); + }); + + it('a step that reads ctx.ip before the stream starts keeps it for the stream', async () => { + const { text, calls } = await via(createApp({ modules: [EarlyIpModule] }), '/early/stream'); + expect(text).toContain('data: "203.0.113.9|203.0.113.9"'); + expect(calls).toBe(1); + }); + + it('a step may assign ctx.ip, and the peer is then never asked', async () => { + const { text, calls } = await via(createApp({ modules: [AssignedIpModule] }), '/assigned'); + expect(JSON.parse(text)).toEqual({ ip: '198.51.100.1', ctx: '198.51.100.1' }); + expect(calls).toBe(0); + }); +}); + describe('app.fetch on a mesh app', () => { // Previously this asserted fetch() *threw* until listen() ran, which made mesh Node-only: // Deno/Bun/edge serve through app.fetch and can never call listen() (it builds an http.Server). @@ -276,9 +370,7 @@ describe('app.fetch bounded body reads (#105)', () => { }); it('T9: a route limit above the server limit wins', async () => { - const res = await limitsApp.fetch( - post('/limits/large', 'x'.repeat(1_500_000), { 'content-type': 'text/plain' }), - ); + const res = await limitsApp.fetch(post('/limits/large', 'x'.repeat(1_500_000), { 'content-type': 'text/plain' })); expect(res.status).toBe(200); expect(await res.json()).toEqual({ length: 1_500_000 });