From 15f8acc3468da8645cbc00441307dbdfd32a7512 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 23 Oct 2026 00:07:48 -0500 Subject: [PATCH] feat(mesh): remote routes follow teapot membership (CARD-19, #124) The teacup built its route table once at boot. A teapot that started late was never served, and one that was gone for good stayed advertised. Implement D15 (accepted 2026-10-18): - A teapot that missed bootTimeoutMs is retried in the background with the reconnect backoff (not with reconnect: false). On connect its routes join the remote table. Its steps do not, because the graph was validated at boot without them. - While a link is reconnecting, its routes stay and answer 503, now with retry-after (seconds until the next attempt). - A link that gives up for good (dropped with reconnect: false, or a permanent refusal while reconnecting) has its routes removed: 404, and Allow drops its methods. A refused reconnect no longer retries forever. - A returning manifest replaces the teapot's routes. missingFromManifest now checks steps only, so a dropped route is removed instead of refusing the reconnect. - A late route that conflicts with another teapot's is refused and logged. The table keeps serving. At boot the same conflict still fails boot. - Each change emits mesh:routes with { url, added, removed }. Mechanics: the remote table publishes a new array per change (copy-on-write). app.fetch and listen() share one table through a getter, and buildFetch/createHttpServer read it once per request, so a request sees the old table or the new one, never a mix. The router reuses local trees when the local entries are identical, so a membership change rebuilds only the remote trees. Dev routes now sit before remote ones in the table to keep the local positions stable. Tests cover T1-T8 on Node (test/mesh/membership.test.ts), plus the local-tree build counter, and T1/T2 on Deno and Bun. The frozen owner-mesh-lifetime.json capture changes in the next commit. Signed-off-by: Diego Resendez --- CHANGELOG.md | 25 ++ src/app/index.ts | 435 +++++++++++++++++++++++-------- src/app/types.ts | 14 + src/bus.ts | 9 + src/http/router.ts | 41 ++- src/http/server.ts | 11 +- src/http/types.ts | 7 + src/http/web.ts | 9 +- src/mesh/link.ts | 182 +++++++++---- test/bun/mesh-reconnect.test.ts | 88 +++++++ test/deno/mesh-reconnect.test.ts | 93 +++++++ test/mesh/membership.test.ts | 341 ++++++++++++++++++++++++ test/mesh/reconnect.test.ts | 8 +- 13 files changed, 1086 insertions(+), 177 deletions(-) create mode 100644 test/mesh/membership.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b3fac6..33e4e3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -81,6 +81,31 @@ npm treats versions as semver and semver forbids leading zeros. param hit −88%, method miss −94%, path miss −96%; at 10 routes, every cell is within noise or faster (late param hit +3.4%, 95% CI −5.0…+12.6%). +- **Mesh (alpha): a teacup's remote routes follow which teapots are connected** (#124, D15). The + route table used to be built once at boot: a teapot that started late was never served, and a + teapot that was gone for good stayed advertised. Now: + + - A teapot that missed `bootTimeoutMs` is retried in the background with the `reconnect` backoff. + When it connects, its routes are served, with no restart. Its steps are not added, because the + graph was validated at boot without them. With `reconnect: false` it is not retried. + - While a link is reconnecting, its routes stay and answer `503`, now with `retry-after` (the + seconds until the next attempt). `Allow` keeps them. + - A link that gives up for good has its routes removed: they answer `404` and leave `Allow`. That + is a link dropped with `reconnect: false`, or one refused permanently (a wrong secret, a protocol + mismatch) while reconnecting. A refused reconnect used to retry forever. It now stops. + - A returning teapot's routes replace its old ones: a route it added is served, one it dropped + answers `404`. A returning manifest is still refused for a missing **step** + (`onManifestChange: 'refuse'`), but no longer for a missing route. + - A late route that conflicts with another teapot's (same shape, or a CARD-13 sibling conflict) + is refused and logged, and the rest keep serving. At boot the same conflict still fails boot. + - Every change emits `mesh:routes` with `{ url, added, removed }` (new `EventPayload` fields). + + Membership changes publish a new table. A request in flight routes against the old one or the + new one, never a mix. Only the remote route trees are rebuilt. `listen()` now reads the same + table as `app.fetch`, and `createHttpServer` accepts a getter as well as an array. Dev + introspection routes (`devGraph`, `devOpenapi`) now sit before remote routes in that table, so + in the one case where a teapot exports the same path at the same specificity, the dev route wins. + ### Fixed - **Mesh (alpha): `HEAD` on a remote `GET` route now works** (#125). The teacup resolved `HEAD` to diff --git a/src/app/index.ts b/src/app/index.ts index 6195570..7bf364a 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -43,7 +43,7 @@ import { buildOpenApi, type OpenApiInfo } from '../openapi'; import { connectLink, isPermanentRefusal, type Link } from '../mesh/link'; import { Rooms } from '../rooms'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; -import { buildRemote } from '../mesh/teacup'; +import { buildRemote, type RemoteRoute as TeacupRemoteRoute } from '../mesh/teacup'; import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot'; import type { MeshControl } from '../http'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; @@ -56,6 +56,9 @@ export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from ' type Runner = (ctx: any) => any; +/** Something shutdown closes: a mesh link, or the retry loop of a teapot that missed boot. */ +type Closable = Pick; + /** Mutable graph state assembled from modules/plugins and later spliced with remote mesh scopes. */ interface Registry { providerNodes: GraphNode[]; @@ -231,8 +234,7 @@ export function createApp(opts: { let orderedProviders: GraphNode[] = []; let orderedSteps: GraphNode[] = []; let booted = false; - let remoteRoutes: RouteDef[] = []; - const meshLinks: Link[] = []; + const meshLinks: Closable[] = []; const finalize = (missingNote?: string): void => { ({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote)); @@ -251,8 +253,7 @@ export function createApp(opts: { // can only be built here, after finalize(), and never at construction time. const prepareGraph = async (): Promise => { if (opts.mesh && !booted) { - const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger); - remoteRoutes = spliced.remoteRoutes; + const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, publishRemote); meshLinks.push(...spliced.meshLinks); // 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. @@ -298,6 +299,11 @@ export function createApp(opts: { return routes; }; + // The one HTTP route table, shared by app.fetch and listen() — see createRouteTable. + const table = createRouteTable(() => [...buildHttpRoutes(routePlans, pipelineDeps), ...devRoutes()]); + const currentTable = table.current; + const publishRemote = table.publish; + // Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling // several never double-boots (which would re-run provider factories and their side effects). const bootApp = makeAppBooter( @@ -323,14 +329,7 @@ export function createApp(opts: { onError: opts.onError, static: staticResolver, }; - const fetchFn = buildAppFetch( - routePlans, - { providedSeed, planSteps, bus, onError: opts.onError, logger }, - fetchOpts, - bootApp, - devRoutes, - () => remoteRoutes, - ); + const fetchFn = buildAppFetch(fetchOpts, bootApp, currentTable); const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, opts.limits); const listen = async (port: number): Promise => { @@ -340,10 +339,10 @@ export function createApp(opts: { // and builds the mesh control channel — so Node and Deno/Bun serve an identical graph await bootApp(); - const httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()]; const wsRoutes = buildWsRoutes(routePlans, deps); - server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { + // A getter, not an array: mesh membership can change the table after this server starts. + server = createHttpServer(currentTable, wsRoutes, bus, meshControl, { bus, logger, limits: opts.limits, @@ -966,40 +965,287 @@ function assertNoRemoteSiblingConflict(accepted: RemoteRoute[], route: RemoteRou } } -/** Connects the configured teapots, splices their remote steps into the registry, and returns their routes. */ +/** A teapot route the remote table serves: its export, its owner, and the def the router files. */ +interface ServedRemote extends RemoteRoute { + def: RouteDef; +} + +/** + * The teacup's remote routes, by teapot, published as a fresh array on every change (D15). + * + * Never mutated in place: the router caches an index by array identity, and a request that is + * already routing keeps the array it read, so it sees the whole old table or the whole new one. + */ +interface RemoteTable { + /** + * Replaces one teapot's routes and publishes the table. With `strict` (boot) a conflicting route + * fails the boot; after boot it is refused and logged, and everything else keeps serving. + */ + set(url: string, routes: TeacupRemoteRoute[], strict: boolean): { added: string[]; removed: string[] }; +} + +const showRoute = (route: { method: string; pattern: string }): string => `${route.method} ${route.pattern}`; + +/** + * Throws when `route` cannot join the remote routes already accepted: the same effective shape and + * method as one of them, or a sibling conflict (CARD-13). Route matching keeps the first of two + * identical patterns, so the loser would be silently dead — and callers could come to depend on + * "first teapot wins", which would make adding balancing later a breaking change. + */ +function assertRemoteRouteFits(accepted: RemoteRoute[], route: RemoteRoute): void { + const shape = compilePattern(route.pattern).shape; + const owner = accepted.find( + (prior) => prior.method === route.method && compilePattern(prior.pattern).shape === shape, + ); + + if (owner) { + throw new Error( + `mesh: ambiguous remote route '${showRoute(route)}' from ${route.url} conflicts with ` + + `'${showRoute(owner)}' from ${owner.url} — ` + + 'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' + + 'Export it from a single teapot.', + ); + } + + assertNoRemoteSiblingConflict(accepted, route); +} + +/** + * Local routes are merged ahead of remote ones (see the route table), so a local twin wins. That + * precedence is deliberate — your own code beats an imported one, and it is how you override a + * teapot — but silently shadowing an export looks exactly like a broken teapot from the outside. + * Warn and let the developer decide. + */ +function warnIfShadowed(registry: Registry, route: RemoteRoute, logger: Logger): void { + const shape = compilePattern(route.pattern).shape; + if (!registry.routePlans.some((plan) => plan.method === route.method && compilePattern(plan.pattern).shape === shape)) + return; + + logger.warn( + `mesh: route '${showRoute(route)}' is exported by teapot ${route.url} but also declared locally — ` + + 'the local route takes precedence and the remote one will not be reached. ' + + 'Remove one if that is not what you meant.', + ); +} + +/** The route the router files for a teapot's export: marked remote, and forwarding a built envelope. */ +function remoteRouteDef(route: TeacupRemoteRoute): RouteDef { + // Marked so the router files it in the remote tree; precedence is unchanged by the split. + return markRemoteRoute({ + method: route.method, + pattern: route.pattern, + transport: 'buffer', + // Built explicitly rather than cast from the handler argument. The cast put the whole + // internal request on the wire — `ip` and `protocol` included — and sent fields the + // protocol never declared, so a teapot could come to rely on something we never promised. + handler: async (req) => + route.handler({ + // HEAD reaches a remote GET through the implicit-HEAD fallback, and the teapot looks + // its plan up by method, so a forwarded HEAD finds none and answers 404. Send it as the + // GET it resolved to; dispatch drops the body for HEAD. Fixed teacup-side (D16) so an + // unchanged, older teapot still answers it during a rolling deploy. + method: req.method === 'HEAD' && route.method === 'GET' ? 'GET' : req.method, + params: req.params, + query: req.query, + body: req.body, + headers: req.headers, + url: req.url, + correlation: { requestId: req.requestId, traceId: req.traceId }, + }), + }); +} + +/** Builds the remote table over the configured teapots, in configuration order. */ +function createRemoteTable( + urls: string[], + registry: Registry, + logger: Logger, + publish: (routes: RouteDef[]) => void, +): RemoteTable { + const byUrl = new Map(); + + return { + set(url, routes, strict) { + const others = urls.filter((other) => other !== url).flatMap((other) => byUrl.get(other) ?? []); + const before = new Set((byUrl.get(url) ?? []).map(showRoute)); + const next: ServedRemote[] = []; + + for (const route of routes) { + const candidate: RemoteRoute = { method: route.method, pattern: route.pattern, url }; + + try { + assertRemoteRouteFits([...others, ...next], candidate); + } catch (error) { + if (strict) throw error; + // Refused for this teapot only; the table that is serving stays as it was (D15, rule 5). + logger.warn(`mesh: not serving a route from ${url} — ${(error as Error).message}`); + continue; + } + + if (!before.has(showRoute(candidate))) warnIfShadowed(registry, candidate, logger); + next.push({ ...candidate, def: remoteRouteDef(route) }); + } + + byUrl.set(url, next); + publish(urls.flatMap((other) => (byUrl.get(other) ?? []).map((served) => served.def))); + + const after = new Set(next.map(showRoute)); + return { + added: [...after].filter((key) => !before.has(key)), + removed: [...before].filter((key) => !after.has(key)), + }; + }, + }; +} + +/** What a teapot's link needs to report membership back to the remote table after boot. */ +interface MembershipContext { + mesh: MeshConfig; + bus: Bus; + logger: Logger; + table: RemoteTable; +} + +/** Applies one teapot's routes after boot and emits `mesh:routes` when the table actually changed. */ +function applyMembership(ctx: MembershipContext, url: string, routes: TeacupRemoteRoute[]): void { + const { added, removed } = ctx.table.set(url, routes, false); + if (!added.length && !removed.length) return; + ctx.bus.emit('mesh:routes', { name: url, url, added, removed }); +} + +/** + * Opens a link to one teapot, wired so a returning manifest updates its routes and a link that + * gives up for good removes them (D15). `holder.link` is filled in once the link exists, because + * the callbacks need the link to rebuild its route proxies. + */ +function connectTeapot( + ctx: MembershipContext, + teapot: { url: string; secret: string }, + holder: { link?: Link }, +): Promise { + const { mesh, bus, logger } = ctx; + + return connectLink({ + url: teapot.url, + secret: teapot.secret, + timeoutMs: mesh.timeoutMs, + heartbeatMs: mesh.heartbeatMs, + reconnect: mesh.reconnect, + onManifestChange: mesh.onManifestChange, + logger, + bus, + onReconnect: () => { + if (holder.link) applyMembership(ctx, teapot.url, buildRemote(holder.link).routes); + }, + onGone: () => { + logger.warn(`mesh: teapot ${teapot.url} is gone for good — its routes are removed and now answer 404.`); + applyMembership(ctx, teapot.url, []); + }, + }); +} + +/** Backoff bounds for retrying a late teapot: the reconnect ones, or nothing when reconnect is off. */ +function lateBounds(mesh: MeshConfig): { initial: number; max: number } | undefined { + if (mesh.reconnect === false) return undefined; + const opts = typeof mesh.reconnect === 'object' ? mesh.reconnect : {}; + return { initial: opts.initialDelayMs ?? 500, max: opts.maxDelayMs ?? 30_000 }; +} + +/** + * Keeps trying a teapot that missed the boot budget, with the reconnect backoff (D15, rule 1). When + * it connects, its routes join the remote table; its steps do not, because the graph was validated + * at boot without them. A permanent refusal stops the retries. The handle's `close()` stops them too, + * and closes the link if one came up, so shutdown never leaves a retry behind. + */ +function retryLateTeapot( + ctx: MembershipContext, + teapot: { url: string; secret: string }, + bounds: { initial: number; max: number }, +): { close: () => void } { + const holder: { link?: Link } = {}; + let stopped = false; + let attempt = 0; + let timer: ReturnType | undefined; + + const schedule = (): void => { + const capped = Math.min(bounds.initial * 2 ** attempt++, bounds.max); + timer = setTimeout(() => void tryOnce(), Math.round(capped / 2 + Math.random() * (capped / 2))); + timer.unref?.(); + }; + + const tryOnce = async (): Promise => { + try { + const link = await connectTeapot(ctx, teapot, holder); + if (stopped) return link.close(); + holder.link = link; + const { steps, routes } = buildRemote(link); + if (steps.length) + ctx.logger.warn( + `mesh: teapot ${teapot.url} connected after boot — its routes are served now, but its steps ` + + `(${steps.map((step) => step.name).join(', ')}) are not: the graph was fixed at boot without them.`, + ); + applyMembership(ctx, teapot.url, routes); + } catch (error) { + if (stopped) return; + + if (isPermanentRefusal(error)) { + ctx.logger.error( + `mesh: teapot ${teapot.url} refused this peer — no longer retrying it (${(error as Error).message})`, + ); + return; + } + + schedule(); + } + }; + + schedule(); + + return { + close: () => { + stopped = true; + clearTimeout(timer); + holder.link?.close(); + }, + }; +} + +/** + * Connects the configured teapots, splices their remote steps into the registry, and publishes their + * routes through `publish`, now and whenever membership changes after boot (D15). + */ async function spliceRemoteScopes( mesh: MeshConfig, bus: Bus, registry: Registry, logger: Logger, -): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[]; absent: string[] }> { - const remoteRoutes: RouteDef[] = []; - const meshLinks: Link[] = []; + publish: (routes: RouteDef[]) => void, +): Promise<{ meshLinks: Closable[]; absent: string[] }> { + const meshLinks: Closable[] = []; const absent: string[] = []; // urls of teapots that never connected within the boot budget - const routeOwners = new Map(); // "METHOD effective-shape" -> owner - const remoteAccepted: RemoteRoute[] = []; // every remote route spliced so far, in teapot order + const teapots = mesh.teapots ?? []; + const table = createRemoteTable( + teapots.map((teapot) => teapot.url), + registry, + logger, + publish, + ); + const ctx: MembershipContext = { mesh, bus, logger, table }; try { - for (const teapot of mesh.teapots ?? []) { + for (const teapot of teapots) { warnIfCleartext(teapot.url, logger); - const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () => - connectLink({ - url: teapot.url, - secret: teapot.secret, - timeoutMs: mesh.timeoutMs, - heartbeatMs: mesh.heartbeatMs, - reconnect: mesh.reconnect, - onManifestChange: mesh.onManifestChange, - logger, - bus, - }), - ); + const holder: { link?: Link } = {}; + const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () => connectTeapot(ctx, teapot, holder)); if (!link) { absent.push(teapot.url); + const bounds = lateBounds(mesh); + if (bounds) meshLinks.push(retryLateTeapot(ctx, teapot, bounds)); continue; } + holder.link = link; meshLinks.push(link); const { steps, routes } = buildRemote(link); const origin = `mesh:${teapot.url}`; @@ -1009,83 +1255,14 @@ async function spliceRemoteScopes( registry.setRunner(step.name, step.run); } - for (const route of routes) { - const display = `${route.method} ${route.pattern}`; - const key = `${route.method} ${compilePattern(route.pattern).shape}`; - const owner = routeOwners.get(key); - - // Fail the boot rather than pick one. Route matching keeps the first of two identical - // patterns, so the loser would be silently dead — and callers could come to depend on - // "first teapot wins", which would make adding balancing later a breaking change. - // Scope tokens already fail this way in setRunner; routes now match. - if (owner) { - throw new Error( - `mesh: ambiguous remote route '${display}' from ${teapot.url} conflicts with ` + - `'${route.method} ${owner.pattern}' from ${owner.url} — ` + - 'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' + - 'Export it from a single teapot.', - ); - } - - routeOwners.set(key, { url: teapot.url, pattern: route.pattern }); - assertNoRemoteSiblingConflict(remoteAccepted, { - method: route.method, - pattern: route.pattern, - url: teapot.url, - }); - remoteAccepted.push({ method: route.method, pattern: route.pattern, url: teapot.url }); - - // Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin - // wins. That precedence is deliberate — your own code beats an imported one, and it is - // how you override a teapot — but silently shadowing an export looks exactly like a - // broken teapot from the outside. Warn and let the developer decide. - if ( - registry.routePlans.some( - (plan) => - plan.method === route.method && - compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape, - ) - ) { - logger.warn( - `mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` + - 'the local route takes precedence and the remote one will not be reached. ' + - 'Remove one if that is not what you meant.', - ); - } - - // Marked so the router files it in the remote tree; precedence is unchanged by the split. - remoteRoutes.push( - markRemoteRoute({ - method: route.method, - pattern: route.pattern, - transport: 'buffer', - // Built explicitly rather than cast from the handler argument. The cast put the whole - // internal request on the wire — `ip` and `protocol` included — and sent fields the - // protocol never declared, so a teapot could come to rely on something we never promised. - handler: async (req) => - route.handler({ - // HEAD reaches a remote GET through the implicit-HEAD fallback, and the teapot looks - // its plan up by method, so a forwarded HEAD finds none and answers 404. Send it as the - // GET it resolved to; dispatch drops the body for HEAD. Fixed teacup-side (D16) so an - // unchanged, older teapot still answers it during a rolling deploy. - method: req.method === 'HEAD' && route.method === 'GET' ? 'GET' : req.method, - params: req.params, - query: req.query, - body: req.body, - headers: req.headers, - url: req.url, - correlation: { requestId: req.requestId, traceId: req.traceId }, - }), - }), - ); - } + table.set(teapot.url, routes, true); } } catch (err) { closeLinks(meshLinks); throw err; } - return { remoteRoutes, meshLinks, absent }; + return { meshLinks, absent }; } /** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */ @@ -1310,8 +1487,39 @@ function buildMeshControl( return createMeshControl({ secret: mesh.secret, manifest, resolveScope, resolveRoute, bus }); } -/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */ -function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] { +/** + * The one HTTP route table, shared by app.fetch and listen(): local and dev routes, then remote ones. + * Built after boot, on first use. A mesh membership change publishes a new array with the same local + * head (D15), so the router reuses its local trees and rebuilds only the remote ones, and a request in + * flight keeps the array it read. Dev routes sit before the remote ones so their positions, and with + * them the local trees, do not move when remote routes come and go. + */ +function createRouteTable(buildLocal: () => RouteDef[]): { + current: () => RouteDef[]; + publish: (remote: RouteDef[]) => void; +} { + let remote: RouteDef[] = []; + let local: RouteDef[] | undefined; + let table: RouteDef[] | undefined; + + return { + current: () => { + if (!table) { + local = buildLocal(); + table = [...local, ...remote]; + } + + return table; + }, + publish: (next) => { + remote = next; + if (local) table = [...local, ...next]; + }, + }; +} + +/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline. */ +function buildHttpRoutes(routePlans: RoutePlan[], deps: PipelineDeps): RouteDef[] { const { providedSeed, planSteps, bus, onError, logger } = deps; const local = routePlans @@ -1356,7 +1564,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps }, })); - return [...local, ...remoteRoutes]; + return local; } /** @@ -1367,12 +1575,9 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps * costs one flag check per request after the first. */ function buildAppFetch( - routePlans: RoutePlan[], - deps: PipelineDeps, fetchOpts: HttpOptions, ensureBooted: () => Promise, - devRoutes: () => RouteDef[], - getRemoteRoutes: () => RouteDef[], + getRoutes: () => RouteDef[], ): (request: Request) => Promise { let handler: ((request: Request) => Promise) | undefined; @@ -1380,7 +1585,7 @@ function buildAppFetch( await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted if (!handler) { - handler = buildFetch([...buildHttpRoutes(routePlans, getRemoteRoutes(), deps), ...devRoutes()], fetchOpts); + handler = buildFetch(getRoutes, fetchOpts); } return handler(request); @@ -1564,7 +1769,7 @@ function runTeardown(teardown: TeardownRegistry, logger: Logger, budgetMs: numbe function closeApp( server: http.Server | undefined, - meshLinks: Link[], + meshLinks: Closable[], streams: Set<() => void>, options: { timeoutMs?: number }, defaultTimeoutMs: number | undefined, @@ -1649,7 +1854,7 @@ function closeApp( } /** Best-effort close of every mesh link, ignoring individual failures. */ -function closeLinks(links: Link[]): void { +function closeLinks(links: Closable[]): void { for (const link of links) { try { link.close(); diff --git a/src/app/types.ts b/src/app/types.ts index f21f6cb..902222b 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -135,6 +135,13 @@ export interface MeshConfig { * `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. + * + * It also decides what a dropped teapot's routes do (D15). While a link is reconnecting its routes + * stay in the table and answer `503` with `retry-after`, and `Allow` keeps them. A link that gives + * up for good — dropped with `reconnect: false`, or refused permanently (a wrong secret, a + * protocol mismatch) while reconnecting — has its routes removed: they answer `404` and leave + * `Allow`. Each change emits `mesh:routes` with `{ url, added, removed }`. A teapot that missed + * `bootTimeoutMs` is retried in the background with this backoff, unless it is `false`. */ reconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number }; /** @@ -145,6 +152,9 @@ export interface MeshConfig { * 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. + * + * Only steps count. Routes are not part of the graph, so a returning teapot's routes replace its + * old ones: a route it added is served, one it dropped answers `404` (D15). */ onManifestChange?: 'refuse'; /** @@ -161,6 +171,10 @@ export interface MeshConfig { * one of its tokens still fails the boot, naming it. A permanent refusal — a wrong secret, a * protocol mismatch — fails at once without spending the grace. * + * After boot, such a teapot keeps being retried in the background with the `reconnect` backoff + * (not with `reconnect: false`). When it connects, its routes are added to the table and served; + * its steps are not, because the graph was validated at boot without them (D15). + * * `0` means one attempt and no grace. That is the attempt count boot used to have, and nothing * more: exhausting it no longer fails the boot, so a single unreachable teapot still warns and * starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens. diff --git a/src/bus.ts b/src/bus.ts index db83d70..002fd5d 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -45,6 +45,9 @@ export type LifecycleEvent = // 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' + // A teacup's remote routes changed after boot (D15): a late teapot connected, a returning one + // exported a different set, or a link gave up for good. Carries `url`, `added` and `removed`. + | 'mesh:routes' | 'plugin:mounted' // Paired: see the guarantee above. `request:start` has no status and no duration — it says a // request arrived, not that it routed. @@ -125,6 +128,12 @@ export interface EventPayload { * framework does not know what was sent, and will not guess. */ status?: number; + /** `mesh:routes`: the teapot whose routes changed. */ + url?: string; + /** `mesh:routes`: routes added to the remote table, as `'METHOD /pattern'`. */ + added?: string[]; + /** `mesh:routes`: routes removed from the remote table, as `'METHOD /pattern'`. */ + removed?: string[]; } /** diff --git a/src/http/router.ts b/src/http/router.ts index bb86f84..5df443a 100644 --- a/src/http/router.ts +++ b/src/http/router.ts @@ -1,4 +1,4 @@ -import type { RouteDef, MatchedRoute } from './types'; +import type { RouteDef, RouteTable, MatchedRoute } from './types'; export type CompiledSegment = | { kind: 'static'; value: string } @@ -152,9 +152,9 @@ function segmentShape(segment: CompiledSegment): string { * spy on the export cannot see it, so the counts are kept here; they let a test prove that misses * after the index is built recompile nothing and rebuild nothing (FPRD-001 CARD-10). */ -const seamCounts = { compilePattern: 0, indexBuilds: 0 }; +const seamCounts = { compilePattern: 0, indexBuilds: 0, localTreeBuilds: 0 }; -/** @internal Calls so far to `compilePattern` (cache hits included) and route-index builds. For tests. */ +/** @internal Calls so far to `compilePattern` (cache hits included), route-index builds and local-tree builds. For tests. */ export const routerSeamCounts = (): Readonly => ({ ...seamCounts }); /** Compiles and validates one route pattern. Results are cached by source string. */ @@ -417,6 +417,11 @@ interface RouteIndex { /** The routes a mesh teacup spliced in from its teapots. Identity-keyed, so a route is remote wherever it travels. */ const remoteRouteDefs = new WeakSet(); +/** The array a {@link RouteTable} holds right now. Servers call it once per request. */ +export function currentRoutes(table: RouteTable): RouteDef[] { + return typeof table === 'function' ? table() : table; +} + /** Marks a route as spliced in from a mesh teapot, so the index files it in the remote tree. */ export function markRemoteRoute(def: T): T { remoteRouteDefs.add(def); @@ -505,6 +510,34 @@ function buildTrees(entries: Array<{ def: RouteDef; order: number }>): Map; trees: Map } +>(); + +function sameEntries(a: Array<{ def: RouteDef; order: number }>, b: Array<{ def: RouteDef; order: number }>): boolean { + return a.length === b.length && a.every((entry, i) => entry.def === b[i].def && entry.order === b[i].order); +} + +function localTrees(local: Array<{ def: RouteDef; order: number }>): Map { + if (!local.length) return buildTrees(local); + const cached = localTreeCache.get(local[0].def); + if (cached && sameEntries(cached.entries, local)) return cached.trees; + + seamCounts.localTreeBuilds++; + const trees = buildTrees(local); + localTreeCache.set(local[0].def, { entries: local, trees }); + return trees; +} + function routeIndex(routes: RouteDef[]): RouteIndex { const cached = routeIndexCache.get(routes); if (cached?.size === routes.length) return cached; @@ -516,7 +549,7 @@ function routeIndex(routes: RouteDef[]): RouteIndex { const index: RouteIndex = { size: routes.length, - local: buildTrees(local), + local: localTrees(local), remote: remote.length ? buildTrees(remote) : undefined, methods: [...new Set(routes.map((route) => route.method))], }; diff --git a/src/http/server.ts b/src/http/server.ts index bf82c08..1cb6bb2 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -17,12 +17,13 @@ import { type Preflight, } from './core'; import type { BodyFailure, BodyReader } from './body'; -import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types'; +import type { RouteTable, WsRouteDef, MeshControl, HttpOptions } from './types'; +import { currentRoutes } from './router'; import type { Logger } from '../logger'; import { nodeRequire } from '../node-require'; interface HandlerConfig { - routes: RouteDef[]; + routes: RouteTable; bus?: Bus; opts?: HttpOptions; trustProxy: boolean; @@ -35,14 +36,14 @@ function errorRequest(req: http.IncomingMessage): ErrorRequest { /** * Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades. - * @param routes HTTP route definitions. + * @param routes HTTP route definitions, or a getter read once per request (a mesh teacup's table changes as peers come and go). * @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency). * @param bus Optional event bus for stream lifecycle events. * @param meshControl Optional mesh gateway hook for a reserved upgrade path. * @param opts Limits, TLS, security, CORS, and body-parsing options. */ export function createHttpServer( - routes: RouteDef[], + routes: RouteTable, wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, @@ -158,7 +159,7 @@ function createRequestHandler(cfg: HandlerConfig) { } result = await handle( - routes, + currentRoutes(routes), // once per request, see buildFetch opts, { ...correlation, diff --git a/src/http/types.ts b/src/http/types.ts index 84304c8..98ec7cc 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -91,6 +91,13 @@ export interface RouteDef { maxParts?: number; // per-route override of the server's multipart maxParts } +/** + * A route table: a fixed array, or a getter the server reads once per request. A mesh teacup passes + * a getter, because its remote routes change as teapots come and go (CARD-19); each change publishes + * a new array, so a request sees the whole old table or the whole new one. + */ +export type RouteTable = RouteDef[] | (() => RouteDef[]); + /** Result of matching a request path against a route: extracted params plus the matched definition. */ export interface MatchedRoute { params: Record; diff --git a/src/http/web.ts b/src/http/web.ts index 82a070a..08c6768 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -15,7 +15,8 @@ import { peerOf } from './peer'; import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body'; import { HttpError } from '../signals'; import { renderError, type ErrorRequest } from '../transformers'; -import type { RouteDef, HttpOptions } from './types'; +import type { RouteTable, HttpOptions } from './types'; +import { currentRoutes } from './router'; /** * Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream @@ -235,7 +236,7 @@ function forwardedFor(headers: Record, opts: HttpOptions | undef * Routing, body parsing, limits and error rendering all live in the core; this file is the part * that knows how to get bytes out of a `Request` and how to put them into a `Response`. */ -export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { +export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) { // Built once per server, not once per request — see `BodyReader`. const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts); const gate = createRequestGate(opts?.limits?.maxConcurrentRequests); @@ -285,7 +286,9 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { acquired = gate.limited; result = await handle( - routes, + // Read once per request: a mesh teacup swaps its table when peers come and go, and one + // request must route and build `Allow` against the same table (CARD-19). + currentRoutes(routes), opts, { ...correlation, diff --git a/src/mesh/link.ts b/src/mesh/link.ts index 1cd38de..4e11c50 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -2,7 +2,6 @@ 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'; @@ -64,6 +63,8 @@ interface LinkState { socket: WsSocket | undefined; closed: boolean; retry: ReturnType | undefined; + /** When the scheduled reconnect attempt fires (epoch ms), for the `retry-after` a 503 carries. */ + retryAt: number | undefined; } /** One established connection: its socket, the manifest it announced, and its heartbeat. */ @@ -81,10 +82,10 @@ const DEFAULT_MAX_DELAY_MS = 30_000; * 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. */ -function rejectAllPending(pending: Map, reason: string): void { +function rejectAllPending(pending: Map, reason: string, headers?: Record): void { for (const [, entry] of pending) { clearTimeout(entry.timer); - entry.reject(new HttpError(503, reason)); + entry.reject(new HttpError(503, reason, undefined, headers)); } pending.clear(); @@ -99,13 +100,14 @@ function sendRpc( name: string, ctx: RequestEnvelope, timeoutMs: number, + downHeaders?: Record, ): Promise { // 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. 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}'`)); + return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`, undefined, downHeaders)); } return new Promise((resolveCall, rejectCall) => { @@ -329,37 +331,109 @@ function stepKeys(manifest: Manifest): Set { } /** - * 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 { - 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 steps 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. + * The graph was validated at boot against the first manifest and is already serving. A step token + * that vanished cannot be validated away after the fact, so a manifest missing one is refused + * rather than accepted — see `ManifestPolicy`. Extra steps are ignored: the graph is fixed at boot + * and nothing new is spliced into it. + * + * Routes are not compared. They are not part of the graph, so a returning teapot's routes replace + * the old ones instead (D15): a route it added is served, one it dropped is removed. */ export function missingFromManifest(booted: Manifest, returned: Manifest): string[] { const steps = stepKeys(returned); - const routes = routeKeys(returned); const missing: string[] = []; for (const step of booted.steps) { if (!steps.has(step)) missing.push(`step '${step}'`); } - for (const route of booted.routes) { - if (!routes.has(`${route.method} ${compilePattern(route.pattern).shape}`)) { - missing.push(`route '${route.method} ${route.pattern}'`); - } + return missing; +} + +/** + * `retry-after` for a 503 while the link is down and will try again: the seconds until the next + * attempt, at least 1. Nothing when it will not try again, so a client is not told to come back to + * a link that has given up. + */ +function retryAfter(state: LinkState, reconnects: boolean): Record | undefined { + if (state.closed || !reconnects) return undefined; + const waitMs = state.retryAt === undefined ? 0 : state.retryAt - Date.now(); + + return { 'retry-after': String(Math.max(1, Math.ceil(waitMs / 1000))) }; +} + +/** A session dropped with reconnection off: the link is gone for good, if it was ever up. */ +function dropWithoutReconnect(adopted: boolean, giveUp: () => void): void { + if (adopted) giveUp(); +} + +/** Stop a link for good and say so: a drop with reconnection off, or a permanent refusal (D15). */ +function stopForGood(state: LinkState, onGone: (() => void) | undefined): void { + if (state.closed) return; + state.closed = true; + clearTimeout(state.retry); + state.retry = undefined; + onGone?.(); +} + +/** + * Whether a failed reconnect attempt was the teapot refusing this peer on purpose, in which case the + * link gives up. Retrying reaches the same answer forever, so the link stops and its routes go (D15), + * the same verdict boot gives a refusal. + */ +function refusedWhileReconnecting( + url: string, + error: unknown, + logger: Logger | undefined, + giveUp: () => void, +): boolean { + if (!isPermanentRefusal(error)) return false; + logger?.warn(`mesh: ${url} refused this peer while reconnecting (${(error as Error).message}) — giving up on it.`); + giveUp(); + + return true; +} + +/** + * Hang up on a session whose manifest no longer backs the graph, and return the fingerprint now logged. + * + * 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. + */ +function refuseSession( + session: Session, + missing: string[], + logged: string, + url: string, + logger: Logger | undefined, +): string { + session.heartbeat.stop(); + session.socket.close(); + const fingerprint = missing.join('|'); + + if (fingerprint !== logged) { + logger?.warn( + `mesh: refusing to reconnect to ${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 missing; + return fingerprint; +} + +/** A session was adopted. When it is a returning one: keep the boot steps, take its routes (D15), and tell the caller. */ +function reconnected( + returning: boolean, + link: Link, + returned: Manifest, + onReconnect: ((manifest: Manifest) => void) | undefined, +): void { + if (!returning) return; + link.manifest = { steps: link.manifest.steps, routes: returned.routes }; + onReconnect?.(link.manifest); } /** Resolved backoff bounds, or `undefined` when the caller turned reconnection off. */ @@ -394,19 +468,36 @@ export function connectLink(args: { /** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */ onManifestChange?: ManifestPolicy; logger?: Logger; + /** + * Called each time a dropped link reconnects and its session is adopted, after `link.manifest` + * has taken the returning manifest's routes. Not called for the first connection: the caller + * has the link, and its manifest, when the returned promise resolves. + */ + onReconnect?: (manifest: Manifest) => void; + /** + * Called once when the link gives up for good: its session dropped with `reconnect: false`, or a + * reconnect attempt was refused permanently (a wrong secret, a protocol mismatch). Not called by + * `close()`, which is the application hanging up, not the teapot going away. + */ + onGone?: () => void; }): Promise { const timeoutMs = args.timeoutMs ?? 30_000; const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS; const bounds = backoffBounds(args.reconnect); const pending = new Map(); - const state: LinkState = { socket: undefined, closed: false, retry: undefined }; + const state: LinkState = { socket: undefined, closed: false, retry: undefined, retryAt: undefined }; let refusalLogged = ''; + let adopted = false; // a session was adopted at least once, so the link has something to lose + + const downHeaders = (): Record | undefined => retryAfter(state, bounds !== undefined); + const giveUp = (): void => stopForGood(state, args.onGone); 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. + // replaced with the real manifest before this object escapes. A reconnect keeps the boot + // manifest's steps, because the graph is fixed at boot, and takes the returning one's routes. manifest: { steps: [], routes: [] }, - rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs), + rpc: (kind, name, ctx) => + sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs, downHeaders()), 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. @@ -438,6 +529,8 @@ export function connectLink(args: { // the teapot the moment it returns. const delay = Math.round(capped / 2 + Math.random() * (capped / 2)); + clearTimeout(state.retry); + state.retryAt = Date.now() + delay; state.retry = setTimeout(() => void attemptReconnect(attempt + 1), delay); state.retry.unref?.(); }; @@ -446,8 +539,12 @@ export function connectLink(args: { 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`); + // Scheduled before the rejection, so the 503s carry the real wait in `retry-after`. scheduleRetry(attempt); + rejectAllPending(pending, `mesh link to ${args.url} is down`, downHeaders()); + // With reconnection off, a link that was up and dropped is gone for good (D15). `adopted` + // keeps a first connect that never succeeded out of this: that link never escaped. + if (!bounds) dropWithoutReconnect(adopted, giveUp); }; /** Adopt an established session, or refuse it when its manifest no longer backs the graph. */ @@ -455,27 +552,16 @@ export function connectLink(args: { 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.', - ); - } - + refusalLogged = refuseSession(session, missing, refusalLogged, args.url, args.logger); return false; } refusalLogged = ''; state.socket = session.socket; + const returning = adopted; + adopted = true; args.bus?.emit('mesh:connect', { name: args.url }); + reconnected(returning, link, session.manifest, args.onReconnect); return true; }; @@ -492,10 +578,12 @@ export function connectLink(args: { } if (!adopt(session)) 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); + } catch (error) { + // A permanent refusal ends the link. Otherwise: 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 (!refusedWhileReconnecting(args.url, error, args.logger, giveUp) && !state.socket && !state.retry) + scheduleRetry(attempt); } }; diff --git a/test/bun/mesh-reconnect.test.ts b/test/bun/mesh-reconnect.test.ts index 5d01d85..3cada4c 100644 --- a/test/bun/mesh-reconnect.test.ts +++ b/test/bun/mesh-reconnect.test.ts @@ -99,3 +99,91 @@ test('mesh on Bun: a teacup reconnects to a teapot that came back', async () => await teapot.stop(); } }); + +// CARD-19 (#124, D15): remote routes follow teapot membership on Bun too. +@Route('/remote') +class PingCtl { + @Get('/ping', { export: true }) + ping() { + return { from: 'teapot' }; + } +} +@Module({ mountpoint: '/api', controllers: [PingCtl] }) +class PingTeapotModule {} +@Module({ mountpoint: '/api', controllers: [] }) +class BareTeacupModule {} + +async function startPingTeapot(port: number) { + const app = createApp({ modules: [PingTeapotModule], experimental: true, mesh: { secret: SECRET } }); + const server = await serveBun(app, { port }); + + return { + stop: async () => { + server.stop(true); + await app.close(); + }, + }; +} + +/** Polls `GET path` until it answers `status`, or fails after `ms`. */ +async function untilStatus(app: ReturnType, path: string, status: number, ms = 3000) { + const deadline = Date.now() + ms; + let last = 0; + while (Date.now() < deadline) { + const res = await app.fetch(new Request(`http://x${path}`)); + await res.text(); + last = res.status; + if (last === status) return; + await settle(25); + } + throw new Error(`${path} answered ${last}, expected ${status}`); +} + +const pingTeacup = (port: number) => + createApp({ + modules: [BareTeacupModule], + experimental: true, + mesh: { + teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }], + reconnect: { initialDelayMs: 20, maxDelayMs: 60 }, + bootTimeoutMs: 100, + heartbeatMs: 50, + timeoutMs: 2000, + }, + }); + +test('mesh on Bun: a teapot absent at boot has its routes served once it connects (CARD-19 T1)', async () => { + const port = freePort(); + const teacup = pingTeacup(port); + let teapot: Awaited> | undefined; + + try { + expect((await teacup.fetch(new Request('http://x/api/remote/ping'))).status).toBe(404); + teapot = await startPingTeapot(port); + await untilStatus(teacup, '/api/remote/ping', 200); + } finally { + await teacup.close(); + await teapot?.stop(); + } +}); + +test('mesh on Bun: a reconnecting teapot keeps its routes with 503 + retry-after (CARD-19 T2)', async () => { + const port = freePort(); + const teapot = await startPingTeapot(port); + const teacup = pingTeacup(port); + + try { + await untilStatus(teacup, '/api/remote/ping', 200); + await teapot.stop(); + await untilStatus(teacup, '/api/remote/ping', 503); + + const down = await teacup.fetch(new Request('http://x/api/remote/ping')); + expect(down.status).toBe(503); + expect(Number(down.headers.get('retry-after'))).toBeGreaterThanOrEqual(1); + + const options = await teacup.fetch(new Request('http://x/api/remote/ping', { method: 'OPTIONS' })); + expect(options.headers.get('allow')).toBe('GET, HEAD, OPTIONS'); + } finally { + await teacup.close(); + } +}); diff --git a/test/deno/mesh-reconnect.test.ts b/test/deno/mesh-reconnect.test.ts index d0a813c..819b414 100644 --- a/test/deno/mesh-reconnect.test.ts +++ b/test/deno/mesh-reconnect.test.ts @@ -99,3 +99,96 @@ Deno.test('mesh on Deno: a teacup reconnects to a teapot that came back', async await teapot.stop(); } }); + +// CARD-19 (#124, D15): remote routes follow teapot membership on Deno too. +@Route('/remote') +class PingCtl { + @Get('/ping', { export: true }) + ping() { + return { from: 'teapot' }; + } +} +@Module({ mountpoint: '/api', controllers: [PingCtl] }) +class PingTeapotModule {} +@Module({ mountpoint: '/api', controllers: [] }) +class BareTeacupModule {} + +async function startPingTeapot(port: number) { + const app = createApp({ modules: [PingTeapotModule], experimental: true, mesh: { secret: SECRET } }); + const server = await serveDeno(app, { port }); + await new Promise((r) => setTimeout(r, 50)); + + return { + stop: async () => { + await server.shutdown(); + await app.close(); + }, + }; +} + +/** Polls `GET path` until it answers `status`, or fails after `ms`. */ +async function untilStatus(app: ReturnType, path: string, status: number, ms = 3000) { + const deadline = Date.now() + ms; + let last = 0; + while (Date.now() < deadline) { + const res = await app.fetch(new Request(`http://x${path}`)); + await res.body?.cancel(); + last = res.status; + if (last === status) return; + await settle(25); + } + throw new Error(`${path} answered ${last}, expected ${status}`); +} + +const pingTeacup = (port: number) => + createApp({ + modules: [BareTeacupModule], + experimental: true, + mesh: { + teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }], + reconnect: { initialDelayMs: 20, maxDelayMs: 60 }, + bootTimeoutMs: 100, + heartbeatMs: 50, + timeoutMs: 2000, + }, + }); + +Deno.test('mesh on Deno: a teapot absent at boot has its routes served once it connects (CARD-19 T1)', async () => { + const port = freePort(); + const teacup = pingTeacup(port); + let teapot: Awaited> | undefined; + + try { + const before = await teacup.fetch(new Request('http://x/api/remote/ping')); + await before.body?.cancel(); + assertEquals(before.status, 404); + + teapot = await startPingTeapot(port); + await untilStatus(teacup, '/api/remote/ping', 200); + } finally { + await teacup.close(); + await teapot?.stop(); + } +}); + +Deno.test('mesh on Deno: a reconnecting teapot keeps its routes with 503 + retry-after (CARD-19 T2)', async () => { + const port = freePort(); + const teapot = await startPingTeapot(port); + const teacup = pingTeacup(port); + + try { + await untilStatus(teacup, '/api/remote/ping', 200); + await teapot.stop(); + await untilStatus(teacup, '/api/remote/ping', 503); + + const down = await teacup.fetch(new Request('http://x/api/remote/ping')); + await down.body?.cancel(); + assertEquals(down.status, 503); + assertEquals(Number(down.headers.get('retry-after')) >= 1, true); + + const options = await teacup.fetch(new Request('http://x/api/remote/ping', { method: 'OPTIONS' })); + assertEquals(options.headers.get('allow'), 'GET, HEAD, OPTIONS'); + } finally { + await teacup.close(); + } +}); diff --git a/test/mesh/membership.test.ts b/test/mesh/membership.test.ts new file mode 100644 index 0000000..6522263 --- /dev/null +++ b/test/mesh/membership.test.ts @@ -0,0 +1,341 @@ +/** + * CARD-19 (#124, D15): a teacup's remote routes follow which teapots are connected. + * + * Late teapot → its routes are added. Reconnecting → they stay and answer 503 with `retry-after`. + * Gone for good → they are removed (404, `Allow` without them). A returning manifest adds and drops + * routes. A late route that conflicts is refused and logged. Every change emits `mesh:routes`, and + * none rebuilds the local route tree. + */ +import 'reflect-metadata'; +import http from 'http'; +import net from 'net'; +import type { AddressInfo } from 'net'; +import { describe, it, expect, afterEach } from 'vitest'; +import { createApp, Route, Get, Module } from '../../src/index'; +import { routerSeamCounts } from '../../src/http/router'; +import type { App, MeshConfig } from '../../src/app/types'; +import type { EventPayload } from '../../src/bus'; + +const SECRET = 'membership-secret'; + +@Route('/remote') +class PingCtl { + @Get('/ping', { export: true }) ping() { + return { from: 'teapot' }; + } +} +@Module({ mountpoint: '/api', controllers: [PingCtl] }) +class PingTeapot {} + +@Route('/remote') +class PingExtraCtl { + @Get('/ping', { export: true }) ping() { + return { from: 'teapot v2' }; + } + @Get('/extra', { export: true }) extra() { + return { extra: true }; + } +} +@Module({ mountpoint: '/api', controllers: [PingExtraCtl] }) +class PingExtraTeapot {} + +@Route('/remote') +class ExtraOnlyCtl { + @Get('/extra', { export: true }) extra() { + return { extra: true }; + } +} +@Module({ mountpoint: '/api', controllers: [ExtraOnlyCtl] }) +class ExtraOnlyTeapot {} + +@Route('/shape') +class ShapeIdCtl { + @Get('/:id', { export: true }) get() { + return { from: 'id' }; + } +} +@Module({ mountpoint: '/api', controllers: [ShapeIdCtl] }) +class ShapeIdTeapot {} + +@Route('/') +class ShapeNameCtl { + @Get('/shape/:name', { export: true }) get() { + return { from: 'name' }; + } + @Get('/other', { export: true }) other() { + return { from: 'other' }; + } +} +@Module({ mountpoint: '/api', controllers: [ShapeNameCtl] }) +class ShapeNameTeapot {} + +@Route('/local') +class LocalCtl { + @Get('/ok') ok() { + return { from: 'teacup' }; + } +} +@Module({ mountpoint: '/api', controllers: [LocalCtl] }) +class TeacupModule {} + +const FAST = { initialDelayMs: 20, maxDelayMs: 60 }; + +/** A port nothing listens on, that a teapot can take later. */ +async function freePort(): Promise { + const server = net.createServer(); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + await new Promise((resolve) => server.close(() => resolve())); + return port; +} + +const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`; + +const open: App[] = []; +afterEach(async () => { + while (open.length) await open.pop()!.close(); +}); + +async function teapotOn(port: number, module: new () => unknown): Promise { + const teapot = createApp({ modules: [module], experimental: true, mesh: { secret: SECRET } }); + await teapot.listen(port); + open.push(teapot); + return teapot; +} + +async function stop(teapot: App): Promise { + await teapot.close(); + open.splice(open.indexOf(teapot), 1); +} + +interface Teacup { + app: App; + warnings: string[]; + events: EventPayload[]; + /** Resolves on the next `name` event. */ + next: (name: 'mesh:routes' | 'mesh:disconnect') => Promise; +} + +function teacup(ports: number[], mesh: Partial = {}): Teacup { + const warnings: string[] = []; + const events: EventPayload[] = []; + const waiting = new Map void>>(); + const app = createApp({ + modules: [TeacupModule], + experimental: true, + logger: { debug() {}, info() {}, warn: (m: string) => warnings.push(m), error: (m: string) => warnings.push(m) }, + mesh: { + teapots: ports.map((port) => ({ url: controlUrl(port), secret: SECRET })), + bootTimeoutMs: 100, + timeoutMs: 1000, + heartbeatMs: 1000, + reconnect: FAST, + ...mesh, + }, + }); + + for (const name of ['mesh:routes', 'mesh:disconnect'] as const) { + app.bus.on(name, (payload) => { + if (name === 'mesh:routes') events.push(payload); + const list = waiting.get(name) ?? []; + waiting.delete(name); + for (const resolve of list) resolve(payload); + }); + } + + open.unshift(app); // closed before the teapots + const next = (name: string) => + new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`no ${name} within 5s`)), 5000); + waiting.set(name, [ + ...(waiting.get(name) ?? []), + (e) => { + clearTimeout(timer); + resolve(e); + }, + ]); + }); + return { app, warnings, events, next }; +} + +const get = (app: App, path: string, method = 'GET') => app.fetch(new Request(`http://mesh.test${path}`, { method })); + +function nodeGet(port: number, path: string) { + return new Promise<{ status: number; body: string }>((resolve, reject) => { + const req = http.request({ host: '127.0.0.1', port, method: 'GET', path, agent: false }, (res) => { + let body = ''; + res.setEncoding('utf8'); + res.on('data', (chunk) => (body += chunk)); + res.on('end', () => resolve({ status: res.statusCode ?? 0, body })); + }); + req.on('error', reject); + req.end(); + }); +} + +describe('mesh: remote routes follow teapot membership (CARD-19, D15)', () => { + it('T1: a teapot absent at boot is served once it connects, on app.fetch and listen(), without rebuilding the local tree', async () => { + const port = await freePort(); + const cup = teacup([port]); + const listenPort = ((await cup.app.listen(0)).address() as AddressInfo).port; + + expect((await get(cup.app, '/api/remote/ping')).status).toBe(404); + expect((await get(cup.app, '/api/local/ok')).status).toBe(200); + const before = routerSeamCounts(); + + const routed = cup.next('mesh:routes'); + await teapotOn(port, PingTeapot); + expect(await routed).toEqual({ + name: controlUrl(port), + url: controlUrl(port), + added: ['GET /api/remote/ping'], + removed: [], + }); + + const res = await get(cup.app, '/api/remote/ping'); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ from: 'teapot' }); + expect(await nodeGet(listenPort, '/api/remote/ping')).toEqual({ status: 200, body: '{"from":"teapot"}' }); + expect((await get(cup.app, '/api/local/ok')).status).toBe(200); + + const after = routerSeamCounts(); + expect(after.indexBuilds).toBeGreaterThan(before.indexBuilds); // the remote trees were rebuilt + expect(after.localTreeBuilds).toBe(before.localTreeBuilds); // the local ones were not + }); + + it('T2/T3: a reconnecting teapot keeps its routes with 503 + retry-after, then serves again', async () => { + const port = await freePort(); + let teapot = await teapotOn(port, PingTeapot); + const cup = teacup([port]); + expect((await get(cup.app, '/api/remote/ping')).status).toBe(200); + + const dropped = cup.next('mesh:disconnect'); + await stop(teapot); + await dropped; + + const down = await get(cup.app, '/api/remote/ping'); + expect(down.status).toBe(503); + expect(Number(down.headers.get('retry-after'))).toBeGreaterThanOrEqual(1); + expect((await get(cup.app, '/api/remote/ping', 'OPTIONS')).headers.get('allow')).toBe('GET, HEAD, OPTIONS'); + expect((await get(cup.app, '/api/remote/ping', 'POST')).headers.get('allow')).toBe('GET, HEAD, OPTIONS'); + + teapot = await teapotOn(port, PingTeapot); + await expect.poll(async () => (await get(cup.app, '/api/remote/ping')).status, { timeout: 5000 }).toBe(200); + // Same routes back: nothing changed in the table, so no event. + expect(cup.events).toEqual([]); + }); + + it('T4: with reconnect: false a dropped teapot is gone — 404, Allow without its methods, local routes unaffected', async () => { + const port = await freePort(); + const teapot = await teapotOn(port, PingTeapot); + const cup = teacup([port], { reconnect: false }); + expect((await get(cup.app, '/api/remote/ping')).status).toBe(200); + + const routed = cup.next('mesh:routes'); + await stop(teapot); + expect(await routed).toMatchObject({ added: [], removed: ['GET /api/remote/ping'] }); + + const gone = await get(cup.app, '/api/remote/ping'); + expect(gone.status).toBe(404); + expect(gone.headers.get('retry-after')).toBeNull(); + const options = await get(cup.app, '/api/remote/ping', 'OPTIONS'); + expect(options.status).toBe(404); + expect(options.headers.get('allow')).toBeNull(); + expect((await get(cup.app, '/api/local/ok')).status).toBe(200); + expect(cup.warnings.some((w) => w.includes('gone for good'))).toBe(true); + }); + + it('T5: a teapot that returns with an extra route has it served', async () => { + const port = await freePort(); + const teapot = await teapotOn(port, PingTeapot); + const cup = teacup([port]); + expect((await get(cup.app, '/api/remote/extra')).status).toBe(404); + + const dropped = cup.next('mesh:disconnect'); + await stop(teapot); + await dropped; + const routed = cup.next('mesh:routes'); + await teapotOn(port, PingExtraTeapot); + expect(await routed).toMatchObject({ added: ['GET /api/remote/extra'], removed: [] }); + + expect((await get(cup.app, '/api/remote/extra')).status).toBe(200); + expect(await (await get(cup.app, '/api/remote/ping')).json()).toEqual({ from: 'teapot v2' }); + }); + + it('T6: a teapot that returns without a route has it removed', async () => { + const port = await freePort(); + const teapot = await teapotOn(port, PingTeapot); + const cup = teacup([port]); + expect((await get(cup.app, '/api/remote/ping')).status).toBe(200); + + const dropped = cup.next('mesh:disconnect'); + await stop(teapot); + await dropped; + const routed = cup.next('mesh:routes'); + await teapotOn(port, ExtraOnlyTeapot); + expect(await routed).toMatchObject({ added: ['GET /api/remote/extra'], removed: ['GET /api/remote/ping'] }); + + expect((await get(cup.app, '/api/remote/ping')).status).toBe(404); + expect((await get(cup.app, '/api/remote/extra')).status).toBe(200); + }); + + it('T7: a late route ambiguous with another teapot’s is refused and logged; everything else serves', async () => { + const [portA, portB] = [await freePort(), await freePort()]; + await teapotOn(portA, ShapeIdTeapot); + const cup = teacup([portA, portB]); + expect(await (await get(cup.app, '/api/shape/1')).json()).toEqual({ from: 'id' }); + + const routed = cup.next('mesh:routes'); + await teapotOn(portB, ShapeNameTeapot); + expect(await routed).toMatchObject({ url: controlUrl(portB), added: ['GET /api/other'], removed: [] }); + + expect(await (await get(cup.app, '/api/shape/1')).json()).toEqual({ from: 'id' }); + expect((await get(cup.app, '/api/other')).status).toBe(200); + expect( + cup.warnings.some((w) => w.includes('not serving a route from') && w.includes("'GET /api/shape/:name'")), + ).toBe(true); + }); + + it('T8: 1 000 requests across a late connect each see the old table or the new one', async () => { + const port = await freePort(); + const cup = teacup([port]); + expect((await get(cup.app, '/api/remote/ping')).status).toBe(404); + + const routed = cup.next('mesh:routes'); + const starting = teapotOn(port, PingTeapot); + const statuses: number[] = []; + let changed = false; + void routed.then(() => (changed = true)); + + // 100 waves of 10 concurrent requests, spread across the moment the table changes. Ten at a time, + // not more: past 16 RPCs in flight on one link the teapot's control channel hits the WebSocket + // inbound-queue bound (#107) and drops the link. That is pre-existing and not about membership. + for (let wave = 0; wave < 100; wave++) { + const batch = await Promise.all( + Array.from({ length: 10 }, () => get(cup.app, '/api/remote/ping').then((res) => res.status)), + ); + statuses.push(...batch); + if (!changed) await new Promise((resolve) => setTimeout(resolve, 2)); + } + + await starting; + await routed; + + expect(statuses).toHaveLength(1000); + expect(statuses.every((status) => status === 404 || status === 200)).toBe(true); + // Both tables were actually seen, so the change happened while requests were flowing. + expect(statuses).toContain(404); + expect(statuses).toContain(200); + expect((await get(cup.app, '/api/remote/ping')).status).toBe(200); + }); + + it('with reconnect: false a teapot absent at boot is not retried (no backoff to retry with)', async () => { + const port = await freePort(); + const cup = teacup([port], { reconnect: false }); + expect((await get(cup.app, '/api/remote/ping')).status).toBe(404); + await teapotOn(port, PingTeapot); + await new Promise((resolve) => setTimeout(resolve, 300)); + expect((await get(cup.app, '/api/remote/ping')).status).toBe(404); + expect(cup.events).toEqual([]); + }); +}); diff --git a/test/mesh/reconnect.test.ts b/test/mesh/reconnect.test.ts index 6aac20e..0443b80 100644 --- a/test/mesh/reconnect.test.ts +++ b/test/mesh/reconnect.test.ts @@ -143,7 +143,7 @@ describe('missingFromManifest', () => { expect(missingFromManifest(booted, booted)).toEqual([]); }); - it('accepts extra exports — the graph is fixed at boot and nothing new is spliced', () => { + it('accepts extra exports — extra steps are ignored, since the graph is fixed at boot', () => { const wider: Manifest = { steps: [...booted.steps, 'billing'], routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }], @@ -161,8 +161,10 @@ describe('missingFromManifest', () => { expect(missingFromManifest(booted, shrunk)).toEqual(["step 'auth'"]); }); - it('reports a missing route by method and pattern', () => { + // D15 (CARD-19): routes are not part of the graph, so a returning teapot's routes replace the old + // ones (a dropped route is removed from the remote table) instead of refusing the reconnect. + it('does not report a missing route — routes follow the returning manifest', () => { const routeless: Manifest = { steps: booted.steps, routes: [] }; - expect(missingFromManifest(booted, routeless)).toEqual(["route 'GET /svc/:id'"]); + expect(missingFromManifest(booted, routeless)).toEqual([]); }); });