From 753b3704634a1691c89a93c9ce646cd3dcf6d60a Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Mon, 30 Nov 2026 11:49:50 -0600 Subject: [PATCH] feat(mesh): cap concurrent RPCs per peer on the teapot A teacup that times out an RPC never cancels it on the teapot, so one peer could pile up unbounded work behind a slow step. MeshConfig.maxInflightPerPeer (default 256) caps the RPCs one connection may have running; over the cap the call is refused before any work starts with a 503 rpc-res and a mesh:rpc:error event. The teacup turns a teapot 503 into retry-after: 1 for its client. Counted per connection until per-teacup identity (M8). Closes #98 Signed-off-by: Diego Resendez --- CHANGELOG.md | 8 ++++ api/index.api.md | 2 + src/app/index.ts | 4 ++ src/app/types.ts | 7 +++ src/mesh/link.ts | 4 +- src/mesh/teapot.ts | 32 +++++++++++++- test/mesh/max-inflight.test.ts | 80 ++++++++++++++++++++++++++++++++++ 7 files changed, 135 insertions(+), 2 deletions(-) create mode 100644 test/mesh/max-inflight.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 28d688f..8d8d569 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,14 @@ npm treats versions as semver and semver forbids leading zeros. ### Added +- **Mesh: `MeshConfig.maxInflightPerPeer` caps one teacup's concurrent RPCs on a teapot** (#98, + default 256). Over the cap a call is refused before any work starts: the teapot answers 503 and + emits `mesh:rpc:error` with `status: 503`, and the teacup's client gets `503` with + `retry-after: 1`. A teacup that times out a call does not cancel it on the teapot (the cancel + frame is #99), so without a cap a slow step let one peer pile up unbounded work. Counted per + connection until per-teacup identity lands. A cap that is not a positive integer fails the boot. + Mesh is `@experimental`. + - **Mesh: peer and RPC latency on `mesh:*` events** (#97). A new `mesh:rpc` event fires for each teacup→teapot call that answered, with `name` (token or route), `url` (the teapot), `durationMs` and the request's `requestId`/`traceId`. `mesh:rpc:error` carries the same fields diff --git a/api/index.api.md b/api/index.api.md index 62ac8d8..c8763c9 100644 --- a/api/index.api.md +++ b/api/index.api.md @@ -570,6 +570,7 @@ export interface MeshConfig { allowInsecure?: boolean; bootTimeoutMs?: number; heartbeatMs?: number; + maxInflightPerPeer?: number; onManifestChange?: 'refuse'; reconnect?: boolean | { initialDelayMs?: number; @@ -592,6 +593,7 @@ export interface MeshControlDeps { // (undocumented) manifest: Manifest; maxBodyBytes?: number; + maxInflightPerPeer?: number; // (undocumented) resolveRoute: (name: string, env: RequestEnvelope) => Promise; // (undocumented) diff --git a/src/app/index.ts b/src/app/index.ts index 1769b82..5c67271 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -1831,6 +1831,9 @@ function buildMeshControl( } if (!mesh?.secret || !hasExports) return undefined; + const cap = mesh.maxInflightPerPeer; + if (cap !== undefined && !(Number.isInteger(cap) && cap > 0)) + throw new Error(`mesh.maxInflightPerPeer must be a positive integer, got ${String(cap)}`); const { container, orderedProviders, orderedSteps } = deps; const { bus, providedSeed, planSteps, onError, logger } = deps.deps; const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes }); @@ -1917,6 +1920,7 @@ function buildMeshControl( resolveRoute, bus, maxBodyBytes: deps.maxBodyBytes, + maxInflightPerPeer: mesh.maxInflightPerPeer, }); } diff --git a/src/app/types.ts b/src/app/types.ts index bae0e11..757b3a8 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -136,6 +136,13 @@ export interface MeshConfig { teapots?: Array<{ url: string; secret: string }>; /** How long an RPC may wait for its teapot before failing with 504 (default: 30s). */ timeoutMs?: number; + /** + * Teapot side: how many RPCs one connected teacup may have running at once (default: 256). Over + * the cap a call is refused before any work starts, and the teacup's client gets `503` with + * `retry-after`. A teacup that times out a call does not cancel it on the teapot, so without a + * cap a slow step lets one peer pile up unbounded work. Counted per connection. + */ + maxInflightPerPeer?: number; /** * Gap between heartbeat pings to each teapot (default: 15s). Two unanswered rounds close the * link, so a half-open connection surfaces as an immediate 503 instead of every request paying diff --git a/src/mesh/link.ts b/src/mesh/link.ts index 4bfdfc6..3cc46bd 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -180,7 +180,9 @@ function settleRpcResponse( // "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 }); - entry.reject(new HttpError(frame.error.status ?? 500, frame.error.message)); + // 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)); } } diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index a276dad..3b8d515 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -107,8 +107,16 @@ export interface MeshControlDeps { * ({@link controlFrameLimit}). Defaults to the 1 MB body default. */ maxBodyBytes?: number; + /** In-flight RPCs one peer may hold before the next answers 503 (#98). Default {@link MAX_INFLIGHT_PER_PEER}. */ + maxInflightPerPeer?: number; } +/** + * Default cap on one peer's concurrent RPCs. A teacup that times out a call does not cancel it here + * (that is the cancel frame's job), so without a cap a slow step lets one peer pile up unbounded work. + */ +const MAX_INFLIGHT_PER_PEER = 256; + /** The rpc-req member of the {@link Frame} union. */ type RpcReqFrame = Extract; @@ -254,6 +262,8 @@ async function serveFrames( maxFrameChars: number, ): Promise { let authed = false; + let inflight = 0; // this peer's RPCs still running (#98) + 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. const handshakeTimer = setTimeout(() => { @@ -297,7 +307,27 @@ async function serveFrames( // deliberately not awaited: RPCs overlap, exactly as they did under the `ws.on('message')` // listener. The id-keyed `pending` map on the peer exists to allow in-flight concurrency — // awaiting here would silently serialize every mesh call. - void handleRpc(socket, frame, deps, exportedScopes, exportedRoutes); + // 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) { + deps.bus?.emit('mesh:rpc:error', { + name: frame.name, + status: 503, + error: new Error('mesh peer over maxInflightPerPeer'), + }); + void reply(socket, { + type: 'rpc-res', + id: frame.id, + ok: false, + error: { message: `mesh: too many concurrent calls from this peer (max ${maxInflight})`, status: 503 }, + }); + continue; + } + + inflight += 1; + void handleRpc(socket, frame, deps, exportedScopes, exportedRoutes).finally(() => { + inflight -= 1; + }); } } catch { /* socket failed; the disconnect emit below is the same signal a clean close gives */ diff --git a/test/mesh/max-inflight.test.ts b/test/mesh/max-inflight.test.ts new file mode 100644 index 0000000..9d31809 --- /dev/null +++ b/test/mesh/max-inflight.test.ts @@ -0,0 +1,80 @@ +import { describe, it, expect } from 'vitest'; +import { createApp, Step, Route, Get, Module, needs } from '../../src/index'; + +// #98: a teapot caps how many RPCs one peer may have running; over the cap, 503 + retry-after. + +@Step({ provides: 'slow', needs: [], export: true }) +class Slow { + async run() { + await new Promise((r) => setTimeout(r, 200)); + return { slow: true }; + } +} +@Module({ mountpoint: '/api', steps: [Slow] }) +class TeapotModule {} + +@Route('/t') +class Ctl { + @Get('/') + get(@needs('slow') slow: any) { + return { slow }; + } +} +@Module({ mountpoint: '/api', controllers: [Ctl] }) +class TeacupModule {} + +const quiet = { debug() {}, info() {}, warn() {}, error() {} }; + +describe('mesh maxInflightPerPeer (#98)', () => { + it('answers 503 with retry-after over the cap, and serves again once calls finish', async () => { + const teapot = createApp({ + modules: [TeapotModule], + experimental: true, + logger: quiet, + mesh: { secret: 's', maxInflightPerPeer: 2 }, + }); + const refused: unknown[] = []; + teapot.bus.on('mesh:rpc:error', (e) => refused.push(e.status)); + const server = await teapot.listen(0); + const url = `ws://127.0.0.1:${(server.address() as { port: number }).port}/__mesh__/control`; + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + logger: quiet, + mesh: { teapots: [{ url, secret: 's' }] }, + }); + + try { + await teacup.ready(); + const get = () => teacup.fetch(new Request('http://x/api/t')); + const results = await Promise.all([get(), get(), get()]); + const statuses = results.map((r) => r.status).sort(); + + expect(statuses).toEqual([200, 200, 503]); + expect(results.find((r) => r.status === 503)!.headers.get('retry-after')).toBe('1'); + expect(refused).toEqual([503]); + + // the counter went back down: the cap is on concurrency, not a budget that runs out + expect((await get()).status).toBe(200); + } finally { + await teacup.close(); + await teapot.close(); + server.close(); + } + }, 15_000); + + it('rejects a cap that is not a positive integer', async () => { + const teapot = createApp({ + modules: [TeapotModule], + experimental: true, + logger: quiet, + mesh: { secret: 's', maxInflightPerPeer: 0 }, + }); + + try { + await expect(teapot.ready()).rejects.toThrow(/maxInflightPerPeer must be a positive integer/); + } finally { + await teapot.close(); + } + }); +});