1 Commits
Author SHA1 Message Date
chrnx 75f9583068 docs: bring the contributor docs and examples in line with the repository
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 21s
CI / build (pull_request) Successful in 31s
CI / runtimes (edge) (pull_request) Successful in 23s
CI / runtimes (deno) (pull_request) Successful in 34s
CONTRIBUTING said none of the Deno, Bun or edge suites run in CI. They do:
the runtimes job runs all three on every push and gates a merge. It now
says so, names test:all, and lists the audit step CI runs.

The README's benchmark section quoted a ranking against Fastify that went
stale with the next measurement. It now explains what the harness measures
and why, and leaves every number to BENCHMARKS.md. The install section
states the Node 22 floor and that Node 18 and 20 are not supported.

The PR template asks which runtime suites were run. The example README
pointed at ts-node, which is not a dependency, and a dist path tsup never
builds; it now runs each example with tsx. example/server.ts crashed at
boot because its teacup lacked experimental: true.

docs/plans held agent implementation plans from August and September.
Those belong in .specs/, which is not committed, so they leave the
repository. The three places that linked the mesh degrade plan now
describe the planned expects list instead.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-28 14:32:03 -05:00
9 changed files with 57 additions and 283 deletions

No files matched your search

-27
View File
@@ -272,33 +272,6 @@ npm treats versions as semver and semver forbids leading zeros.
introspection routes (`devGraph`, `devOpenapi`) now sit before remote routes in that table, so 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. 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 - **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 `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 longer touches the request stream at all. A JSON `POST` reads its body with stream
+10 -35
View File
@@ -1722,40 +1722,6 @@ 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. */ /** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline. */
function buildHttpRoutes(routePlans: RoutePlan[], deps: PipelineDeps): RouteDef[] { function buildHttpRoutes(routePlans: RoutePlan[], deps: PipelineDeps): RouteDef[] {
const { providedSeed, planSteps, bus, onError, logger } = deps; const { providedSeed, planSteps, bus, onError, logger } = deps;
@@ -1788,7 +1754,16 @@ function buildHttpRoutes(routePlans: RoutePlan[], deps: PipelineDeps): RouteDef[
method: plan.method, method: plan.method,
transport: plan.transport, transport: plan.transport,
}, },
seed: new HttpSeed(provided, req), seed: {
...provided,
req,
params: req.params,
query: req.query,
body: req.body,
headers: req.headers,
protocol: req.protocol,
ip: req.ip,
},
}); });
}, },
})); }));
+2 -3
View File
@@ -127,9 +127,8 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
return new Response('WebSocket upgrade failed', { status: 400 }); return new Response('WebSocket upgrade failed', { status: 400 });
} }
// The same object goes to `app.fetch`, which is what lets it find the peer again. The server, // The same object goes to `app.fetch`, which is what lets it find the peer again.
// not its answer: `requestIP` runs only if something reads `ctx.ip` (see `peer.ts`). setPeer(request, server.requestIP(request)?.address ?? '');
setPeer(request, server);
return app.fetch(request); return app.fetch(request);
}, },
websocket: { websocket: {
+20 -77
View File
@@ -9,7 +9,7 @@ import { acquireBody, type BodyReader } from './body';
import { bodyEtag, findHeader, isNotModified, notModifiedHeaders, staticEtag } from './conditional'; import { bodyEtag, findHeader, isNotModified, notModifiedHeaders, staticEtag } from './conditional';
import type { StaticHit } from '../views'; import type { StaticHit } from '../views';
import type { Encoding } from './compression'; import type { Encoding } from './compression';
import type { RouteDef, HttpOptions, MatchedRoute } from './types'; import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders'; import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
@@ -41,11 +41,7 @@ export interface NeutralRequest {
/** The runtime's own request object, passed back to {@link readBody} untouched and never inspected here. */ /** The runtime's own request object, passed back to {@link readBody} untouched and never inspected here. */
source: unknown; source: unknown;
secure: boolean; 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; requestId: string;
traceId?: string; traceId?: string;
} }
@@ -362,76 +358,6 @@ async function observedDispatch(
return result; 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( async function dispatch(
routes: RouteDef[], routes: RouteDef[],
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
@@ -502,7 +428,24 @@ async function dispatch(
// caller merges `injected` into it exactly as it does for every other outcome. // caller merges `injected` into it exactly as it does for every other outcome.
if ('fail' in acquired) return { injected, outcome: { kind: 'buffered', ...acquired.fail } }; if ('fail' in acquired) return { injected, outcome: { kind: 'buffered', ...acquired.fail } };
const result = await runHandler(matched, req, acquired.body, opts); 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)) { if (isStreamResult(result)) {
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? '')); const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
+6 -18
View File
@@ -12,30 +12,18 @@
// with no shared chunk, so each carries its own copy of this one: a module-private map in // 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 // `@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. // 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 KEY = Symbol.for('@green-tea/core:peer');
const registry = globalThis as { [KEY]?: WeakMap<Request, string> };
const peers = (registry[KEY] ??= new WeakMap<Request, string>());
/** Names a request's socket peer on demand: Bun's server. */ /** Records `ip` as the peer of `request`. An empty address — a unix socket has none — is not recorded. */
export interface PeerSource { export function setPeer(request: Request, ip: string): void {
requestIP(request: Request): { address: string } | null; if (ip) peers.set(request, ip);
}
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. */ /** The peer an adapter recorded for `request`, or `''` when none did. */
export function peerOf(request: Request): string { export function peerOf(request: Request): string {
const peer = peers.get(request); return 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 // The client address a runtime adapter read from a header its platform's proxy sets — today only the
+1 -6
View File
@@ -45,11 +45,6 @@ function errorRequest(req: http.IncomingMessage): ErrorRequest {
* @param meshControl Optional mesh gateway hook for a reserved upgrade path. * @param meshControl Optional mesh gateway hook for a reserved upgrade path.
* @param opts Limits, TLS, security, CORS, and body-parsing options. * @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( export function createHttpServer(
routes: RouteTable, routes: RouteTable,
wsRoutes: WsRouteDef[] = [], wsRoutes: WsRouteDef[] = [],
@@ -179,7 +174,7 @@ function createRequestHandler(cfg: HandlerConfig) {
readBody, readBody,
source: req, source: req,
secure, secure,
resolveIp: nodeIp, ip: deriveIp(req, trustProxy),
}, },
injected, injected,
); );
+12 -17
View File
@@ -245,24 +245,12 @@ function outcomeToResponse(
} }
/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */ /** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */
function forwardedFor(request: Request, opts: HttpOptions | undefined): string { function forwardedFor(headers: Record<string, string>, opts: HttpOptions | undefined): string {
if (!opts?.trustProxy) return ''; if (!opts?.trustProxy) return '';
return (request.headers.get('x-forwarded-for') ?? '').split(',')[0].trim(); return String(headers['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);
} }
/** /**
@@ -336,7 +324,14 @@ export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) {
readBody, readBody,
source: request, source: request,
secure, secure,
resolveIp: fetchIp, // 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),
}, },
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to // Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
// one call per request. // one call per request.
+1 -3
View File
@@ -120,9 +120,7 @@ export async function runPipeline(args: {
}): Promise<PipelineResult> { }): Promise<PipelineResult> {
const { steps, handler, transformer, seed, bus, transport, onError, logger, correlation = {} } = args; const { steps, handler, transformer, seed, bus, transport, onError, logger, correlation = {} } = args;
// context is intentionally `any`: each step merges arbitrary keys into the accumulator // context is intentionally `any`: each step merges arbitrary keys into the accumulator
// The seed itself, not a copy. Both callers build it fresh per request, and a spread would evaluate let context: any = { ...seed };
// `ctx.ip`'s accessor, resolving on every request the address most routes never read.
let context: any = seed;
try { try {
context = await runSteps(steps, context, bus, correlation); context = await runSteps(steps, context, bus, correlation);
+5 -97
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from 'vitest'; import { describe, it, expect, vi } from 'vitest';
import { createApp, Provider, Step, Route, Get, Post, Sse, Module, needs, body, ctx } from '../src/index'; import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index';
import { countingStream } from './helpers/counting-stream'; import { countingStream } from './helpers/counting-stream';
import { setPeer } from '../src/http/peer'; 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'); 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'); const original = new Request('http://x/ip/whoami');
setPeer(original, '127.0.0.1'); setPeer(original, '127.0.0.1');
@@ -163,100 +163,6 @@ 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', () => { describe('app.fetch on a mesh app', () => {
// Previously this asserted fetch() *threw* until listen() ran, which made mesh Node-only: // 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). // Deno/Bun/edge serve through app.fetch and can never call listen() (it builds an http.Server).
@@ -370,7 +276,9 @@ describe('app.fetch bounded body reads (#105)', () => {
}); });
it('T9: a route limit above the server limit wins', async () => { 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(res.status).toBe(200);
expect(await res.json()).toEqual({ length: 1_500_000 }); expect(await res.json()).toEqual({ length: 1_500_000 });