diff --git a/CHANGELOG.md b/CHANGELOG.md
index a90946c..ce2fbde 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -139,6 +139,33 @@ npm treats versions as semver and semver forbids leading zeros.
`?` and before `#`, if there is one: `q: 'what?now'`, and `/search?a=1&b=?` gives `b: '?'`. URLs
with a single `?` parse as before. Path extraction is unchanged.
+- **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.
+ - A late or returning route on a reserved path (`/__mesh__/control`, and `/__live__`/`/__ready__`
+ with `health` on) is refused and logged the same way. At boot it 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
- **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler`
diff --git a/src/app/index.ts b/src/app/index.ts
index 988cc8a..9cc3d75 100644
--- a/src/app/index.ts
+++ b/src/app/index.ts
@@ -44,7 +44,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_DISABLED_REASON, MESH_CONTROL_PATH } from '../mesh/teapot';
import type { MeshControl } from '../http';
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
@@ -59,6 +59,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[];
@@ -258,8 +261,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));
@@ -278,8 +280,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, reserved);
- remoteRoutes = spliced.remoteRoutes;
+ const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, reserved, 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.
@@ -325,6 +326,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 bootGraph = makeAppBooter(
@@ -353,14 +359,7 @@ export function createApp(opts: {
static: staticResolver,
health: healthProbe,
};
- 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, {
limits: opts.limits,
trustProxy: opts.trustProxy,
@@ -373,10 +372,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,
@@ -1046,41 +1045,295 @@ 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,
+ reserved: readonly ReservedPath[],
+ 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 {
+ // A teapot's own boot refuses a reserved path, but the manifest is whatever arrives on the
+ // wire: an older or foreign teapot could still advertise one, at boot or later, and the
+ // teacup must not splice it (CARD-21/CARD-17).
+ assertNotReserved(route.pattern, `mesh: remote route '${showRoute(route)}' from ${url}`, reserved);
+ 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).
+ // The same goes for a reserved path: that one route is skipped, the rest are served.
+ 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,
reserved: readonly ReservedPath[],
-): 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,
+ reserved,
+ 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}`;
@@ -1090,86 +1343,14 @@ async function spliceRemoteScopes(
registry.setRunner(step.name, step.run);
}
- for (const route of routes) {
- const display = `${route.method} ${route.pattern}`;
- // A teapot's own boot refuses such a route, but the manifest is whatever arrives on the wire:
- // an older or foreign teapot could still advertise one, and the teacup must not splice it.
- assertNotReserved(route.pattern, `mesh: remote route '${display}' from ${teapot.url}`, reserved);
- 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. */
@@ -1394,8 +1575,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
@@ -1440,7 +1652,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
},
}));
- return [...local, ...remoteRoutes];
+ return local;
}
/**
@@ -1451,12 +1663,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;
@@ -1475,7 +1684,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);
@@ -1669,7 +1878,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,
@@ -1754,7 +1963,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 3d31b8f..79c4b33 100644
--- a/src/app/types.ts
+++ b/src/app/types.ts
@@ -144,6 +144,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 };
/**
@@ -154,6 +161,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';
/**
@@ -170,6 +180,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 8c06c6c..2179dba 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 45e35f6..c74ab00 100644
--- a/src/http/server.ts
+++ b/src/http/server.ts
@@ -17,13 +17,14 @@ 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';
import { answerProbe } from './health';
interface HandlerConfig {
- routes: RouteDef[];
+ routes: RouteTable;
bus?: Bus;
opts?: HttpOptions;
trustProxy: boolean;
@@ -36,14 +37,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,
@@ -161,7 +162,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 b88ffc2..327e8b8 100644
--- a/src/http/types.ts
+++ b/src/http/types.ts
@@ -97,6 +97,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 acaaa0a..9905de1 100644
--- a/src/http/web.ts
+++ b/src/http/web.ts
@@ -15,8 +15,9 @@ import { peerOf, trustedProxyClient } 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 { answerProbe } from './health';
+import { currentRoutes } from './router';
/**
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
@@ -236,7 +237,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);
@@ -286,7 +287,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..a6b8765
--- /dev/null
+++ b/test/mesh/membership.test.ts
@@ -0,0 +1,438 @@
+/**
+ * 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 { WebSocketServer } from 'ws';
+import { encode, decode, MESH_PROTOCOL_VERSION, type RouteEntry } from '../../src/mesh/protocol';
+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 = {}, extra: { health?: boolean } = {}): Teacup {
+ const warnings: string[] = [];
+ const events: EventPayload[] = [];
+ const waiting = new Map void>>();
+ const app = createApp({
+ modules: [TeacupModule],
+ experimental: true,
+ ...extra,
+ 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();
+ });
+}
+
+/**
+ * A teapot speaking the wire protocol directly, so its manifest can carry what a real teapot's own
+ * boot refuses — an older or foreign peer advertising a reserved path. Every RPC answers `answer`.
+ */
+async function rawTeapotOn(
+ port: number,
+ routes: RouteEntry[],
+ answer: unknown,
+): Promise<{ close: () => Promise }> {
+ const wss = new WebSocketServer({ port, host: '127.0.0.1' });
+ wss.on('connection', (ws) => {
+ ws.on('message', (data) => {
+ const frame = decode(data.toString());
+ if (frame.type === 'hello') ws.send(encode({ type: 'manifest', v: MESH_PROTOCOL_VERSION, steps: [], routes }));
+ else if (frame.type === 'ping') ws.send(encode({ type: 'pong' }));
+ else if (frame.type === 'rpc-req')
+ ws.send(
+ encode({
+ type: 'rpc-res',
+ id: frame.id,
+ ok: true,
+ result: { status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify(answer) },
+ }),
+ );
+ });
+ });
+ await new Promise((resolve) => wss.on('listening', resolve));
+
+ return {
+ close: () =>
+ new Promise((done) => {
+ for (const client of wss.clients) client.terminate();
+ wss.close(() => done());
+ }),
+ };
+}
+
+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([]);
+ });
+ it('a late teapot advertising /__mesh__/control has that route refused; its other routes are served', async () => {
+ const port = await freePort();
+ const cup = teacup([port]);
+ expect((await get(cup.app, '/api/fake/ok')).status).toBe(404);
+
+ const routed = cup.next('mesh:routes');
+ const raw = await rawTeapotOn(
+ port,
+ [
+ { method: 'GET', pattern: '/__mesh__/control' },
+ { method: 'GET', pattern: '/api/fake/ok' },
+ ],
+ { from: 'raw teapot' },
+ );
+
+ try {
+ expect(await routed).toMatchObject({ added: ['GET /api/fake/ok'], removed: [] });
+ expect(await (await get(cup.app, '/api/fake/ok')).json()).toEqual({ from: 'raw teapot' });
+ expect(await (await get(cup.app, '/__mesh__/control')).text()).not.toContain('raw teapot');
+ expect(
+ cup.warnings.some((w) => w.includes('not serving a route from') && w.includes("'GET /__mesh__/control'")),
+ ).toBe(true);
+ } finally {
+ await cup.app.close();
+ open.splice(open.indexOf(cup.app), 1);
+ await raw.close();
+ }
+ });
+
+ it('with health on, a late teapot advertising /__ready__ has that route refused; its other routes are served', async () => {
+ const port = await freePort();
+ const cup = teacup([port], {}, { health: true });
+ expect((await get(cup.app, '/api/fake/ok')).status).toBe(404);
+
+ const routed = cup.next('mesh:routes');
+ const raw = await rawTeapotOn(
+ port,
+ [
+ { method: 'GET', pattern: '/__ready__' },
+ { method: 'GET', pattern: '/api/fake/ok' },
+ ],
+ { from: 'raw teapot' },
+ );
+
+ try {
+ expect(await routed).toMatchObject({ added: ['GET /api/fake/ok'], removed: [] });
+ expect((await get(cup.app, '/api/fake/ok')).status).toBe(200);
+ expect(await (await get(cup.app, '/__ready__')).text()).not.toContain('raw teapot');
+ expect(cup.warnings.some((w) => w.includes('not serving a route from') && w.includes("'GET /__ready__'"))).toBe(
+ true,
+ );
+ } finally {
+ await cup.app.close();
+ open.splice(open.indexOf(cup.app), 1);
+ await raw.close();
+ }
+ });
+});
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([]);
});
});
diff --git a/test/router-parity/README.md b/test/router-parity/README.md
index 281394b..bbb591b 100644
--- a/test/router-parity/README.md
+++ b/test/router-parity/README.md
@@ -31,7 +31,7 @@ Nothing can regenerate the baseline by accident:
| `frozen/matcher-*.json` | Captured matcher outputs: declaration ID, decoded params, `implicitHead`, ordered `Allow`, or the normalization error. The generated file also stores the seed, the generator rules and every generated input. |
| `frozen/app-*.json` | Status, headers, `Allow` and body through `app.fetch` and through a Node socket, including HEAD body suppression. |
| `frozen/ws-*.json` | WS upgrade selection through `app.upgrade` and the Node listener, plus HTTP requests at the WS paths. |
-| `frozen/owner-*.json` | Owner additions needing a running app: cross-pattern `Allow` through both adapters, and the mesh HTTP route table across a peer's lifetime (it is built once at boot and never changes — see `owner.test.ts`). |
+| `frozen/owner-*.json` | Owner additions needing a running app: cross-pattern `Allow` through both adapters, and the mesh HTTP route table across a peer's lifetime (built once at boot at the pinned revision; since CARD-19 it follows teapot membership — see `owner.test.ts`). |
| `frozen/boot-*.json` | Boot-time rejections: pattern compilation, local ambiguity, mesh splicing. |
| `frozen/golden-*.json` | `graph()`, `explain()`, `openapi({ title: 'Parity', version: '1' })`, and a mesh teacup before and after `ready()`. |
diff --git a/test/router-parity/frozen/owner-mesh-lifetime.json b/test/router-parity/frozen/owner-mesh-lifetime.json
index 5eecf90..16e3d37 100644
--- a/test/router-parity/frozen/owner-mesh-lifetime.json
+++ b/test/router-parity/frozen/owner-mesh-lifetime.json
@@ -101,17 +101,17 @@
"phase": "B2 teapot up after boot",
"method": "GET",
"path": "/api/remote/ping",
- "status": 404,
+ "status": 200,
"allow": null,
- "body": "{\"error\":\"Not Found\"}"
+ "body": "{\"from\":\"teapot\"}"
},
{
"phase": "B2 teapot up after boot",
"method": "POST",
"path": "/api/remote/ping",
- "status": 404,
- "allow": null,
- "body": "{\"error\":\"Not Found\"}"
+ "status": 405,
+ "allow": "GET, HEAD, OPTIONS",
+ "body": "{\"error\":\"Method Not Allowed\"}"
},
{
"phase": "B2 teapot up after boot",
diff --git a/test/router-parity/owner.test.ts b/test/router-parity/owner.test.ts
index a2d04a0..d48dd73 100644
--- a/test/router-parity/owner.test.ts
+++ b/test/router-parity/owner.test.ts
@@ -88,15 +88,30 @@ const teacupFor = (port: number) =>
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
bootTimeoutMs: 300,
timeoutMs: 500,
- reconnect: false,
+ // Reconnect on (CARD-19, D15): a dropped teapot is "reconnecting" and keeps its routes (A2),
+ // and one absent at boot is retried in the background (B). Captured at ed47836 with
+ // `reconnect: false`, when neither depended on it. Fast backoff keeps the test short.
+ reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
},
});
+/** Resolves on the teacup's next `mesh:routes` event: its remote table changed. */
+const routesChanged = (app: App) =>
+ new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('no mesh:routes within 5s')), 5000);
+ const off = app.bus.on('mesh:routes', () => {
+ clearTimeout(timer);
+ off();
+ resolve();
+ });
+ });
+
/**
* Two lifetimes. A: the teapot is up at boot, then goes away. B: the teapot is absent at boot and
- * comes up afterwards. The current code builds the HTTP table once, at boot, and never changes it:
- * routes spliced at boot stay in the table after their peer leaves, and a peer that arrives late
- * is never spliced in. CARD-10 can reuse this to assert the index is not rebuilt per request.
+ * comes up afterwards. At ed47836 the HTTP table was built once, at boot, and never changed, so B2
+ * answered 404. Since CARD-19 (D15, owner approval) the remote routes follow membership: a teapot
+ * that is reconnecting keeps its routes and answers 503 (A2), and a late one is spliced in when it
+ * connects (B2). CARD-10 can reuse this to assert the index is not rebuilt per request.
*/
async function meshLifetimes() {
const results = [];
@@ -118,7 +133,9 @@ async function meshLifetimes() {
const teapotB = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
try {
results.push(...(await probe(teacupB, 'B1 teapot absent at boot')));
+ const spliced = routesChanged(teacupB);
await teapotB.listen(portB);
+ await spliced;
results.push(...(await probe(teacupB, 'B2 teapot up after boot')));
} finally {
await teacupB.close();