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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions api/index.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,7 @@ export interface MeshConfig {
allowInsecure?: boolean;
bootTimeoutMs?: number;
heartbeatMs?: number;
maxInflightPerPeer?: number;
onManifestChange?: 'refuse';
reconnect?: boolean | {
initialDelayMs?: number;
Expand All @@ -592,6 +593,7 @@ export interface MeshControlDeps {
// (undocumented)
manifest: Manifest;
maxBodyBytes?: number;
maxInflightPerPeer?: number;
// (undocumented)
resolveRoute: (name: string, env: RequestEnvelope) => Promise<ResponseShape>;
// (undocumented)
Expand Down
4 changes: 4 additions & 0 deletions src/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@

export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';

type Runner = (ctx: any) => any;

Check warning on line 81 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type

Check warning on line 81 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type

/** Something shutdown closes: a mesh link, or the retry loop of a teapot that missed boot. */
type Closable = Pick<Link, 'close'>;
Expand Down Expand Up @@ -671,7 +671,7 @@
'is the object itself, and the mesh transports data, not objects. ' +
'Export a @Step instead, which runs on the teapot per request and returns its result.',
);
const instance: any = new ProviderClass();

Check warning on line 674 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
registry.providerInstances.set(meta.provides, instance);
registry.setRunner(
meta.provides,
Expand All @@ -686,7 +686,7 @@
const meta = getStepMeta(StepClass)!;
registry.stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
if (meta.export) registry.exportedSteps.push(meta.provides);
const instance: any = new StepClass();

Check warning on line 689 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
registry.setRunner(
meta.provides,
keyedRunner('step', meta.provides, [meta.provides], (ctx) => instance.run(ctx)),
Expand All @@ -704,7 +704,7 @@
): void {
for (const ControllerClass of controllers) {
for (const route of getRoutes(ControllerClass)) {
const instance: any = new ControllerClass();

Check warning on line 707 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
const argSpecs = getArgs(ControllerClass, route.handlerName);
const pattern = joinPath(mountpoint, route.path);
const declaration = `${ControllerClass.name}.${route.handlerName}`;
Expand All @@ -726,7 +726,7 @@
steps: [],
handlerName: route.handlerName,
needs: getHandlerNeeds(argSpecs),
run: async (context: any) => instance[route.handlerName](...(await resolveArgs(argSpecs, context))),

Check warning on line 729 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
transformer,
duplicates: route.duplicates,
maxBodyBytes: route.maxBodyBytes,
Expand Down Expand Up @@ -1831,6 +1831,9 @@
}

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 });
Expand All @@ -1854,7 +1857,7 @@

const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
// context is intentionally `any`: providers and steps merge arbitrary keys into it
const seed: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers };

Check warning on line 1860 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
// The teapot gates names before this runs, so an exported token always has a slice.
const { providers, steps } = slices.get(name)!;

Expand All @@ -1877,7 +1880,7 @@
const plan = routePlans.find((candidate) => candidate.pattern === name && candidate.method === env.method);

if (!plan) {
const error: any = new Error(`no route ${name}`);

Check warning on line 1883 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
error.status = 404;
throw error;
}
Expand All @@ -1902,7 +1905,7 @@
});

if ('stream' in result) {
const error: any = new Error('cannot proxy a streaming route');

Check warning on line 1908 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
error.status = 500;
throw error;
}
Expand All @@ -1917,6 +1920,7 @@
resolveRoute,
bus,
maxBodyBytes: deps.maxBodyBytes,
maxInflightPerPeer: mesh.maxInflightPerPeer,
});
}

Expand Down
7 changes: 7 additions & 0 deletions src/app/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@
steps: GraphNode[];
handlerName: string;
needs: string[];
run: (ctx: any) => Promise<unknown>;

Check warning on line 120 in src/app/types.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
transformer: typeof JsonTransformer;
duplicates?: 'array' | 'last';
maxBodyBytes?: number;
Expand All @@ -136,6 +136,13 @@
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
Expand Down
4 changes: 3 additions & 1 deletion src/mesh/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}

Expand Down
32 changes: 31 additions & 1 deletion src/mesh/teapot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Frame, { type: 'rpc-req' }>;

Expand Down Expand Up @@ -254,6 +262,8 @@ async function serveFrames(
maxFrameChars: number,
): Promise<void> {
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(() => {
Expand Down Expand Up @@ -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 */
Expand Down
80 changes: 80 additions & 0 deletions test/mesh/max-inflight.test.ts
Original file line number Diff line number Diff line change
@@ -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();
}
});
});