feat(mesh): give boot a grace period for a slow teapot, and fail for an absent one
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / runtimes (bun) (pull_request) Successful in 16m11s

A teapot that is thirty seconds behind and a teapot that does not exist look
identical for the first thirty seconds, and only one of them should stop a
deploy. bootTimeoutMs is that grace: retries with backoff until it passes.

It still fails after that, deliberately. A provider the graph depends on is
not optional, and booting without it would only move the failure to the first
request, where it is a caller's 503 rather than the deploy's error.

The full battery caught what the first cut got wrong: a bad secret was being
retried. That is not a transient failure — it is the teapot's decision, and it
will be the same decision in thirty seconds, so retrying only spends the
deploy's patience to arrive at the identical error. Refusals now fail at once.

Telling them apart without threading close codes through the neutral socket
contract of four runtimes: a peer that accepted the connection and then hung
up before answering rejected us on purpose; one that never accepted it may
simply not be listening yet. That is exactly the distinction needed here.

Retries are logged and emitted as mesh:boot:retry, kept separate from
mesh:disconnect — that one is a link that was up and went away, this one never
came up, and a deploy watching for trouble wants to tell those apart.

437 vitest / 12 Deno / 7 Bun / edge / JSR dry run.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-08-18 11:28:44 -05:00
1 parent f2cb411eac
commit 1975a7c03f
6 files changed
+277 -15

No files matched your search

