feat(mesh): heartbeat the link, and tell the truth when a teapot is gone

Three bugs, found by writing the tests for the status codes.

A teapot with a live control channel could never shut down. Control connections
were never registered with the stream registry, so server.close() sat waiting on
a connected teacup that had no reason to hang up, and app.close() never resolved.
Every other long-lived socket was already tracked; the control channel was the
one that skipped it.

A downed teapot answered 500 — after 30 seconds. sendRpc queued the frame on a
closed socket and waited out the full timeout for a verdict already known. It now
rejects immediately with 503: a dead upstream is not "this service broke", and the
status is what tells a caller it may retry and an operator where to look. An RPC
that times out on a *live* link is 504 — a slow teapot and a gone one are
different stories.

Heartbeat: each teacup pings its teapots (`mesh.heartbeatMs`, default 15s) and
closes a link after two unanswered rounds. This is what catches a half-open
connection, where the socket looks open with nobody home — otherwise a teacup only
learns on the next request. Ping/pong are mesh frames rather than WebSocket
protocol pings because Deno's and Bun's platform WebSocket does not expose
ws.ping(), so a protocol-level heartbeat could not work everywhere mesh runs.
Added to v1 while the wire still has no deployed peers; later it would be a
version bump that refuses every old peer.

The heartbeat's first close code was 1011, which silently did nothing: a *client*
may only send 1000 or 3000-4999, so it threw `invalid code` — and our neutral
close swallows throws, so the link stayed open while looking closed. 4011 mirrors
1011's meaning inside the application range.

Reconnect (and reconciling app-scope values, which survive their teapot from
cache) stays out — it is a post-beta spec of its own.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-15 23:32:45 -05:00
1 parent 5e7d952f45
commit dba40b0c8b
11 files changed
+378 -13

No files matched your search

+121
View File
@@ -0,0 +1,121 @@
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index';
const SECRET = 's3cr3t';
@Provider({ provides: 'config', export: true })
class Config {
provide() {
return { config: { region: 'mx' } };
}
}
@Step({ provides: 'auth', needs: [], export: true })
class Auth {
run() {
return { auth: { token: 'ok' } };
}
}
@Route('/svc')
class SvcCtl {
@Get('/ping', { export: true })
ping() {
return { pong: true };
}
}
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [SvcCtl] })
class TeapotModule {}
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('auth') auth: any) {
return { auth };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const controlUrl = (server: any) => `ws://127.0.0.1:${(server.address() as any).port}/__mesh__/control`;
/**
* What a teacup answers once its teapot is gone. The status is the whole point: a dead upstream
* is not "I broke" (500) — it is "my dependency is unavailable" (503), which is what tells an
* operator where to look and what a caller may retry.
*/
describe('mesh link failure', () => {
it('answers 503 on a remote step once the teapot is gone', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer), secret: SECRET }] },
});
const ok = await teacup.fetch(new Request('http://x/api/local/who'));
expect(ok.status).toBe(200);
await teapot.close();
await new Promise((r) => setTimeout(r, 50));
const down = await teacup.fetch(new Request('http://x/api/local/who'));
expect(down.status).toBe(503);
await teacup.close();
});
it('answers 503 on a proxied remote route once the teapot is gone', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer), secret: SECRET }] },
});
const ok = await teacup.fetch(new Request('http://x/api/svc/ping'));
expect(ok.status).toBe(200);
await teapot.close();
await new Promise((r) => setTimeout(r, 50));
const down = await teacup.fetch(new Request('http://x/api/svc/ping'));
expect(down.status).toBe(503);
await teacup.close();
});
it('keeps serving an app-scope remote from cache after the link drops', async () => {
// Not a bug, but worth pinning: an app-scope export is resolved once and memoised, so it
// survives its teapot — with a value that can go stale. Reconciling on reconnect is a
// known gap (see the mesh guide), and this test is what would catch it changing by accident.
@Route('/cached')
class CachedCtl {
@Get('/cfg')
cfg(@needs('config') config: any) {
return { config };
}
}
@Module({ mountpoint: '/api', controllers: [CachedCtl] })
class CachedModule {}
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const teacup = createApp({
modules: [CachedModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer), secret: SECRET }] },
});
expect((await teacup.fetch(new Request('http://x/api/cached/cfg'))).status).toBe(200);
await teapot.close();
await new Promise((r) => setTimeout(r, 50));
const after = await teacup.fetch(new Request('http://x/api/cached/cfg'));
expect(after.status).toBe(200); // cached, so still answering
expect(await after.json()).toEqual({ config: { region: 'mx' } });
await teacup.close();
});
});
+86
View File
@@ -0,0 +1,86 @@
import { describe, it, expect } from 'vitest';
import { WebSocketServer } from 'ws';
import { connectLink } from '../../src/mesh/link';
import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
const V = MESH_PROTOCOL_VERSION;
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
/**
* A teapot that handshakes and answers RPCs, and optionally ignores pings — the shape of a
* half-open link: TCP still looks alive, the peer is not. Without a heartbeat a teacup only
* finds out when a request pays the full rpc timeout.
*/
function startTeapot(opts: { answerPings: boolean }) {
const wss = new WebSocketServer({ port: 0 });
const seen: string[] = [];
wss.on('connection', (ws) => {
ws.on('message', (data) => {
const frame = decode(data.toString());
seen.push(frame.type);
if (frame.type === 'hello') {
ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] }));
}
if (frame.type === 'ping' && opts.answerPings) ws.send(encode({ type: 'pong' }));
if (frame.type === 'rpc-req') ws.send(encode({ type: 'rpc-res', id: frame.id, ok: true, result: { got: 1 } }));
});
});
const port = (wss.address() as any).port;
return { url: `ws://127.0.0.1:${port}/__mesh__/control`, seen, close: () => wss.close() };
}
describe('mesh heartbeat', () => {
it('pings the teapot and keeps the link alive while it pongs', async () => {
const t = startTeapot({ answerPings: true });
const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30 });
await new Promise((r) => setTimeout(r, 120));
expect(t.seen.filter((f) => f === 'ping').length).toBeGreaterThan(1);
expect(await link.rpc('scope', 'auth', env)).toEqual({ got: 1 }); // still usable
link.close();
t.close();
});
it('closes the link when the teapot stops answering pings', async () => {
// the half-open case: the socket never errors, the peer just stops talking
const t = startTeapot({ answerPings: false });
const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30, timeoutMs: 10_000 });
await new Promise((r) => setTimeout(r, 200));
// 503 immediately from the dead-link guard, not a 10s wait on the rpc timeout
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
t.close();
});
it('emits mesh:disconnect when the heartbeat gives up', async () => {
const t = startTeapot({ answerPings: false });
const seen: string[] = [];
const bus = { emit: (e: string, p: any) => seen.push(`${e}:${p.name}`), on: () => () => {} } as any;
const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30, bus });
await new Promise((r) => setTimeout(r, 200));
expect(seen.some((s) => s.startsWith('mesh:disconnect'))).toBe(true);
link.close();
t.close();
});
it('does not ping before the handshake completes', async () => {
const t = startTeapot({ answerPings: true });
const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30 });
// hello must be first on the wire: an unauthenticated peer has no business pinging
expect(t.seen[0]).toBe('hello');
link.close();
t.close();
});
});