Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions bench/compare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' } },
];

Expand Down
49 changes: 49 additions & 0 deletions bench/results/mesh-week1-46e0bc9-20f5094/README.md
Original file line number Diff line number Diff line change
@@ -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.
28 changes: 25 additions & 3 deletions bench/servers/compare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
Expand All @@ -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 } : {}),
Expand All @@ -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<number> {
async function listen(app: ReturnType<typeof createApp>): Promise<number> {
const g = globalThis as { Deno?: unknown; Bun?: unknown };
if (g.Deno) {
const { serveDeno } = await import('../../src/deno');
Expand All @@ -108,8 +125,13 @@ async function listen(): Promise<number> {
}

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); });
68 changes: 46 additions & 22 deletions src/mesh/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,31 @@ type PendingEntry = {
resolve: (v: unknown) => void;
reject: (e: unknown) => void;
timer: ReturnType<typeof setTimeout>;
/** 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<PendingEntry, 'name' | 'started' | 'correlation'>, 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;
Expand Down Expand Up @@ -101,12 +122,12 @@ function rejectAllPending(
pending: Map<string, PendingEntry>,
reason: string,
headers?: Record<string, string>,
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));
}

Expand All @@ -133,26 +154,30 @@ 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,
// which is a different operational story from a link that is down.
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, () =>
Expand All @@ -165,21 +190,22 @@ function sendRpc(
function settleRpcResponse(
pending: Map<string, PendingEntry>,
frame: Extract<Frame, { type: 'rpc-res' }>,
bus?: Bus,
bus: Bus | undefined,
url: string,
): void {
const entry = pending.get(frame.id);
if (!entry) return;
pending.delete(frame.id);
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));
Expand Down Expand Up @@ -277,7 +303,7 @@ async function readFrames(hs: Handshake): Promise<void> {

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

Expand Down Expand Up @@ -534,17 +560,15 @@ export function connectLink(args: {
let adopted = false; // a session was adopted at least once, so the link has something to lose

const downHeaders = (): Record<string, string> | 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 = {
// replaced with the real manifest before this object escapes. A reconnect keeps the boot
// 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.
Expand Down Expand Up @@ -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);
Expand Down
30 changes: 23 additions & 7 deletions src/mesh/teapot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,10 +209,28 @@ async function handleRpc(
deps: MeshControlDeps,
exportedScopes: Set<string>,
exportedRoutes: Set<string>,
peer: { inflight: number },
): Promise<void> {
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<string>,
exportedRoutes: Set<string>,
started: number,
): Promise<void> {
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
Expand Down Expand Up @@ -262,7 +280,7 @@ async function serveFrames(
maxFrameChars: number,
): Promise<void> {
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.
Expand Down Expand Up @@ -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,
Expand All @@ -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 */
Expand Down
Loading