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

+9 -3
View File
@@ -7,7 +7,7 @@ import { runPipeline, runSteps, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
import type { HttpOptions } from '../http';
import { buildFetch } from '../http/web';
import { matchWsRoute, runWsConnection, type WsRequest, type WsSocket } from '../http/ws-core';
import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocket } from '../http/ws-core';
import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
@@ -491,7 +491,13 @@ async function spliceRemoteScopes(
try {
for (const teapot of mesh.teapots ?? []) {
const link = await connectLink({ url: teapot.url, secret: teapot.secret, timeoutMs: mesh.timeoutMs, bus });
const link = await connectLink({
url: teapot.url,
secret: teapot.secret,
timeoutMs: mesh.timeoutMs,
heartbeatMs: mesh.heartbeatMs,
bus,
});
meshLinks.push(link);
const { providers, steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`;
@@ -816,7 +822,7 @@ function buildAppUpgrade(
return;
}
await meshControl.handle(ready);
await trackUntil(ready, meshControl.handle(ready), streams);
return;
}
+7
View File
@@ -86,5 +86,12 @@ export interface RoutePlan {
export interface MeshConfig {
secret?: string;
teapots?: Array<{ url: string; secret: string }>;
/** How long an RPC may wait for its teapot before failing with 504 (default: 30s). */
timeoutMs?: 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
* `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter.
*/
heartbeatMs?: number;
}
+19
View File
@@ -31,6 +31,25 @@ export function matchWsRoute(
.find((entry) => entry.params);
}
/**
* Runs `connection` with the socket registered for force-close on shutdown, unregistering it
* when the connection ends. Without this a long-lived socket keeps `server.close()` waiting for
* a peer that has no reason to hang up — the mesh control channel is exactly that shape.
*/
export async function trackUntil(
socket: WsSocket,
connection: Promise<void>,
streams?: Set<() => void>,
): Promise<void> {
const { closer } = trackConnection(socket, streams);
try {
await connection;
} finally {
streams?.delete(closer);
}
}
/** Registers the connection with the stream registry so it can be force-closed on shutdown. */
function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer: () => void } {
const closer = () => {
+11 -4
View File
@@ -1,7 +1,7 @@
import type http from 'http';
import { channel } from '../channel';
import type { Bus } from '../bus';
import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from './ws-core';
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
import type { WsRouteDef, MeshControl } from './types';
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
@@ -30,6 +30,7 @@ function handleMeshUpgrade(
req: http.IncomingMessage,
socket: any,
head: Buffer,
streams?: Set<() => void>,
): boolean {
if (path !== meshControl.path) return false;
@@ -40,8 +41,14 @@ function handleMeshUpgrade(
// nodeSocket, not the raw ws: the control channel is the last consumer that spoke the
// `ws` EventEmitter API directly. It now takes the same neutral socket every route does.
// serveFrames swallows its own failures, so the floating promise cannot reject
wss.handleUpgrade(req, socket, head, (ws: any) => void meshControl.handle(nodeSocket(ws)));
// Tracked like any other long-lived socket: a connected teacup has no reason to hang up, so
// an untracked control channel leaves the teapot's server.close() waiting on it forever.
// serveFrames swallows its own failures, so the floating promise cannot reject.
wss.handleUpgrade(req, socket, head, (ws: any) => {
const neutral = nodeSocket(ws);
void trackUntil(neutral, meshControl.handle(neutral), streams);
});
return true;
}
@@ -97,7 +104,7 @@ export function attachWs(
server.on('upgrade', (req, socket, head) => {
const path = (req.url ?? '/').split('?')[0];
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head)) return;
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return;
const route = matchWsRoute(wsRoutes, path);
+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')`