From 3b680480ab2502dba7b6a0983cffb7a1e0a3b5e0 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 16:35:56 -0500 Subject: [PATCH] feat(mesh): an unreachable teapot no longer stops the teacup from booting Blocking existed for app-scope exports, which have to resolve at boot because there is no later. Steps and proxied routes are all later. The grace budget stays -- a co-deploy still waits -- but exhausting it now warns instead of throwing. A missing token still fails the boot, and the error now names the teapots that were away. Also drops connectLink's onReconnect hook and the reconnected flag that fed it: its only caller was removed by an earlier commit on this branch, and it is not part of the public API (not re-exported, not documented). Signed-off-by: Diego Resendez --- src/app/index.ts | 44 +++++++++++++++++------ src/graph.ts | 4 +-- src/mesh/link.ts | 9 ++--- test/mesh/boot-retry.test.ts | 69 ++++++++++++++++++++++++++++++++++-- 4 files changed, 104 insertions(+), 22 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index 4913df2..06b37f5 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -221,8 +221,8 @@ export function createApp(opts: { let remoteRoutes: RouteDef[] = []; const meshLinks: Link[] = []; - const finalize = (): void => { - ({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth)); + const finalize = (missingNote?: (key: string) => string): void => { + ({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote)); booted = true; }; @@ -241,7 +241,12 @@ export function createApp(opts: { const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger); remoteRoutes = spliced.remoteRoutes; meshLinks.push(...spliced.meshLinks); - finalize(); + // Without this the error is `missing dependency: auth needed by getUser` and says nothing + // about the teapot that was away — which is the actual cause every time it is the cause. + const meshNote = spliced.absent.length + ? () => ` — these teapots did not connect, so their exports are absent: ${spliced.absent.join(', ')}` + : undefined; + finalize(meshNote); } meshControl = buildMeshControl(opts.mesh, registry, { @@ -662,9 +667,10 @@ function finalizeGraph( registry: Registry, logger: Logger, warnDepth: number | false = DEEP_GRAPH_WARN, + missingNote?: (key: string) => string, ): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } { const { providerNodes, stepNodes, routePlans } = registry; - const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']); + const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params'], missingNote); const orderedProviders = ordered.filter((node) => providerNodes.includes(node)); const orderedSteps = ordered.filter((node) => stepNodes.includes(node)); const alwaysSteps = stepNodes.filter((node) => node.provides.length === 0); // side-effect/observer steps (plugins) @@ -739,13 +745,18 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod * 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. + * + * Exhausting the budget no longer throws (D4 keeps the one exception: a permanent refusal still + * does). Every export a teapot makes is now lazy — a request-scope step or a proxied route — so + * nothing needs it resolved by boot; an absent teapot only costs a 503 on the requests that need + * it, and a teacup that refuses to start would take down the half of itself that never did. */ async function connectUntilDeadline( mesh: MeshConfig, bus: Bus, logger: Logger, attempt: () => Promise, -): Promise { +): Promise { const budgetMs = mesh.bootTimeoutMs ?? mesh.timeoutMs ?? 30_000; const deadline = Date.now() + budgetMs; let delay = 500; @@ -766,11 +777,15 @@ async function connectUntilDeadline( 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. + // The budget is a grace for a co-deploy, not a requirement. Every export is a lazy step or a + // proxied route now, so an absent teapot costs a 503 on the requests that need it — and a + // teacup that refuses to start takes down the half of itself that never needed the teapot. if (remaining <= 0) { - logger.error(`mesh: giving up after ${attempts} attempt(s) over ${budgetMs}ms — ${(error as Error).message}`); - throw error; + logger.warn( + `mesh: teapot unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` + + `(${(error as Error).message}) — starting without it; its steps and routes will 503`, + ); + return undefined; } bus.emit('mesh:boot:retry', { name: `attempt ${attempts}`, error }); @@ -809,9 +824,10 @@ async function spliceRemoteScopes( bus: Bus, registry: Registry, logger: Logger, -): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> { +): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[]; absent: string[] }> { const remoteRoutes: RouteDef[] = []; const meshLinks: Link[] = []; + const absent: string[] = []; // urls of teapots that never connected within the boot budget const routeOwners = new Map(); // "METHOD effective-shape" -> owner try { @@ -829,6 +845,12 @@ async function spliceRemoteScopes( bus, }), ); + + if (!link) { + absent.push(teapot.url); + continue; + } + meshLinks.push(link); const { steps, routes } = buildRemote(link); const origin = `mesh:${teapot.url}`; @@ -901,7 +923,7 @@ async function spliceRemoteScopes( throw err; } - return { remoteRoutes, meshLinks }; + return { remoteRoutes, meshLinks, absent }; } /** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */ diff --git a/src/graph.ts b/src/graph.ts index 75e22e4..66c8d4d 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -43,7 +43,7 @@ export interface GraphNode { } /** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */ -export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { +export function topoSort(nodes: GraphNode[], seedKeys: string[], note?: (key: string) => string): GraphNode[] { const producedBy = new Map(); for (const node of nodes) for (const key of node.provides) producedBy.set(key, node); @@ -51,7 +51,7 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { for (const node of nodes) { for (const key of node.needs) { if (!seedKeys.includes(key) && !producedBy.has(key)) { - throw new Error(`missing dependency: ${key} needed by ${node.name}`); + throw new Error(`missing dependency: ${key} needed by ${node.name}${note?.(key) ?? ''}`); } } } diff --git a/src/mesh/link.ts b/src/mesh/link.ts index a53bcf5..ff50981 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -393,8 +393,6 @@ export function connectLink(args: { 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 { const timeoutMs = args.timeoutMs ?? 30_000; @@ -453,7 +451,7 @@ export function connectLink(args: { }; /** 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 adopt = (session: Session, _attempt: number): boolean => { const missing = missingFromManifest(link.manifest, session.manifest); if (missing.length > 0) { @@ -478,7 +476,6 @@ export function connectLink(args: { refusalLogged = ''; state.socket = session.socket; args.bus?.emit('mesh:connect', { name: args.url }); - if (reconnected) args.onReconnect?.(); return true; }; @@ -494,7 +491,7 @@ export function connectLink(args: { return; } - if (!adopt(session, attempt, true)) scheduleRetry(attempt); + if (!adopt(session, attempt)) 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. @@ -504,7 +501,7 @@ export function connectLink(args: { return openSession(sessionArgs(() => endSession(0))).then((session) => { link.manifest = session.manifest; - adopt(session, 0, false); + adopt(session, 0); return link; }); diff --git a/test/mesh/boot-retry.test.ts b/test/mesh/boot-retry.test.ts index 5c7ff67..5b0bf2e 100644 --- a/test/mesh/boot-retry.test.ts +++ b/test/mesh/boot-retry.test.ts @@ -1,3 +1,4 @@ +import * as net from 'node:net'; import { describe, it, expect } from 'vitest'; import { createApp, Step, Route, Get, Module, needs } from '../../src/index'; @@ -20,6 +21,28 @@ class LocalCtl { @Module({ mountpoint: '/api', controllers: [LocalCtl] }) class TeacupModule {} +@Route('/ping') +class PingCtl { + @Get('/') + ping() { + return { ok: true }; + } +} +@Module({ mountpoint: '/api', controllers: [PingCtl] }) +class LocalOnlyModule {} + +// A step (not a route handler) needing 'auth' so the missing-dependency check that fires is +// `topoSort`'s — the one that gets the "these teapots did not connect" note — rather than the +// route-level `assertNeedsSatisfiable` check, which is untouched by this change. +@Step({ provides: 'profile', needs: ['auth'] }) +class NeedsAuth { + run() { + return { profile: {} }; + } +} +@Module({ mountpoint: '/api', steps: [NeedsAuth] }) +class NeedsAuthModule {} + const collect = () => { const lines: string[] = []; return { lines, logger: { debug() {}, info() {}, warn: (m: string) => lines.push(m), error: (m: string) => lines.push(m) } }; @@ -28,9 +51,9 @@ const collect = () => { 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(); + const probe = net.createServer(); probe.listen(0, () => { - const { port: p } = probe.address(); + const { port: p } = probe.address() as { port: number }; probe.close(() => resolve(p)); }); }); @@ -78,8 +101,10 @@ describe('mesh boot retry', () => { }); try { + // exhausting the budget is no longer fatal by itself (that's the point of this change) — + // the boot still fails here because `who` needs 'auth' and nothing local provides it. 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); + expect(lines.some((l) => l.includes('starting without it'))).toBe(true); } finally { await teacup.close(); } @@ -116,6 +141,44 @@ describe('mesh boot retry', () => { } }, 40_000); + it('boots when a teapot is unreachable and nothing local needs it', async () => { + const teacup = createApp({ + modules: [LocalOnlyModule], // declares no needs on a remote token + experimental: true, + mesh: { + teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], + secret: 's', + bootTimeoutMs: 300, + }, + }); + + try { + await expect(teacup.ready()).resolves.toBeUndefined(); + const res = await teacup.fetch(new Request('http://x/api/ping')); + expect(res.status).toBe(200); + } finally { + await teacup.close(); + } + }, 15_000); + + it('still fails the boot when a local step needs a token the absent teapot owned', async () => { + const teacup = createApp({ + modules: [NeedsAuthModule], // a step with needs: ['auth'] + experimental: true, + mesh: { + teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], + secret: 's', + bootTimeoutMs: 300, + }, + }); + + try { + await expect(teacup.ready()).rejects.toThrow(/missing dependency: auth[\s\S]*did not connect/i); + } finally { + await teacup.close(); + } + }, 15_000); + it('bootTimeoutMs: 0 makes one attempt, as before', async () => { const { lines, logger } = collect(); const teacup = createApp({