diff --git a/CHANGELOG.md b/CHANGELOG.md index ea91b58..6e7df31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,22 @@ npm treats versions as semver and semver forbids leading zeros. object, which had been putting `ip` and `protocol` on the wire — fields the protocol never declared and a teapot could have come to depend on. +- **Boot waits for a teapot that is merely slow, and still fails for one that is absent.** + `createApp({ mesh: { bootTimeoutMs } })` gives a teacup a grace period — default `timeoutMs`, so + 30s — in which a teapot that has not finished starting is retried with backoff. When it passes, + the boot still fails, because a provider the graph depends on is not optional: 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. `bootTimeoutMs: 0` restores a single attempt. + + **A refusal is not retried.** A wrong secret or a protocol-version mismatch is the teapot's + decision and will be the same decision in thirty seconds, so it fails immediately rather than + spending the whole budget to reach an identical error. The two are told apart by whether the + socket ever opened — a peer that accepted the connection and then hung up rejected us on purpose; + one that never accepted it may simply not be listening yet. + + Every retry is logged *and* emitted as the new `mesh:boot:retry` lifecycle event, so a slow boot + is visible to whatever collects events and not only to whoever is watching a terminal. + ### Fixed - **A mesh teacup now reconnects to a teapot that came back.** A dropped link used to stay dead for diff --git a/src/app/index.ts b/src/app/index.ts index 2cb5aec..dac515e 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -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, +): Promise { + 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}`; diff --git a/src/app/types.ts b/src/app/types.ts index 5dd7a74..578f728 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -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; } /** diff --git a/src/bus.ts b/src/bus.ts index f293bec..0d248ee 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -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' diff --git a/src/mesh/link.ts b/src/mesh/link.ts index a7c066c..5bc2f62 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -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, 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 { const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined); let heartbeat: Session['heartbeat'] | undefined; let handshook = false; + let accepted = false; return new Promise((resolve, reject) => { const connectTimer = setTimeout(() => { @@ -268,7 +289,10 @@ function openSession(args: SessionArgs): Promise { }; 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 { () => { 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 }, diff --git a/test/mesh/boot-retry.test.ts b/test/mesh/boot-retry.test.ts new file mode 100644 index 0000000..5c7ff67 --- /dev/null +++ b/test/mesh/boot-retry.test.ts @@ -0,0 +1,139 @@ +import { describe, it, expect } from 'vitest'; +import { createApp, Step, Route, Get, Module, needs } from '../../src/index'; + +@Step({ provides: 'auth', needs: [], export: true }) +class Auth { + run() { + return { auth: { ok: true } }; + } +} +@Module({ mountpoint: '/api', steps: [Auth] }) +class TeapotModule {} + +@Route('/local') +class LocalCtl { + @Get('/who') + who(@needs('auth') auth: any) { + return { auth }; + } +} +@Module({ mountpoint: '/api', controllers: [LocalCtl] }) +class TeacupModule {} + +const collect = () => { + const lines: string[] = []; + return { lines, logger: { debug() {}, info() {}, warn: (m: string) => lines.push(m), error: (m: string) => lines.push(m) } }; +}; + +describe('mesh boot retry', () => { + it('waits for a teapot that starts late, rather than failing the deploy', async () => { + const port = await new Promise((resolve) => { + const probe = require('node:net').createServer(); + probe.listen(0, () => { + const { port: p } = probe.address(); + probe.close(() => resolve(p)); + }); + }); + const { lines, logger } = collect(); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + logger, + mesh: { + teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }], + timeoutMs: 500, + bootTimeoutMs: 4000, + }, + }); + + // the teapot arrives *after* the teacup has already started trying + const pending = teacup.fetch(new Request('http://x/api/local/who')); + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } }); + await new Promise((r) => setTimeout(r, 300)); + const server = await teapot.listen(port); + + try { + const res = await pending; + expect(res.status).toBe(200); + expect(lines.some((l) => l.includes('of boot budget left'))).toBe(true); + } finally { + await teacup.close(); + await teapot.close(); + server.close(); + } + }, 15_000); + + it('still fails the boot once the budget is spent — a needed provider is not optional', async () => { + const { lines, logger } = collect(); + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + logger, + mesh: { + teapots: [{ url: 'ws://127.0.0.1:1/__mesh__/control', secret: 'good' }], + timeoutMs: 200, + bootTimeoutMs: 600, + }, + }); + + try { + await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/); + expect(lines.some((l) => l.includes('giving up after'))).toBe(true); + } finally { + await teacup.close(); + } + }, 15_000); + + it('does not retry a wrong secret — the teapot refused, and it will refuse again', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } }); + const server = await teapot.listen(0); + const port = (server.address() as { port: number }).port; + const { lines, logger } = collect(); + + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + logger, + mesh: { + teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'WRONG' }], + timeoutMs: 500, + bootTimeoutMs: 30_000, + }, + }); + + try { + const started = Date.now(); + await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/); + // with a 30s budget, retrying would have taken 30s to reach the same error + expect(Date.now() - started).toBeLessThan(3000); + expect(lines.some((l) => l.includes('refused this peer'))).toBe(true); + expect(lines.filter((l) => l.includes('of boot budget left'))).toEqual([]); + } finally { + await teacup.close(); + await teapot.close(); + server.close(); + } + }, 40_000); + + it('bootTimeoutMs: 0 makes one attempt, as before', async () => { + const { lines, logger } = collect(); + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + logger, + mesh: { + teapots: [{ url: 'ws://127.0.0.1:1/__mesh__/control', secret: 'good' }], + timeoutMs: 200, + bootTimeoutMs: 0, + }, + }); + + try { + await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/); + expect(lines.filter((l) => l.includes('of boot budget left'))).toEqual([]); + } finally { + await teacup.close(); + } + }, 15_000); +});