fix(mesh): reconnect to a teapot that came back, refusing a manifest that no longer fits
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 18s

A dropped link stayed dead for the life of the process. Every RPC answered
503 until the teacup restarted, so deploying a teapot forced a restart of
every teacup depending on it and boot order became load-bearing — a worse
operational property than any gap the docs actually listed.

The Link now outlives any single socket, because the graph captured its rpc
closure at boot and a reconnect that produced a new Link would leave the graph
pointing at the dead one. Backoff doubles from 500ms to 30s with full jitter,
so teacups that went down together do not return in lockstep.

A returning teapot whose manifest no longer exports what the graph was
validated against is refused, not adopted: that graph is already serving, and
a token cannot be validated away after the fact. The link keeps retrying,
since a partial deploy may still restore it, and logs once per distinct
manifest rather than once per attempt. Refusal ships as a named policy
(onManifestChange: 'refuse') so hot reconciliation can arrive later as an
addition rather than as a change of what the default means — these are
separate processes on separate deploy cadences.

close() is terminal. closeLinks runs on shutdown, and a link that reconnected
after the application hung up would leave a process that cannot exit.

Also closes the documented gap where an app-scope export outlived its teapot
with a stale value: a successful reconnect re-registers those bindings, so the
next resolve re-runs the RPC. That invalidation is a named function rather
than inline, because it is the seam a future 'reconcile' reuses.

Tested on all three runtimes rather than on Node alone — Node's ws package,
Deno's global WebSocket and Bun's server-level socket handler are three
implementations, and swapping a socket under a live graph is where they stop
agreeing. 7 of the 9 new Node tests were verified to fail against the old
code; the 2 that pass are the ones that should, since the old code never
reconnected at all.

Mesh stays alpha.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-08-18 10:53:24 -05:00
1 parent 6672185ba2
commit 6ffbad9825
8 files changed
+819 -57

No files matched your search

