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:
11 files changed
+378
-13
No files matched your search
@@ -35,10 +35,22 @@ green-tea uses calendar versioning: `YY.MM.PATCH`.
|
||||
ready to serve are different things, and drawing a diagram should not open your database
|
||||
connections. Serving boots them too and shares the same memoized step.
|
||||
|
||||
- **Mesh heartbeat** (`mesh.heartbeatMs`, default 15s): each teacup pings its teapots and closes a
|
||||
link after two unanswered rounds, so a half-open connection surfaces as an immediate 503 rather
|
||||
than every request paying `timeoutMs` first. Ping/pong are mesh frames, not WebSocket protocol
|
||||
pings — the platform `WebSocket` on Deno/Bun does not expose `ws.ping()`.
|
||||
|
||||
### Fixed
|
||||
- The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now
|
||||
served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge),
|
||||
not only the Node `app.listen()` path.
|
||||
- **A teapot with a live control channel could never shut down.** Mesh control connections were
|
||||
not registered with the stream registry, so `server.close()` waited on a connected teacup that
|
||||
had no reason to hang up, and `app.close()` never resolved.
|
||||
- **A downed teapot now answers 503 immediately** instead of hanging for the full `timeoutMs`
|
||||
(30s by default) and then answering 500. A closed socket cannot deliver the frame, so the wait
|
||||
bought nothing. An RPC that times out on a live link is now 504, not 500 — a dead upstream and
|
||||
a slow one are different operational stories, and neither is "this service broke".
|
||||
- **`request:step:enter`/`leave` are now emitted for `@Ws` and mesh routes.** Only HTTP routes
|
||||
emitted them, so a logging plugin silently observed nothing on a WebSocket route — a gap in a
|
||||
documented plugin API. All transports now run their steps through one path.
|
||||
|
||||
+9
-3
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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
@@ -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. */
|
||||
|
||||
@@ -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')`
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -112,6 +112,28 @@ declared locally — the local route takes precedence and the remote one will no
|
||||
reached. Remove one if that is not what you meant.
|
||||
```
|
||||
|
||||
## When a teapot goes away
|
||||
|
||||
A dead upstream is not a broken service, and the status says which:
|
||||
|
||||
| What happened | Status |
|
||||
| --- | --- |
|
||||
| The link is down (closed, or the heartbeat gave up) | **503** Service Unavailable |
|
||||
| The link is up but the teapot didn't answer in `timeoutMs` | **504** Gateway Timeout |
|
||||
| The teapot answered with an error | whatever it said |
|
||||
|
||||
503 arrives **immediately** — a closed socket cannot deliver the frame, so waiting `timeoutMs` (30s by default) would just make the caller pay for a verdict already known.
|
||||
|
||||
Each teacup pings its teapots every `heartbeatMs` (15s by default) and closes a link after two unanswered rounds. This is what catches a **half-open** connection — a dropped route, a killed container, a NAT that timed out — where the socket still looks open with nobody home. Without it, a teacup only finds out on the next request, which pays the full timeout first.
|
||||
|
||||
```typescript
|
||||
mesh: { teapots: [...], heartbeatMs: 5000 } // notice sooner, chatter more
|
||||
```
|
||||
|
||||
Ping and pong are ordinary mesh frames rather than WebSocket protocol pings, because the platform `WebSocket` on Deno and Bun does not expose `ws.ping()` — a protocol-level heartbeat could not work on every runtime mesh supports.
|
||||
|
||||
**An app-scope export survives its teapot.** It is resolved once and memoised, so a provider keeps answering from cache after the link drops — with a value that can go stale. Reconnect reconciliation is a known gap.
|
||||
|
||||
## Protocol version
|
||||
|
||||
Peers are separate processes on separate deploy cadences, so the wire is versioned: `MESH_PROTOCOL_VERSION` travels in the `hello` and `manifest` frames, and a mismatch is refused on both sides with both versions named. A teapot checks the version **before** the secret — a skewed peer is not an authentication failure, and reporting it as one would send you hunting the wrong bug.
|
||||
|
||||
Reference in new issue
Block a user