fix(mesh): reconnect to a teapot that came back, refusing a manifest that no longer fits
A dropped link stayed dead for the life of the process. Every RPC answered 503 until the teacup restarted, so deploying a teapot forced a restart of every teacup depending on it and boot order became load-bearing — a worse operational property than any gap the docs actually listed. The Link now outlives any single socket, because the graph captured its rpc closure at boot and a reconnect that produced a new Link would leave the graph pointing at the dead one. Backoff doubles from 500ms to 30s with full jitter, so teacups that went down together do not return in lockstep. A returning teapot whose manifest no longer exports what the graph was validated against is refused, not adopted: that graph is already serving, and a token cannot be validated away after the fact. The link keeps retrying, since a partial deploy may still restore it, and logs once per distinct manifest rather than once per attempt. Refusal ships as a named policy (onManifestChange: 'refuse') so hot reconciliation can arrive later as an addition rather than as a change of what the default means — these are separate processes on separate deploy cadences. close() is terminal. closeLinks runs on shutdown, and a link that reconnected after the application hung up would leave a process that cannot exit. Also closes the documented gap where an app-scope export outlived its teapot with a stale value: a successful reconnect re-registers those bindings, so the next resolve re-runs the RPC. That invalidation is a named function rather than inline, because it is the seam a future 'reconcile' reuses. Tested on all three runtimes rather than on Node alone — Node's ws package, Deno's global WebSocket and Bun's server-level socket handler are three implementations, and swapping a socket under a live graph is where they stop agreeing. 7 of the 9 new Node tests were verified to fail against the old code; the 2 that pass are the ones that should, since the old code never reconnected at all. Mesh stays alpha. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
8 files changed
+819
-57
No files matched your search
+26
-1
@@ -217,7 +217,7 @@ export function createApp(opts: {
|
||||
// can only be built here, after finalize(), and never at construction time.
|
||||
const prepareGraph = async (): Promise<void> => {
|
||||
if (opts.mesh && !booted) {
|
||||
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger);
|
||||
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, container);
|
||||
remoteRoutes = spliced.remoteRoutes;
|
||||
meshLinks.push(...spliced.meshLinks);
|
||||
finalize();
|
||||
@@ -615,12 +615,26 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-register a link's app-scope bindings after it reconnects, so their next resolve re-runs the RPC.
|
||||
*
|
||||
* Named and separate rather than inlined in the reconnect handler: this is the seam a future
|
||||
* `onManifestChange: 'reconcile'` reuses, and burying it would mean writing it twice.
|
||||
*
|
||||
* Lazy on purpose — the RPC runs on the next resolve, not here. Re-resolving eagerly would put a
|
||||
* network call on the reconnect path, where a failure has nowhere to go but a swallowed rejection.
|
||||
*/
|
||||
function invalidateRemoteBindings(rebind: Array<() => void>): void {
|
||||
for (const bind of rebind) bind();
|
||||
}
|
||||
|
||||
/** Connects the configured teapots, splices their remote providers/steps into the registry, and returns their routes. */
|
||||
async function spliceRemoteScopes(
|
||||
mesh: MeshConfig,
|
||||
bus: Bus,
|
||||
registry: Registry,
|
||||
logger: Logger,
|
||||
container: Container,
|
||||
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
|
||||
const remoteRoutes: RouteDef[] = [];
|
||||
const meshLinks: Link[] = [];
|
||||
@@ -628,11 +642,18 @@ async function spliceRemoteScopes(
|
||||
|
||||
try {
|
||||
for (const teapot of mesh.teapots ?? []) {
|
||||
// Deferred so the reconnect callback can name this link's provider tokens, which are only
|
||||
// known once its manifest arrives — the callback is registered before the link can drop.
|
||||
const rebind: Array<() => void> = [];
|
||||
const link = await connectLink({
|
||||
url: teapot.url,
|
||||
secret: teapot.secret,
|
||||
timeoutMs: mesh.timeoutMs,
|
||||
heartbeatMs: mesh.heartbeatMs,
|
||||
reconnect: mesh.reconnect,
|
||||
onManifestChange: mesh.onManifestChange,
|
||||
onReconnect: () => invalidateRemoteBindings(rebind),
|
||||
logger,
|
||||
bus,
|
||||
});
|
||||
meshLinks.push(link);
|
||||
@@ -643,6 +664,10 @@ async function spliceRemoteScopes(
|
||||
registry.providerNodes.push({ name: provider.name, needs: [], provides: [provider.name], origin });
|
||||
registry.providerMeta.set(provider.name, { optional: false });
|
||||
registry.setRunner(provider.name, provider.run);
|
||||
// A remote app-scope value is resolved once at boot and frozen into the container, so it
|
||||
// would keep answering from a cache the teapot no longer stands behind. Re-registering
|
||||
// gives the binding a factory that re-runs the RPC, and `register` drops the memo with it.
|
||||
rebind.push(() => container.register(provider.name, 'app', () => provider.run({})));
|
||||
}
|
||||
|
||||
for (const step of steps) {
|
||||
|
||||
@@ -103,6 +103,25 @@ export interface MeshConfig {
|
||||
* `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter.
|
||||
*/
|
||||
heartbeatMs?: number;
|
||||
/**
|
||||
* Reconnect to a teapot after its link drops (default: on). A dropped link used to stay dead for
|
||||
* the life of the process, which meant deploying a teapot forced a restart of every teacup.
|
||||
*
|
||||
* `false` restores that fail-once behaviour. An object tunes the backoff, which doubles from
|
||||
* `initialDelayMs` (500ms) up to `maxDelayMs` (30s) with jitter, so teacups that went down
|
||||
* together do not come back in lockstep.
|
||||
*/
|
||||
reconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number };
|
||||
/**
|
||||
* What to do when a returning teapot's manifest no longer exports something the graph was
|
||||
* validated against at boot (default: `'refuse'`).
|
||||
*
|
||||
* `'refuse'` hangs up on that session and keeps retrying — a partial deploy may still restore it.
|
||||
* Serving against a manifest that no longer backs the graph would surface as a 500 that looks
|
||||
* like application code. A future `'reconcile'` will rebuild the graph instead; it is named here
|
||||
* rather than left implicit so that arriving is additive rather than a change of default.
|
||||
*/
|
||||
onManifestChange?: 'refuse';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+271
-56
@@ -1,6 +1,8 @@
|
||||
import type { Bus } from '../bus';
|
||||
import type { Logger } from '../logger';
|
||||
import { HttpError } from '../signals';
|
||||
import { connectSocket, type SocketCtor } from '../http/ws-adapter';
|
||||
import { compilePattern } from '../http/router';
|
||||
import type { WsSocket } from '../http/ws-core';
|
||||
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol';
|
||||
|
||||
@@ -11,6 +13,23 @@ export interface Link {
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/** Backoff bounds for reconnection. `false` disables reconnecting entirely. */
|
||||
export interface ReconnectOptions {
|
||||
/** Delay before the first retry; doubles from here (default: 500ms). */
|
||||
initialDelayMs?: number;
|
||||
/** Ceiling the doubling stops at (default: 30s). */
|
||||
maxDelayMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* What to do when a reconnecting teapot answers with a manifest that no longer backs the graph.
|
||||
*
|
||||
* Only `'refuse'` exists. It is a named strategy rather than implicit behaviour so that hot graph
|
||||
* reconciliation can arrive later as `'reconcile'` *additively* — peers run on separate deploy
|
||||
* cadences, and silently changing what the default means is the worst kind of breaking change.
|
||||
*/
|
||||
export type ManifestPolicy = 'refuse';
|
||||
|
||||
/** An in-flight RPC awaiting its `rpc-res`, keyed by id in the pending map. */
|
||||
type PendingEntry = {
|
||||
resolve: (v: unknown) => void;
|
||||
@@ -18,8 +37,25 @@ type PendingEntry = {
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
};
|
||||
|
||||
/** Mutable per-link state: which socket is current, and whether the application hung up for good. */
|
||||
interface LinkState {
|
||||
socket: WsSocket | undefined;
|
||||
closed: boolean;
|
||||
retry: ReturnType<typeof setTimeout> | undefined;
|
||||
}
|
||||
|
||||
/** One established connection: its socket, the manifest it announced, and its heartbeat. */
|
||||
interface Session {
|
||||
socket: WsSocket;
|
||||
manifest: Manifest;
|
||||
heartbeat: { stop: () => void; markAlive: () => void };
|
||||
}
|
||||
|
||||
const DEFAULT_INITIAL_DELAY_MS = 500;
|
||||
const DEFAULT_MAX_DELAY_MS = 30_000;
|
||||
|
||||
/**
|
||||
* Reject and clear every in-flight RPC — used when the link closes.
|
||||
* Reject and clear every in-flight RPC — used when a session ends.
|
||||
* 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.
|
||||
*/
|
||||
@@ -34,7 +70,7 @@ function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): v
|
||||
|
||||
/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */
|
||||
function sendRpc(
|
||||
socket: WsSocket,
|
||||
socket: WsSocket | undefined,
|
||||
pending: Map<string, PendingEntry>,
|
||||
id: string,
|
||||
kind: 'scope' | 'route',
|
||||
@@ -44,8 +80,9 @@ function sendRpc(
|
||||
): 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) {
|
||||
// before failing anyway — the caller pays for a verdict already known. This is also the
|
||||
// window a reconnecting link sits in: down, and answering immediately.
|
||||
if (!socket?.isOpen) {
|
||||
return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`));
|
||||
}
|
||||
|
||||
@@ -62,25 +99,6 @@ function sendRpc(
|
||||
});
|
||||
}
|
||||
|
||||
/** Assemble the client-facing Link once the manifest arrives. */
|
||||
function buildLink(socket: WsSocket, pending: Map<string, PendingEntry>, manifest: Manifest, timeoutMs: number): Link {
|
||||
// ids only need to be unique within this link: `pending` is per-connection, so a
|
||||
// per-link counter suffices (no module-global sequence, no test-order coupling).
|
||||
let counter = 0;
|
||||
|
||||
return {
|
||||
manifest,
|
||||
rpc(kind, name, ctx) {
|
||||
const id = String(counter++);
|
||||
|
||||
return sendRpc(socket, pending, id, kind, name, ctx, timeoutMs);
|
||||
},
|
||||
close() {
|
||||
socket.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Settle a pending RPC from its `rpc-res` frame — resolve on ok, reject (and emit) on error. */
|
||||
function settleRpcResponse(
|
||||
pending: Map<string, PendingEntry>,
|
||||
@@ -118,7 +136,8 @@ const CLOSE_HEARTBEAT_TIMEOUT = 4011;
|
||||
* 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`.
|
||||
* turns that into an immediate 503 from the dead-link guard, emits `mesh:disconnect`, and starts
|
||||
* the reconnect backoff.
|
||||
*
|
||||
* The interval is unref'd, so a heartbeat never holds the process open by itself.
|
||||
*/
|
||||
@@ -144,20 +163,19 @@ function startHeartbeat(socket: WsSocket, everyMs: number): { stop: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
/** Handle for the in-flight handshake, so the frame loop can settle `connectLink`'s promise. */
|
||||
/** Handle for the in-flight handshake, so the frame loop can settle the session promise. */
|
||||
interface Handshake {
|
||||
url: string;
|
||||
socket: WsSocket;
|
||||
pending: Map<string, PendingEntry>;
|
||||
timeoutMs: number;
|
||||
bus?: Bus;
|
||||
resolve: (link: Link) => void;
|
||||
resolve: (session: Session) => void;
|
||||
reject: (error: unknown) => void;
|
||||
onManifest: () => void;
|
||||
onManifest: (socket: WsSocket) => Session['heartbeat'];
|
||||
onPong: () => void;
|
||||
}
|
||||
|
||||
/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else build the Link. */
|
||||
/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else hand back the session. */
|
||||
function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handshake): void {
|
||||
if (frame.v !== MESH_PROTOCOL_VERSION) {
|
||||
hs.socket.close();
|
||||
@@ -170,12 +188,15 @@ function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handsha
|
||||
return;
|
||||
}
|
||||
|
||||
hs.onManifest();
|
||||
hs.bus?.emit('mesh:connect', { name: hs.url });
|
||||
hs.resolve(buildLink(hs.socket, hs.pending, { scopes: frame.scopes, routes: frame.routes }, hs.timeoutMs));
|
||||
const heartbeat = hs.onManifest(hs.socket);
|
||||
|
||||
// `mesh:connect` is emitted by the caller, not here: a reconnect whose manifest no longer backs
|
||||
// the graph is refused after this point, and announcing a connection we are about to hang up on
|
||||
// would tell an operator the opposite of what happened.
|
||||
hs.resolve({ socket: hs.socket, manifest: { scopes: frame.scopes, routes: frame.routes }, heartbeat });
|
||||
}
|
||||
|
||||
/** Consume the link's inbound frames until it closes, settling the handshake then each RPC. */
|
||||
/** Consume the session's inbound frames until it closes, settling the handshake then each RPC. */
|
||||
async function readFrames(hs: Handshake): Promise<void> {
|
||||
for await (const data of hs.socket.inbound) {
|
||||
let frame: Frame;
|
||||
@@ -192,43 +213,51 @@ async function readFrames(hs: Handshake): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest
|
||||
* arrives. `Ctor` is injectable to exercise both client implementations on a single runtime.
|
||||
*/
|
||||
export function connectLink(args: {
|
||||
/** Everything a link needs to open one session, shared by the first connect and every retry. */
|
||||
interface SessionArgs {
|
||||
url: string;
|
||||
secret: string;
|
||||
timeoutMs?: number;
|
||||
heartbeatMs?: number;
|
||||
timeoutMs: number;
|
||||
heartbeatMs: number;
|
||||
pending: Map<string, PendingEntry>;
|
||||
bus?: Bus;
|
||||
Ctor?: SocketCtor;
|
||||
}): Promise<Link> {
|
||||
const timeoutMs = args.timeoutMs ?? 30_000;
|
||||
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;
|
||||
onEnd: () => void;
|
||||
}
|
||||
|
||||
return new Promise<Link>((resolve, reject) => {
|
||||
/**
|
||||
* Open one authenticated session: connect, handshake, and resolve once the manifest arrives.
|
||||
*
|
||||
* `onEnd` fires when this session's socket aborts — on a clean close and on an error alike — and is
|
||||
* where the supervisor rejects in-flight RPCs and decides whether to retry. It fires for a session
|
||||
* that never handshook too, which is what turns a refused connection into a scheduled retry rather
|
||||
* than a silent stall.
|
||||
*/
|
||||
function openSession(args: SessionArgs): Promise<Session> {
|
||||
const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined);
|
||||
let heartbeat: Session['heartbeat'] | undefined;
|
||||
let handshook = false;
|
||||
|
||||
return new Promise<Session>((resolve, reject) => {
|
||||
const connectTimer = setTimeout(() => {
|
||||
socket.close();
|
||||
reject(new Error(`mesh connect timeout: ${args.url}`));
|
||||
}, timeoutMs);
|
||||
}, args.timeoutMs);
|
||||
|
||||
const hs: Handshake = {
|
||||
url: args.url,
|
||||
socket,
|
||||
pending,
|
||||
timeoutMs,
|
||||
pending: args.pending,
|
||||
bus: args.bus,
|
||||
resolve,
|
||||
reject,
|
||||
onManifest: () => {
|
||||
manifest = true;
|
||||
onManifest: (established) => {
|
||||
handshook = true;
|
||||
clearTimeout(connectTimer);
|
||||
// started only once authenticated: an unauthenticated peer should not be pinging
|
||||
heartbeat = startHeartbeat(socket, args.heartbeatMs ?? HEARTBEAT_MS);
|
||||
heartbeat = startHeartbeat(established, args.heartbeatMs);
|
||||
|
||||
return heartbeat;
|
||||
},
|
||||
onPong: () => heartbeat?.markAlive(),
|
||||
};
|
||||
@@ -245,9 +274,8 @@ export function connectLink(args: {
|
||||
() => {
|
||||
clearTimeout(connectTimer);
|
||||
heartbeat?.stop();
|
||||
args.bus?.emit('mesh:disconnect', { name: args.url });
|
||||
rejectAllPending(pending, `mesh link to ${args.url} is down`);
|
||||
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
|
||||
if (!handshook) reject(new Error(`mesh handshake failed: ${args.url}`));
|
||||
args.onEnd();
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
@@ -257,3 +285,190 @@ export function connectLink(args: {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** A scope token and its lifetime, flattened to the string the refusal check compares. */
|
||||
function scopeKeys(manifest: Manifest): Set<string> {
|
||||
return new Set(manifest.scopes.map((scope) => `${scope.scope}:${scope.token}`));
|
||||
}
|
||||
|
||||
/**
|
||||
* Route keys by method plus *effective shape*, the same comparison `spliceRemoteScopes` uses to
|
||||
* detect ambiguity — so `/:id` renamed to `/:name` is the same route and does not trip the refusal.
|
||||
*/
|
||||
function routeKeys(manifest: Manifest): Set<string> {
|
||||
return new Set(manifest.routes.map((route) => `${route.method} ${compilePattern(route.pattern).shape}`));
|
||||
}
|
||||
|
||||
/**
|
||||
* What the boot manifest had that a returning one does not.
|
||||
*
|
||||
* The graph was validated at boot against the first manifest and is already serving. A token that
|
||||
* vanished cannot be validated away after the fact, so a manifest missing anything this link
|
||||
* contributed is refused rather than accepted — see `ManifestPolicy`. Extra exports are *not*
|
||||
* missing and are ignored: the graph is fixed at boot and nothing new is spliced into it.
|
||||
*/
|
||||
export function missingFromManifest(booted: Manifest, returned: Manifest): string[] {
|
||||
const scopes = scopeKeys(returned);
|
||||
const routes = routeKeys(returned);
|
||||
const missing: string[] = [];
|
||||
|
||||
for (const scope of booted.scopes) {
|
||||
if (!scopes.has(`${scope.scope}:${scope.token}`)) missing.push(`${scope.scope}-scope '${scope.token}'`);
|
||||
}
|
||||
|
||||
for (const route of booted.routes) {
|
||||
if (!routes.has(`${route.method} ${compilePattern(route.pattern).shape}`)) {
|
||||
missing.push(`route '${route.method} ${route.pattern}'`);
|
||||
}
|
||||
}
|
||||
|
||||
return missing;
|
||||
}
|
||||
|
||||
/** Resolved backoff bounds, or `undefined` when the caller turned reconnection off. */
|
||||
function backoffBounds(
|
||||
reconnect: boolean | ReconnectOptions | undefined,
|
||||
): { initial: number; max: number } | undefined {
|
||||
if (reconnect === false) return undefined;
|
||||
const opts = typeof reconnect === 'object' ? reconnect : {};
|
||||
|
||||
return {
|
||||
initial: opts.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS,
|
||||
max: opts.maxDelayMs ?? DEFAULT_MAX_DELAY_MS,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest
|
||||
* arrives. The returned `Link` outlives any single socket: when a session drops, the link keeps its
|
||||
* identity — the graph captured `rpc` at boot — and reconnects underneath it.
|
||||
*
|
||||
* `Ctor` is injectable to exercise both client implementations on a single runtime.
|
||||
*/
|
||||
export function connectLink(args: {
|
||||
url: string;
|
||||
secret: string;
|
||||
timeoutMs?: number;
|
||||
heartbeatMs?: number;
|
||||
bus?: Bus;
|
||||
Ctor?: SocketCtor;
|
||||
/** Reconnect after a dropped session (default: on). `false` restores the old fail-once behaviour. */
|
||||
reconnect?: boolean | ReconnectOptions;
|
||||
/** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */
|
||||
onManifestChange?: ManifestPolicy;
|
||||
/** Called after a *successful* reconnect, so app-scope values resolved from this link are re-resolved. */
|
||||
onReconnect?: () => void;
|
||||
logger?: Logger;
|
||||
}): Promise<Link> {
|
||||
const timeoutMs = args.timeoutMs ?? 30_000;
|
||||
const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS;
|
||||
const bounds = backoffBounds(args.reconnect);
|
||||
const pending = new Map<string, PendingEntry>();
|
||||
const state: LinkState = { socket: undefined, closed: false, retry: undefined };
|
||||
let refusalLogged = '';
|
||||
|
||||
const link: Link = {
|
||||
// replaced with the real manifest before this object escapes; a reconnect never changes it,
|
||||
// because the graph is fixed at boot and only the *boot* manifest describes what it holds.
|
||||
manifest: { scopes: [], routes: [] },
|
||||
rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs),
|
||||
close: () => {
|
||||
// Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after
|
||||
// the application hung up would leave a process that cannot exit.
|
||||
state.closed = true;
|
||||
clearTimeout(state.retry);
|
||||
state.socket?.close();
|
||||
},
|
||||
};
|
||||
// ids only need to be unique within this link: `pending` is per-link, so a per-link counter
|
||||
// suffices (no module-global sequence, no test-order coupling).
|
||||
let counter = 0;
|
||||
|
||||
const sessionArgs = (onEnd: () => void): SessionArgs => ({
|
||||
url: args.url,
|
||||
secret: args.secret,
|
||||
timeoutMs,
|
||||
heartbeatMs,
|
||||
pending,
|
||||
bus: args.bus,
|
||||
Ctor: args.Ctor,
|
||||
onEnd,
|
||||
});
|
||||
|
||||
/** Schedule the next attempt, doubling from `initial` up to `max` with jitter. */
|
||||
const scheduleRetry = (attempt: number): void => {
|
||||
if (state.closed || !bounds) return;
|
||||
const capped = Math.min(bounds.initial * 2 ** attempt, bounds.max);
|
||||
// Full jitter: peers that went down together must not come back in lockstep and stampede
|
||||
// the teapot the moment it returns.
|
||||
const delay = Math.round(capped / 2 + Math.random() * (capped / 2));
|
||||
|
||||
state.retry = setTimeout(() => void attemptReconnect(attempt + 1), delay);
|
||||
state.retry.unref?.();
|
||||
};
|
||||
|
||||
/** End the current session: nothing can be delivered on it, so fail what was waiting. */
|
||||
const endSession = (attempt: number): void => {
|
||||
state.socket = undefined;
|
||||
args.bus?.emit('mesh:disconnect', { name: args.url });
|
||||
rejectAllPending(pending, `mesh link to ${args.url} is down`);
|
||||
scheduleRetry(attempt);
|
||||
};
|
||||
|
||||
/** Adopt an established session, or refuse it when its manifest no longer backs the graph. */
|
||||
const adopt = (session: Session, attempt: number, reconnected: boolean): boolean => {
|
||||
const missing = missingFromManifest(link.manifest, session.manifest);
|
||||
|
||||
if (missing.length > 0) {
|
||||
session.heartbeat.stop();
|
||||
session.socket.close();
|
||||
// Logged once per distinct manifest, not once per attempt: at the 30s ceiling this would
|
||||
// otherwise be ~2,880 identical lines a day. A rollback can still fix it, which is why the
|
||||
// link keeps retrying rather than giving up.
|
||||
const fingerprint = missing.join('|');
|
||||
|
||||
if (fingerprint !== refusalLogged) {
|
||||
refusalLogged = fingerprint;
|
||||
args.logger?.warn(
|
||||
`mesh: refusing to reconnect to ${args.url} — its manifest no longer exports ${missing.join(', ')}, ` +
|
||||
'which the graph was validated against at boot. Retrying in case this is a partial deploy.',
|
||||
);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
refusalLogged = '';
|
||||
state.socket = session.socket;
|
||||
args.bus?.emit('mesh:connect', { name: args.url });
|
||||
if (reconnected) args.onReconnect?.();
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const attemptReconnect = async (attempt: number): Promise<void> => {
|
||||
if (state.closed) return;
|
||||
|
||||
try {
|
||||
const session = await openSession(sessionArgs(() => endSession(attempt)));
|
||||
|
||||
if (state.closed) {
|
||||
session.socket.close(); // hung up while this attempt was in flight
|
||||
return;
|
||||
}
|
||||
|
||||
if (!adopt(session, attempt, true)) scheduleRetry(attempt);
|
||||
} catch {
|
||||
// openSession's own abort listener already scheduled the retry through `onEnd`; a rejection
|
||||
// that never opened a socket (a bad URL, DNS) needs one scheduled here instead.
|
||||
if (!state.socket && !state.retry) scheduleRetry(attempt);
|
||||
}
|
||||
};
|
||||
|
||||
return openSession(sessionArgs(() => endSession(0))).then((session) => {
|
||||
link.manifest = session.manifest;
|
||||
adopt(session, 0, false);
|
||||
|
||||
return link;
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user