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 }.
- The reserved-path check from CARD-21/CARD-17 (#141, #145) runs in
the table for every remote route: at boot a route on /__mesh__/control
(or /__live__ and /__ready__ with health on) fails boot as before. A
late or returning one is refused and logged, and the teapot's other
routes are served.
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 late reserved-path routes, and T1/T2 on
Deno and Bun.
The frozen owner-mesh-lifetime.json capture changes in the next commit.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
13 files changed
+1192
-180
No files matched your search
+37
-4
@@ -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<typeof seamCounts> => ({ ...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<RouteDef>();
|
||||
|
||||
/** 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<T extends RouteDef>(def: T): T {
|
||||
remoteRouteDefs.add(def);
|
||||
@@ -505,6 +510,34 @@ function buildTrees(entries: Array<{ def: RouteDef; order: number }>): Map<strin
|
||||
return trees;
|
||||
}
|
||||
|
||||
/**
|
||||
* The last local trees built, and the `(def, position)` entries they were built from.
|
||||
*
|
||||
* When mesh membership changes, the app publishes a new array whose local entries are the same
|
||||
* objects at the same positions, with only the remote tail different (CARD-19, D15). Reusing the
|
||||
* local trees then means a peer coming or going rebuilds the remote trees alone. Keyed by the
|
||||
* first local def, so it is collected with the table that owns it.
|
||||
*/
|
||||
const localTreeCache = new WeakMap<
|
||||
RouteDef,
|
||||
{ entries: Array<{ def: RouteDef; order: number }>; trees: Map<string, MethodTree> }
|
||||
>();
|
||||
|
||||
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<string, MethodTree> {
|
||||
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))],
|
||||
};
|
||||
|
||||
+6
-5
@@ -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,
|
||||
|
||||
@@ -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<string, string>;
|
||||
|
||||
+6
-3
@@ -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<string, string>, 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,
|
||||
|
||||
Reference in new issue
Block a user