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

+69 -4
View File
@@ -18,11 +18,15 @@ type PendingEntry = {
timer: ReturnType<typeof setTimeout>;
};
/** Reject and clear every in-flight RPC — used when the link closes. */
/**
* Reject and clear every in-flight RPC — used when the link closes.
* 503, not a bare Error: 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. A bare Error renders as a 500.
*/
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): void {
for (const [, entry] of pending) {
clearTimeout(entry.timer);
entry.reject(new Error(reason));
entry.reject(new HttpError(503, reason));
}
pending.clear();
@@ -38,10 +42,19 @@ function sendRpc(
ctx: RequestEnvelope,
timeoutMs: number,
): Promise<unknown> {
// Answer now rather than in timeoutMs. A closed socket cannot deliver the frame, so waiting
// would make every request to a downed teapot hang for the full timeout (30s by default)
// before failing anyway — the caller pays for a verdict already known.
if (!socket.isOpen) {
return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`));
}
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);
rejectCall(new Error(`mesh rpc timeout: ${name}`));
rejectCall(new HttpError(504, `mesh rpc timeout: ${name}`));
}, timeoutMs);
pending.set(id, { resolve: resolveCall, reject: rejectCall, timer });
@@ -87,6 +100,50 @@ function settleRpcResponse(
}
}
/** Default gap between heartbeat pings. Two missed rounds close the link. */
const HEARTBEAT_MS = 15_000;
/**
* Close code for a link we hang up on because its teapot went quiet.
*
* Not 1011: a *client* may only send 1000 or 3000-4999 — anything else throws `invalid code`,
* and our neutral close swallows throws, so a reserved code would leave the link open while
* looking like it closed. 4000+ is the application range, so 4011 mirrors 1011's meaning.
*/
const CLOSE_HEARTBEAT_TIMEOUT = 4011;
/**
* Pings the teapot on an interval and closes the link if a round goes unanswered.
*
* A TCP connection can die without either side noticing — a dropped route, a killed container,
* a NAT timing out — leaving the socket "open" with nobody home. Without this, a teacup only
* learns on the next request, which pays the full rpc timeout before failing. Closing the socket
* turns that into an immediate 503 from the dead-link guard, and emits `mesh:disconnect`.
*
* The interval is unref'd, so a heartbeat never holds the process open by itself.
*/
function startHeartbeat(socket: WsSocket, everyMs: number): { stop: () => void; markAlive: () => void } {
let answered = true;
const timer = setInterval(() => {
if (!answered) {
socket.close(CLOSE_HEARTBEAT_TIMEOUT, 'mesh heartbeat timeout'); // aborts -> disconnect + reject pending
return;
}
answered = false;
socket.send(encode({ type: 'ping' }));
}, everyMs);
timer.unref?.();
return {
stop: () => clearInterval(timer),
markAlive: () => {
answered = true;
},
};
}
/** Handle for the in-flight handshake, so the frame loop can settle `connectLink`'s promise. */
interface Handshake {
url: string;
@@ -97,6 +154,7 @@ interface Handshake {
resolve: (link: Link) => void;
reject: (error: unknown) => void;
onManifest: () => void;
onPong: () => void;
}
/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else build the Link. */
@@ -129,6 +187,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);
}
}
@@ -141,6 +200,7 @@ export function connectLink(args: {
url: string;
secret: string;
timeoutMs?: number;
heartbeatMs?: number;
bus?: Bus;
Ctor?: SocketCtor;
}): Promise<Link> {
@@ -148,6 +208,7 @@ export function connectLink(args: {
const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined);
const pending = new Map<string, PendingEntry>();
let manifest = false;
let heartbeat: { stop: () => void; markAlive: () => void } | undefined;
return new Promise<Link>((resolve, reject) => {
const connectTimer = setTimeout(() => {
@@ -166,7 +227,10 @@ export function connectLink(args: {
onManifest: () => {
manifest = true;
clearTimeout(connectTimer);
// started only once authenticated: an unauthenticated peer should not be pinging
heartbeat = startHeartbeat(socket, args.heartbeatMs ?? HEARTBEAT_MS);
},
onPong: () => heartbeat?.markAlive(),
};
opened.then(
@@ -180,8 +244,9 @@ export function connectLink(args: {
'abort',
() => {
clearTimeout(connectTimer);
heartbeat?.stop();
args.bus?.emit('mesh:disconnect', { name: args.url });
rejectAllPending(pending, 'mesh link closed');
rejectAllPending(pending, `mesh link to ${args.url} is down`);
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
},
{ once: true },
+16 -2
View File
@@ -31,13 +31,21 @@ export interface Manifest {
routes: RouteEntry[];
}
/** Discriminated union of every message on the mesh wire. The handshake frames carry `v`. */
/**
* Discriminated union of every message on the mesh wire. The handshake frames carry `v`.
*
* `ping`/`pong` are application frames rather than WebSocket protocol pings on purpose: the `ws`
* package exposes `ws.ping()`, but the platform `WebSocket` that Deno and Bun provide does not,
* so a protocol-level heartbeat could not work on every runtime mesh claims to support.
*/
export type Frame =
| { type: 'hello'; v: number; secret: string }
| { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] }
| { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope }
| { type: 'rpc-res'; id: string; ok: true; result: unknown }
| { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } };
| { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } }
| { type: 'ping' }
| { type: 'pong' };
const isString = (value: unknown): value is string => typeof value === 'string';
const isNumber = (value: unknown): boolean => typeof value === 'number';
@@ -71,6 +79,12 @@ const SHAPE: Record<Frame['type'], ShapeCheck> = {
if (typeof frame.ok !== 'boolean') bad('ok must be a boolean');
if (frame.ok === false && !isObject(frame.error)) bad('error must be an object when ok is false');
},
ping: () => {
/* the tag is the whole frame */
},
pong: () => {
/* the tag is the whole frame */
},
};
/** Serialize a frame to a JSON wire string. */
+6
View File
@@ -167,6 +167,12 @@ async function serveFrames(
continue;
}
// answered only after the handshake: an unauthenticated peer gets no signal at all
if (frame.type === 'ping') {
socket.send(encode({ type: 'pong' }));
continue;
}
if (frame.type !== 'rpc-req') continue;
// deliberately not awaited: RPCs overlap, exactly as they did under the `ws.on('message')`