perf(http): resolve ctx.ip on first read instead of on every request #176
No files matched your search
@@ -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
|
||||
|
||||
+35
-10
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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);
|
||||
|
||||
+97
-5
@@ -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<typeof createApp>, 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 });
|
||||
|
||||
Reference in new issue
Block a user