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
+327
-118
@@ -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<Link, 'close'>;
|
||||
|
||||
/** 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<void> => {
|
||||
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<string, ServedRemote[]>();
|
||||
|
||||
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<Link> {
|
||||
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<typeof setTimeout> | 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<void> => {
|
||||
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<string, { url: string; pattern: string }>(); // "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<void>,
|
||||
devRoutes: () => RouteDef[],
|
||||
getRemoteRoutes: () => RouteDef[],
|
||||
getRoutes: () => RouteDef[],
|
||||
): (request: Request) => Promise<Response> {
|
||||
let handler: ((request: Request) => Promise<Response>) | 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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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[];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+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,
|
||||
|
||||
+135
-47
@@ -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<typeof setTimeout> | 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<string, PendingEntry>, reason: string): void {
|
||||
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string, headers?: Record<string, string>): 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<string, string>,
|
||||
): Promise<unknown> {
|
||||
// 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<string> {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<string> {
|
||||
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<string, string> | 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<Link> {
|
||||
const timeoutMs = args.timeoutMs ?? 30_000;
|
||||
const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS;
|
||||
const bounds = backoffBounds(args.reconnect);
|
||||
const pending = new Map<string, PendingEntry>();
|
||||
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<string, string> | 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);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user