+70 -12
View File
@@ -29,7 +29,7 @@ import {
import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views';
import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
import { buildOpenApi, type OpenApiInfo } from '../openapi';
import { connectLink, type Link } from '../mesh/link';
import { connectLink, isPermanentRefusal, type Link } from '../mesh/link';
import { Rooms } from '../rooms';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import { buildRemote } from '../mesh/teacup';
@@ -615,6 +615,62 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
}
}
/**
* Keep trying to reach a teapot until `bootTimeoutMs` passes, then give up and fail the boot.
*
* The grace exists because "the container is thirty seconds behind" and "the teapot does not
* exist" look identical for the first thirty seconds, and only one of them should stop a deploy.
* When the deadline passes it still throws: a provider the graph depends on is not optional, and
* booting without it would only move the failure to the first request, where it becomes a caller's
* 503 instead of the deploy's error.
*
* Each failed attempt is both logged and emitted as `mesh:boot:retry` — logged so an operator
* watching a deploy sees why it is taking so long, emitted so the wait is visible to whatever
* collects lifecycle events rather than only to whoever is reading a terminal.
*/
async function connectUntilDeadline(
mesh: MeshConfig,
bus: Bus,
logger: Logger,
attempt: () => Promise<Link>,
): Promise<Link> {
const budgetMs = mesh.bootTimeoutMs ?? mesh.timeoutMs ?? 30_000;
const deadline = Date.now() + budgetMs;
let delay = 500;
let attempts = 0;
for (;;) {
try {
return await attempt();
} catch (error) {
attempts += 1;
const remaining = deadline - Date.now();
// A refusal is the teapot's decision, not the network's, and it will be the same decision in
// thirty seconds. Retrying a wrong secret only spends the deploy's patience to reach the
// identical error, so it fails now.
if (isPermanentRefusal(error)) {
logger.error(`mesh: the teapot refused this peer, which retrying cannot fix — ${(error as Error).message}`);
throw error;
}
// Rethrown as-is rather than wrapped: connectLink already says whether this was a refused
// handshake, a version mismatch or a timeout, and each sends you somewhere different.
if (remaining <= 0) {
logger.error(`mesh: giving up after ${attempts} attempt(s) over ${budgetMs}ms — ${(error as Error).message}`);
throw error;
}
bus.emit('mesh:boot:retry', { name: `attempt ${attempts}`, error });
logger.warn(
`mesh: teapot unreachable (${(error as Error).message}) — retrying, ${remaining}ms of boot budget left`,
);
await new Promise((resolve) => setTimeout(resolve, Math.min(delay, Math.max(0, remaining))));
delay = Math.min(delay * 2, 5_000);
}
}
}
/**
* Warn when a teapot's shared secret would cross a network in cleartext.
*
@@ -666,17 +722,19 @@ async function spliceRemoteScopes(
// 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,
});
const link = await connectUntilDeadline(mesh, bus, logger, () =>
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);
const { providers, steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`;
+13
View File
@@ -122,6 +122,19 @@ export interface MeshConfig {
* rather than left implicit so that arriving is additive rather than a change of default.
*/
onManifestChange?: 'refuse';
/**
* How long boot keeps trying to reach a teapot before giving up on it (default: `timeoutMs`,
* so 30s). Attempts use the same backoff as reconnection.
*
* A teapot that is merely slow to start — a container scheduled a moment later, a network that
* has not settled — should not fail a deploy, and this is the grace for that. A teapot that is
* genuinely absent still fails the boot when the deadline passes, because a provider the graph
* depends on is not optional: booting without it would only move the failure to the first
* request, where it is somebody else's 503 instead of your deploy's error.
*
* `0` restores the old behaviour of a single attempt.
*/
bootTimeoutMs?: number;
}
/**
+4
View File
@@ -12,6 +12,10 @@ export type LifecycleEvent =
| 'mesh:connect'
| 'mesh:disconnect'
| 'mesh:rpc:error'
// A boot-time connect attempt that failed and will be retried until `bootTimeoutMs` passes.
// Separate from `mesh:disconnect`, which is a link that was up and went away — this one never
// came up, and a deploy watching for trouble wants to tell those apart.
| 'mesh:boot:retry'
| 'plugin:mounted'
| 'request:start'
| 'request:end'
+35 -3
View File
@@ -30,6 +30,26 @@ export interface ReconnectOptions {
*/
export type ManifestPolicy = 'refuse';
/**
* A connection failure the peer decided, rather than one the network caused.
*
* The distinction is what boot retry needs: a refused secret or a version mismatch will fail
* identically forever, so retrying one spends a deploy's patience to reach the same error. It is
* derived from whether the socket ever *opened* — a peer that accepted the connection and then hung
* up before the manifest rejected us on purpose; one that never accepted it may simply not be up.
*/
export function isPermanentRefusal(error: unknown): boolean {
return (error as { meshRefused?: boolean } | undefined)?.meshRefused === true;
}
/** Tag an error as a decision by the peer, so the caller does not retry it. */
function refused(message: string): Error {
const error = new Error(message) as Error & { meshRefused: boolean };
error.meshRefused = true;
return error;
}
/** An in-flight RPC awaiting its `rpc-res`, keyed by id in the pending map. */
type PendingEntry = {
/** The token or route asked for. Kept so an error can be reported by name — the frame only carries the id. */
@@ -185,7 +205,7 @@ function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handsha
if (frame.v !== MESH_PROTOCOL_VERSION) {
hs.socket.close();
hs.reject(
new Error(
refused(
`mesh protocol version mismatch at ${hs.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`,
),
);
@@ -242,6 +262,7 @@ function openSession(args: SessionArgs): Promise<Session> {
const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined);
let heartbeat: Session['heartbeat'] | undefined;
let handshook = false;
let accepted = false;
return new Promise<Session>((resolve, reject) => {
const connectTimer = setTimeout(() => {
@@ -268,7 +289,10 @@ function openSession(args: SessionArgs): Promise<Session> {
};
opened.then(
() => socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret })),
() => {
accepted = true;
socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret }));
},
(error) => reject(error),
);
@@ -279,7 +303,15 @@ function openSession(args: SessionArgs): Promise<Session> {
() => {
clearTimeout(connectTimer);
heartbeat?.stop();
if (!handshook) reject(new Error(`mesh handshake failed: ${args.url}`));
if (!handshook) {
// Opened and then hung up before answering: the teapot refused this peer — a bad secret,
// or a version it would not speak. Never opened: it may just not be listening yet.
const message = `mesh handshake failed: ${args.url}`;
reject(accepted ? refused(message) : new Error(message));
}
args.onEnd();
},
{ once: true },