diff --git a/bench/compare.ts b/bench/compare.ts index e2238fa..c1094f1 100644 --- a/bench/compare.ts +++ b/bench/compare.ts @@ -91,6 +91,8 @@ const CASES: Case[] = [ // takes the compressed frame sink, whose drain wait is a different emitter. { name: 'static 2KB file', path: '/app.js', env: { GT_STATIC: '1' } }, { name: 'sse 100 events', path: '/sse' }, + // One teacup→teapot round trip per request, both in the server process (#95–#98). + { name: 'mesh rpc (1 remote step)', path: '/mesh', env: { GT_MESH: '1' } }, { name: 'sse 100 events + gzip', path: '/sse', env: { GT_COMPRESS: '1' }, headers: { 'accept-encoding': 'gzip' } }, ]; diff --git a/bench/results/mesh-week1-46e0bc9-20f5094/README.md b/bench/results/mesh-week1-46e0bc9-20f5094/README.md new file mode 100644 index 0000000..139c734 --- /dev/null +++ b/bench/results/mesh-week1-46e0bc9-20f5094/README.md @@ -0,0 +1,49 @@ +# Week-1 mesh regression: `46e0bc9` → `20f5094` (#95–#98), and the #97 fix + +Regression A/B for the "Mesh: resilience" week (#112–#115) before the board marks it done. + +## Method + +- **Host and container:** jarvis, `docker run --rm --cpuset-cpus 6,7,14,15 --user 1000:1000 node:22` + (`sha256:7c400d78…`), Deno 2.9.8 and Bun 1.4.4 binaries mounted into the same image. +- **Trees:** `git archive` of each revision, sharing one `npm ci`. `package.json` is identical across them. +- **Harness:** `bench/compare.ts` with the `mesh rpc (1 remote step)` case added in this branch (a teapot + in the server process exports one step; `/mesh` on the teacup needs it), overlaid on every tree. +- Node 3 × 10 s, Deno and Bun 3 × 5 s, 100 connections. Mesh-only reruns 5 rounds. + +## Full suite, base `46e0bc9` vs `develop` `20f5094` + +Every request-path case is within noise on all three runtimes (Node −2.1% … +1.5%; Deno −3.2% … +5.7%; +Bun −3.4% … +8.3%, all overlapping except Bun steps5 −2.6% and br −1.6%, the second-measured-side bias +seen before on jarvis; the week did not touch the request path). The mesh case did not hold: + +| Runtime | mesh rpc | | +|---|---|---| +| Node | 17,298 → 16,546 (−4.3%) | separated; A/A −1.2% | +| Deno | 24,789 → 23,221 (−6.3%) | separated | +| Bun | 31,605 → 30,757 (−2.7%) | separated | + +## Bisect (Node, 5 × 10 s, mesh only) + +| Step | Δ | +|---|---| +| base → #95 | −0.7% overlaps | +| #95 → #96 | +0.2% overlaps | +| **#96 → #97** | **−4.2% separated** | +| #97 → #98 | +0.6% overlaps | + +Locally, #97 with `src/mesh/link.ts` swapped back to #96 measured −0.5%; with `teapot.ts` or +`bus.ts` swapped back, still −2.8% / −2.4%. The cost was a closure and a `performance.now()` per call in +`sendRpc` to build an event payload. Hoisting the observer object and guarding only the emit did not +help (develop vs that first attempt: +0.2%). + +## After the fix (base `46e0bc9` vs this branch, mesh only) + +| Runtime | Rounds | mesh rpc | +|---|---|---| +| Node | 5 × 10 s | 16,985 → 17,082 (+0.6%) overlaps | +| Deno | 5 × 5 s | 24,520 → 24,181 (−1.4%) overlaps | +| Bun | 5 × 5 s | 31,138 → 30,955 (−0.6%) overlaps | + +**Not measured:** mesh RPC with a `mesh:rpc` listener attached (the metrics-plugin case: it pays one +`performance.now()` pair and one payload per call by design); route proxying over the mesh; WebSocket. diff --git a/bench/servers/compare.ts b/bench/servers/compare.ts index d425ade..f6efa10 100644 --- a/bench/servers/compare.ts +++ b/bench/servers/compare.ts @@ -64,6 +64,20 @@ const EXTRA = Number(process.env.GT_ROUTES ?? 0); @Module({ mountpoint: '/', steps, controllers: [...fillerRoutes(EXTRA), Bench] }) class BenchModule {} +// Mesh RPC (GT_MESH=1): a teapot in this same process exports one step, and `/mesh` on the teacup +// needs it, so every request is one teacup→teapot round trip over the loopback control channel. +const MESH = process.env.GT_MESH === '1'; +@Step({ provides: 'remote', needs: [], export: true }) +class Remote { run() { return { remote: { ok: true } }; } } +@Module({ mountpoint: '/', steps: [Remote] }) +class TeapotModule {} +@Route('/') +class MeshBench { + @Get('/mesh') mesh(@needs('remote') remote: unknown) { return { hello: 'world', remote }; } +} +@Module({ mountpoint: '/', controllers: [MeshBench] }) +class MeshModule {} + // A predicate rather than a list: that is the shape `cors.origins` takes a function for, and the // one this release stopped evaluating two and three times per request. const ALLOWED = new Set(['http://bench.example']); @@ -79,8 +93,11 @@ const cors = : undefined; // Only passed when asked for, so the file still boots against a revision without compression. +const teapot = MESH ? createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'bench' } }) : undefined; +let meshUrl = ''; const app = createApp({ - modules: [BenchModule], + modules: MESH ? [BenchModule, MeshModule] : [BenchModule], + ...(MESH ? { experimental: true, mesh: { teapots: [{ get url() { return meshUrl; }, secret: 'bench' }] } } : {}), security: process.env.GT_SECURE === '1', ...(cors ? { cors } : {}), ...(process.env.GT_COMPRESS === '1' ? { compression: true } : {}), @@ -90,7 +107,7 @@ const app = createApp({ // Each runtime through its own adapter, the way an app deploys there: Deno and Bun take the fetch // path (`src/http/web.ts`), Node the `node:http` one. `AB_RUNTIME` in the harness picks the binary. -async function listen(): Promise { +async function listen(app: ReturnType): Promise { const g = globalThis as { Deno?: unknown; Bun?: unknown }; if (g.Deno) { const { serveDeno } = await import('../../src/deno'); @@ -108,8 +125,13 @@ async function listen(): Promise { } async function main() { + // A mesh graph is finalized at boot, once the teapot has answered, so introspection waits for it. + if (teapot) { + meshUrl = `ws://127.0.0.1:${await listen(teapot)}/__mesh__/control`; + await app.ready(); + } try { if (app.inspect('/hello').length === 0) throw new Error('empty'); } catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); } - console.log(`READY ${await listen()}`); + console.log(`READY ${await listen(app)}`); } main().catch((e) => { console.error(e); process.exit(1); }); diff --git a/src/mesh/link.ts b/src/mesh/link.ts index 3cc46bd..153f083 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -69,10 +69,31 @@ type PendingEntry = { resolve: (v: unknown) => void; reject: (e: unknown) => void; timer: ReturnType; - /** The call's `mesh:rpc` payload as of now: name, teapot url, elapsed ms and the request's ids (#97). */ - event: () => EventPayload; + /** `performance.now()` when sent, or 0 when nothing listened to RPC events then (#97). */ + started: number; + /** The request's ids, for the RPC events. */ + correlation: RequestEnvelope['correlation']; }; +/** + * The `mesh:rpc` / `mesh:rpc:error` payload for one call (#97). A plain function over plain fields: + * a closure per call measured ~4% of mesh RPC throughput, for events most apps never listen to. + */ +function rpcEvent(entry: Pick, url: string): EventPayload { + return { + name: entry.name, + url, + durationMs: entry.started ? performance.now() - entry.started : undefined, + requestId: entry.correlation?.requestId, + traceId: entry.correlation?.traceId, + }; +} + +/** Whether anything listens to RPC events, so a call is worth timing. */ +function observed(bus: Bus | undefined): boolean { + return bus !== undefined && (bus.hasListeners('mesh:rpc') || bus.hasListeners('mesh:rpc:error')); +} + /** Mutable per-link state: which socket is current, and whether the application hung up for good. */ interface LinkState { socket: WsSocket | undefined; @@ -101,12 +122,12 @@ function rejectAllPending( pending: Map, reason: string, headers?: Record, - bus?: Bus, + obs?: { bus?: Bus; url: string }, ): void { for (const [, entry] of pending) { clearTimeout(entry.timer); // A call cut off mid-request by the session ending is an RPC failure like any other (#97). - bus?.emit('mesh:rpc:error', { ...entry.event(), status: 503, error: new Error(reason) }); + obs?.bus?.emit('mesh:rpc:error', { ...rpcEvent(entry, obs.url), status: 503, error: new Error(reason) }); entry.reject(new HttpError(503, reason, undefined, headers)); } @@ -133,14 +154,11 @@ function sendRpc( return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`, undefined, downHeaders)); } - const started = performance.now(); - const event = (): EventPayload => ({ + const entry = { name, - url: obs?.url, - durationMs: performance.now() - started, - requestId: ctx.correlation?.requestId, - traceId: ctx.correlation?.traceId, - }); + started: observed(obs?.bus) ? performance.now() : 0, + correlation: ctx.correlation, + }; return new Promise((resolveCall, rejectCall) => { // 504: the link is alive but the teapot did not answer in time — a gateway timeout, @@ -148,11 +166,18 @@ function sendRpc( const timer = setTimeout(() => { pending.delete(id); const error = new HttpError(504, `mesh rpc timeout: ${name}`); - obs?.bus?.emit('mesh:rpc:error', { ...event(), status: 504, error }); + obs?.bus?.emit('mesh:rpc:error', { ...rpcEvent(entry, obs.url), status: 504, error }); rejectCall(error); }, timeoutMs); - pending.set(id, { name, resolve: resolveCall, reject: rejectCall, timer, event }); + pending.set(id, { + name, + started: entry.started, + correlation: entry.correlation, + resolve: resolveCall, + reject: rejectCall, + timer, + }); // Not before the socket has room (#41); the timeout already runs, so a teapot that stops // reading still answers 504. Settled while waiting (timeout, close): nothing left to send. void sendWhenDrained(socket, () => @@ -165,7 +190,8 @@ function sendRpc( function settleRpcResponse( pending: Map, frame: Extract, - bus?: Bus, + bus: Bus | undefined, + url: string, ): void { const entry = pending.get(frame.id); if (!entry) return; @@ -173,13 +199,13 @@ function settleRpcResponse( clearTimeout(entry.timer); if (frame.ok) { - bus?.emit('mesh:rpc', entry.event()); + if (entry.started) bus?.emit('mesh:rpc', rpcEvent(entry, url)); entry.resolve(frame.result); } else { // `entry.name`, not `frame.id`: the id is a per-link counter, so this event used to report // "0" or "1" where every other emitter reports what failed — including the teapot's own // emit for the same call, which made the two sides of one failure impossible to line up. - bus?.emit('mesh:rpc:error', { ...entry.event(), status: frame.error.status ?? 500, error: frame.error }); + bus?.emit('mesh:rpc:error', { ...rpcEvent(entry, url), status: frame.error.status ?? 500, error: frame.error }); // A teapot's 503 is load shedding (maxInflightPerPeer): tell the client when to come back. const headers = frame.error.status === 503 ? { 'retry-after': '1' } : undefined; entry.reject(new HttpError(frame.error.status ?? 500, frame.error.message, undefined, headers)); @@ -277,7 +303,7 @@ async function readFrames(hs: Handshake): Promise { if (frame.type === 'manifest') settleManifest(frame, hs); else if (frame.type === 'pong') hs.onPong(); - else if (frame.type === 'rpc-res') settleRpcResponse(hs.pending, frame, hs.bus); + else if (frame.type === 'rpc-res') settleRpcResponse(hs.pending, frame, hs.bus, hs.url); } } @@ -534,6 +560,7 @@ export function connectLink(args: { let adopted = false; // a session was adopted at least once, so the link has something to lose const downHeaders = (): Record | undefined => retryAfter(state, bounds !== undefined); + const obs = { bus: args.bus, url: args.url }; // one per link, not one per RPC const giveUp = (): void => stopForGood(state, args.onGone); const link: Link = { @@ -541,10 +568,7 @@ export function connectLink(args: { // manifest's steps, because the graph is fixed at boot, and takes the returning one's routes. manifest: { steps: [], routes: [] }, rpc: (kind, name, ctx) => - sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs, downHeaders(), { - bus: args.bus, - url: args.url, - }), + sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs, downHeaders(), obs), close: () => { // Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after // the application hung up would leave a process that cannot exit. @@ -588,7 +612,7 @@ export function connectLink(args: { args.bus?.emit('mesh:disconnect', { name: args.url, url: args.url }); // Scheduled before the rejection, so the 503s carry the real wait in `retry-after`. scheduleRetry(attempt); - rejectAllPending(pending, `mesh link to ${args.url} is down`, downHeaders(), args.bus); + rejectAllPending(pending, `mesh link to ${args.url} is down`, downHeaders(), obs); // With reconnection off, a link that was up and dropped is gone for good (D15). `adopted` // keeps a first connect that never succeeded out of this: that link never escaped. if (!bounds) dropWithoutReconnect(adopted, giveUp); diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index 3b8d515..6f8b18b 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -209,10 +209,28 @@ async function handleRpc( deps: MeshControlDeps, exportedScopes: Set, exportedRoutes: Set, + peer: { inflight: number }, ): Promise { - const { id, name } = frame; const started = performance.now(); + try { + await serveRpc(socket, frame, deps, exportedScopes, exportedRoutes, started); + } finally { + peer.inflight -= 1; // here rather than a `.finally()` per call: one promise less on the hot path + } +} + +/** The body of {@link handleRpc}: resolve, check transportability, and frame the answer. */ +async function serveRpc( + socket: WsSocket, + frame: RpcReqFrame, + deps: MeshControlDeps, + exportedScopes: Set, + exportedRoutes: Set, + started: number, +): Promise { + const { id, name } = frame; + try { const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes); // Checked here, on the side that still holds the real value. Past `encode` the evidence is @@ -262,7 +280,7 @@ async function serveFrames( maxFrameChars: number, ): Promise { let authed = false; - let inflight = 0; // this peer's RPCs still running (#98) + const peer = { inflight: 0 }; // this peer's RPCs still running (#98); handleRpc decrements it const maxInflight = deps.maxInflightPerPeer ?? MAX_INFLIGHT_PER_PEER; // Armed before the loop, and cleared by the handshake. An unauthenticated peer that simply // says nothing is indistinguishable from a slow one until this fires. @@ -309,7 +327,7 @@ async function serveFrames( // awaiting here would silently serialize every mesh call. // Over the cap the call is refused before any work starts; the teacup turns this 503 into a // `retry-after` for its client. Per connection, which is per peer until identity lands (M8). - if (inflight >= maxInflight) { + if (peer.inflight >= maxInflight) { deps.bus?.emit('mesh:rpc:error', { name: frame.name, status: 503, @@ -324,10 +342,8 @@ async function serveFrames( continue; } - inflight += 1; - void handleRpc(socket, frame, deps, exportedScopes, exportedRoutes).finally(() => { - inflight -= 1; - }); + peer.inflight += 1; + void handleRpc(socket, frame, deps, exportedScopes, exportedRoutes, peer); } } catch { /* socket failed; the disconnect emit below is the same signal a clean close gives */