3 Commits
Author SHA1 Message Date
chrnx 29f6406c96 feat(http): response compression with gzip and br (CARD-16, #112)
CI / runtimes (bun) (pull_request) Successful in 18s
CI / build (pull_request) Successful in 28s
CI / runtimes (deno) (pull_request) Successful in 23s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 5s
Text responses went out uncompressed unless a proxy sat in front of every
runtime. createApp({ compression: true | { threshold, encodings } }), off
by default, implements D13 strategy B as accepted on 2026-10-22.

- One function, compressOutcome, runs after handle() and before either
  adapter writes, so Node and the fetch runtimes cannot diverge.
- Accept-Encoding negotiation with q-values, identity, * and q=0; ties go
  to server preference (br before gzip). Vary: Accept-Encoding is merged
  wherever the request decided the outcome, including every 304. Skips:
  existing Content-Encoding or Content-Range, no or an incompressible
  Content-Type (ndjson is compressible), Cache-Control: no-transform.
  HEAD and bodies under threshold keep Vary; 204 gets none.
- Node, Deno, Bun: node:zlib only, loaded lazily through nodeRequire.
  Buffered bodies use the async API, never the sync one; br at quality 4.
  Content-Length is dropped from an encoded body.
- Streams (SSE, ndjson): a zlib stream flushed after every frame, error
  frame and ping, piped into res on Node and wrapped around the
  ReadableStream on fetch runtimes. Backpressure follows the compressor;
  a client leaving destroys it.
- Edge: core never encodes and sets Vary only. Edge is recognised by
  edgeHandler, which marks the app through an internal symbol, and by
  createApp detecting workerd (navigator.userAgent, or node:zlib failing
  to load), which covers a bare app.fetch export.
- ETags from CARD-15 are taken on the identity body and stay weak, so the
  tag does not change with the coding.

Deno runs zlib's async API on the main thread; that is documented and
pinned by a test, not worked around.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:03:30 -05:00
chrnx ea19ee21b7 feat(http): ETag and 304 for static files and buffered responses (CARD-15, #114)
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 4s
Conditional GETs were never answered: every revalidation re-downloaded
the file or response.

- Static (D12, always on): a hit carries W/"<size>-<mtimeMs base36>",
  Last-Modified and Cache-Control from the stat the resolver already did.
  A matching If-None-Match, or If-Modified-Since when If-None-Match is
  absent, answers 304 before the file is read. StaticHit now carries the
  stat and a read() for the bytes, and HEAD no longer reads either.
- static: { dir?, cacheControl? } (rule 1a): Cache-Control defaults to
  no-cache so browsers revalidate rather than reuse a file for a lifetime
  guessed from Last-Modified. An unknown key or CR/LF throws at boot.
- createApp({ etag: true }) (off by default, boolean only): a buffered 200
  to GET/HEAD gets a weak tag from a 32-bit FNV-1a hash of its UTF-8 bytes
  plus its length, computed before HEAD blanks the body. A handler-set
  etag is kept and only compared. Weak comparison, lists split outside
  quotes, and * are supported.
- Every buffered 304 leaves dispatch bodiless, with its content-* headers
  dropped, so NotModified matches the ETag path on every adapter.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:01:07 -05:00
chrnx 88945b0b1f feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
Reading a cookie meant parsing the Cookie header by hand, and a response
could not carry more than one Set-Cookie: response header values were
Record<string, string>, and the fetch adapters would have stringified an
array into one broken "a,b" cookie anyway.

- @cookie('name') / @cookies() sit next to @header/@headers as a new
  'cookies' arg source. The header is parsed on first use per request and
  cached on the context, so a route without a cookie argument never parses
  it. RFC 6265: first value wins, %-sequences decoded, malformed pairs
  skipped (never a 400), undecodable values kept raw. Several cookie lines
  are joined with "; ". The map has no prototype. @needs('cookies') reads
  the same map, and 'cookies' joins the seed-key allow-list.
- setCookie(name, value, options) serialises one Set-Cookie value with
  HttpOnly, SameSite=Lax, Path=/ and Secure by default (D10), and throws,
  naming the field, on anything that could inject a header or that browsers
  reject (sameSite none / partitioned without secure).
- Response header values widen to string | string[] (D11) across
  TransformerFn, ErrorResponse, HttpError(Like).headers, ResponseShape and
  the neutral outcome. Node writes a set-cookie array as one line per
  element and joins every other array with ", " before writeHead; the
  fetch adapters build a Headers and append each set-cookie element.
  mergeInjectedHeaders keeps arrays by reference and joins a vary array
  before merging it.
- OpenAPI maps a cookie argument to an in: cookie parameter.

BREAKING CHANGE: code that reads a header value from TransformerFn,
ErrorResponse, HttpError or ResponseShape as a string must handle string[].

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:00:43 -05:00
21 changed files with 191 additions and 1506 deletions

No files matched your search

-35
View File
@@ -198,33 +198,6 @@ 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 `?` 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. 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 ### Fixed
- **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler` - **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler`
@@ -234,14 +207,6 @@ npm treats versions as semver and semver forbids leading zeros.
Without `trustProxy` it is ignored. Only `edgeHandler` reads it: the Node, Deno and Bun adapters, and a Without `trustProxy` it is ignored. Only `edgeHandler` reads it: the Node, Deno and Bun adapters, and a
bare `app.fetch`, ignore it as before. bare `app.fetch`, ignore it as before.
- **Mesh (alpha): `HEAD` on a remote `GET` route now works** (#125). The teacup resolved `HEAD` to
the remote `GET` and `OPTIONS` advertised `HEAD`, but the request went to the teapot as `HEAD`,
which has no `HEAD` plan, so it answered `404`. The teacup now forwards it as a `GET` and drops
the body, so it answers like a local route: the `GET`'s status and headers, no body, and a
`404`/`500` from the route keeps its status. An explicit remote `HEAD` route still takes
precedence. The teapot is unchanged, so a new teacup works against an older teapot during a
rolling deploy.
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard - **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts` compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
was served. Containment now compares real paths: the requested file, and a directory's was served. Containment now compares real paths: the requested file, and a directory's
+114 -327
View File
@@ -45,7 +45,7 @@ import { buildOpenApi, type OpenApiInfo } from '../openapi';
import { connectLink, isPermanentRefusal, type Link } from '../mesh/link'; import { connectLink, isPermanentRefusal, type Link } from '../mesh/link';
import { Rooms } from '../rooms'; import { Rooms } from '../rooms';
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import { buildRemote, type RemoteRoute as TeacupRemoteRoute } from '../mesh/teacup'; import { buildRemote } from '../mesh/teacup';
import { buildManifest, createMeshControl, MESH_CONTROL_DISABLED_REASON, MESH_CONTROL_PATH } from '../mesh/teapot'; import { buildManifest, createMeshControl, MESH_CONTROL_DISABLED_REASON, MESH_CONTROL_PATH } from '../mesh/teapot';
import type { MeshControl } from '../http'; import type { MeshControl } from '../http';
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
@@ -60,9 +60,6 @@ export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from '
type Runner = (ctx: any) => any; 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. */ /** Mutable graph state assembled from modules/plugins and later spliced with remote mesh scopes. */
interface Registry { interface Registry {
providerNodes: GraphNode[]; providerNodes: GraphNode[];
@@ -308,7 +305,8 @@ export function createApp(opts: {
let orderedProviders: GraphNode[] = []; let orderedProviders: GraphNode[] = [];
let orderedSteps: GraphNode[] = []; let orderedSteps: GraphNode[] = [];
let booted = false; let booted = false;
const meshLinks: Closable[] = []; let remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = [];
const finalize = (missingNote?: string): void => { const finalize = (missingNote?: string): void => {
({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote)); ({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote));
@@ -327,7 +325,8 @@ export function createApp(opts: {
// can only be built here, after finalize(), and never at construction time. // can only be built here, after finalize(), and never at construction time.
const prepareGraph = async (): Promise<void> => { const prepareGraph = async (): Promise<void> => {
if (opts.mesh && !booted) { if (opts.mesh && !booted) {
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, reserved, publishRemote); const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, reserved);
remoteRoutes = spliced.remoteRoutes;
meshLinks.push(...spliced.meshLinks); meshLinks.push(...spliced.meshLinks);
// Without this the error is `missing dependency: auth needed by getUser` and says nothing // 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. // about the teapot that was away — which is the actual cause every time it is the cause.
@@ -373,11 +372,6 @@ export function createApp(opts: {
return routes; 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 // 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). // several never double-boots (which would re-run provider factories and their side effects).
const bootGraph = makeAppBooter( const bootGraph = makeAppBooter(
@@ -410,7 +404,14 @@ export function createApp(opts: {
health: healthProbe, health: healthProbe,
etag: opts.etag, etag: opts.etag,
}; };
const fetchFn = buildAppFetch(fetchOpts, bootApp, currentTable); const fetchFn = buildAppFetch(
routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError, logger },
fetchOpts,
bootApp,
devRoutes,
() => remoteRoutes,
);
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, { const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, {
limits: opts.limits, limits: opts.limits,
trustProxy: opts.trustProxy, trustProxy: opts.trustProxy,
@@ -423,10 +424,10 @@ export function createApp(opts: {
// and builds the mesh control channel — so Node and Deno/Bun serve an identical graph // and builds the mesh control channel — so Node and Deno/Bun serve an identical graph
await bootApp(); await bootApp();
const httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()];
const wsRoutes = buildWsRoutes(routePlans, deps); const wsRoutes = buildWsRoutes(routePlans, deps);
// A getter, not an array: mesh membership can change the table after this server starts. server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, {
server = createHttpServer(currentTable, wsRoutes, bus, meshControl, {
compression, compression,
bus, bus,
logger, logger,
@@ -1111,295 +1112,41 @@ function assertNoRemoteSiblingConflict(accepted: RemoteRoute[], route: RemoteRou
} }
} }
/** A teapot route the remote table serves: its export, its owner, and the def the router files. */ /** Connects the configured teapots, splices their remote steps into the registry, and returns their routes. */
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( async function spliceRemoteScopes(
mesh: MeshConfig, mesh: MeshConfig,
bus: Bus, bus: Bus,
registry: Registry, registry: Registry,
logger: Logger, logger: Logger,
reserved: readonly ReservedPath[], reserved: readonly ReservedPath[],
publish: (routes: RouteDef[]) => void, ): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[]; absent: string[] }> {
): Promise<{ meshLinks: Closable[]; absent: string[] }> { const remoteRoutes: RouteDef[] = [];
const meshLinks: Closable[] = []; const meshLinks: Link[] = [];
const absent: string[] = []; // urls of teapots that never connected within the boot budget const absent: string[] = []; // urls of teapots that never connected within the boot budget
const teapots = mesh.teapots ?? []; const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner
const table = createRemoteTable( const remoteAccepted: RemoteRoute[] = []; // every remote route spliced so far, in teapot order
teapots.map((teapot) => teapot.url),
registry,
logger,
reserved,
publish,
);
const ctx: MembershipContext = { mesh, bus, logger, table };
try { try {
for (const teapot of teapots) { for (const teapot of mesh.teapots ?? []) {
warnIfCleartext(teapot.url, logger); warnIfCleartext(teapot.url, logger);
const holder: { link?: Link } = {}; const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () =>
const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () => connectTeapot(ctx, teapot, holder)); connectLink({
url: teapot.url,
secret: teapot.secret,
timeoutMs: mesh.timeoutMs,
heartbeatMs: mesh.heartbeatMs,
reconnect: mesh.reconnect,
onManifestChange: mesh.onManifestChange,
logger,
bus,
}),
);
if (!link) { if (!link) {
absent.push(teapot.url); absent.push(teapot.url);
const bounds = lateBounds(mesh);
if (bounds) meshLinks.push(retryLateTeapot(ctx, teapot, bounds));
continue; continue;
} }
holder.link = link;
meshLinks.push(link); meshLinks.push(link);
const { steps, routes } = buildRemote(link); const { steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`; const origin = `mesh:${teapot.url}`;
@@ -1409,14 +1156,82 @@ async function spliceRemoteScopes(
registry.setRunner(step.name, step.run); registry.setRunner(step.name, step.run);
} }
table.set(teapot.url, routes, true); 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({
method: req.method,
params: req.params,
query: req.query,
body: req.body,
headers: req.headers,
url: req.url,
correlation: { requestId: req.requestId, traceId: req.traceId },
}),
}),
);
}
} }
} catch (err) { } catch (err) {
closeLinks(meshLinks); closeLinks(meshLinks);
throw err; throw err;
} }
return { meshLinks, absent }; return { remoteRoutes, meshLinks, absent };
} }
/** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */ /** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */
@@ -1641,39 +1456,8 @@ function buildMeshControl(
return createMeshControl({ secret: mesh.secret, manifest, resolveScope, resolveRoute, bus }); 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. */
* The one HTTP route table, shared by app.fetch and listen(): local and dev routes, then remote ones. function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
* 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 { providedSeed, planSteps, bus, onError, logger } = deps;
const local = routePlans const local = routePlans
@@ -1718,7 +1502,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], deps: PipelineDeps): RouteDef[
}, },
})); }));
return local; return [...local, ...remoteRoutes];
} }
/** /**
@@ -1729,9 +1513,12 @@ function buildHttpRoutes(routePlans: RoutePlan[], deps: PipelineDeps): RouteDef[
* costs one flag check per request after the first. * costs one flag check per request after the first.
*/ */
function buildAppFetch( function buildAppFetch(
routePlans: RoutePlan[],
deps: PipelineDeps,
fetchOpts: HttpOptions, fetchOpts: HttpOptions,
ensureBooted: () => Promise<void>, ensureBooted: () => Promise<void>,
getRoutes: () => RouteDef[], devRoutes: () => RouteDef[],
getRemoteRoutes: () => RouteDef[],
): (request: Request) => Promise<Response> { ): (request: Request) => Promise<Response> {
let handler: ((request: Request) => Promise<Response>) | undefined; let handler: ((request: Request) => Promise<Response>) | undefined;
@@ -1750,7 +1537,7 @@ function buildAppFetch(
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
if (!handler) { if (!handler) {
handler = buildFetch(getRoutes, fetchOpts); handler = buildFetch([...buildHttpRoutes(routePlans, getRemoteRoutes(), deps), ...devRoutes()], fetchOpts);
} }
return handler(request); return handler(request);
@@ -1944,7 +1731,7 @@ function runTeardown(teardown: TeardownRegistry, logger: Logger, budgetMs: numbe
function closeApp( function closeApp(
server: http.Server | undefined, server: http.Server | undefined,
meshLinks: Closable[], meshLinks: Link[],
streams: Set<() => void>, streams: Set<() => void>,
options: { timeoutMs?: number }, options: { timeoutMs?: number },
defaultTimeoutMs: number | undefined, defaultTimeoutMs: number | undefined,
@@ -2029,7 +1816,7 @@ function closeApp(
} }
/** Best-effort close of every mesh link, ignoring individual failures. */ /** Best-effort close of every mesh link, ignoring individual failures. */
function closeLinks(links: Closable[]): void { function closeLinks(links: Link[]): void {
for (const link of links) { for (const link of links) {
try { try {
link.close(); link.close();
-14
View File
@@ -144,13 +144,6 @@ export interface MeshConfig {
* `false` restores that fail-once behaviour. An object tunes the backoff, which doubles from * `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 * `initialDelayMs` (500ms) up to `maxDelayMs` (30s) with jitter, so teacups that went down
* together do not come back in lockstep. * 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 }; reconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number };
/** /**
@@ -161,9 +154,6 @@ export interface MeshConfig {
* Serving against a manifest that no longer backs the graph would surface as a 500 that looks * 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 * 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. * 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'; onManifestChange?: 'refuse';
/** /**
@@ -180,10 +170,6 @@ export interface MeshConfig {
* one of its tokens still fails the boot, naming it. A permanent refusal — a wrong secret, a * 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. * 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 * `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 * 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. * starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens.
-9
View File
@@ -45,9 +45,6 @@ export type LifecycleEvent =
// Separate from `mesh:disconnect`, which is a link that was up and went away — this one never // 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. // came up, and a deploy watching for trouble wants to tell those apart.
| 'mesh:boot:retry' | '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' | 'plugin:mounted'
// Paired: see the guarantee above. `request:start` has no status and no duration — it says a // Paired: see the guarantee above. `request:start` has no status and no duration — it says a
// request arrived, not that it routed. // request arrived, not that it routed.
@@ -128,12 +125,6 @@ export interface EventPayload {
* framework does not know what was sent, and will not guess. * framework does not know what was sent, and will not guess.
*/ */
status?: number; 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[];
} }
/** /**
+4 -37
View File
@@ -1,4 +1,4 @@
import type { RouteDef, RouteTable, MatchedRoute } from './types'; import type { RouteDef, MatchedRoute } from './types';
export type CompiledSegment = export type CompiledSegment =
| { kind: 'static'; value: string } | { 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 * 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). * after the index is built recompile nothing and rebuild nothing (FPRD-001 CARD-10).
*/ */
const seamCounts = { compilePattern: 0, indexBuilds: 0, localTreeBuilds: 0 }; const seamCounts = { compilePattern: 0, indexBuilds: 0 };
/** @internal Calls so far to `compilePattern` (cache hits included), route-index builds and local-tree builds. For tests. */ /** @internal Calls so far to `compilePattern` (cache hits included) and route-index builds. For tests. */
export const routerSeamCounts = (): Readonly<typeof seamCounts> => ({ ...seamCounts }); export const routerSeamCounts = (): Readonly<typeof seamCounts> => ({ ...seamCounts });
/** Compiles and validates one route pattern. Results are cached by source string. */ /** Compiles and validates one route pattern. Results are cached by source string. */
@@ -417,11 +417,6 @@ interface RouteIndex {
/** The routes a mesh teacup spliced in from its teapots. Identity-keyed, so a route is remote wherever it travels. */ /** 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>(); 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. */ /** 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 { export function markRemoteRoute<T extends RouteDef>(def: T): T {
remoteRouteDefs.add(def); remoteRouteDefs.add(def);
@@ -510,34 +505,6 @@ function buildTrees(entries: Array<{ def: RouteDef; order: number }>): Map<strin
return trees; 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 { function routeIndex(routes: RouteDef[]): RouteIndex {
const cached = routeIndexCache.get(routes); const cached = routeIndexCache.get(routes);
if (cached?.size === routes.length) return cached; if (cached?.size === routes.length) return cached;
@@ -549,7 +516,7 @@ function routeIndex(routes: RouteDef[]): RouteIndex {
const index: RouteIndex = { const index: RouteIndex = {
size: routes.length, size: routes.length,
local: localTrees(local), local: buildTrees(local),
remote: remote.length ? buildTrees(remote) : undefined, remote: remote.length ? buildTrees(remote) : undefined,
methods: [...new Set(routes.map((route) => route.method))], methods: [...new Set(routes.map((route) => route.method))],
}; };
+5 -6
View File
@@ -17,15 +17,14 @@ import {
type Preflight, type Preflight,
} from './core'; } from './core';
import type { BodyFailure, BodyReader } from './body'; import type { BodyFailure, BodyReader } from './body';
import type { RouteTable, WsRouteDef, MeshControl, HttpOptions } from './types'; import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
import { currentRoutes } from './router';
import type { Logger } from '../logger'; import type { Logger } from '../logger';
import { nodeRequire } from '../node-require'; import { nodeRequire } from '../node-require';
import { answerProbe } from './health'; import { answerProbe } from './health';
import { compressOutcome } from './compression'; import { compressOutcome } from './compression';
interface HandlerConfig { interface HandlerConfig {
routes: RouteTable; routes: RouteDef[];
bus?: Bus; bus?: Bus;
opts?: HttpOptions; opts?: HttpOptions;
trustProxy: boolean; trustProxy: boolean;
@@ -38,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. * Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
* @param routes HTTP route definitions, or a getter read once per request (a mesh teacup's table changes as peers come and go). * @param routes HTTP route definitions.
* @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency). * @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency).
* @param bus Optional event bus for stream lifecycle events. * @param bus Optional event bus for stream lifecycle events.
* @param meshControl Optional mesh gateway hook for a reserved upgrade path. * @param meshControl Optional mesh gateway hook for a reserved upgrade path.
* @param opts Limits, TLS, security, CORS, and body-parsing options. * @param opts Limits, TLS, security, CORS, and body-parsing options.
*/ */
export function createHttpServer( export function createHttpServer(
routes: RouteTable, routes: RouteDef[],
wsRoutes: WsRouteDef[] = [], wsRoutes: WsRouteDef[] = [],
bus?: Bus, bus?: Bus,
meshControl?: MeshControl, meshControl?: MeshControl,
@@ -163,7 +162,7 @@ function createRequestHandler(cfg: HandlerConfig) {
} }
result = await handle( result = await handle(
currentRoutes(routes), // once per request, see buildFetch routes,
opts, opts,
{ {
...correlation, ...correlation,
-7
View File
@@ -102,13 +102,6 @@ export interface RouteDef {
maxParts?: number; // per-route override of the server's multipart maxParts 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. */ /** Result of matching a request path against a route: extracted params plus the matched definition. */
export interface MatchedRoute { export interface MatchedRoute {
params: Record<string, string>; params: Record<string, string>;
+3 -6
View File
@@ -15,9 +15,8 @@ import { peerOf, trustedProxyClient } from './peer';
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body'; import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers'; import { renderError, type ErrorRequest } from '../transformers';
import type { RouteTable, HttpOptions } from './types'; import type { RouteDef, HttpOptions } from './types';
import { answerProbe } from './health'; import { answerProbe } from './health';
import { currentRoutes } from './router';
import { compressOutcome, compressWebStream } from './compression'; import { compressOutcome, compressWebStream } from './compression';
import type { NeutralOutcome } from './core'; import type { NeutralOutcome } from './core';
@@ -238,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 * 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`. * that knows how to get bytes out of a `Request` and how to put them into a `Response`.
*/ */
export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) { export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
// Built once per server, not once per request — see `BodyReader`. // Built once per server, not once per request — see `BodyReader`.
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts); const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests); const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
@@ -290,9 +289,7 @@ export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) {
acquired = gate.limited; acquired = gate.limited;
result = await handle( result = await handle(
// Read once per request: a mesh teacup swaps its table when peers come and go, and one routes,
// request must route and build `Allow` against the same table (CARD-19).
currentRoutes(routes),
opts, opts,
{ {
...correlation, ...correlation,
+47 -135
View File
@@ -2,6 +2,7 @@ import type { Bus } from '../bus';
import type { Logger } from '../logger'; import type { Logger } from '../logger';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
import { connectSocket, type SocketCtor } from '../http/ws-adapter'; import { connectSocket, type SocketCtor } from '../http/ws-adapter';
import { compilePattern } from '../http/router';
import type { WsSocket } from '../http/ws-core'; import type { WsSocket } from '../http/ws-core';
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol'; import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol';
@@ -63,8 +64,6 @@ interface LinkState {
socket: WsSocket | undefined; socket: WsSocket | undefined;
closed: boolean; closed: boolean;
retry: ReturnType<typeof setTimeout> | undefined; 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. */ /** One established connection: its socket, the manifest it announced, and its heartbeat. */
@@ -82,10 +81,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 * 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. * 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, headers?: Record<string, string>): void { function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): void {
for (const [, entry] of pending) { for (const [, entry] of pending) {
clearTimeout(entry.timer); clearTimeout(entry.timer);
entry.reject(new HttpError(503, reason, undefined, headers)); entry.reject(new HttpError(503, reason));
} }
pending.clear(); pending.clear();
@@ -100,14 +99,13 @@ function sendRpc(
name: string, name: string,
ctx: RequestEnvelope, ctx: RequestEnvelope,
timeoutMs: number, timeoutMs: number,
downHeaders?: Record<string, string>,
): Promise<unknown> { ): Promise<unknown> {
// Answer now rather than in timeoutMs. A closed socket cannot deliver the frame, so waiting // 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) // 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 // 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. // window a reconnecting link sits in: down, and answering immediately.
if (!socket?.isOpen) { if (!socket?.isOpen) {
return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`, undefined, downHeaders)); return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`));
} }
return new Promise((resolveCall, rejectCall) => { return new Promise((resolveCall, rejectCall) => {
@@ -331,109 +329,37 @@ function stepKeys(manifest: Manifest): Set<string> {
} }
/** /**
* The steps the boot manifest had that a returning one does not. * 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 graph was validated at boot against the first manifest and is already serving. A step token * The graph was validated at boot against the first manifest and is already serving. A token that
* that vanished cannot be validated away after the fact, so a manifest missing one is refused * vanished cannot be validated away after the fact, so a manifest missing anything this link
* rather than accepted — see `ManifestPolicy`. Extra steps are ignored: the graph is fixed at boot * contributed is refused rather than accepted — see `ManifestPolicy`. Extra exports are *not*
* and nothing new is spliced into it. * missing and 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[] { export function missingFromManifest(booted: Manifest, returned: Manifest): string[] {
const steps = stepKeys(returned); const steps = stepKeys(returned);
const routes = routeKeys(returned);
const missing: string[] = []; const missing: string[] = [];
for (const step of booted.steps) { for (const step of booted.steps) {
if (!steps.has(step)) missing.push(`step '${step}'`); if (!steps.has(step)) missing.push(`step '${step}'`);
} }
return missing; for (const route of booted.routes) {
} if (!routes.has(`${route.method} ${compilePattern(route.pattern).shape}`)) {
missing.push(`route '${route.method} ${route.pattern}'`);
/** }
* `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 fingerprint; return missing;
}
/** 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. */ /** Resolved backoff bounds, or `undefined` when the caller turned reconnection off. */
@@ -468,36 +394,19 @@ export function connectLink(args: {
/** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */ /** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */
onManifestChange?: ManifestPolicy; onManifestChange?: ManifestPolicy;
logger?: Logger; 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> { }): Promise<Link> {
const timeoutMs = args.timeoutMs ?? 30_000; const timeoutMs = args.timeoutMs ?? 30_000;
const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS; const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS;
const bounds = backoffBounds(args.reconnect); const bounds = backoffBounds(args.reconnect);
const pending = new Map<string, PendingEntry>(); const pending = new Map<string, PendingEntry>();
const state: LinkState = { socket: undefined, closed: false, retry: undefined, retryAt: undefined }; const state: LinkState = { socket: undefined, closed: false, retry: undefined };
let refusalLogged = ''; 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 = { const link: Link = {
// replaced with the real manifest before this object escapes. A reconnect keeps the boot // replaced with the real manifest before this object escapes; a reconnect never changes it,
// manifest's steps, because the graph is fixed at boot, and takes the returning one's routes. // because the graph is fixed at boot and only the *boot* manifest describes what it holds.
manifest: { steps: [], routes: [] }, manifest: { steps: [], routes: [] },
rpc: (kind, name, ctx) => rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs),
sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs, downHeaders()),
close: () => { close: () => {
// Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after // Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after
// the application hung up would leave a process that cannot exit. // the application hung up would leave a process that cannot exit.
@@ -529,8 +438,6 @@ export function connectLink(args: {
// the teapot the moment it returns. // the teapot the moment it returns.
const delay = Math.round(capped / 2 + Math.random() * (capped / 2)); 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 = setTimeout(() => void attemptReconnect(attempt + 1), delay);
state.retry.unref?.(); state.retry.unref?.();
}; };
@@ -539,12 +446,8 @@ export function connectLink(args: {
const endSession = (attempt: number): void => { const endSession = (attempt: number): void => {
state.socket = undefined; state.socket = undefined;
args.bus?.emit('mesh:disconnect', { name: args.url }); args.bus?.emit('mesh:disconnect', { name: args.url });
// Scheduled before the rejection, so the 503s carry the real wait in `retry-after`. rejectAllPending(pending, `mesh link to ${args.url} is down`);
scheduleRetry(attempt); 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. */ /** Adopt an established session, or refuse it when its manifest no longer backs the graph. */
@@ -552,16 +455,27 @@ export function connectLink(args: {
const missing = missingFromManifest(link.manifest, session.manifest); const missing = missingFromManifest(link.manifest, session.manifest);
if (missing.length > 0) { if (missing.length > 0) {
refusalLogged = refuseSession(session, missing, refusalLogged, args.url, args.logger); 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.',
);
}
return false; return false;
} }
refusalLogged = ''; refusalLogged = '';
state.socket = session.socket; state.socket = session.socket;
const returning = adopted;
adopted = true;
args.bus?.emit('mesh:connect', { name: args.url }); args.bus?.emit('mesh:connect', { name: args.url });
reconnected(returning, link, session.manifest, args.onReconnect);
return true; return true;
}; };
@@ -578,12 +492,10 @@ export function connectLink(args: {
} }
if (!adopt(session)) scheduleRetry(attempt); if (!adopt(session)) scheduleRetry(attempt);
} catch (error) { } catch {
// A permanent refusal ends the link. Otherwise: openSession's own abort listener already // openSession's own abort listener already scheduled the retry through `onEnd`; a rejection
// scheduled the retry through `onEnd`; a rejection that never opened a socket (a bad URL, // that never opened a socket (a bad URL, DNS) needs one scheduled here instead.
// DNS) needs one scheduled here instead. if (!state.socket && !state.retry) scheduleRetry(attempt);
if (!refusedWhileReconnecting(args.url, error, args.logger, giveUp) && !state.socket && !state.retry)
scheduleRetry(attempt);
} }
}; };
-88
View File
@@ -99,91 +99,3 @@ test('mesh on Bun: a teacup reconnects to a teapot that came back', async () =>
await teapot.stop(); 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<typeof createApp>, 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<ReturnType<typeof startPingTeapot>> | 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();
}
});
-36
View File
@@ -112,39 +112,3 @@ test('mesh on Bun: a remote step colliding with a local token fails the splice',
tServer.stop(true); tServer.stop(true);
} }
}); });
// CARD-20 (#125, D16): HEAD on a remote GET answers like HEAD on a local one.
@Route('/remote')
class RemoteHeadCtl {
@Get('/x', { export: true })
x() {
return { a: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [RemoteHeadCtl] })
class RemoteHeadTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class EmptyTeacupModule {}
test('mesh on Bun: HEAD on a remote GET answers 200 with the GET headers and no body', async () => {
const teapot = createApp({ modules: [RemoteHeadTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await serveBun(teapot, { port: 0 });
const teacup = createApp({
modules: [EmptyTeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }], reconnect: false },
});
const cServer = await serveBun(teacup, { port: 0 });
try {
const res = await fetch(`http://127.0.0.1:${cServer.port}/api/remote/x`, { method: 'HEAD' });
expect(res.status).toBe(200);
expect(res.headers.get('content-type') ?? '').toContain('application/json');
expect(await res.text()).toBe('');
} finally {
await teacup.close();
cServer.stop(true);
tServer.stop(true);
}
});
-93
View File
@@ -99,96 +99,3 @@ Deno.test('mesh on Deno: a teacup reconnects to a teapot that came back', async
await teapot.stop(); 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<typeof createApp>, 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<ReturnType<typeof startPingTeapot>> | 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();
}
});
-36
View File
@@ -142,39 +142,3 @@ Deno.test('mesh on Deno: a remote step colliding with a local token fails the sp
await t.server.shutdown(); await t.server.shutdown();
} }
}); });
// CARD-20 (#125, D16): HEAD on a remote GET answers like HEAD on a local one.
@Route('/remote')
class RemoteHeadCtl {
@Get('/x', { export: true })
x() {
return { a: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [RemoteHeadCtl] })
class RemoteHeadTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class EmptyTeacupModule {}
Deno.test('mesh on Deno: HEAD on a remote GET answers 200 with the GET headers and no body', async () => {
const teapot = createApp({ modules: [RemoteHeadTeapotModule], experimental: true, mesh: { secret: SECRET } });
const t = await serve(teapot);
const teacup = createApp({
modules: [EmptyTeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(t.port), secret: SECRET }], reconnect: false },
});
const c = await serve(teacup);
try {
const res = await fetch(`http://127.0.0.1:${c.port}/api/remote/x`, { method: 'HEAD' });
assertEquals(res.status, 200);
assertStringIncludes(res.headers.get('content-type') ?? '', 'application/json');
assertEquals(await res.text(), '');
} finally {
await teacup.close();
await c.server.shutdown();
await t.server.shutdown();
}
});
-50
View File
@@ -311,53 +311,3 @@ describe('mesh: Set-Cookie arrays (CARD-14, T10)', () => {
} }
}); });
}); });
describe('mesh: compression of remote routes (CARD-16)', () => {
it('a remote buffered response is compressed by the teacup like a local one', async () => {
const { gunzipSync } = await import('node:zlib');
const http = await import('node:http');
const payload = { rows: Array.from({ length: 200 }, (_, i) => ({ i, name: `row ${i}` })) };
@Route('/big')
class BigCtl {
@Get('/json', { export: true })
json() {
return payload;
}
}
@Module({ mountpoint: '/api', controllers: [BigCtl] })
class BigTeapotModule {}
const teapot = createApp({ modules: [BigTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`;
const teacup = createApp({
modules: [PlainTeacupModule],
experimental: true,
compression: true,
mesh: { teapots: [{ url, secret: SECRET }] },
});
const cServer = await teacup.listen(0);
try {
const raw = await new Promise<{ headers: Record<string, unknown>; bytes: Buffer }>((resolve, reject) => {
http
.get(
{ port: (cServer.address() as any).port, path: '/api/big/json', headers: { 'accept-encoding': 'gzip' } },
(res) => {
const chunks: Buffer[] = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => resolve({ headers: res.headers, bytes: Buffer.concat(chunks) }));
},
)
.on('error', reject);
});
expect(raw.headers['content-encoding']).toBe('gzip');
expect(String(raw.headers.vary)).toMatch(/Accept-Encoding/);
expect(JSON.parse(gunzipSync(raw.bytes).toString())).toEqual(payload);
} finally {
tServer.close();
cServer.close();
}
});
});
-438
View File
@@ -1,438 +0,0 @@
/**
* 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<number> {
const server = net.createServer();
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address() as AddressInfo;
await new Promise<void>((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<App> {
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<void> {
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<EventPayload>;
}
function teacup(ports: number[], mesh: Partial<MeshConfig> = {}, extra: { health?: boolean } = {}): Teacup {
const warnings: string[] = [];
const events: EventPayload[] = [];
const waiting = new Map<string, Array<(e: EventPayload) => 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<EventPayload>((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<void> }> {
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<void>((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();
}
});
});
+3 -5
View File
@@ -143,7 +143,7 @@ describe('missingFromManifest', () => {
expect(missingFromManifest(booted, booted)).toEqual([]); expect(missingFromManifest(booted, booted)).toEqual([]);
}); });
it('accepts extra exports — extra steps are ignored, since the graph is fixed at boot', () => { it('accepts extra exports — the graph is fixed at boot and nothing new is spliced', () => {
const wider: Manifest = { const wider: Manifest = {
steps: [...booted.steps, 'billing'], steps: [...booted.steps, 'billing'],
routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }], routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }],
@@ -161,10 +161,8 @@ describe('missingFromManifest', () => {
expect(missingFromManifest(booted, shrunk)).toEqual(["step 'auth'"]); expect(missingFromManifest(booted, shrunk)).toEqual(["step 'auth'"]);
}); });
// D15 (CARD-19): routes are not part of the graph, so a returning teapot's routes replace the old it('reports a missing route by method and pattern', () => {
// 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: [] }; const routeless: Manifest = { steps: booted.steps, routes: [] };
expect(missingFromManifest(booted, routeless)).toEqual([]); expect(missingFromManifest(booted, routeless)).toEqual(["route 'GET /svc/:id'"]);
}); });
}); });
-152
View File
@@ -1,152 +0,0 @@
/**
* CARD-20 (#125, D16): `HEAD` on a remote buffered `GET` behaves like `HEAD` on a local one.
*
* The teacup resolves `HEAD` to the remote `GET` (implicit HEAD) and forwards it to the teapot as a
* `GET`, then drops the body. The teapot is unchanged, so an older teapot works too.
*/
import 'reflect-metadata';
import http from 'http';
import type { AddressInfo } from 'net';
import { describe, it, expect, afterEach } from 'vitest';
import { createApp, Route, Get, Head, Module, NotFound, ctx } from '../../src/index';
import type { App } from '../../src/app/types';
import type { Logger } from '../../src/logger';
const SECRET = 'head-secret';
const quiet: Logger = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} };
const seen: string[] = [];
@Route('/')
class RemoteCtl {
@Get('/x', { export: true }) x(@ctx() c: { req: { method: string } }) {
seen.push(`x ${c.req.method}`);
return { a: 1 };
}
@Get('/missing', { export: true }) missing() {
seen.push('missing');
throw new NotFound();
}
@Get('/boom', { export: true }) boom() {
seen.push('boom');
throw new Error('kaboom');
}
@Get('/both', { export: true }) bothGet() {
seen.push('both GET');
return { via: 'get' };
}
@Head('/both', { export: true }) bothHead(@ctx() c: { req: { method: string } }) {
seen.push(`both HEAD as ${c.req.method}`);
return { via: 'head' };
}
}
@Module({ mountpoint: '/api', controllers: [RemoteCtl] })
class TeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class TeacupModule {}
const open: App[] = [];
afterEach(async () => {
while (open.length) await open.pop()!.close();
seen.length = 0;
});
async function mesh(): Promise<{ teacup: App; port: number }> {
const teapot = createApp({ modules: [TeapotModule], experimental: true, logger: quiet, mesh: { secret: SECRET } });
open.push(teapot);
const tPort = ((await teapot.listen(0)).address() as AddressInfo).port;
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
logger: quiet,
mesh: { teapots: [{ url: `ws://127.0.0.1:${tPort}/__mesh__/control`, secret: SECRET }], reconnect: false },
});
open.unshift(teacup); // closed first
const port = ((await teacup.listen(0)).address() as AddressInfo).port;
return { teacup, port };
}
function nodeRequest(port: number, method: string, path: string) {
return new Promise<{ status: number; headers: http.IncomingHttpHeaders; body: string }>((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port, method, path, agent: false }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => (body += chunk));
res.on('end', () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body }));
});
req.on('error', reject);
req.end();
});
}
const fetchVia = (app: App, method: string, path: string) =>
app.fetch(new Request(`http://mesh.test${path}`, { method }));
describe('mesh: HEAD on a remote GET route (CARD-20, D16)', () => {
it('T1: HEAD via app.fetch answers 200 with the GET headers and no body', async () => {
const { teacup } = await mesh();
const get = await fetchVia(teacup, 'GET', '/api/x');
const head = await fetchVia(teacup, 'HEAD', '/api/x');
expect(head.status).toBe(200);
expect(head.headers.get('content-type')).toBe(get.headers.get('content-type'));
expect(head.headers.get('content-type')).toContain('application/json');
expect(await head.text()).toBe('');
expect(await get.json()).toEqual({ a: 1 });
});
it('T2: HEAD via the Node listener answers 200 with the GET headers and no body', async () => {
const { port } = await mesh();
const get = await nodeRequest(port, 'GET', '/api/x');
const head = await nodeRequest(port, 'HEAD', '/api/x');
expect(head.status).toBe(200);
expect(head.headers['content-type']).toBe(get.headers['content-type']);
expect(head.body).toBe('');
});
it('OPTIONS still advertises GET, HEAD, OPTIONS', async () => {
const { teacup, port } = await mesh();
expect((await fetchVia(teacup, 'OPTIONS', '/api/x')).headers.get('allow')).toBe('GET, HEAD, OPTIONS');
expect((await nodeRequest(port, 'OPTIONS', '/api/x')).headers.allow).toBe('GET, HEAD, OPTIONS');
});
it('T3: an explicit remote HEAD route keeps precedence over the implicit fallback', async () => {
const { teacup, port } = await mesh();
const viaFetch = await fetchVia(teacup, 'HEAD', '/api/both');
expect(viaFetch.status).toBe(200);
expect(await viaFetch.text()).toBe('');
const viaNode = await nodeRequest(port, 'HEAD', '/api/both');
expect(viaNode.status).toBe(200);
expect(viaNode.body).toBe('');
// The explicit HEAD handler ran, reached as HEAD — the GET handler never did.
expect(seen).toEqual(['both HEAD as HEAD', 'both HEAD as HEAD']);
});
it('T4: a remote GET that throws NotFound answers HEAD with 404 and no body', async () => {
const { teacup, port } = await mesh();
const viaFetch = await fetchVia(teacup, 'HEAD', '/api/missing');
expect(viaFetch.status).toBe(404);
expect(await viaFetch.text()).toBe('');
const viaNode = await nodeRequest(port, 'HEAD', '/api/missing');
expect(viaNode.status).toBe(404);
expect(viaNode.body).toBe('');
// The teapot handler ran: the 404 is the route's, not a missing HEAD plan on the teapot.
expect(seen).toEqual(['missing', 'missing']);
});
it('a remote GET that fails answers HEAD with 500 and no body', async () => {
const { teacup, port } = await mesh();
const viaFetch = await fetchVia(teacup, 'HEAD', '/api/boom');
expect(viaFetch.status).toBe(500);
expect(await viaFetch.text()).toBe('');
const viaNode = await nodeRequest(port, 'HEAD', '/api/boom');
expect(viaNode.status).toBe(500);
expect(viaNode.body).toBe('');
});
it('T5: one HEAD calls the teapot handler once, as a GET', async () => {
const { teacup } = await mesh();
await fetchVia(teacup, 'HEAD', '/api/x');
expect(seen).toEqual(['x GET']);
});
});
+1 -1
View File
@@ -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/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/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/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 (built once at boot at the pinned revision; since CARD-19 it follows teapot membership — 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 (it is built once at boot and never changes — see `owner.test.ts`). |
| `frozen/boot-*.json` | Boot-time rejections: pattern compilation, local ambiguity, mesh splicing. | | `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()`. | | `frozen/golden-*.json` | `graph()`, `explain()`, `openapi({ title: 'Parity', version: '1' })`, and a mesh teacup before and after `ready()`. |
@@ -206,7 +206,7 @@
"adapter": "fetch", "adapter": "fetch",
"method": "HEAD", "method": "HEAD",
"path": "/api/x", "path": "/api/x",
"status": 200, "status": 404,
"headers": { "headers": {
"content-type": "application/json", "content-type": "application/json",
"referrer-policy": "no-referrer", "referrer-policy": "no-referrer",
@@ -472,7 +472,7 @@
"adapter": "node", "adapter": "node",
"method": "HEAD", "method": "HEAD",
"path": "/api/x", "path": "/api/x",
"status": 200, "status": 404,
"headers": { "headers": {
"content-type": "application/json", "content-type": "application/json",
"referrer-policy": "no-referrer", "referrer-policy": "no-referrer",
@@ -101,17 +101,17 @@
"phase": "B2 teapot up after boot", "phase": "B2 teapot up after boot",
"method": "GET", "method": "GET",
"path": "/api/remote/ping", "path": "/api/remote/ping",
"status": 200, "status": 404,
"allow": null, "allow": null,
"body": "{\"from\":\"teapot\"}" "body": "{\"error\":\"Not Found\"}"
}, },
{ {
"phase": "B2 teapot up after boot", "phase": "B2 teapot up after boot",
"method": "POST", "method": "POST",
"path": "/api/remote/ping", "path": "/api/remote/ping",
"status": 405, "status": 404,
"allow": "GET, HEAD, OPTIONS", "allow": null,
"body": "{\"error\":\"Method Not Allowed\"}" "body": "{\"error\":\"Not Found\"}"
}, },
{ {
"phase": "B2 teapot up after boot", "phase": "B2 teapot up after boot",
+7 -24
View File
@@ -88,30 +88,15 @@ const teacupFor = (port: number) =>
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }], teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
bootTimeoutMs: 300, bootTimeoutMs: 300,
timeoutMs: 500, timeoutMs: 500,
// Reconnect on (CARD-19, D15): a dropped teapot is "reconnecting" and keeps its routes (A2), reconnect: false,
// 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<void>((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 * Two lifetimes. A: the teapot is up at boot, then goes away. B: the teapot is absent at boot and
* comes up afterwards. At ed47836 the HTTP table was built once, at boot, and never changed, so B2 * comes up afterwards. The current code builds the HTTP table once, at boot, and never changes it:
* answered 404. Since CARD-19 (D15, owner approval) the remote routes follow membership: a teapot * routes spliced at boot stay in the table after their peer leaves, and a peer that arrives late
* that is reconnecting keeps its routes and answers 503 (A2), and a late one is spliced in when it * is never spliced in. CARD-10 can reuse this to assert the index is not rebuilt per request.
* connects (B2). CARD-10 can reuse this to assert the index is not rebuilt per request.
*/ */
async function meshLifetimes() { async function meshLifetimes() {
const results = []; const results = [];
@@ -133,9 +118,7 @@ async function meshLifetimes() {
const teapotB = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const teapotB = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
try { try {
results.push(...(await probe(teacupB, 'B1 teapot absent at boot'))); results.push(...(await probe(teacupB, 'B1 teapot absent at boot')));
const spliced = routesChanged(teacupB);
await teapotB.listen(portB); await teapotB.listen(portB);
await spliced;
results.push(...(await probe(teacupB, 'B2 teapot up after boot'))); results.push(...(await probe(teacupB, 'B2 teapot up after boot')));
} finally { } finally {
await teacupB.close(); await teacupB.close();
@@ -158,9 +141,9 @@ class RemoteMixCtl {
return { from: 'teapot', route: 'POST /api/v/:id' }; return { from: 'teapot', route: 'POST /api/v/:id' };
} }
// Remote only: remote routes are `buffer`, so the teacup's router resolves HEAD to it implicitly. // Remote only: remote routes are `buffer`, so the teacup's router resolves HEAD to it implicitly.
// Captured at ed47836 as HEAD → 404 (the teacup forwarded HEAD, and the teapot has no HEAD plan). // Captured as observed at ed47836: the teacup forwards the request as HEAD, the teapot looks its
// CARD-20 (#125, D16) changed that deliberately, with owner approval: the teacup forwards the // plan up by (pattern, method) and has none for HEAD, so HEAD answers 404 while OPTIONS still
// HEAD as a GET and drops the body, so HEAD now answers 200 like a local route. // advertises HEAD. That is the mesh proxy's behaviour, not the matcher's; CARD-07 must keep it.
@Get('/x', { export: true }) x() { @Get('/x', { export: true }) x() {
return { from: 'teapot', route: 'GET /api/x' }; return { from: 'teapot', route: 'GET /api/x' };
} }