+101
View File
@@ -0,0 +1,101 @@
// Reconnection under the real Bun runtime.
//
// Separate from the Node and Deno suites deliberately. Bun's WebSocket lifecycle is a third
// implementation — its socket events land on a server-level handler rather than the socket — and a
// link that swaps its socket underneath a live graph is precisely where three implementations
// stop behaving the same. Defining this on Node and hoping is not enough.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { runtime: 'bun' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
/** A port nobody is on, so the teapot can be killed and brought back at the same address. */
function freePort(): number {
const probe = Bun.serve({ port: 0, fetch: () => new Response('') });
const { port } = probe;
probe.stop(true);
return port;
}
/** Boot a teapot on a fixed port; the handle kills it and leaves the port free again. */
function startTeapot(port: number) {
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = serveBun(app, { port });
return {
stop: async () => {
server.stop(true);
await app.close();
},
};
}
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
test('mesh on Bun: a teacup reconnects to a teapot that came back', async () => {
const port = freePort();
let teapot = startTeapot(port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
heartbeatMs: 50,
timeoutMs: 2000,
},
});
try {
const before = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
expect(before.status).toBe(200);
await teapot.stop();
await settle(100);
// the down window answers immediately rather than waiting out timeoutMs
const down = await teacup.fetch(new Request('http://x/api/local/who'));
expect(down.status).toBe(503);
teapot = startTeapot(port);
await settle(400);
const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } }));
expect(after.status).toBe(200);
expect((await after.json()).auth).toEqual({ token: 'xyz' });
} finally {
await teacup.close();
await teapot.stop();
}
});
+101
View File
@@ -0,0 +1,101 @@
// Reconnection under the real Deno runtime.
//
// This exists separately from the Node suite because the teacup's WebSocket client is a different
// implementation here — Deno's global `WebSocket`, not the `ws` package — and a link that swaps its
// socket underneath a live graph is exactly the kind of thing that works on one and not the other.
//
// Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { runtime: 'deno' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run(ctx: any) {
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
/** A port nobody is on, so the teapot can be killed and brought back at the same address. */
function freePort(): number {
const probe = Deno.listen({ port: 0 });
const { port } = probe.addr as Deno.NetAddr;
probe.close();
return port;
}
/** Boot a teapot on a fixed port; the returned handle can kill it and leave the port free again. */
async function startTeapot(port: number) {
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = serveDeno(app, { port });
await new Promise((r) => setTimeout(r, 50));
return {
stop: async () => {
await server.shutdown();
await app.close();
},
};
}
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
Deno.test('mesh on Deno: a teacup reconnects to a teapot that came back', async () => {
const port = freePort();
let teapot = await startTeapot(port);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
heartbeatMs: 50,
timeoutMs: 2000,
},
});
try {
const before = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
assertEquals(before.status, 200);
await teapot.stop();
await settle(100);
// the down window answers immediately rather than waiting out timeoutMs
const down = await teacup.fetch(new Request('http://x/api/local/who'));
assertEquals(down.status, 503);
teapot = await startTeapot(port);
await settle(400);
const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } }));
assertEquals(after.status, 200);
assertEquals((await after.json()).auth, { token: 'xyz' });
} finally {
await teacup.close();
await teapot.stop();
}
});
+177
View File
@@ -0,0 +1,177 @@
import { describe, it, expect } from 'vitest';
import { WebSocketServer } from 'ws';
import { connectLink, missingFromManifest } from '../../src/mesh/link';
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest } from '../../src/mesh/protocol';
const V = MESH_PROTOCOL_VERSION;
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
/**
* A teapot bound to a fixed port so it can be killed and restarted at the same URL — which is the
* whole point here: reconnection means returning to the *same* teapot, not finding another one.
* Its manifest is swappable so a restart can come back exporting something different.
*/
function teapotOn(port: number, manifest: Manifest, answer: unknown = { ok: true }) {
const wss = new WebSocketServer({ port });
wss.on('connection', (ws) => {
let authed = false;
ws.on('message', (d) => {
const frame = decode(d.toString());
if (!authed) {
if (frame.type === 'hello' && frame.secret === 'good') {
authed = true;
ws.send(encode({ type: 'manifest', v: V, scopes: manifest.scopes, routes: manifest.routes }));
} else ws.close(1008);
return;
}
if (frame.type === 'ping') ws.send(encode({ type: 'pong' }));
if (frame.type === 'rpc-req') ws.send(encode({ type: 'rpc-res', id: frame.id, ok: true, result: answer }));
});
});
return new Promise<{ close: () => Promise<void> }>((resolve) => {
wss.on('listening', () =>
resolve({
close: () =>
new Promise<void>((done) => {
for (const client of wss.clients) client.terminate();
wss.close(() => done());
}),
}),
);
});
}
/** A free port, taken by opening and immediately closing a server on port 0. */
async function freePort(): Promise<number> {
const probe = new WebSocketServer({ port: 0 });
await new Promise((r) => probe.on('listening', r));
const port = (probe.address() as { port: number }).port;
await new Promise((r) => probe.close(r));
return port;
}
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
const url = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
const SCOPES: Manifest = { scopes: [{ token: 'auth', scope: 'app' }], routes: [] };
const fast = { initialDelayMs: 20, maxDelayMs: 60 };
describe('mesh reconnection', () => {
it('reconnects to the same teapot and serves again', async () => {
const port = await freePort();
let teapot = await teapotOn(port, SCOPES);
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 });
expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: true });
await teapot.close();
await settle(50);
// the window where the link is down answers immediately rather than after timeoutMs
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
teapot = await teapotOn(port, SCOPES, { ok: 'again' });
await settle(300);
expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: 'again' });
link.close();
await teapot.close();
});
it('refuses a returning teapot whose manifest lost a token the graph needs', async () => {
const port = await freePort();
let teapot = await teapotOn(port, SCOPES);
const warnings: string[] = [];
const logger = { debug() {}, info() {}, warn: (m: string) => warnings.push(m), error() {} };
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50, logger });
await teapot.close();
await settle(50);
// comes back exporting nothing — the graph was validated against 'auth' at boot
teapot = await teapotOn(port, { scopes: [], routes: [] });
await settle(300);
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
expect(warnings.some((w) => w.includes("app-scope 'auth'") && w.includes('refusing to reconnect'))).toBe(true);
// logged once per distinct manifest, not once per attempt
expect(warnings.filter((w) => w.includes('refusing to reconnect')).length).toBe(1);
link.close();
await teapot.close();
});
it('stops reconnecting once the application closes the link', async () => {
const port = await freePort();
const teapot = await teapotOn(port, SCOPES);
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 });
await teapot.close();
link.close();
// if close() were not terminal, the link would reconnect to the teapot that comes back here —
// which is what would leave app.close() with a process that cannot exit
const revived = await teapotOn(port, SCOPES, { ok: 'revived' });
await settle(300);
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
await revived.close();
});
it('reconnect: false keeps the old fail-once behaviour', async () => {
const port = await freePort();
let teapot = await teapotOn(port, SCOPES);
const link = await connectLink({ url: url(port), secret: 'good', reconnect: false, heartbeatMs: 50 });
await teapot.close();
teapot = await teapotOn(port, SCOPES);
await settle(300);
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
link.close();
await teapot.close();
});
});
describe('missingFromManifest', () => {
const booted: Manifest = {
scopes: [
{ token: 'auth', scope: 'request' },
{ token: 'config', scope: 'app' },
],
routes: [{ method: 'GET', pattern: '/svc/:id' }],
};
it('accepts an identical manifest', () => {
expect(missingFromManifest(booted, booted)).toEqual([]);
});
it('accepts extra exports — the graph is fixed at boot and nothing new is spliced', () => {
const wider: Manifest = {
scopes: [...booted.scopes, { token: 'billing', scope: 'app' }],
routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }],
};
expect(missingFromManifest(booted, wider)).toEqual([]);
});
it('accepts a route parameter that was only renamed', () => {
const renamed: Manifest = { scopes: booted.scopes, routes: [{ method: 'GET', pattern: '/svc/:name' }] };
expect(missingFromManifest(booted, renamed)).toEqual([]);
});
it('reports a token whose lifetime changed, since the graph resolved it under the old one', () => {
const flipped: Manifest = {
scopes: [
{ token: 'auth', scope: 'app' },
{ token: 'config', scope: 'app' },
],
routes: booted.routes,
};
expect(missingFromManifest(booted, flipped)).toEqual(["request-scope 'auth'"]);
});
it('reports a missing route by method and pattern', () => {
const routeless: Manifest = { scopes: booted.scopes, routes: [] };
expect(missingFromManifest(booted, routeless)).toEqual(["route 'GET /svc/:id'"]);
});
});