Files
core/src/http/ws-core.ts
T
chrnx dba40b0c8b 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>
2026-07-15 23:32:45 -05:00

138 lines
3.9 KiB
TypeScript

import { isHttpError } from '../signals';
import type { Bus } from '../bus';
import { matchPattern } from './router';
import type { WsRouteDef } from './types';
/** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */
export interface WsRequest {
url: string;
headers: Record<string, string | string[] | undefined>;
protocol: 'http' | 'https';
ip: string;
}
/** Capability an adapter builds from its runtime socket. The neutral core talks only to this. */
export interface WsSocket {
readonly inbound: AsyncIterable<unknown>;
readonly abort: AbortSignal;
readonly isOpen: boolean;
send(data: string): void;
close(code?: number, reason?: string): void;
terminate(): void;
}
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
export function matchWsRoute(
wsRoutes: WsRouteDef[],
path: string,
): { def: WsRouteDef; params: Record<string, string> | undefined } | undefined {
return wsRoutes
.map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) }))
.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 = () => {
try {
socket.terminate();
} catch {
/* */
}
};
streams?.add(closer);
return { closer };
}
/** Drives the outbound async iterator, sending each yielded value until done or the socket closes. */
async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator<unknown>): Promise<void> {
while (true) {
const { value, done } = await iterator.next();
if (done) break;
if (!socket.isOpen) break;
socket.send(typeof value === 'string' ? value : JSON.stringify(value));
}
try {
socket.close();
} catch {
/* already closed */
}
}
/** Closes with 4000+status for HttpErrors, 1011 otherwise. */
function closeOnError(socket: WsSocket, err: unknown): void {
if (isHttpError(err)) {
const reason = new TextDecoder().decode(new TextEncoder().encode(String(err.message)).subarray(0, 120));
try {
socket.close(4000 + err.status, reason);
} catch {
/* already closed */
}
} else {
try {
socket.close(1011);
} catch {
/* already closed */
}
}
}
/** Runs the full per-connection lifecycle over a neutral socket capability. */
export async function runWsConnection(
socket: WsSocket,
request: WsRequest,
route: { def: WsRouteDef; params: Record<string, string> | undefined },
bus?: Bus,
streams?: Set<() => void>,
): Promise<void> {
const { closer } = trackConnection(socket, streams);
const name = route.def.pattern;
let iterator: AsyncIterator<unknown> | undefined;
const onAbort = () => {
streams?.delete(closer);
void Promise.resolve(iterator?.return?.()).catch(() => {});
};
socket.abort.addEventListener('abort', onAbort, { once: true });
bus?.emit('stream:open', { name });
try {
const outbound = await route.def.open({
params: route.params ?? {},
inbound: socket.inbound,
abort: socket.abort,
req: request,
});
iterator = outbound[Symbol.asyncIterator]();
await pumpOutbound(socket, iterator);
} catch (err) {
bus?.emit('stream:error', { name, error: err });
closeOnError(socket, err);
} finally {
bus?.emit('stream:close', { name });
}
}