From 419ba092d4bd619e4246938fa5227c9cb9557c97 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 15:58:14 -0500 Subject: [PATCH 01/18] docs(plans): a mesh that exports steps, not providers Plan for dropping @Provider export from the mesh: the manifest carries step names, an unreachable teapot stops blocking the boot, and the app-scope binding that cached a remote value for the process lifetime goes away. Signed-off-by: Diego Resendez --- docs/plans/2026-09-06-mesh-steps-only-plan.md | 710 ++++++++++++++++++ 1 file changed, 710 insertions(+) create mode 100644 docs/plans/2026-09-06-mesh-steps-only-plan.md diff --git a/docs/plans/2026-09-06-mesh-steps-only-plan.md b/docs/plans/2026-09-06-mesh-steps-only-plan.md new file mode 100644 index 0000000..10b98ee --- /dev/null +++ b/docs/plans/2026-09-06-mesh-steps-only-plan.md @@ -0,0 +1,710 @@ +# A mesh that exports steps, not providers + +> **For agentic workers:** REQUIRED SUB-SKILL: use `superpowers:subagent-driven-development` or +> `superpowers:executing-plans` to work through this task by task. Steps use `- [ ]` for tracking. + +**Status:** planned, 2026-09-06 +**Scope:** `src/mesh/protocol.ts`, `src/mesh/teapot.ts`, `src/mesh/teacup.ts`, `src/app/index.ts`, +mesh tests on all runtimes, `README.md`, `CHANGELOG.md` +**Mesh stays alpha.** It remains behind `experimental: true`, and the wire changes without a +protocol bump because of it. + +**Goal:** A teapot exports **steps and routes only**. Exporting a `@Provider` becomes a boot error, +and a teapot that is unreachable at boot no longer stops the teacup from starting. + +## The problem + +`@Provider` is a factory whose value *is* the object — `db`, a client, a pool. That object cannot +cross a wire, and the mesh already knows it: `untransportable` (`src/mesh/protocol.ts:145`) refuses +any class instance, so an exported provider can only ever return plain data. What survives is the +worst half of the idea — `src/app/index.ts:854` registers the remote provider as an **app-scope** +binding, so the teacup resolves it once at boot and answers from that snapshot for the life of the +process. It is a cache the teapot no longer stands behind, wearing the word "provider". + +A step is the shape that actually works across the mesh. It runs per request, the teacup sends the +envelope, the teapot resolves its own graph and sends back the result, and the teacup binds it to +the token. Transparent to the caller, and nothing is held. + +Two things follow from that, and they are the whole of this plan: + +1. **Exporting a provider is not a feature to fix, it is a thing to forbid.** The alternative + already exists and is spelled `@Step({ export: true })`. +2. **The boot no longer needs to block on a teapot.** Blocking existed because an app-scope value + has to be resolved *at boot* — there is no later. A step has nothing but later. A teapot that is + away costs a `503` on the requests that need it, and the app starts. + +## Decisions + +**D1 — `export: true` on a `@Provider` is a boot error, not a silent no-op.** Turning it into a +warning would leave a running app whose token resolves locally and looks exported. The error names +the replacement, so the message is a fix and not a complaint. + +**D2 — No protocol bump.** Removing `ScopeEntry.scope` is a field removal, which the rule in +`src/mesh/protocol.ts:11` would normally make a bump. Mesh is alpha and behind `experimental: true`, +both peers ship from this repo, and a bump would spend the number on a version nobody deployed. +`MESH_PROTOCOL_VERSION` stays `1`. + +**D3 — Keep `connectUntilDeadline`; delete only its `throw`.** *This corrects what was said in the +design conversation.* The retry loop is not the boot blocker — the `throw` at the end of it is. The +loop is the co-deploy grace: a teacup that starts two seconds ahead of its teapot waits, gets the +manifest, and has its steps for the process lifetime. Delete the loop and that teacup instead boots +into a graph with no `authorization` node, which is strictly worse than today. So the budget stays; +exhausting it now warns and contributes nothing, instead of failing the boot. + +**D4 — A permanent refusal still fails the boot.** `isPermanentRefusal` covers a wrong secret and a +protocol mismatch. Those are configuration errors — the same class as a typo in a token name — and +they will be the same errors in thirty seconds. Failing at boot with the reason beats a `503` at +3am that says nothing about a secret. Only *unreachable* becomes non-fatal. + +**D5 — A missing token still fails the boot, through the ordinary validator.** If a teapot is away +and a local step declares `needs: ['authorization']`, `topoSort` throws +`missing dependency: authorization needed by …` (`src/graph.ts:54`). That is not a mesh step to +remove: it is what catches a typo, and tolerating it would let a misspelled token boot clean and +`503` forever. The message gains the teapots that did not connect, so the cause is on the screen. + +**D6 — The `expects` / degrade plan survives; its D6 does not.** +`docs/plans/2026-08-18-mesh-degrade-plan.md` is still the right answer for "this teapot may +legitimately be absent", and it is already steps-only. But its D6 reuses +`invalidateRemoteBindings`, which this plan deletes. That seam was app-scope-specific; a degraded +step swaps a runner, not a container binding. Note it there rather than leave a dangling reference. + +## File structure + +| File | Change | +| --- | --- | +| `src/mesh/protocol.ts` | `Manifest` → `{ steps: string[]; routes: RouteEntry[] }`; drop `ScopeEntry`; update the `manifest` frame and its `SHAPE` row | +| `src/mesh/teapot.ts` | `buildManifest({ steps, routes })` | +| `src/mesh/teacup.ts` | `buildRemote` → `{ steps, routes }` | +| `src/graph.ts` | `topoSort` takes an optional note appended to the missing-dependency error | +| `src/app/index.ts` | forbid provider export; drop the remote-provider loop, `rebind`, `invalidateRemoteBindings`, `exportedProviders`; `connectUntilDeadline` exhaustion becomes non-fatal | +| tests | `test/mesh/*`, `test/deno/mesh*`, `test/bun/mesh*`, `test/interop/_node-peer.ts`, `test/edge/_worker.mjs` | +| docs | `README.md` mesh section, `CHANGELOG.md`, the degrade plan's D6 | + +## A note on the line numbers + +Every `file:line` below is accurate as of `85b6c70` and drifts as tasks land. Locate code by symbol — +`collectProviders`, `spliceRemoteScopes`, `connectUntilDeadline`, `buildMeshControl`, `finalizeGraph` +— and treat the numbers as hints. + +--- + +## Task 1: Forbid exporting a provider + +The prohibition lands first and alone, because every later task assumes it. Nothing on the wire +changes yet. + +**Files** +- Modify: `src/app/index.ts:440` (`collectProviders`) +- Test: `test/mesh/failure.test.ts` + +- [ ] **Step 1: Write the failing test** + +```ts +// test/mesh/failure.test.ts +import { describe, it, expect } from 'vitest'; +import { createApp, Provider, Module } from '../../src/index'; + +describe('provider export', () => { + it('refuses to boot when a provider is exported over the mesh', async () => { + @Provider({ provides: 'db', needs: [], export: true } as any) + class Db { + provide() { + return { db: { query: () => [] } }; + } + } + @Module({ mountpoint: '/api', providers: [Db] }) + class AppModule {} + + expect(() => createApp({ modules: [AppModule], mesh: { secret: 's' } })).toThrow( + /provider 'db' cannot be exported/i, + ); + }); +}); +``` + +- [ ] **Step 2: Run it and watch it fail** + +```bash +npx vitest run test/mesh/failure.test.ts -t 'refuses to boot' +``` + +Expected: FAIL — no error is thrown, the app builds. + +- [ ] **Step 3: Throw in `collectProviders`** + +Replace `src/app/index.ts:440`: + +```ts + if (meta.export) registry.exportedProviders.push(meta.provides); +``` + +with: + +```ts + // A provider's value IS the object it builds — a pool, a client, a `db`. That cannot cross a + // wire, and the half of it that could (plain data) arrived as an app-scope binding the teacup + // resolved once and cached for the life of the process. A step is the shape that travels: + // it runs per request, on the teapot, and only its result comes back. + if (meta.export) + throw new Error( + `mesh: provider '${meta.provides}' cannot be exported — a provider is a factory whose value ` + + 'is the object itself, and the mesh transports data, not objects. ' + + 'Export a @Step instead, which runs on the teapot per request and returns its result.', + ); +``` + +- [ ] **Step 4: Run it and watch it pass** + +```bash +npx vitest run test/mesh/failure.test.ts -t 'refuses to boot' +``` + +Expected: PASS. + +- [ ] **Step 5: Fix every test that exported a provider** + +```bash +npx vitest run test/mesh/ +``` + +Convert any `@Provider({ ..., export: true })` in a fixture to `@Step({ ..., export: true })`. +Check `test/mesh/integration.test.ts`, `test/mesh/envelope.test.ts`, `test/mesh/transport.test.ts`, +`test/mesh/fetch-boot.test.ts`, `test/interop/_node-peer.ts`, `test/edge/_worker.mjs`. + +- [ ] **Step 6: Commit** + +```bash +git add src/app/index.ts test/ +git commit -m "feat(mesh)!: refuse to export a provider + +A provider's value is the object it builds, which cannot cross a JSON wire. +What did cross became an app-scope binding the teacup resolved once at boot +and served from a cache the teapot no longer stood behind. A step is the +shape that travels; the error says so." +``` + +--- + +## Task 2: A manifest of steps and routes + +**Files** +- Modify: `src/mesh/protocol.ts` (`ScopeEntry`, `Manifest`, `Frame`, `SHAPE.manifest`) +- Modify: `src/mesh/teapot.ts` (`buildManifest`, and wherever the manifest frame is sent) +- Modify: `src/mesh/teacup.ts` (`buildRemote`) +- Modify: `src/mesh/link.ts` (manifest handling and the refuse-policy comparison) +- Test: `test/mesh/protocol.test.ts`, `test/mesh/teapot.test.ts`, `test/mesh/teacup.test.ts` + +**Interfaces** +- Produces: `interface Manifest { steps: string[]; routes: RouteEntry[] }` +- Produces: `buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest` +- Produces: `buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] }` +- Gone: `ScopeEntry`, and the `scopes` field of the `manifest` frame + +- [ ] **Step 1: Write the failing tests** + +```ts +// test/mesh/protocol.test.ts +it('encodes a manifest of step names', () => { + const frame = decode(encode({ type: 'manifest', v: 1, steps: ['auth'], routes: [] })); + expect(frame).toEqual({ type: 'manifest', v: 1, steps: ['auth'], routes: [] }); +}); + +it('rejects a manifest whose steps are not an array', () => { + expect(() => decode(JSON.stringify({ type: 'manifest', v: 1, steps: 'auth', routes: [] }))).toThrow( + /steps and routes must be arrays/, + ); +}); +``` + +```ts +// test/mesh/teapot.test.ts +it('builds a manifest from step tokens and routes', () => { + expect(buildManifest({ steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] })).toEqual({ + steps: ['auth'], + routes: [{ method: 'GET', pattern: '/u/:id' }], + }); +}); +``` + +```ts +// test/mesh/teacup.test.ts +it('turns every manifest step into a lazy remote node', async () => { + const link = { manifest: { steps: ['auth'], routes: [] }, rpc: async () => ({ ok: true }) } as any; + const { steps, routes } = buildRemote(link); + + expect(routes).toEqual([]); + expect(steps.map((s: any) => s.name)).toEqual(['auth']); + expect(await steps[0].run({})).toEqual({ auth: { ok: true } }); +}); +``` + +- [ ] **Step 2: Run them and watch them fail** + +```bash +npx vitest run test/mesh/protocol.test.ts test/mesh/teapot.test.ts test/mesh/teacup.test.ts +``` + +Expected: FAIL — `steps` is not a field, `buildManifest` still wants `providers`. + +- [ ] **Step 3: Change the protocol** + +In `src/mesh/protocol.ts`, delete `ScopeEntry` (`:45-49`) and replace the `Manifest` interface: + +```ts +/** + * A mesh server's advertised steps and routes. + * + * Steps only: a provider's value is the object it builds, which cannot cross a JSON wire, so + * exporting one is refused at boot (`collectProviders`). Every entry here is request-scope and + * lazy — the token exists in the teacup's graph, and running it is an RPC. + */ +export interface Manifest { + steps: string[]; + routes: RouteEntry[]; +} +``` + +In the `Frame` union, replace the `manifest` member: + +```ts + | { type: 'manifest'; v: number; steps: string[]; routes: RouteEntry[] } +``` + +And its `SHAPE` row: + +```ts + manifest: (frame, bad) => { + if (!isNumber(frame.v)) bad('missing protocol version'); + if (!Array.isArray(frame.steps) || !Array.isArray(frame.routes)) bad('steps and routes must be arrays'); + }, +``` + +Leave `MESH_PROTOCOL_VERSION` at `1` (D2). Leave `untransportable` alone — a step result can still +carry a `Date` or a `Map`. + +- [ ] **Step 4: Change `buildManifest`** + +In `src/mesh/teapot.ts`, replace the function at `:43-56`: + +```ts +/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */ +export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest { + return { steps: [...args.steps], routes: args.routes }; +} +``` + +Then follow the type errors: wherever the teapot sends the `manifest` frame it now sends +`steps: manifest.steps` in place of `scopes: manifest.scopes`. + +The only other caller is `buildMeshControl` (`src/app/index.ts:1088`). Update it here, not in Task 3 +— a task must leave the tree typechecking, and splitting a signature from its only call site across +two commits leaves a broken commit in history: + +```ts + const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes }); +``` + +`exportedProviders` is still destructured on the line above; leave it, Task 3 removes the field. + +- [ ] **Step 5: Change `buildRemote`** + +In `src/mesh/teacup.ts`, replace the scope loop (`:44-54`): + +```ts +/** Turn a link's manifest into local proxy nodes: lazy request-scope steps, and routes. */ +export function buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] } { + const steps: RemoteScopeNode[] = link.manifest.steps.map((token) => ({ + name: token, + run: async (ctx: any) => ({ [token]: await link.rpc('scope', token, envelopeFrom(ctx)) }), + })); + + const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({ + method: route.method, + pattern: route.pattern, + handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape, + })); + + return { steps, routes }; +} +``` + +The RPC `kind` stays `'scope'` — renaming it to `'step'` is a wire change with no benefit, and +`resolveScope` on the teapot side resolves both the same way. + +- [ ] **Step 6: Update the refuse policy in `link.ts`** + +Find the manifest comparison used by `onManifestChange: 'refuse'` and drop the lifetime half of it: +a returned manifest must still contain every step token the link contributed at boot, and every +route by method plus effective shape. There is no `scope` field left to compare (D6 of the reconnect +plan). + +- [ ] **Step 7: Typecheck, then run the mesh suite** + +```bash +npm run typecheck && npx vitest run test/mesh/ +``` + +Expected: PASS both. A typecheck failure here means a `manifest` frame send or the `buildMeshControl` +call site was missed. + +- [ ] **Step 8: Commit** + +```bash +git add src/mesh/ test/mesh/ +git commit -m "refactor(mesh)!: a manifest carries step names, not scoped tokens + +Every exported token is request-scope now, so the lifetime field had one +value and told a reader nothing. No protocol bump: mesh is alpha, both +peers ship from this repo, and the number should mean incompatibility +between deployed versions." +``` + +--- + +## Task 3: The teacup stops splicing providers + +**Files** +- Modify: `src/app/index.ts:62,427` (`Registry.exportedProviders`) +- Modify: `src/app/index.ts:808` (delete `invalidateRemoteBindings`) +- Modify: `src/app/index.ts:813-856` (`spliceRemoteScopes`) +- Modify: `src/app/index.ts:1078-1088` (`buildMeshControl`) +- Test: `test/mesh/integration.test.ts` + +- [ ] **Step 1: Write the failing test** + +This file's teapot fixture opens with `@Provider({ provides: 'config', export: true })` +(`test/mesh/integration.test.ts:6`), and `LocalCtl` declares `@needs('config')`. Task 1 already made +that fixture fail at boot, so converting it is not optional — and converting it is the regression +guard, because a step re-runs where the provider was cached: + +```ts +// test/mesh/integration.test.ts — replaces the @Provider fixture at :6 +let configCalls = 0; +@Step({ provides: 'config', needs: [], export: true }) +class Config { + run() { + configCalls += 1; + return { config: { region: 'mx', call: configCalls } }; + } +} +``` + +and add, alongside the existing `/local/who` assertion: + +```ts +it('re-runs the RPC on every request rather than caching a boot value', async () => { + // same teapot/teacup pair the '/local/who' test stands up + expect((await hit('/api/local/who')).config.call).toBe(1); + expect((await hit('/api/local/who')).config.call).toBe(2); +}); +``` + +- [ ] **Step 2: Run it — it should already pass, and that is the point** + +```bash +npx vitest run test/mesh/integration.test.ts -t 're-runs the RPC' +``` + +Expected: PASS. This is a regression guard, not a red test. The caching bug was only reachable +through provider export, which Task 1 made impossible — once `config` is a step it lands in the +request-scope bucket and already re-runs. The guard exists so that removing the splice in the next +steps cannot quietly reintroduce a cached remote value. Do not manufacture a red state for it. + +- [ ] **Step 3: Delete `exportedProviders`** + +Remove the field from the `Registry` interface (`:62`) and its initializer (`:427`). In +`buildMeshControl` (`:1078-1088`): + +```ts + const { exportedSteps, exportedRoutes, routePlans, runners } = registry; + const hasExports = exportedSteps.length || exportedRoutes.length; + // ... + const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes }); +``` + +- [ ] **Step 4: Delete the remote-provider splice** + +In `spliceRemoteScopes`, delete the `rebind` array (`:829`), the `onReconnect` callback that calls +`invalidateRemoteBindings` (`:838`), and the whole `for (const provider of providers)` block +(`:846-856`). Destructure only what is left: + +```ts + const { steps, routes } = buildRemote(link); +``` + +Then delete `invalidateRemoteBindings` (`:808-810`) and drop the now-unused `container` parameter +from `spliceRemoteScopes` (`:818`) and its call site (`:242`) — `container` was used at `:854` and +nowhere else in the function. + +The reconnect handler no longer needs an `onReconnect`. A remote step holds no state between +requests, so a reconnected link is simply usable again on the next RPC. + +- [ ] **Step 5: Run the full suite and the typechecker** + +```bash +npm run typecheck && npx vitest run test/mesh/ +``` + +Expected: PASS, and no unused-symbol errors. + +- [ ] **Step 6: Commit** + +```bash +git add src/app/index.ts test/mesh/ +git commit -m "refactor(mesh): drop the remote app-scope binding and its rebind seam + +A remote provider was registered app-scope, resolved once, and cached for +the process lifetime; invalidateRemoteBindings existed only to un-cache it +on reconnect. With providers gone from the manifest, both go, and a remote +step needs nothing on reconnect because it holds nothing between requests." +``` + +--- + +## Task 4: An unreachable teapot does not stop the boot + +**Files** +- Modify: `src/app/index.ts:736-776` (`connectUntilDeadline`) +- Modify: `src/app/index.ts:824-843` (the `try` in `spliceRemoteScopes`) +- Modify: `src/graph.ts:54` (the missing-dependency message) +- Test: `test/mesh/boot-retry.test.ts` + +- [ ] **Step 1: Write the failing tests** + +```ts +// test/mesh/boot-retry.test.ts +it('boots when a teapot is unreachable and nothing local needs it', async () => { + const app = createApp({ + modules: [LocalOnlyModule], // declares no needs on a remote token + mesh: { secret: 's', teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], bootTimeoutMs: 300 }, + }); + + await expect(app.ready()).resolves.toBeUndefined(); +}); + +it('still fails the boot when a local step needs a token the absent teapot owned', async () => { + const app = createApp({ + modules: [NeedsAuthModule], // a step with needs: ['auth'] + mesh: { secret: 's', teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], bootTimeoutMs: 300 }, + }); + + await expect(app.ready()).rejects.toThrow(/missing dependency: auth[\s\S]*did not connect/i); +}); + +it('still fails the boot when the teapot refuses the secret', async () => { + // stand up a teapot with secret 'right', connect with 'wrong' + await expect(app.ready()).rejects.toThrow(/refused/i); +}); +``` + +- [ ] **Step 2: Run them and watch the first two fail** + +```bash +npx vitest run test/mesh/boot-retry.test.ts +``` + +Expected: the first fails (boot throws on an unreachable teapot), the second fails on the message +(it says `missing dependency: auth` with no mention of the teapot), the third passes already. + +- [ ] **Step 3: Make budget exhaustion non-fatal** + +In `connectUntilDeadline`, keep the loop, the backoff, the `mesh:boot:retry` event and the +permanent-refusal `throw` (D4). Change the return type to `Promise` and replace +the exhaustion branch: + +```ts + // The budget is a grace for a co-deploy, not a requirement. Every export is a lazy step or a + // proxied route now, so an absent teapot costs a 503 on the requests that need it — and a + // teacup that refuses to start takes down the half of itself that never needed the teapot. + if (remaining <= 0) { + logger.warn( + `mesh: teapot unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` + + `(${(error as Error).message}) — starting without it; its steps and routes will 503`, + ); + return undefined; + } +``` + +In `spliceRemoteScopes`, skip a link that came back `undefined`, and record its url: + +```ts + const link = await connectUntilDeadline(/* … */); + if (!link) { + absent.push(teapot.url); + continue; + } +``` + +Return `absent` alongside `remoteRoutes` and `meshLinks`. + +- [ ] **Step 4: Name the absent teapots in the missing-dependency error** + +`topoSort` (`src/graph.ts:46`) is generic and must stay that way. Give it an optional trailing note +instead of mesh knowledge — note the capital S, and that `seedKeys` stays second: + +```ts +// src/graph.ts:46 +export function topoSort(nodes: GraphNode[], seedKeys: string[], note?: (key: string) => string): GraphNode[] { +``` + +and at the throw (`src/graph.ts:54`): + +```ts + throw new Error(`missing dependency: ${key} needed by ${node.name}${note?.(key) ?? ''}`); +``` + +The only call site is `finalizeGraph` (`src/app/index.ts:660`), so thread the note through its +signature rather than reaching for a module-level variable: + +```ts +// src/app/index.ts:654 — finalizeGraph gains a trailing optional param +function finalizeGraph( + registry: Registry, + logger: Logger, + warnDepth: number | false = DEEP_GRAPH_WARN, + missingNote?: (key: string) => string, +): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } { + const { providerNodes, stepNodes, routePlans } = registry; + const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params'], missingNote); +``` + +`finalize` in `createApp` is the closure that calls it; give it the note built from `absent`: + +```ts + // 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. + const meshNote = absent.length + ? () => ` — these teapots did not connect, so their exports are absent: ${absent.join(', ')}` + : undefined; +``` + +The note is unconditional on the key rather than per-token on purpose: the teacup does not know +which teapot *would* have owned a token it never received a manifest for, and guessing would put a +wrong url in an error. Listing the ones that were away is true and enough. + +- [ ] **Step 5: Run them and watch them pass** + +```bash +npx vitest run test/mesh/boot-retry.test.ts +``` + +Expected: PASS, all three. + +- [ ] **Step 6: Commit** + +```bash +git add src/app/index.ts src/graph.ts test/mesh/boot-retry.test.ts +git commit -m "feat(mesh): an unreachable teapot no longer stops the teacup from booting + +Blocking existed for app-scope exports, which have to resolve at boot +because there is no later. Steps and proxied routes are all later. The +grace budget stays -- a co-deploy still waits -- but exhausting it now +warns instead of throwing. A missing token still fails the boot, and the +error now names the teapots that were away." +``` + +--- + +## Task 5: The other runtimes + +`npm test` does not cover Deno, Bun or the edge, and this change touches `src/mesh/` and +`src/app/index.ts` — exactly the code AGENTS.md says to run them for. + +**Files** +- Modify: `test/deno/mesh.test.ts`, `test/deno/mesh-hardening.test.ts`, `test/deno/mesh-interop.test.ts`, + `test/deno/mesh-reconnect.test.ts`, `test/bun/mesh.test.ts`, `test/bun/mesh-reconnect.test.ts` +- Modify: `test/interop/_node-peer.ts`, `test/edge/_worker.mjs` + +- [ ] **Step 1: Convert every exported provider in the runtime fixtures to a step** + +```bash +grep -rn "export: true" test/deno test/bun test/interop test/edge +``` + +- [ ] **Step 2: Run each runtime suite** + +```bash +npm run test:deno +npm run test:bun +npm run test:edge +``` + +Expected: PASS on all three. The interop peer and the worker both speak the new manifest, so a +mismatch here means one side was missed. + +- [ ] **Step 3: Commit** + +```bash +git add test/ +git commit -m "test(mesh): steps-only exports across Deno, Bun and the edge" +``` + +--- + +## Task 6: Say it in the docs + +**Files** +- Modify: `README.md` (mesh section) +- Modify: `CHANGELOG.md` (`[Unreleased]`) +- Modify: `docs/plans/2026-08-18-mesh-degrade-plan.md` (D6) + +- [ ] **Step 1: README** + +In the mesh section: only `@Step` and routes are exportable; `@Provider` with `export: true` fails +at boot and why; an unreachable teapot no longer blocks the boot, and its steps and routes `503`; +a missing token still fails the boot, and that is deliberate. + +- [ ] **Step 2: CHANGELOG** + +Under `[Unreleased]`, with no date and no version heading — the heading is written the day the tag +ships, never earlier. + +```markdown +### Changed + +- **Mesh (alpha): only steps and routes can be exported.** `@Provider({ export: true })` now fails + at boot. A provider's value is the object it builds, which cannot cross a JSON wire; what did + cross became an app-scope binding the teacup resolved once and cached for the life of the + process. Export a `@Step` instead — it runs on the teapot per request and returns its result. +- **Mesh (alpha): an unreachable teapot no longer stops a teacup from booting.** The + `bootTimeoutMs` grace still waits for a co-deploy; exhausting it now warns and starts without + that teapot, whose steps and routes answer `503`. A local step that *needs* an absent token still + fails the boot, and the error names the teapots that did not connect. +- **Mesh (alpha): the manifest carries step names.** The wire changed without a protocol bump, + which alpha permits and a stable version would not. +``` + +- [ ] **Step 3: Note the broken seam in the degrade plan** + +Add one line under its D6: `invalidateRemoteBindings` no longer exists — a degraded step swaps a +runner, not a container binding. + +- [ ] **Step 4: The full gate** + +```bash +npm run lint && npm run format:check && npm run typecheck && npm test && npm run complexity:check +npm run test:deno && npm run test:bun && npm run test:edge +``` + +- [ ] **Step 5: Commit** + +```bash +git add README.md CHANGELOG.md docs/plans/ +git commit -m "docs(mesh): steps and routes are what a teapot exports" +``` + +--- + +## Size + +Smaller than the reconnect work, and mostly subtraction: roughly 120 lines out, 20 in. No new +subsystem, no new configuration, no background loop. The risk is not in the code but in the wire — +both peers change at once, which alpha allows and which the runtime suites are there to prove. + +## Branch + +From `develop`, per AGENTS.md — `develop` and `main` refuse direct pushes. + +```bash +git fetch origin && git checkout -b feat/mesh-steps-only origin/develop +``` From f6c05a0929da1263c2d6688b6238402d28d1ce91 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 16:06:02 -0500 Subject: [PATCH 02/18] feat(mesh)!: refuse to export a provider A provider's value is the object it builds, which cannot cross a JSON wire. What did cross became an app-scope binding the teacup resolved once at boot and served from a cache the teapot no longer stood behind. A step is the shape that travels; the error says so. Signed-off-by: Diego Resendez --- example/server.ts | 8 +++---- src/app/index.ts | 11 +++++++++- test/interop/_node-peer.ts | 8 +++---- test/mesh/failure.test.ts | 40 +++++++++++++++++++++++++++-------- test/mesh/fetch-boot.test.ts | 14 ++++++------ test/mesh/integration.test.ts | 8 +++---- test/mesh/transport.test.ts | 18 +++++++++------- 7 files changed, 70 insertions(+), 37 deletions(-) diff --git a/example/server.ts b/example/server.ts index ed43747..33c188f 100644 --- a/example/server.ts +++ b/example/server.ts @@ -75,9 +75,9 @@ if (require.main === module) { // ── Mesh Demo (teapot / teacup) ─────────────────────────────────────────── -@Provider({ provides: 'config', export: true }) -class ConfigProvider { - provide() { +@Step({ provides: 'config', needs: [], export: true }) +class ConfigStep { + run() { return { config: { env: 'demo' } }; } } @@ -98,7 +98,7 @@ class PingController { } } -@Module({ mountpoint: '/mesh', providers: [ConfigProvider], steps: [AuthStep], controllers: [PingController] }) +@Module({ mountpoint: '/mesh', steps: [ConfigStep, AuthStep], controllers: [PingController] }) class TeapotModule {} export const teapotApp = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'demo-secret' } }); diff --git a/src/app/index.ts b/src/app/index.ts index 71ae619..ffabc06 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -437,7 +437,16 @@ function collectProviders(providers: Ctor[], origin: string, registry: Registry) const meta = getProviderMeta(ProviderClass)!; registry.providerNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin }); registry.providerMeta.set(meta.provides, { optional: meta.optional }); - if (meta.export) registry.exportedProviders.push(meta.provides); + // A provider's value IS the object it builds — a pool, a client, a `db`. That cannot cross a + // wire, and the half of it that could (plain data) arrived as an app-scope binding the teacup + // resolved once and cached for the life of the process. A step is the shape that travels: + // it runs per request, on the teapot, and only its result comes back. + if (meta.export) + throw new Error( + `mesh: provider '${meta.provides}' cannot be exported — a provider is a factory whose value ` + + 'is the object itself, and the mesh transports data, not objects. ' + + 'Export a @Step instead, which runs on the teapot per request and returns its result.', + ); const instance: any = new ProviderClass(); registry.providerInstances.set(meta.provides, instance); registry.setRunner(meta.provides, (ctx) => instance.provide(ctx)); diff --git a/test/interop/_node-peer.ts b/test/interop/_node-peer.ts index dada500..e22e0b7 100644 --- a/test/interop/_node-peer.ts +++ b/test/interop/_node-peer.ts @@ -10,13 +10,13 @@ // teapot -> exports scopes, prints {"port":N}, serves until killed // teacup -> consumes the remote scopes, prints {"ok":true,"body":{...}} import 'reflect-metadata'; -import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index'; +import { createApp, Step, Route, Get, Module, needs } from '../../src/index'; const SECRET = process.env.MESH_SECRET ?? 's3cr3t'; -@Provider({ provides: 'config', export: true }) +@Step({ provides: 'config', needs: [], export: true }) class Config { - provide() { + run() { return { config: { region: 'mx', runtime: 'node' } }; } } @@ -26,7 +26,7 @@ class Auth { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } } -@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) +@Module({ mountpoint: '/api', steps: [Config, Auth] }) class TeapotModule {} @Route('/local') diff --git a/test/mesh/failure.test.ts b/test/mesh/failure.test.ts index 88c1a75..4333874 100644 --- a/test/mesh/failure.test.ts +++ b/test/mesh/failure.test.ts @@ -3,9 +3,9 @@ import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/ const SECRET = 's3cr3t'; -@Provider({ provides: 'config', export: true }) +@Step({ provides: 'config', needs: [], export: true }) class Config { - provide() { + run() { return { config: { region: 'mx' } }; } } @@ -22,7 +22,7 @@ class SvcCtl { return { pong: true }; } } -@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [SvcCtl] }) +@Module({ mountpoint: '/api', steps: [Config, Auth], controllers: [SvcCtl] }) class TeapotModule {} @Route('/local') @@ -85,10 +85,13 @@ describe('mesh link failure', () => { await teacup.close(); }); - it('keeps serving an app-scope remote from cache after the link drops', async () => { - // Not a bug, but worth pinning: an app-scope export is resolved once and memoised, so it - // survives its teapot — with a value that can go stale. Reconciling on reconnect is a - // known gap (see the mesh guide), and this test is what would catch it changing by accident. + it('answers 503 on an exported step that used to be a cached app-scope provider', async () => { + // Superseded by "forbid exporting a provider": `config` used to be an app-scope @Provider, + // resolved once and memoised so it kept answering (stale) after the teapot died — a known gap + // the old test pinned on purpose. A provider can no longer be exported at all, so `config` is + // now a @Step like everything else on the wire: request-scope, re-run every time, and gone + // the moment its teapot is. This is the same 503 as the other cases in this file, which is + // the point — there is no more "cached" category left to special-case. @Route('/cached') class CachedCtl { @Get('/cfg') @@ -113,9 +116,28 @@ describe('mesh link failure', () => { await new Promise((r) => setTimeout(r, 50)); const after = await teacup.fetch(new Request('http://x/api/cached/cfg')); - expect(after.status).toBe(200); // cached, so still answering - expect(await after.json()).toEqual({ config: { region: 'mx' } }); + expect(after.status).toBe(503); await teacup.close(); }); }); + +describe('provider export', () => { + it('refuses to boot when a provider is exported over the mesh', async () => { + @Provider({ provides: 'db', needs: [], export: true } as any) + class Db { + provide() { + return { db: { query: () => [] } }; + } + } + @Module({ mountpoint: '/api', providers: [Db] }) + class AppModule {} + + // `experimental: true` so the boot reaches module/provider collection instead of stopping + // at the earlier "mesh is an alpha feature" gate — this check is about the provider's own + // declared metadata (`export: true` on a factory), not about whether mesh is wired up. + expect(() => createApp({ modules: [AppModule], experimental: true, mesh: { secret: 's' } })).toThrow( + /provider 'db' cannot be exported/i, + ); + }); +}); diff --git a/test/mesh/fetch-boot.test.ts b/test/mesh/fetch-boot.test.ts index c75f4c5..d1a7e8a 100644 --- a/test/mesh/fetch-boot.test.ts +++ b/test/mesh/fetch-boot.test.ts @@ -1,14 +1,14 @@ import { describe, it, expect } from 'vitest'; -import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index'; +import { createApp, Step, Route, Get, Module, needs } from '../../src/index'; import { channel } from '../../src/channel'; import { encode, decode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol'; import type { WsSocket, WsRequest } from '../../src/http/ws-core'; const SECRET = 's3cr3t'; -@Provider({ provides: 'config', export: true }) +@Step({ provides: 'config', needs: [], export: true }) class Config { - provide() { + run() { return { config: { region: 'mx' } }; } } @@ -18,7 +18,7 @@ class Auth { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } } -@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) +@Module({ mountpoint: '/api', steps: [Config, Auth] }) class TeapotModule {} @Route('/local') @@ -134,7 +134,7 @@ describe('mesh over app.fetch (no listen)', () => { const chain = teacup.inspect('/api/local/who').map((line) => `${line.kind}:${line.name}`); // the remote provider and step spliced into the local route's chain - expect(chain).toContain('provider:config'); + expect(chain).toContain('step:config'); expect(chain).toContain('step:auth'); expect(teacup.graph().nodes.some((n) => n.name === 'config')).toBe(true); @@ -183,7 +183,7 @@ describe('mesh over app.fetch (no listen)', () => { await teacup.ready(); expect(teacup.graph().nodes.some((n) => n.name === 'config')).toBe(true); - expect(teacup.inspect('/api/local/who').map((l) => `${l.kind}:${l.name}`)).toContain('provider:config'); + expect(teacup.inspect('/api/local/who').map((l) => `${l.kind}:${l.name}`)).toContain('step:config'); expect(teacup.explain('/api/local/who')).toBeTruthy(); await teacup.close(); @@ -276,7 +276,7 @@ describe('mesh control over app.upgrade (no listen)', () => { expect(peer.sent[0]).toMatchObject({ type: 'manifest', v: MESH_PROTOCOL_VERSION, - scopes: expect.arrayContaining([{ token: 'config', scope: 'app' }]), + scopes: expect.arrayContaining([{ token: 'config', scope: 'request' }]), }); await teapot.close(); }); diff --git a/test/mesh/integration.test.ts b/test/mesh/integration.test.ts index cde3020..ae5bd11 100644 --- a/test/mesh/integration.test.ts +++ b/test/mesh/integration.test.ts @@ -1,10 +1,10 @@ import { describe, it, expect, vi } from 'vitest'; -import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index'; +import { createApp, Step, Route, Get, Module, needs } from '../../src/index'; const SECRET = 's3cr3t'; -@Provider({ provides: 'config', export: true }) -class Config { provide() { return { config: { region: 'mx' } }; } } +@Step({ provides: 'config', needs: [], export: true }) +class Config { run() { return { config: { region: 'mx' } }; } } @Step({ provides: 'auth', needs: [], export: true }) class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } } @@ -12,7 +12,7 @@ class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? @Route('/remote') class RemoteCtl { @Get('/ping', { export: true }) ping() { return { pong: true }; } } -@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [RemoteCtl] }) +@Module({ mountpoint: '/api', steps: [Config, Auth], controllers: [RemoteCtl] }) class TeapotModule {} @Route('/local') diff --git a/test/mesh/transport.test.ts b/test/mesh/transport.test.ts index 628a668..8f720c6 100644 --- a/test/mesh/transport.test.ts +++ b/test/mesh/transport.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { createApp, Provider, Route, Get, Module, needs } from '../../src/index'; +import { createApp, Step, Route, Get, Module, needs } from '../../src/index'; import { untransportable } from '../../src/mesh/protocol'; describe('untransportable', () => { @@ -45,13 +45,13 @@ class Pool { } } -@Provider({ provides: 'db', export: true }) +@Step({ provides: 'db', needs: [], export: true }) class Db { - provide() { + run() { return { db: new Pool() }; } } -@Module({ mountpoint: '/api', providers: [Db] }) +@Module({ mountpoint: '/api', steps: [Db] }) class TeapotModule {} @Route('/local') @@ -78,10 +78,12 @@ describe('exporting a handle over the mesh', () => { try { // before this guard: HTTP 200 with `{}` — an object that passes any truthiness check and - // then throws "db.query is not a function" somewhere else entirely - await expect(teacup.fetch(new Request('http://x/api/local/use'))).rejects.toThrow( - /mesh cannot transport 'db'[\s\S]*Pool instance/, - ); + // then throws "db.query is not a function" somewhere else entirely. `db` is now exported by + // a @Step (a @Provider can no longer be exported at all), so the failure happens per request + // and surfaces as an ordinary 500 response rather than a rejected fetch promise. + const res = await teacup.fetch(new Request('http://x/api/local/use')); + expect(res.status).toBe(500); + expect(await res.text()).toMatch(/mesh cannot transport 'db'[\s\S]*Pool instance/); } finally { await teacup.close(); await teapot.close(); From 55890442fe3739e02e57e12647b526404d55f3f0 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 16:14:00 -0500 Subject: [PATCH 03/18] refactor(mesh)!: a manifest carries step names, not scoped tokens Every exported token is request-scope now, so the lifetime field had one value and told a reader nothing. No protocol bump: mesh is alpha, both peers ship from this repo, and the number should mean incompatibility between deployed versions. Signed-off-by: Diego Resendez --- src/app/index.ts | 10 +++++--- src/mesh/link.ts | 16 ++++++------- src/mesh/protocol.ts | 20 ++++++++-------- src/mesh/teacup.ts | 25 +++++++------------- src/mesh/teapot.ts | 20 ++++------------ test/mesh/envelope.test.ts | 4 ++-- test/mesh/fetch-boot.test.ts | 2 +- test/mesh/heartbeat.test.ts | 2 +- test/mesh/link.test.ts | 12 +++++----- test/mesh/protocol.test.ts | 19 +++++++++++---- test/mesh/reconnect.test.ts | 45 +++++++++++++++--------------------- test/mesh/teacup.test.ts | 22 ++++++++++++------ test/mesh/teapot.test.ts | 15 ++++++------ 13 files changed, 104 insertions(+), 108 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index ffabc06..9e64599 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -33,7 +33,7 @@ import { buildOpenApi, type OpenApiInfo } from '../openapi'; import { connectLink, isPermanentRefusal, type Link } from '../mesh/link'; import { Rooms } from '../rooms'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; -import { buildRemote } from '../mesh/teacup'; +import { buildRemote, type RemoteScopeNode } from '../mesh/teacup'; import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot'; import type { MeshControl } from '../http'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; @@ -850,7 +850,11 @@ async function spliceRemoteScopes( }), ); meshLinks.push(link); - const { providers, steps, routes } = buildRemote(link); + // `buildRemote` no longer returns `providers` — every exported token is a step now (Task 1 + // refuses a provider export at boot). Kept as an empty array, not deleted, so the loop below + // still typechecks; Task 3 removes the loop itself along with the rest of provider-splicing. + const providers: RemoteScopeNode[] = []; + const { steps, routes } = buildRemote(link); const origin = `mesh:${teapot.url}`; for (const provider of providers) { @@ -1094,7 +1098,7 @@ function buildMeshControl( if (!mesh?.secret || !hasExports) return undefined; const { container, orderedProviders, orderedSteps } = deps; const { bus, providedSeed, planSteps, onError, logger } = deps.deps; - const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes }); + const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes }); const resolveScope = async (name: string, env: RequestEnvelope): Promise => { // context is intentionally `any`: providers and steps merge arbitrary keys into it diff --git a/src/mesh/link.ts b/src/mesh/link.ts index 5bc2f62..a53bcf5 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -218,7 +218,7 @@ function settleManifest(frame: Extract, hs: Handsha // `mesh:connect` is emitted by the caller, not here: a reconnect whose manifest no longer backs // the graph is refused after this point, and announcing a connection we are about to hang up on // would tell an operator the opposite of what happened. - hs.resolve({ socket: hs.socket, manifest: { scopes: frame.scopes, routes: frame.routes }, heartbeat }); + hs.resolve({ socket: hs.socket, manifest: { steps: frame.steps, routes: frame.routes }, heartbeat }); } /** Consume the session's inbound frames until it closes, settling the handshake then each RPC. */ @@ -323,9 +323,9 @@ function openSession(args: SessionArgs): Promise { }); } -/** A scope token and its lifetime, flattened to the string the refusal check compares. */ -function scopeKeys(manifest: Manifest): Set { - return new Set(manifest.scopes.map((scope) => `${scope.scope}:${scope.token}`)); +/** A manifest's step tokens, flattened to the set the refusal check compares. */ +function stepKeys(manifest: Manifest): Set { + return new Set(manifest.steps); } /** @@ -345,12 +345,12 @@ function routeKeys(manifest: Manifest): Set { * missing and are ignored: the graph is fixed at boot and nothing new is spliced into it. */ export function missingFromManifest(booted: Manifest, returned: Manifest): string[] { - const scopes = scopeKeys(returned); + const steps = stepKeys(returned); const routes = routeKeys(returned); const missing: string[] = []; - for (const scope of booted.scopes) { - if (!scopes.has(`${scope.scope}:${scope.token}`)) missing.push(`${scope.scope}-scope '${scope.token}'`); + for (const step of booted.steps) { + if (!steps.has(step)) missing.push(`step '${step}'`); } for (const route of booted.routes) { @@ -407,7 +407,7 @@ export function connectLink(args: { const link: Link = { // replaced with the real manifest before this object escapes; a reconnect never changes it, // because the graph is fixed at boot and only the *boot* manifest describes what it holds. - manifest: { scopes: [], routes: [] }, + manifest: { steps: [], routes: [] }, rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs), close: () => { // Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after diff --git a/src/mesh/protocol.ts b/src/mesh/protocol.ts index d1c6ede..3ce3bc3 100644 --- a/src/mesh/protocol.ts +++ b/src/mesh/protocol.ts @@ -43,19 +43,21 @@ export interface RequestEnvelope { correlation?: { requestId?: string; traceId?: string }; } -/** Manifest entry for an exported scope token and its lifetime. */ -export interface ScopeEntry { - token: string; - scope: 'app' | 'request'; -} /** Manifest entry for an exported route. */ export interface RouteEntry { method: string; pattern: string; } -/** A mesh server's advertised scopes and routes. */ + +/** + * A mesh server's advertised steps and routes. + * + * Steps only: a provider's value is the object it builds, which cannot cross a JSON wire, so + * exporting one is refused at boot (`collectProviders`). Every entry here is request-scope and + * lazy — the token exists in the teacup's graph, and running it is an RPC. + */ export interface Manifest { - scopes: ScopeEntry[]; + steps: string[]; routes: RouteEntry[]; } @@ -68,7 +70,7 @@ export interface Manifest { */ export type Frame = | { type: 'hello'; v: number; secret: string } - | { type: 'manifest'; v: number; scopes: ScopeEntry[]; routes: RouteEntry[] } + | { type: 'manifest'; v: number; steps: string[]; routes: RouteEntry[] } | { type: 'rpc-req'; id: string; kind: 'scope' | 'route'; name: string; ctx: RequestEnvelope } | { type: 'rpc-res'; id: string; ok: true; result: unknown } | { type: 'rpc-res'; id: string; ok: false; error: { message: string; status?: number } } @@ -94,7 +96,7 @@ const SHAPE: Record = { }, manifest: (frame, bad) => { if (!isNumber(frame.v)) bad('missing protocol version'); - if (!Array.isArray(frame.scopes) || !Array.isArray(frame.routes)) bad('scopes and routes must be arrays'); + if (!Array.isArray(frame.steps) || !Array.isArray(frame.routes)) bad('steps and routes must be arrays'); }, 'rpc-req': (frame, bad) => { if (!isString(frame.id)) bad('id must be a string'); diff --git a/src/mesh/teacup.ts b/src/mesh/teacup.ts index bd20fad..8a05ec4 100644 --- a/src/mesh/teacup.ts +++ b/src/mesh/teacup.ts @@ -37,27 +37,18 @@ export function envelopeFrom(ctx: any): RequestEnvelope { }; } -/** Turn a link's manifest into local proxy nodes: app-scope providers, request-scope steps, and routes. */ -export function buildRemote(link: Link): { - providers: RemoteScopeNode[]; - steps: RemoteScopeNode[]; - routes: RemoteRoute[]; -} { - const providers: RemoteScopeNode[] = []; - const steps: RemoteScopeNode[] = []; - - for (const scope of link.manifest.scopes) { - const node: RemoteScopeNode = { - name: scope.token, - run: async (ctx: any) => ({ [scope.token]: await link.rpc('scope', scope.token, envelopeFrom(ctx)) }), - }; - (scope.scope === 'app' ? providers : steps).push(node); - } +/** Turn a link's manifest into local proxy nodes: lazy request-scope steps, and routes. */ +export function buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] } { + const steps: RemoteScopeNode[] = link.manifest.steps.map((token) => ({ + name: token, + run: async (ctx: any) => ({ [token]: await link.rpc('scope', token, envelopeFrom(ctx)) }), + })); const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({ method: route.method, pattern: route.pattern, handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape, })); - return { providers, steps, routes }; + + return { steps, routes }; } diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index 47aa784..3c4e651 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -42,19 +42,9 @@ const HANDSHAKE_TIMEOUT_MS = 10_000; */ const MAX_FRAME_CHARS = 4_000_000; -/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */ -export function buildManifest(args: { - providers: string[]; // exported provider tokens (app-scope) - steps: string[]; // exported step tokens (request-scope) - routes: RouteEntry[]; // exported buffered routes -}): Manifest { - return { - scopes: [ - ...args.providers.map((token) => ({ token, scope: 'app' as const })), - ...args.steps.map((token) => ({ token, scope: 'request' as const })), - ], - routes: args.routes, - }; +/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */ +export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest { + return { steps: [...args.steps], routes: args.routes }; } function safeEqual(left: string, right: string): boolean { @@ -115,7 +105,7 @@ function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps): encode({ type: 'manifest', v: MESH_PROTOCOL_VERSION, - scopes: deps.manifest.scopes, + steps: deps.manifest.steps, routes: deps.manifest.routes, }), ); @@ -244,7 +234,7 @@ export function createMeshControl(deps: MeshControlDeps): { path: string; handle: (socket: WsSocket) => Promise; } { - const exportedScopes = new Set(deps.manifest.scopes.map((scope) => scope.token)); + const exportedScopes = new Set(deps.manifest.steps); const exportedRoutes = new Set(deps.manifest.routes.map((route) => `${route.method} ${route.pattern}`)); return { diff --git a/test/mesh/envelope.test.ts b/test/mesh/envelope.test.ts index e85c546..df375ad 100644 --- a/test/mesh/envelope.test.ts +++ b/test/mesh/envelope.test.ts @@ -103,7 +103,7 @@ describe('mesh rpc errors', () => { const frame = decode(data.toString()); if (!authed && frame.type === 'hello') { authed = true; - ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'billing', scope: 'request' }], routes: [] })); + ws.send(encode({ type: 'manifest', v: V, steps: ['billing'], routes: [] })); return; } if (frame.type === 'rpc-req') { @@ -130,7 +130,7 @@ describe('teapot hardening', () => { const control = () => createMeshControl({ secret: 'good', - manifest: { scopes: [{ token: 'auth', scope: 'request' }], routes: [] }, + manifest: { steps: ['auth'], routes: [] }, resolveScope: async () => 'value', resolveRoute: async () => ({ status: 200, headers: {}, body: '' }), }); diff --git a/test/mesh/fetch-boot.test.ts b/test/mesh/fetch-boot.test.ts index d1a7e8a..71e7828 100644 --- a/test/mesh/fetch-boot.test.ts +++ b/test/mesh/fetch-boot.test.ts @@ -276,7 +276,7 @@ describe('mesh control over app.upgrade (no listen)', () => { expect(peer.sent[0]).toMatchObject({ type: 'manifest', v: MESH_PROTOCOL_VERSION, - scopes: expect.arrayContaining([{ token: 'config', scope: 'request' }]), + steps: expect.arrayContaining(['config']), }); await teapot.close(); }); diff --git a/test/mesh/heartbeat.test.ts b/test/mesh/heartbeat.test.ts index 9acf2f4..2242f96 100644 --- a/test/mesh/heartbeat.test.ts +++ b/test/mesh/heartbeat.test.ts @@ -21,7 +21,7 @@ function startTeapot(opts: { answerPings: boolean }) { seen.push(frame.type); if (frame.type === 'hello') { - ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); + ws.send(encode({ type: 'manifest', v: V, steps: ['auth'], routes: [] })); } if (frame.type === 'ping' && opts.answerPings) ws.send(encode({ type: 'pong' })); if (frame.type === 'rpc-req') ws.send(encode({ type: 'rpc-res', id: frame.id, ok: true, result: { got: 1 } })); diff --git a/test/mesh/link.test.ts b/test/mesh/link.test.ts index d80965e..ce3bf7f 100644 --- a/test/mesh/link.test.ts +++ b/test/mesh/link.test.ts @@ -16,7 +16,7 @@ function startTeapot(secret = 'good') { ws.on('message', (d) => { const f = decode(d.toString()); if (!authed) { - if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'auth', scope: 'request' }], routes: [] })); } + if (f.type === 'hello' && f.secret === secret) { authed = true; ws.send(encode({ type: 'manifest', v: V, steps: ['auth'], routes: [] })); } else ws.close(1008); return; } @@ -36,7 +36,7 @@ function startSilentTeapot(secret = 'good') { wss.on('connection', (ws) => { ws.on('message', (d) => { const f = decode(d.toString()); - if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] })); + if (f.type === 'hello' && f.secret === secret) ws.send(encode({ type: 'manifest', v: V, steps: [], routes: [] })); // ignore rpc-req entirely }); }); @@ -48,7 +48,7 @@ function startSilentTeapot(secret = 'good') { function startSkewedTeapot() { const wss = new WebSocketServer({ port: 0 }); wss.on('connection', (ws) => { - ws.on('message', () => ws.send(encode({ type: 'manifest', v: V + 1, scopes: [], routes: [] } as any))); + ws.on('message', () => ws.send(encode({ type: 'manifest', v: V + 1, steps: [], routes: [] } as any))); }); const port = (wss.address() as any).port; return { url: `ws://127.0.0.1:${port}/__mesh__/control`, close: () => wss.close() }; @@ -68,7 +68,7 @@ describe('WebSocket client implementations', () => { const t = startTeapot(); const link = await connectLink({ url: t.url, secret: 'good', Ctor }); - expect(link.manifest.scopes).toEqual([{ token: 'auth', scope: 'request' }]); + expect(link.manifest.steps).toEqual(['auth']); expect(await link.rpc('scope', 'auth', env)).toEqual({ got: 'auth' }); link.close(); t.close(); @@ -86,7 +86,7 @@ describe('connectLink', () => { wss.on('connection', (ws) => ws.on('message', (d) => { seen.push(decode(d.toString())); - ws.send(encode({ type: 'manifest', v: V, scopes: [], routes: [] })); + ws.send(encode({ type: 'manifest', v: V, steps: [], routes: [] })); }), ); const url = `ws://127.0.0.1:${(wss.address() as any).port}/__mesh__/control`; @@ -105,7 +105,7 @@ describe('connectLink', () => { it('handshakes and exposes the manifest', async () => { const t = startTeapot(); const link = await connectLink({ url: t.url, secret: 'good' }); - expect(link.manifest.scopes).toEqual([{ token: 'auth', scope: 'request' }]); + expect(link.manifest.steps).toEqual(['auth']); link.close(); t.close(); }); diff --git a/test/mesh/protocol.test.ts b/test/mesh/protocol.test.ts index 029fe06..53580d4 100644 --- a/test/mesh/protocol.test.ts +++ b/test/mesh/protocol.test.ts @@ -11,7 +11,7 @@ describe('protocol codec', () => { { type: 'manifest', v: V, - scopes: [{ token: 'auth', scope: 'request' }], + steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }], }, { type: 'rpc-req', id: '1', kind: 'scope', name: 'auth', ctx: env }, @@ -21,6 +21,17 @@ describe('protocol codec', () => { for (const f of frames) expect(decode(encode(f))).toEqual(f); }); + it('encodes a manifest of step names', () => { + const frame = decode(encode({ type: 'manifest', v: V, steps: ['auth'], routes: [] })); + expect(frame).toEqual({ type: 'manifest', v: V, steps: ['auth'], routes: [] }); + }); + + it('rejects a manifest whose steps are not an array', () => { + expect(() => decode(JSON.stringify({ type: 'manifest', v: V, steps: 'auth', routes: [] }))).toThrow( + /steps and routes must be arrays/, + ); + }); + it('throws on malformed json', () => { expect(() => decode('{not json')).toThrow(); }); @@ -46,7 +57,7 @@ describe('protocol codec', () => { describe('protocol versioning', () => { it('carries the protocol version on the handshake frames', () => { const hello = decode(encode({ type: 'hello', v: V, secret: 's' })); - const manifest = decode(encode({ type: 'manifest', v: V, scopes: [], routes: [] })); + const manifest = decode(encode({ type: 'manifest', v: V, steps: [], routes: [] })); expect(hello).toMatchObject({ v: V }); expect(manifest).toMatchObject({ v: V }); @@ -54,7 +65,7 @@ describe('protocol versioning', () => { it('rejects a handshake frame with no version — an unversioned peer is not decodable', () => { expect(() => decode(JSON.stringify({ type: 'hello', secret: 's' }))).toThrow(/malformed hello/i); - expect(() => decode(JSON.stringify({ type: 'manifest', scopes: [], routes: [] }))).toThrow(/malformed manifest/i); + expect(() => decode(JSON.stringify({ type: 'manifest', steps: [], routes: [] }))).toThrow(/malformed manifest/i); }); }); @@ -64,7 +75,7 @@ describe('protocol field validation', () => { it.each([ ['hello without secret', { type: 'hello', v: V }], ['hello with non-string secret', { type: 'hello', v: V, secret: 42 }], - ['manifest with non-array scopes', { type: 'manifest', v: V, scopes: 'nope', routes: [] }], + ['manifest with non-array steps', { type: 'manifest', v: V, steps: 'nope', routes: [] }], ['rpc-req without id', { type: 'rpc-req', kind: 'scope', name: 'auth', ctx: env }], ['rpc-req without ctx', { type: 'rpc-req', id: '1', kind: 'scope', name: 'auth' }], ['rpc-req with unknown kind', { type: 'rpc-req', id: '1', kind: 'bogus', name: 'auth', ctx: env }], diff --git a/test/mesh/reconnect.test.ts b/test/mesh/reconnect.test.ts index 14e2169..6aac20e 100644 --- a/test/mesh/reconnect.test.ts +++ b/test/mesh/reconnect.test.ts @@ -20,7 +20,7 @@ function teapotOn(port: number, manifest: Manifest, answer: unknown = { ok: true if (!authed) { if (frame.type === 'hello' && frame.secret === 'good') { authed = true; - ws.send(encode({ type: 'manifest', v: V, scopes: manifest.scopes, routes: manifest.routes })); + ws.send(encode({ type: 'manifest', v: V, steps: manifest.steps, routes: manifest.routes })); } else ws.close(1008); return; } @@ -54,13 +54,13 @@ async function freePort(): Promise { const settle = (ms: number) => new Promise((r) => setTimeout(r, ms)); const url = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`; -const SCOPES: Manifest = { scopes: [{ token: 'auth', scope: 'app' }], routes: [] }; +const STEPS: Manifest = { steps: ['auth'], routes: [] }; const fast = { initialDelayMs: 20, maxDelayMs: 60 }; describe('mesh reconnection', () => { it('reconnects to the same teapot and serves again', async () => { const port = await freePort(); - let teapot = await teapotOn(port, SCOPES); + let teapot = await teapotOn(port, STEPS); const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 }); expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: true }); @@ -70,7 +70,7 @@ describe('mesh reconnection', () => { // the window where the link is down answers immediately rather than after timeoutMs await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 }); - teapot = await teapotOn(port, SCOPES, { ok: 'again' }); + teapot = await teapotOn(port, STEPS, { ok: 'again' }); await settle(300); expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: 'again' }); @@ -80,7 +80,7 @@ describe('mesh reconnection', () => { it('refuses a returning teapot whose manifest lost a token the graph needs', async () => { const port = await freePort(); - let teapot = await teapotOn(port, SCOPES); + let teapot = await teapotOn(port, STEPS); const warnings: string[] = []; const logger = { debug() {}, info() {}, warn: (m: string) => warnings.push(m), error() {} }; const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50, logger }); @@ -89,11 +89,11 @@ describe('mesh reconnection', () => { await settle(50); // comes back exporting nothing — the graph was validated against 'auth' at boot - teapot = await teapotOn(port, { scopes: [], routes: [] }); + teapot = await teapotOn(port, { steps: [], routes: [] }); await settle(300); await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 }); - expect(warnings.some((w) => w.includes("app-scope 'auth'") && w.includes('refusing to reconnect'))).toBe(true); + expect(warnings.some((w) => w.includes("step 'auth'") && w.includes('refusing to reconnect'))).toBe(true); // logged once per distinct manifest, not once per attempt expect(warnings.filter((w) => w.includes('refusing to reconnect')).length).toBe(1); @@ -103,7 +103,7 @@ describe('mesh reconnection', () => { it('stops reconnecting once the application closes the link', async () => { const port = await freePort(); - const teapot = await teapotOn(port, SCOPES); + const teapot = await teapotOn(port, STEPS); const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 }); await teapot.close(); @@ -111,7 +111,7 @@ describe('mesh reconnection', () => { // if close() were not terminal, the link would reconnect to the teapot that comes back here — // which is what would leave app.close() with a process that cannot exit - const revived = await teapotOn(port, SCOPES, { ok: 'revived' }); + const revived = await teapotOn(port, STEPS, { ok: 'revived' }); await settle(300); await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 }); @@ -120,11 +120,11 @@ describe('mesh reconnection', () => { it('reconnect: false keeps the old fail-once behaviour', async () => { const port = await freePort(); - let teapot = await teapotOn(port, SCOPES); + let teapot = await teapotOn(port, STEPS); const link = await connectLink({ url: url(port), secret: 'good', reconnect: false, heartbeatMs: 50 }); await teapot.close(); - teapot = await teapotOn(port, SCOPES); + teapot = await teapotOn(port, STEPS); await settle(300); await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 }); @@ -135,10 +135,7 @@ describe('mesh reconnection', () => { describe('missingFromManifest', () => { const booted: Manifest = { - scopes: [ - { token: 'auth', scope: 'request' }, - { token: 'config', scope: 'app' }, - ], + steps: ['auth', 'config'], routes: [{ method: 'GET', pattern: '/svc/:id' }], }; @@ -148,30 +145,24 @@ describe('missingFromManifest', () => { it('accepts extra exports — the graph is fixed at boot and nothing new is spliced', () => { const wider: Manifest = { - scopes: [...booted.scopes, { token: 'billing', scope: 'app' }], + steps: [...booted.steps, 'billing'], routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }], }; expect(missingFromManifest(booted, wider)).toEqual([]); }); it('accepts a route parameter that was only renamed', () => { - const renamed: Manifest = { scopes: booted.scopes, routes: [{ method: 'GET', pattern: '/svc/:name' }] }; + const renamed: Manifest = { steps: booted.steps, routes: [{ method: 'GET', pattern: '/svc/:name' }] }; expect(missingFromManifest(booted, renamed)).toEqual([]); }); - it('reports a token whose lifetime changed, since the graph resolved it under the old one', () => { - const flipped: Manifest = { - scopes: [ - { token: 'auth', scope: 'app' }, - { token: 'config', scope: 'app' }, - ], - routes: booted.routes, - }; - expect(missingFromManifest(booted, flipped)).toEqual(["request-scope 'auth'"]); + it('reports a step token that vanished, since the graph resolved it under the old manifest', () => { + const shrunk: Manifest = { steps: ['config'], routes: booted.routes }; + expect(missingFromManifest(booted, shrunk)).toEqual(["step 'auth'"]); }); it('reports a missing route by method and pattern', () => { - const routeless: Manifest = { scopes: booted.scopes, routes: [] }; + const routeless: Manifest = { steps: booted.steps, routes: [] }; expect(missingFromManifest(booted, routeless)).toEqual(["route 'GET /svc/:id'"]); }); }); diff --git a/test/mesh/teacup.test.ts b/test/mesh/teacup.test.ts index 81f026c..0920194 100644 --- a/test/mesh/teacup.test.ts +++ b/test/mesh/teacup.test.ts @@ -3,20 +3,28 @@ import { buildRemote, envelopeFrom } from '../../src/mesh/teacup'; import type { Link } from '../../src/mesh/link'; const fakeLink = (calls: any[]): Link => ({ - manifest: { scopes: [{ token: 'config', scope: 'app' }, { token: 'auth', scope: 'request' }], routes: [{ method: 'GET', pattern: '/u/:id' }] }, + manifest: { steps: ['config', 'auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] }, rpc: async (kind, name, ctx) => { calls.push({ kind, name, ctx }); return name === 'config' ? { url: 'db://x' } : { id: 'u1' }; }, close() {}, }); describe('teacup buildRemote', () => { - it('makes a provider node (app) and a step node (request) with RPC runners returning merge objects', async () => { + it('turns every manifest step into a lazy remote node', async () => { + const link = { manifest: { steps: ['auth'], routes: [] }, rpc: async () => ({ ok: true }) } as any; + const { steps, routes } = buildRemote(link); + + expect(routes).toEqual([]); + expect(steps.map((s: any) => s.name)).toEqual(['auth']); + expect(await steps[0].run({})).toEqual({ auth: { ok: true } }); + }); + + it('makes a step node per manifest token, with RPC runners returning merge objects', async () => { const calls: any[] = []; - const { providers, steps } = buildRemote(fakeLink(calls)); - expect(providers.map((p) => p.name)).toEqual(['config']); - expect(steps.map((s) => s.name)).toEqual(['auth']); - expect(await providers[0].run({})).toEqual({ config: { url: 'db://x' } }); + const { steps } = buildRemote(fakeLink(calls)); + expect(steps.map((s) => s.name)).toEqual(['config', 'auth']); + expect(await steps[0].run({})).toEqual({ config: { url: 'db://x' } }); const ctx = { req: {}, params: { id: '9' }, query: {}, body: undefined, headers: { x: '1' } }; - expect(await steps[0].run(ctx)).toEqual({ auth: { id: 'u1' } }); + expect(await steps[1].run(ctx)).toEqual({ auth: { id: 'u1' } }); expect(calls.find((c) => c.name === 'auth').ctx).toMatchObject({ params: { id: '9' }, headers: { x: '1' } }); }); diff --git a/test/mesh/teapot.test.ts b/test/mesh/teapot.test.ts index 50f92fb..0dec46f 100644 --- a/test/mesh/teapot.test.ts +++ b/test/mesh/teapot.test.ts @@ -43,18 +43,17 @@ const fakeSocket = () => { }; describe('buildManifest', () => { - it('maps providers to app scope and steps to request scope', () => { - const m = buildManifest({ providers: ['config'], steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] }); - expect(m.scopes).toContainEqual({ token: 'config', scope: 'app' }); - expect(m.scopes).toContainEqual({ token: 'auth', scope: 'request' }); - expect(m.routes).toEqual([{ method: 'GET', pattern: '/u/:id' }]); + it('builds a manifest from step tokens and routes', () => { + expect(buildManifest({ steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] })).toEqual({ + steps: ['auth'], + routes: [{ method: 'GET', pattern: '/u/:id' }], + }); }); }); describe('createMeshControl', () => { const manifest = buildManifest({ - providers: ['config'], - steps: ['auth'], + steps: ['config', 'auth'], routes: [{ method: 'GET', pattern: '/u/:id' }], }); const make = (over: Partial[0]> = {}) => @@ -82,7 +81,7 @@ describe('createMeshControl', () => { const t = fakeSocket(); make().handle(t.socket); await t.deliver({ type: 'hello', v: V, secret: 'good' }); - expect(t.sent[0]).toMatchObject({ type: 'manifest', v: V, scopes: manifest.scopes }); + expect(t.sent[0]).toMatchObject({ type: 'manifest', v: V, steps: manifest.steps }); }); it('rejects a version-skewed peer before checking its secret, naming both versions', async () => { From 6e66b05a4123e0bde967c5e70bdcbdbdefac90b8 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 16:25:21 -0500 Subject: [PATCH 04/18] refactor(mesh): drop the remote app-scope binding and its rebind seam A remote provider was registered app-scope, resolved once, and cached for the process lifetime; invalidateRemoteBindings existed only to un-cache it on reconnect. With providers gone from the manifest, both go, and a remote step needs nothing on reconnect because it holds nothing between requests. Signed-off-by: Diego Resendez --- src/app/index.ts | 44 ++++--------------------------- test/mesh/integration.test.ts | 49 +++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 39 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index 9e64599..4913df2 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -33,7 +33,7 @@ import { buildOpenApi, type OpenApiInfo } from '../openapi'; import { connectLink, isPermanentRefusal, type Link } from '../mesh/link'; import { Rooms } from '../rooms'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; -import { buildRemote, type RemoteScopeNode } from '../mesh/teacup'; +import { buildRemote } from '../mesh/teacup'; import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot'; import type { MeshControl } from '../http'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; @@ -59,7 +59,6 @@ interface Registry { */ providerInstances: Map void | Promise }>; routePlans: RoutePlan[]; - exportedProviders: string[]; exportedSteps: string[]; exportedRoutes: RouteEntry[]; setRunner(name: string, runner: Runner, framework?: boolean): void; @@ -239,7 +238,7 @@ export function createApp(opts: { // can only be built here, after finalize(), and never at construction time. const prepareGraph = async (): Promise => { if (opts.mesh && !booted) { - const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, container); + const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger); remoteRoutes = spliced.remoteRoutes; meshLinks.push(...spliced.meshLinks); finalize(); @@ -424,7 +423,6 @@ function emptyRegistry(): Registry { providerMeta: new Map(), providerInstances: new Map(), routePlans: [], - exportedProviders: [], exportedSteps: [], exportedRoutes: [], setRunner, @@ -805,26 +803,12 @@ function warnIfCleartext(url: string, logger: Logger): void { ); } -/** - * Re-register a link's app-scope bindings after it reconnects, so their next resolve re-runs the RPC. - * - * Named and separate rather than inlined in the reconnect handler: this is the seam a future - * `onManifestChange: 'reconcile'` reuses, and burying it would mean writing it twice. - * - * Lazy on purpose — the RPC runs on the next resolve, not here. Re-resolving eagerly would put a - * network call on the reconnect path, where a failure has nowhere to go but a swallowed rejection. - */ -function invalidateRemoteBindings(rebind: Array<() => void>): void { - for (const bind of rebind) bind(); -} - -/** Connects the configured teapots, splices their remote providers/steps into the registry, and returns their routes. */ +/** Connects the configured teapots, splices their remote steps into the registry, and returns their routes. */ async function spliceRemoteScopes( mesh: MeshConfig, bus: Bus, registry: Registry, logger: Logger, - container: Container, ): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> { const remoteRoutes: RouteDef[] = []; const meshLinks: Link[] = []; @@ -833,9 +817,6 @@ async function spliceRemoteScopes( try { for (const teapot of mesh.teapots ?? []) { warnIfCleartext(teapot.url, logger); - // Deferred so the reconnect callback can name this link's provider tokens, which are only - // known once its manifest arrives — the callback is registered before the link can drop. - const rebind: Array<() => void> = []; const link = await connectUntilDeadline(mesh, bus, logger, () => connectLink({ url: teapot.url, @@ -844,29 +825,14 @@ async function spliceRemoteScopes( heartbeatMs: mesh.heartbeatMs, reconnect: mesh.reconnect, onManifestChange: mesh.onManifestChange, - onReconnect: () => invalidateRemoteBindings(rebind), logger, bus, }), ); meshLinks.push(link); - // `buildRemote` no longer returns `providers` — every exported token is a step now (Task 1 - // refuses a provider export at boot). Kept as an empty array, not deleted, so the loop below - // still typechecks; Task 3 removes the loop itself along with the rest of provider-splicing. - const providers: RemoteScopeNode[] = []; const { steps, routes } = buildRemote(link); const origin = `mesh:${teapot.url}`; - for (const provider of providers) { - registry.providerNodes.push({ name: provider.name, needs: [], provides: [provider.name], origin }); - registry.providerMeta.set(provider.name, { optional: false }); - registry.setRunner(provider.name, provider.run); - // A remote app-scope value is resolved once at boot and frozen into the container, so it - // would keep answering from a cache the teapot no longer stands behind. Re-registering - // gives the binding a factory that re-runs the RPC, and `register` drops the memo with it. - rebind.push(() => container.register(provider.name, 'app', () => provider.run({}))); - } - for (const step of steps) { registry.stepNodes.push({ name: step.name, needs: [], provides: [step.name], origin }); registry.setRunner(step.name, step.run); @@ -1088,8 +1054,8 @@ function buildMeshControl( registry: Registry, deps: { container: Container; orderedProviders: GraphNode[]; orderedSteps: GraphNode[]; deps: PipelineDeps }, ): MeshControl | undefined { - const { exportedProviders, exportedSteps, exportedRoutes, routePlans, runners } = registry; - const hasExports = exportedProviders.length || exportedSteps.length || exportedRoutes.length; + const { exportedSteps, exportedRoutes, routePlans, runners } = registry; + const hasExports = exportedSteps.length || exportedRoutes.length; if (hasExports && !mesh?.secret) { throw new Error('mesh: exports declared (export: true) but no mesh.secret configured to gate the control channel'); diff --git a/test/mesh/integration.test.ts b/test/mesh/integration.test.ts index ae5bd11..10d154c 100644 --- a/test/mesh/integration.test.ts +++ b/test/mesh/integration.test.ts @@ -93,6 +93,55 @@ describe('mesh skeleton integration', () => { tServer.close(); cServer.close(); }); + it('re-runs the RPC on every request rather than caching a boot value', async () => { + // A dedicated single-step teapot/teacup pair, not the shared TeapotModule above: exporting + // two scopes (config + auth) makes resolveScope re-run the whole step graph per scope RPC, + // which would make a call counter here track that unrelated behaviour instead of the thing + // this test guards. With one exported step, a per-request counter is unambiguous: a step + // re-runs where a provider used to be resolved once at boot and cached for the process + // lifetime — this is the regression guard for removing the remote app-scope splice, proving + // it does not quietly reintroduce a cached value. + let calls = 0; + @Step({ provides: 'counter', needs: [], export: true }) + class Counter { + run() { + calls += 1; + return { counter: calls }; + } + } + @Module({ mountpoint: '/api', steps: [Counter] }) + class CounterTeapotModule {} + + @Route('/local') + class CounterLocalCtl { + @Get('/counter') + counter(@needs('counter') counter: number) { + return { counter }; + } + } + @Module({ mountpoint: '/api', controllers: [CounterLocalCtl] }) + class CounterTeacupModule {} + + const teapot = createApp({ modules: [CounterTeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const tPort = (tServer.address() as any).port; + const url = `ws://127.0.0.1:${tPort}/__mesh__/control`; + + const teacup = createApp({ + modules: [CounterTeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + const cServer = await teacup.listen(0); + const cPort = (cServer.address() as any).port; + const hit = () => fetch(`http://127.0.0.1:${cPort}/api/local/counter`).then((r) => r.json() as Promise<{ counter: number }>); + + expect((await hit()).counter).toBe(1); + expect((await hit()).counter).toBe(2); + + tServer.close(); cServer.close(); + }); + it('mesh is gated behind experimental: true', () => { expect(() => createApp({ modules: [TeapotModule], mesh: { secret: SECRET } })).toThrow(/alpha feature/); }); From 414b18879265c7841a73fa3e603c178f7f8921f2 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 16:25:27 -0500 Subject: [PATCH 05/18] fix(mesh): reject a manifest step that is not a string decode is the mesh's trust boundary, reached before the handshake authenticates the peer. The manifest row checked that steps was an array but not what was in it, so {"steps":[123]} decoded cleanly and 123 would have become a graph node name in buildRemote. Signed-off-by: Diego Resendez --- src/mesh/protocol.ts | 3 +++ test/mesh/protocol.test.ts | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/src/mesh/protocol.ts b/src/mesh/protocol.ts index 3ce3bc3..85d082f 100644 --- a/src/mesh/protocol.ts +++ b/src/mesh/protocol.ts @@ -97,6 +97,9 @@ const SHAPE: Record = { manifest: (frame, bad) => { if (!isNumber(frame.v)) bad('missing protocol version'); if (!Array.isArray(frame.steps) || !Array.isArray(frame.routes)) bad('steps and routes must be arrays'); + // Array.isArray above already guarantees this, but TS does not carry that narrowing through a + // `never`-typed callback parameter — the cast is safe, not a bypass. + if (!(frame.steps as unknown[]).every(isString)) bad('every step must be a string'); }, 'rpc-req': (frame, bad) => { if (!isString(frame.id)) bad('id must be a string'); diff --git a/test/mesh/protocol.test.ts b/test/mesh/protocol.test.ts index 53580d4..67323a8 100644 --- a/test/mesh/protocol.test.ts +++ b/test/mesh/protocol.test.ts @@ -32,6 +32,12 @@ describe('protocol codec', () => { ); }); + it('rejects a manifest whose steps array contains a non-string element', () => { + expect(() => decode(JSON.stringify({ type: 'manifest', v: V, steps: [123], routes: [] }))).toThrow( + /every step must be a string/, + ); + }); + it('throws on malformed json', () => { expect(() => decode('{not json')).toThrow(); }); From 3b680480ab2502dba7b6a0983cffb7a1e0a3b5e0 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 16:35:56 -0500 Subject: [PATCH 06/18] feat(mesh): an unreachable teapot no longer stops the teacup from booting Blocking existed for app-scope exports, which have to resolve at boot because there is no later. Steps and proxied routes are all later. The grace budget stays -- a co-deploy still waits -- but exhausting it now warns instead of throwing. A missing token still fails the boot, and the error now names the teapots that were away. Also drops connectLink's onReconnect hook and the reconnected flag that fed it: its only caller was removed by an earlier commit on this branch, and it is not part of the public API (not re-exported, not documented). Signed-off-by: Diego Resendez --- src/app/index.ts | 44 +++++++++++++++++------ src/graph.ts | 4 +-- src/mesh/link.ts | 9 ++--- test/mesh/boot-retry.test.ts | 69 ++++++++++++++++++++++++++++++++++-- 4 files changed, 104 insertions(+), 22 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index 4913df2..06b37f5 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -221,8 +221,8 @@ export function createApp(opts: { let remoteRoutes: RouteDef[] = []; const meshLinks: Link[] = []; - const finalize = (): void => { - ({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth)); + const finalize = (missingNote?: (key: string) => string): void => { + ({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote)); booted = true; }; @@ -241,7 +241,12 @@ export function createApp(opts: { const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger); remoteRoutes = spliced.remoteRoutes; meshLinks.push(...spliced.meshLinks); - finalize(); + // 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. + const meshNote = spliced.absent.length + ? () => ` — these teapots did not connect, so their exports are absent: ${spliced.absent.join(', ')}` + : undefined; + finalize(meshNote); } meshControl = buildMeshControl(opts.mesh, registry, { @@ -662,9 +667,10 @@ function finalizeGraph( registry: Registry, logger: Logger, warnDepth: number | false = DEEP_GRAPH_WARN, + missingNote?: (key: string) => string, ): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } { const { providerNodes, stepNodes, routePlans } = registry; - const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']); + const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params'], missingNote); const orderedProviders = ordered.filter((node) => providerNodes.includes(node)); const orderedSteps = ordered.filter((node) => stepNodes.includes(node)); const alwaysSteps = stepNodes.filter((node) => node.provides.length === 0); // side-effect/observer steps (plugins) @@ -739,13 +745,18 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod * Each failed attempt is both logged and emitted as `mesh:boot:retry` — logged so an operator * watching a deploy sees why it is taking so long, emitted so the wait is visible to whatever * collects lifecycle events rather than only to whoever is reading a terminal. + * + * Exhausting the budget no longer throws (D4 keeps the one exception: a permanent refusal still + * does). Every export a teapot makes is now lazy — a request-scope step or a proxied route — so + * nothing needs it resolved by boot; an absent teapot only costs a 503 on the requests that need + * it, and a teacup that refuses to start would take down the half of itself that never did. */ async function connectUntilDeadline( mesh: MeshConfig, bus: Bus, logger: Logger, attempt: () => Promise, -): Promise { +): Promise { const budgetMs = mesh.bootTimeoutMs ?? mesh.timeoutMs ?? 30_000; const deadline = Date.now() + budgetMs; let delay = 500; @@ -766,11 +777,15 @@ async function connectUntilDeadline( throw error; } - // Rethrown as-is rather than wrapped: connectLink already says whether this was a refused - // handshake, a version mismatch or a timeout, and each sends you somewhere different. + // The budget is a grace for a co-deploy, not a requirement. Every export is a lazy step or a + // proxied route now, so an absent teapot costs a 503 on the requests that need it — and a + // teacup that refuses to start takes down the half of itself that never needed the teapot. if (remaining <= 0) { - logger.error(`mesh: giving up after ${attempts} attempt(s) over ${budgetMs}ms — ${(error as Error).message}`); - throw error; + logger.warn( + `mesh: teapot unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` + + `(${(error as Error).message}) — starting without it; its steps and routes will 503`, + ); + return undefined; } bus.emit('mesh:boot:retry', { name: `attempt ${attempts}`, error }); @@ -809,9 +824,10 @@ async function spliceRemoteScopes( bus: Bus, registry: Registry, logger: Logger, -): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> { +): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[]; absent: string[] }> { const remoteRoutes: RouteDef[] = []; const meshLinks: Link[] = []; + const absent: string[] = []; // urls of teapots that never connected within the boot budget const routeOwners = new Map(); // "METHOD effective-shape" -> owner try { @@ -829,6 +845,12 @@ async function spliceRemoteScopes( bus, }), ); + + if (!link) { + absent.push(teapot.url); + continue; + } + meshLinks.push(link); const { steps, routes } = buildRemote(link); const origin = `mesh:${teapot.url}`; @@ -901,7 +923,7 @@ async function spliceRemoteScopes( throw err; } - return { remoteRoutes, meshLinks }; + return { remoteRoutes, meshLinks, absent }; } /** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */ diff --git a/src/graph.ts b/src/graph.ts index 75e22e4..66c8d4d 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -43,7 +43,7 @@ export interface GraphNode { } /** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */ -export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { +export function topoSort(nodes: GraphNode[], seedKeys: string[], note?: (key: string) => string): GraphNode[] { const producedBy = new Map(); for (const node of nodes) for (const key of node.provides) producedBy.set(key, node); @@ -51,7 +51,7 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { for (const node of nodes) { for (const key of node.needs) { if (!seedKeys.includes(key) && !producedBy.has(key)) { - throw new Error(`missing dependency: ${key} needed by ${node.name}`); + throw new Error(`missing dependency: ${key} needed by ${node.name}${note?.(key) ?? ''}`); } } } diff --git a/src/mesh/link.ts b/src/mesh/link.ts index a53bcf5..ff50981 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -393,8 +393,6 @@ export function connectLink(args: { reconnect?: boolean | ReconnectOptions; /** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */ onManifestChange?: ManifestPolicy; - /** Called after a *successful* reconnect, so app-scope values resolved from this link are re-resolved. */ - onReconnect?: () => void; logger?: Logger; }): Promise { const timeoutMs = args.timeoutMs ?? 30_000; @@ -453,7 +451,7 @@ export function connectLink(args: { }; /** Adopt an established session, or refuse it when its manifest no longer backs the graph. */ - const adopt = (session: Session, attempt: number, reconnected: boolean): boolean => { + const adopt = (session: Session, _attempt: number): boolean => { const missing = missingFromManifest(link.manifest, session.manifest); if (missing.length > 0) { @@ -478,7 +476,6 @@ export function connectLink(args: { refusalLogged = ''; state.socket = session.socket; args.bus?.emit('mesh:connect', { name: args.url }); - if (reconnected) args.onReconnect?.(); return true; }; @@ -494,7 +491,7 @@ export function connectLink(args: { return; } - if (!adopt(session, attempt, true)) scheduleRetry(attempt); + if (!adopt(session, attempt)) scheduleRetry(attempt); } catch { // openSession's own abort listener already scheduled the retry through `onEnd`; a rejection // that never opened a socket (a bad URL, DNS) needs one scheduled here instead. @@ -504,7 +501,7 @@ export function connectLink(args: { return openSession(sessionArgs(() => endSession(0))).then((session) => { link.manifest = session.manifest; - adopt(session, 0, false); + adopt(session, 0); return link; }); diff --git a/test/mesh/boot-retry.test.ts b/test/mesh/boot-retry.test.ts index 5c7ff67..5b0bf2e 100644 --- a/test/mesh/boot-retry.test.ts +++ b/test/mesh/boot-retry.test.ts @@ -1,3 +1,4 @@ +import * as net from 'node:net'; import { describe, it, expect } from 'vitest'; import { createApp, Step, Route, Get, Module, needs } from '../../src/index'; @@ -20,6 +21,28 @@ class LocalCtl { @Module({ mountpoint: '/api', controllers: [LocalCtl] }) class TeacupModule {} +@Route('/ping') +class PingCtl { + @Get('/') + ping() { + return { ok: true }; + } +} +@Module({ mountpoint: '/api', controllers: [PingCtl] }) +class LocalOnlyModule {} + +// A step (not a route handler) needing 'auth' so the missing-dependency check that fires is +// `topoSort`'s — the one that gets the "these teapots did not connect" note — rather than the +// route-level `assertNeedsSatisfiable` check, which is untouched by this change. +@Step({ provides: 'profile', needs: ['auth'] }) +class NeedsAuth { + run() { + return { profile: {} }; + } +} +@Module({ mountpoint: '/api', steps: [NeedsAuth] }) +class NeedsAuthModule {} + const collect = () => { const lines: string[] = []; return { lines, logger: { debug() {}, info() {}, warn: (m: string) => lines.push(m), error: (m: string) => lines.push(m) } }; @@ -28,9 +51,9 @@ const collect = () => { describe('mesh boot retry', () => { it('waits for a teapot that starts late, rather than failing the deploy', async () => { const port = await new Promise((resolve) => { - const probe = require('node:net').createServer(); + const probe = net.createServer(); probe.listen(0, () => { - const { port: p } = probe.address(); + const { port: p } = probe.address() as { port: number }; probe.close(() => resolve(p)); }); }); @@ -78,8 +101,10 @@ describe('mesh boot retry', () => { }); try { + // exhausting the budget is no longer fatal by itself (that's the point of this change) — + // the boot still fails here because `who` needs 'auth' and nothing local provides it. await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/); - expect(lines.some((l) => l.includes('giving up after'))).toBe(true); + expect(lines.some((l) => l.includes('starting without it'))).toBe(true); } finally { await teacup.close(); } @@ -116,6 +141,44 @@ describe('mesh boot retry', () => { } }, 40_000); + it('boots when a teapot is unreachable and nothing local needs it', async () => { + const teacup = createApp({ + modules: [LocalOnlyModule], // declares no needs on a remote token + experimental: true, + mesh: { + teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], + secret: 's', + bootTimeoutMs: 300, + }, + }); + + try { + await expect(teacup.ready()).resolves.toBeUndefined(); + const res = await teacup.fetch(new Request('http://x/api/ping')); + expect(res.status).toBe(200); + } finally { + await teacup.close(); + } + }, 15_000); + + it('still fails the boot when a local step needs a token the absent teapot owned', async () => { + const teacup = createApp({ + modules: [NeedsAuthModule], // a step with needs: ['auth'] + experimental: true, + mesh: { + teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], + secret: 's', + bootTimeoutMs: 300, + }, + }); + + try { + await expect(teacup.ready()).rejects.toThrow(/missing dependency: auth[\s\S]*did not connect/i); + } finally { + await teacup.close(); + } + }, 15_000); + it('bootTimeoutMs: 0 makes one attempt, as before', async () => { const { lines, logger } = collect(); const teacup = createApp({ From 4e8aacb6b7bbd032bd1b3f43d485ae2b1776a2fb Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 16:41:46 -0500 Subject: [PATCH 07/18] fix(mesh): name the absent teapot in the route-level missing-need error too assertNeedsSatisfiable is a separate check from topoSort, so it didn't get the note threaded into finalizeGraph -- a handler-level @needs against an absent teapot's token read as a typo or a forgotten export: true, which is worse than the pre-task behavior (the boot used to throw naming the teapot). Thread missingNote through and soften "local or mesh" to "local or connected mesh" when it's set, so the message doesn't claim a search that never happened. Also tightens two test assertions that only passed because "mesh" happened to appear inside the unrelated "(local or mesh)" wording, and removes adopt()'s now-fully-unused attempt parameter in mesh/link.ts instead of leaving it underscored. Signed-off-by: Diego Resendez --- src/app/index.ts | 16 +++++++++++++--- src/mesh/link.ts | 6 +++--- test/mesh/boot-retry.test.ts | 34 +++++++++++++++++++++++++++++++--- 3 files changed, 47 insertions(+), 9 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index 06b37f5..b359ac2 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -695,12 +695,17 @@ function finalizeGraph( } } - assertNeedsSatisfiable(routePlans, providerNodes, stepNodes); + assertNeedsSatisfiable(routePlans, providerNodes, stepNodes, missingNote); return { orderedProviders, orderedSteps }; } /** Throws if any route needs a key that nothing (local or mesh) provides, suggesting the nearest match. */ -function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNode[], stepNodes: GraphNode[]): void { +function assertNeedsSatisfiable( + routePlans: RoutePlan[], + providerNodes: GraphNode[], + stepNodes: GraphNode[], + missingNote?: (key: string) => string, +): void { const producedKeys = new Set([ ...providerNodes.flatMap((node) => node.provides), ...stepNodes.flatMap((node) => node.provides), @@ -726,8 +731,13 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod } const hint = nearest(need, allowed); + // "local or mesh" claims the mesh was consulted and came up empty — true only when every + // teapot connected. When one didn't, say "connected mesh" instead so the message doesn't + // assert a search that never happened, and let missingNote name which teapots were away. + const scope = missingNote ? 'local or connected mesh' : 'local or mesh'; throw new Error( - `handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`, + `handler '${plan.handlerName}' needs '${need}' but nothing (${scope}) provides it` + + `${hint ? ` — did you mean '${hint}'?` : ''}${missingNote?.(need) ?? ''}`, ); } } diff --git a/src/mesh/link.ts b/src/mesh/link.ts index ff50981..e02662a 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -451,7 +451,7 @@ export function connectLink(args: { }; /** Adopt an established session, or refuse it when its manifest no longer backs the graph. */ - const adopt = (session: Session, _attempt: number): boolean => { + const adopt = (session: Session): boolean => { const missing = missingFromManifest(link.manifest, session.manifest); if (missing.length > 0) { @@ -491,7 +491,7 @@ export function connectLink(args: { return; } - if (!adopt(session, attempt)) scheduleRetry(attempt); + if (!adopt(session)) scheduleRetry(attempt); } catch { // openSession's own abort listener already scheduled the retry through `onEnd`; a rejection // that never opened a socket (a bad URL, DNS) needs one scheduled here instead. @@ -501,7 +501,7 @@ export function connectLink(args: { return openSession(sessionArgs(() => endSession(0))).then((session) => { link.manifest = session.manifest; - adopt(session, 0); + adopt(session); return link; }); diff --git a/test/mesh/boot-retry.test.ts b/test/mesh/boot-retry.test.ts index 5b0bf2e..5a68b93 100644 --- a/test/mesh/boot-retry.test.ts +++ b/test/mesh/boot-retry.test.ts @@ -102,14 +102,40 @@ describe('mesh boot retry', () => { try { // exhausting the budget is no longer fatal by itself (that's the point of this change) — - // the boot still fails here because `who` needs 'auth' and nothing local provides it. - await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/); + // the boot still fails here because `who` needs 'auth' and nothing local provides it. The + // exact message, not a bare /mesh/ match (which would also match this message's own + // "(local or connected mesh)" wording for an unrelated reason). + await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow( + /needs 'auth' but nothing \(local or connected mesh\) provides it[\s\S]*did not connect/i, + ); expect(lines.some((l) => l.includes('starting without it'))).toBe(true); } finally { await teacup.close(); } }, 15_000); + it('names the absent teapot when a route handler needs its token directly', async () => { + // `who` needs 'auth' via `@needs`, not through a `@Step` — this goes through + // `assertNeedsSatisfiable`, a different check than `topoSort`'s, and must carry the same note. + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { + teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], + secret: 's', + bootTimeoutMs: 300, + }, + }); + + try { + await expect(teacup.ready()).rejects.toThrow( + /needs 'auth' but nothing \(local or connected mesh\) provides it[\s\S]*did not connect.*127\.0\.0\.1:9/i, + ); + } finally { + await teacup.close(); + } + }, 15_000); + it('does not retry a wrong secret — the teapot refused, and it will refuse again', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } }); const server = await teapot.listen(0); @@ -193,7 +219,9 @@ describe('mesh boot retry', () => { }); try { - await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/); + await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow( + /needs 'auth' but nothing \(local or connected mesh\) provides it[\s\S]*did not connect/i, + ); expect(lines.filter((l) => l.includes('of boot budget left'))).toEqual([]); } finally { await teacup.close(); From 9f5792c1c5234e7ef831bc8ebc77a8eb9cb15fe3 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 16:48:26 -0500 Subject: [PATCH 08/18] test(mesh): steps-only exports across Deno, Bun and the edge Deno and Bun mesh fixtures still exported a @Provider, which now throws at boot. Convert each to a @Step (provide() -> run(), move the class from providers: [] to steps: []) so the fixtures build a graph the current mesh actually allows. test/edge/_worker.mjs is a gitignored esbuild bundle rebuilt by test/edge/run.ts on every test:edge run, so no source change was needed there once the fixtures matched. All four suites pass: vitest (Node), deno test, bun test, and the workerd/miniflare edge run, plus typecheck. Signed-off-by: Diego Resendez --- test/bun/mesh-reconnect.test.ts | 8 ++++---- test/bun/mesh.test.ts | 8 ++++---- test/deno/mesh-interop.test.ts | 8 ++++---- test/deno/mesh-reconnect.test.ts | 8 ++++---- test/deno/mesh.test.ts | 8 ++++---- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/test/bun/mesh-reconnect.test.ts b/test/bun/mesh-reconnect.test.ts index 7fc379b..cdb2e8c 100644 --- a/test/bun/mesh-reconnect.test.ts +++ b/test/bun/mesh-reconnect.test.ts @@ -8,14 +8,14 @@ // Run with: npm run test:bun import 'reflect-metadata'; import { test, expect } from 'bun:test'; -import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts'; +import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts'; import { serveBun } from '../../src/bun.ts'; const SECRET = 's3cr3t'; -@Provider({ provides: 'config', export: true }) +@Step({ provides: 'config', needs: [], export: true }) class Config { - provide() { + run() { return { config: { runtime: 'bun' } }; } } @@ -25,7 +25,7 @@ class Auth { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } } -@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) +@Module({ mountpoint: '/api', steps: [Config, Auth] }) class TeapotModule {} @Route('/local') diff --git a/test/bun/mesh.test.ts b/test/bun/mesh.test.ts index 136a496..a5b2234 100644 --- a/test/bun/mesh.test.ts +++ b/test/bun/mesh.test.ts @@ -8,14 +8,14 @@ // Run with: npm run test:bun import 'reflect-metadata'; import { test, expect } from 'bun:test'; -import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts'; +import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts'; import { serveBun } from '../../src/bun.ts'; const SECRET = 's3cr3t'; -@Provider({ provides: 'config', export: true }) +@Step({ provides: 'config', needs: [], export: true }) class Config { - provide() { + run() { return { config: { region: 'mx', runtime: 'bun' } }; } } @@ -25,7 +25,7 @@ class Auth { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } } -@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) +@Module({ mountpoint: '/api', steps: [Config, Auth] }) class TeapotModule {} @Route('/local') diff --git a/test/deno/mesh-interop.test.ts b/test/deno/mesh-interop.test.ts index 9fae7d4..47f94ff 100644 --- a/test/deno/mesh-interop.test.ts +++ b/test/deno/mesh-interop.test.ts @@ -10,14 +10,14 @@ // Run with: npm run test:deno (needs --allow-run to spawn the Node peer) import 'npm:reflect-metadata'; import { assertEquals, assertStringIncludes } from 'jsr:@std/assert'; -import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts'; +import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts'; const SECRET = 's3cr3t'; const NODE_PEER = 'test/interop/_node-peer.ts'; -@Provider({ provides: 'config', export: true }) +@Step({ provides: 'config', needs: [], export: true }) class Config { - provide() { + run() { return { config: { region: 'mx', runtime: 'deno' } }; } } @@ -27,7 +27,7 @@ class Auth { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } } -@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) +@Module({ mountpoint: '/api', steps: [Config, Auth] }) class TeapotModule {} @Route('/local') diff --git a/test/deno/mesh-reconnect.test.ts b/test/deno/mesh-reconnect.test.ts index daaafd1..7b031e6 100644 --- a/test/deno/mesh-reconnect.test.ts +++ b/test/deno/mesh-reconnect.test.ts @@ -7,14 +7,14 @@ // Run with: npm run test:deno import 'npm:reflect-metadata'; import { assertEquals } from 'jsr:@std/assert'; -import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts'; +import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts'; import { serveDeno } from '../../src/deno.ts'; const SECRET = 's3cr3t'; -@Provider({ provides: 'config', export: true }) +@Step({ provides: 'config', needs: [], export: true }) class Config { - provide() { + run() { return { config: { runtime: 'deno' } }; } } @@ -24,7 +24,7 @@ class Auth { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } } -@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) +@Module({ mountpoint: '/api', steps: [Config, Auth] }) class TeapotModule {} @Route('/local') diff --git a/test/deno/mesh.test.ts b/test/deno/mesh.test.ts index cb8fc28..172f3c8 100644 --- a/test/deno/mesh.test.ts +++ b/test/deno/mesh.test.ts @@ -13,14 +13,14 @@ // including Node-only modules this test never executes. tsc covers those. import 'npm:reflect-metadata'; import { assertEquals, assertStringIncludes } from 'jsr:@std/assert'; -import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts'; +import { createApp, Step, Route, Get, Module, needs } from '../../src/index.ts'; import { serveDeno } from '../../src/deno.ts'; const SECRET = 's3cr3t'; -@Provider({ provides: 'config', export: true }) +@Step({ provides: 'config', needs: [], export: true }) class Config { - provide() { + run() { return { config: { region: 'mx', runtime: 'deno' } }; } } @@ -30,7 +30,7 @@ class Auth { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } } -@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] }) +@Module({ mountpoint: '/api', steps: [Config, Auth] }) class TeapotModule {} @Route('/local') From 03132b2048d407ceec0465d7ab7bbb2339f4dc79 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 16:55:26 -0500 Subject: [PATCH 09/18] docs(mesh): steps and routes are what a teapot exports MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CHANGELOG gains an [Unreleased] section — no version heading, no date — covering the three mesh changes on this branch and why each one follows from the first: a remote export is a step now, so it holds nothing between requests, so an absent teapot costs a 503 rather than a boot. The README says it in the Honest scope section, where the mesh caveats already live: what can be exported, what happens if you export a provider anyway, and why a missing token still fails the boot when an unreachable teapot no longer does. Two stale bits go with it. The JSDoc over assertNeedsSatisfiable still quoted the old unconditional message; the Deno and Bun fixtures still said a teapot exports its scopes. And the degrade plan's D6 planned to reuse a seam this branch deleted — a dated note says so, and why a degraded step never needed it. Signed-off-by: Diego Resendez --- CHANGELOG.md | 48 ++++++++++++++++++++++ README.md | 2 + docs/plans/2026-08-18-mesh-degrade-plan.md | 7 ++++ src/app/index.ts | 9 +++- test/bun/mesh.test.ts | 2 +- test/deno/mesh-interop.test.ts | 4 +- test/deno/mesh.test.ts | 2 +- 7 files changed, 69 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1edf726..c65bb14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,54 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since npm treats versions as semver and semver forbids leading zeros. +## [Unreleased] + +### Changed + +- **Mesh (alpha): only steps and routes can be exported.** `@Provider({ export: true })` now fails + the boot, with an error naming the provider and the replacement. A provider is a factory whose + value *is* the object it builds — a pool, a client, a `db` — and an object is not what a JSON wire + carries. What did cross was whatever half of it survived serialization, and it arrived as an + app-scope binding: the teacup resolved it once at boot and then served that value for the life of + the process, out of a cache the teapot no longer stood behind. Restarting the teapot, or changing + what it built, changed nothing on the teacup until the teacup itself restarted. + + Export a `@Step` instead. It runs on the teapot, per request, and only its result comes back — + which is why the two entries below follow from this one: a remote export now holds nothing between + requests. `invalidateRemoteBindings`, the `rebind` array and the `onReconnect` callback that drove + them are gone with it. All three existed to throw away a cached app-scope value when a link came + back; there is no longer a cached value, so a reconnected link is simply usable again on the next + RPC. Internal, so nothing importable changed. + + **A teapot that boots today can stop booting**, and the replacement is mechanical: the exported + `@Provider` becomes a `@Step` that returns what the provider's value carried. + +- **Mesh (alpha): an unreachable teapot no longer stops a teacup from booting.** Blocking was never + caution, it was arithmetic: an app-scope value has to resolve *at boot*, because there is no later + to resolve it in. A step is nothing but later. The `bootTimeoutMs` grace still waits, since "the + container is thirty seconds behind" and "the teapot does not exist" look identical for the first + thirty seconds; exhausting it now warns and starts without that teapot, whose steps and routes + answer `503`. Refusing to start took down the half of the teacup that never needed that teapot at + all, and moved a `503` on some requests into an outage on every one of them. + + Two conditions still fail the boot, both deliberately. A **permanent refusal** — a wrong secret, + a protocol mismatch — is the teapot's decision rather than the network's, and it will be the same + decision in thirty seconds; retrying only spends the deploy's patience to arrive at the identical + error. And a local step that **needs a token nothing provides** still fails, because that check is + what catches a typo in a token name, and a typo does not come good by waiting. That error now + names the teapots that did not connect, and says "local or connected mesh" rather than "local or + mesh" — the old wording claimed a search that had not happened. + +- **Mesh (alpha): the manifest carries step names.** `{ scopes: [{ token, scope }], routes }` is now + `{ steps: string[], routes }`. Every export is request-scope after the change above, so the + lifetime field had one possible value left and told a reader nothing. A manifest step that is not + a string is now rejected on arrival, rather than trusted because a peer sent it. + + `MESH_PROTOCOL_VERSION` deliberately stays at `1`. Mesh is alpha behind `experimental: true`, both + peers ship from this repository, and there is no deployed pair of versions for a bump to protect — + it would spend the number on nobody. A stable wire would not get that option; alpha is exactly + what the word buys, and this is the last comfortable moment to use it. + ## [26.9.0-beta.1] - 2026-09-04 ### Added diff --git a/README.md b/README.md index 9dfcc8e..3fe23b3 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,8 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h **mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet. +**What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what makes an absent teapot survivable. A remote step holds nothing between requests, so a teacup whose teapot never answers still boots once the `bootTimeoutMs` grace runs out — it warns, starts without it, and that teapot's steps and routes answer `503` until it arrives. What still fails the boot is a local step that `@needs` a token *nothing* provides, and that is deliberate: it is the check that catches a typo in a token name, which no amount of waiting will fix. The error names the teapots that did not connect, so the two cases read differently. + **What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which gained `onShutdown` this week; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it. ## Docs & development diff --git a/docs/plans/2026-08-18-mesh-degrade-plan.md b/docs/plans/2026-08-18-mesh-degrade-plan.md index d38bc85..753d61f 100644 --- a/docs/plans/2026-08-18-mesh-degrade-plan.md +++ b/docs/plans/2026-08-18-mesh-degrade-plan.md @@ -64,6 +64,13 @@ instead of a boot manifest. (`invalidateRemoteBindings`). If that seam turns out not to fit, that is a signal the seam was wrong, not a reason to write a second one. +**Note, 2026-09-06: that seam is gone.** `invalidateRemoteBindings`, the `rebind` array and the +`onReconnect` callback were removed along with the remote app-scope binding when the mesh stopped +exporting providers — with nothing cached between requests, there is nothing left to invalidate. +This does not block D6, and it is not the "seam was wrong" case either: a degraded token swaps the +*runner* behind a step node, which is a graph mutation, not a container rebind. It never needed the +seam. Whatever the swap is written on, it is still one mechanism, decided when the work starts. + ## Tasks 1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without diff --git a/src/app/index.ts b/src/app/index.ts index b359ac2..b19fe52 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -699,7 +699,14 @@ function finalizeGraph( return { orderedProviders, orderedSteps }; } -/** Throws if any route needs a key that nothing (local or mesh) provides, suggesting the nearest match. */ +/** + * Throws if any route needs a key that nothing provides, suggesting the nearest match. + * + * `missingNote` arrives only from a mesh boot, and only when a teapot did not connect. It changes + * what the message can honestly claim: "local or connected mesh" instead of "local or mesh", since + * the exports of an absent teapot were never searched — and it appends which teapots those were, + * which is the actual cause every time it is the cause. + */ function assertNeedsSatisfiable( routePlans: RoutePlan[], providerNodes: GraphNode[], diff --git a/test/bun/mesh.test.ts b/test/bun/mesh.test.ts index a5b2234..d4410ab 100644 --- a/test/bun/mesh.test.ts +++ b/test/bun/mesh.test.ts @@ -1,4 +1,4 @@ -// Real Bun integration test for mesh: a teapot exporting its scopes and a teacup consuming +// Real Bun integration test for mesh: a teapot exporting its steps and a teacup consuming // them, both under the actual Bun runtime, driven entirely through serveBun. // // Bun's ws lifecycle differs from Deno's — its socket events land on a server-level handler diff --git a/test/deno/mesh-interop.test.ts b/test/deno/mesh-interop.test.ts index 47f94ff..423175e 100644 --- a/test/deno/mesh-interop.test.ts +++ b/test/deno/mesh-interop.test.ts @@ -112,7 +112,7 @@ Deno.test('interop: a Deno teacup consumes a Node teapot', async () => { try { const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } })); assertEquals(res.status, 200); - // the config came from the Node process: proof the scope crossed the runtime boundary + // the config came from the Node process: proof the remote step crossed the runtime boundary assertEquals(await res.json(), { config: { region: 'mx', runtime: 'node' }, auth: { token: 'abc' }, @@ -140,7 +140,7 @@ Deno.test('interop: a Node teacup consumes a Deno teapot', async () => { try { const result = await firstJsonLine(node); assertEquals(result.ok, true); - // the Node peer resolved a scope served by Deno's app.upgrade control channel + // the Node peer ran a step served by Deno's app.upgrade control channel assertEquals(result.body.config, { region: 'mx', runtime: 'deno' }); assertEquals(result.body.auth, { token: 'abc' }); } finally { diff --git a/test/deno/mesh.test.ts b/test/deno/mesh.test.ts index 172f3c8..41d71ec 100644 --- a/test/deno/mesh.test.ts +++ b/test/deno/mesh.test.ts @@ -1,4 +1,4 @@ -// Real Deno integration test for mesh: a teapot exporting its scopes and a teacup consuming +// Real Deno integration test for mesh: a teapot exporting its steps and a teacup consuming // them, both under the actual Deno runtime, driven entirely through serveDeno. // // This is the test that makes "mesh runs off Node" a fact rather than an intention. It covers, From f5d4d0cd7412e01fe0baa00575e86ddbdb46198a Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 17:05:49 -0500 Subject: [PATCH 10/18] docs(mesh): an absent teapot 404s, it does not 503 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A teapot that never connected sent no manifest, so spliceRemoteScopes registers nothing for it — no step runner, no route. Its routes therefore take the ordinary unmatched path and 404, and a local node that needs one of its tokens still fails the boot naming it. The 503 belongs to a teapot that connected and later died, where the link and its exports exist and the dead-link guard answers. The previous commit said 503 for the absent case in five places, including the warning an operator reads during a deploy. All five now tell the same story, and the bootTimeoutMs JSDoc — stale in the other direction, still claiming an absent teapot fails the boot — with them. The connectUntilDeadline JSDoc also had a paragraph saying it still throws, contradicted three paragraphs later; that one is gone. No behaviour changed. Serving 503 for an absent teapot's tokens means knowing what it would have exported, which is the expects list in the degrade plan and is deliberately not built. Signed-off-by: Diego Resendez --- CHANGELOG.md | 31 +++++++++++++++++++++---------- README.md | 2 +- src/app/index.ts | 27 +++++++++++++++++---------- src/app/types.ts | 12 ++++++++---- 4 files changed, 47 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c65bb14..cee632e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,17 +32,28 @@ npm treats versions as semver and semver forbids leading zeros. caution, it was arithmetic: an app-scope value has to resolve *at boot*, because there is no later to resolve it in. A step is nothing but later. The `bootTimeoutMs` grace still waits, since "the container is thirty seconds behind" and "the teapot does not exist" look identical for the first - thirty seconds; exhausting it now warns and starts without that teapot, whose steps and routes - answer `503`. Refusing to start took down the half of the teacup that never needed that teapot at - all, and moved a `503` on some requests into an outage on every one of them. + thirty seconds; exhausting it now warns and starts without that teapot. - Two conditions still fail the boot, both deliberately. A **permanent refusal** — a wrong secret, - a protocol mismatch — is the teapot's decision rather than the network's, and it will be the same - decision in thirty seconds; retrying only spends the deploy's patience to arrive at the identical - error. And a local step that **needs a token nothing provides** still fails, because that check is - what catches a typo in a token name, and a typo does not come good by waiting. That error now - names the teapots that did not connect, and says "local or connected mesh" rather than "local or - mesh" — the old wording claimed a search that had not happened. + What that buys is narrower than it sounds, and worth stating exactly. A teapot that never + connected sent no manifest, so the teacup learned nothing about it — no step runners, no routes, + a graph identical to the one it would have had if that teapot were never configured. Its routes + therefore **404**, through the ordinary unmatched-route path, because nothing was ever registered + to match. And any local step or handler that needs one of its tokens **still fails the boot**, + naming the teapot that did not connect. `503` is what a teapot that connected and *later* died + answers: that link exists, its steps and routes are registered, and the dead link is what returns + the status. Never reachable and reachable-then-gone are different situations, and they read + differently on purpose. + + So the change is for the teacup that does *not* depend on that teapot: it starts, rather than + refusing over a dependency it never had. It is not graceful degradation of the dependency, and + cannot be — answering `503` for an absent teapot's tokens means knowing what it *would* have + exported, and only a declaration can say. That declaration is the `expects` list in + `docs/plans/2026-08-18-mesh-degrade-plan.md`, which is planned and not built. Two things are + unchanged: a **permanent refusal** — a wrong secret, a protocol mismatch — still fails the boot + without spending the grace, because it is the teapot's decision rather than the network's and will + be the same decision in thirty seconds; and the missing-token error, which now says "local or + connected mesh" rather than "local or mesh", the old wording having claimed a search that never + happened. - **Mesh (alpha): the manifest carries step names.** `{ scopes: [{ token, scope }], routes }` is now `{ steps: string[], routes }`. Every export is request-scope after the change above, so the diff --git a/README.md b/README.md index 3fe23b3..1a4883d 100644 --- a/README.md +++ b/README.md @@ -286,7 +286,7 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h **mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet. -**What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what makes an absent teapot survivable. A remote step holds nothing between requests, so a teacup whose teapot never answers still boots once the `bootTimeoutMs` grace runs out — it warns, starts without it, and that teapot's steps and routes answer `503` until it arrives. What still fails the boot is a local step that `@needs` a token *nothing* provides, and that is deliberate: it is the check that catches a typo in a token name, which no amount of waiting will fix. The error names the teapots that did not connect, so the two cases read differently. +**What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is the `expects` list in [the mesh degrade plan](./docs/plans/2026-08-18-mesh-degrade-plan.md), which is planned and not built. **What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which gained `onShutdown` this week; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it. diff --git a/src/app/index.ts b/src/app/index.ts index b19fe52..fdacab7 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -755,18 +755,21 @@ function assertNeedsSatisfiable( * * The grace exists because "the container is thirty seconds behind" and "the teapot does not * exist" look identical for the first thirty seconds, and only one of them should stop a deploy. - * When the deadline passes it still throws: a provider the graph depends on is not optional, and - * booting without it would only move the failure to the first request, where it becomes a caller's - * 503 instead of the deploy's error. * * Each failed attempt is both logged and emitted as `mesh:boot:retry` — logged so an operator * watching a deploy sees why it is taking so long, emitted so the wait is visible to whatever * collects lifecycle events rather than only to whoever is reading a terminal. * - * Exhausting the budget no longer throws (D4 keeps the one exception: a permanent refusal still - * does). Every export a teapot makes is now lazy — a request-scope step or a proxied route — so - * nothing needs it resolved by boot; an absent teapot only costs a 503 on the requests that need - * it, and a teacup that refuses to start would take down the half of itself that never did. + * Exhausting the budget returns `undefined` rather than throwing (D4 keeps the one exception: a + * permanent refusal still does). Every export a teapot makes is lazy now — a request-scope step or + * a proxied route — so nothing needed this link resolved by boot, and a teacup that refuses to + * start takes down the half of itself that never needed the teapot. + * + * Returning `undefined` is not the same as degrading it. The caller registers nothing for a link it + * never got, because a teapot that did not connect sent no manifest and so nobody knows what it + * would have exported. Its routes 404 like any unregistered path, and a local node that needs one + * of its tokens still fails the boot in finalize(), named. Serving 503 for those tokens instead + * needs an `expects` declaration — see docs/plans/2026-08-18-mesh-degrade-plan.md, still planned. */ async function connectUntilDeadline( mesh: MeshConfig, @@ -795,12 +798,16 @@ async function connectUntilDeadline( } // The budget is a grace for a co-deploy, not a requirement. Every export is a lazy step or a - // proxied route now, so an absent teapot costs a 503 on the requests that need it — and a - // teacup that refuses to start takes down the half of itself that never needed the teapot. + // proxied route now, so nothing needed this link resolved by boot, and a teacup that refuses + // to start takes down the half of itself that never needed the teapot. What starting does NOT + // do is degrade the dependency: an absent teapot sent no manifest, so it contributes no nodes + // at all — its routes 404 and a local `needs` on its tokens still fails in finalize(). if (remaining <= 0) { logger.warn( `mesh: teapot unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` + - `(${(error as Error).message}) — starting without it; its steps and routes will 503`, + `(${(error as Error).message}) — starting without it. It sent no manifest, so none of ` + + `its steps or routes are in this graph: its routes 404, and the boot still fails if ` + + `anything local needs one of its tokens.`, ); return undefined; } diff --git a/src/app/types.ts b/src/app/types.ts index 6e9626c..1483896 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -136,10 +136,14 @@ export interface MeshConfig { * so 30s). Attempts use the same backoff as reconnection. * * A teapot that is merely slow to start — a container scheduled a moment later, a network that - * has not settled — should not fail a deploy, and this is the grace for that. A teapot that is - * genuinely absent still fails the boot when the deadline passes, because a provider the graph - * depends on is not optional: booting without it would only move the failure to the first - * request, where it is somebody else's 503 instead of your deploy's error. + * has not settled — should not fail a deploy, and this is the grace for that. When the deadline + * passes the teacup warns and starts anyway: every export is a step or a proxied route, so + * nothing needed that link resolved by boot. + * + * Starting is not degrading, though. A teapot that never connected sent no manifest, so none of + * its steps or routes are registered: its routes 404 rather than 503, and a local node that needs + * 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. * * `0` restores the old behaviour of a single attempt. */ From 1bcaa463f2276f1a8e95e10e91ebf0324ceadac3 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 17:36:50 -0500 Subject: [PATCH 11/18] fix(mesh): a rejected first connect no longer leaks a retry supervisor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit openSession's abort listener runs onEnd -> endSession -> scheduleRetry on every socket abort, including the ones where the connect promise rejected. A rejected connect means no caller ever received the Link, so nothing can close it and closeLinks never sees it — connectUntilDeadline pushes to meshLinks only on success. Every boot attempt against an unreachable teapot therefore left a live supervisor behind, reconnecting forever on a handle nobody holds. Before this branch the boot then threw and the process died with them. Now the teacup starts without that teapot, so they outlive the boot: close() the teacup, bring the teapot up afterwards, and three mesh:connect events fire for a URL contributing nothing to the graph, each holding an open socket. The initial openSession now marks the link closed and clears the pending timer before rethrowing. connectUntilDeadline is already the retry loop above this; a second one underneath it was never wanted. Reconnection for a link that did connect is untouched — that path runs through endSession on a session that dropped after the Link escaped, and the rejection handler here fires only on the first connect. The regression test asserts both sides: no mesh:connect on the teacup, and none on the teapot either, so a socket that opens without being adopted still fails it. Signed-off-by: Diego Resendez --- src/mesh/link.ts | 25 ++++++++++++--- test/mesh/boot-retry.test.ts | 62 ++++++++++++++++++++++++++++++++---- 2 files changed, 75 insertions(+), 12 deletions(-) diff --git a/src/mesh/link.ts b/src/mesh/link.ts index e02662a..1cd38de 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -499,10 +499,25 @@ export function connectLink(args: { } }; - return openSession(sessionArgs(() => endSession(0))).then((session) => { - link.manifest = session.manifest; - adopt(session); + return openSession(sessionArgs(() => endSession(0))).then( + (session) => { + link.manifest = session.manifest; + adopt(session); - return link; - }); + return link; + }, + (error) => { + // The first connect failed, so this `Link` never escaped — nobody holds it and nobody can + // ever call `close()` on it. But `openSession`'s abort listener has already run `onEnd`, + // which scheduled a retry: left alone, that supervisor reconnects forever to a handle no + // caller has, and `closeLinks` cannot reach it because the link was never pushed to + // `meshLinks`. Boot already retries above this (`connectUntilDeadline`), so a second + // supervisor underneath it is pure leak — every failed attempt used to leave one behind. + // Reconnection for a link that *did* connect is untouched: this path runs only on the + // initial rejection, and a session that drops later still goes through `endSession`. + state.closed = true; + clearTimeout(state.retry); + throw error; + }, + ); } diff --git a/test/mesh/boot-retry.test.ts b/test/mesh/boot-retry.test.ts index 5a68b93..3ee4ae1 100644 --- a/test/mesh/boot-retry.test.ts +++ b/test/mesh/boot-retry.test.ts @@ -43,6 +43,16 @@ class NeedsAuth { @Module({ mountpoint: '/api', steps: [NeedsAuth] }) class NeedsAuthModule {} +/** A free port, taken by opening and immediately closing a server on port 0. */ +const freePort = async (): Promise => + new Promise((resolve) => { + const probe = net.createServer(); + probe.listen(0, () => { + const { port } = probe.address() as { port: number }; + probe.close(() => resolve(port)); + }); + }); + const collect = () => { const lines: string[] = []; return { lines, logger: { debug() {}, info() {}, warn: (m: string) => lines.push(m), error: (m: string) => lines.push(m) } }; @@ -50,13 +60,7 @@ const collect = () => { describe('mesh boot retry', () => { it('waits for a teapot that starts late, rather than failing the deploy', async () => { - const port = await new Promise((resolve) => { - const probe = net.createServer(); - probe.listen(0, () => { - const { port: p } = probe.address() as { port: number }; - probe.close(() => resolve(p)); - }); - }); + const port = await freePort(); const { lines, logger } = collect(); const teacup = createApp({ @@ -205,6 +209,50 @@ describe('mesh boot retry', () => { } }, 15_000); + it('leaves no reconnect supervisor behind when the boot never reached its teapot', async () => { + // Every failed boot attempt used to leak one. `openSession`'s abort listener runs `onEnd` even + // when the connect promise *rejects*, and `onEnd` schedules a retry — but a link that never + // resolved was never handed to anyone, so it was never pushed to `meshLinks` and `close()` + // could not reach it. Before the app was allowed to start without a teapot the process died + // with them; now it survives, and each one holds a socket open forever. + const port = await freePort(); + const { logger } = collect(); + const teacupConnects: string[] = []; + + const teacup = createApp({ + modules: [LocalOnlyModule], // nothing local needs the teapot, so the boot is allowed to finish + experimental: true, + logger, + mesh: { + teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }], + timeoutMs: 200, + bootTimeoutMs: 600, // several attempts, each of which used to leave a supervisor running + reconnect: { initialDelayMs: 20, maxDelayMs: 60 }, // a leak would hammer, not trickle + }, + }); + teacup.bus.on('mesh:connect', (event) => teacupConnects.push(event.name)); + + await teacup.ready(); + await teacup.close(); + + // Only now does the teapot arrive. Nothing in this process holds a link to it. + const teapotConnects: string[] = []; + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } }); + teapot.bus.on('mesh:connect', (event) => teapotConnects.push(event.name)); + const server = await teapot.listen(port); + + try { + await new Promise((r) => setTimeout(r, 500)); // ~8 retries at the bounds above + + expect(teacupConnects).toEqual([]); + // the teapot side, so this fails on a socket that opened even if the teacup never adopted it + expect(teapotConnects).toEqual([]); + } finally { + await teapot.close(); + server.close(); + } + }, 15_000); + it('bootTimeoutMs: 0 makes one attempt, as before', async () => { const { lines, logger } = collect(); const teacup = createApp({ From bff87781129b81cc9efa632d8ecf173b928c5b85 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 17:37:00 -0500 Subject: [PATCH 12/18] refactor(mesh): @Provider's options no longer advertise `export` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The framework's public type offered an option whose only behaviour is to throw at boot. Removing the field from the options type means a TypeScript caller gets a compile error at the decorator, where the mistake is, instead of a boot error a deploy away. The runtime throw in collectProviders stays as the JavaScript backstop, so ProviderMeta keeps the field and the decorator still records it through a cast — a JS caller reaches the error naming the provider and its replacement rather than having the option silently ignored. The `as any` in the boot-throw test is now genuinely load-bearing, since no TypeScript caller can write that decorator at all, and says so. test/metadata.test.ts asserted the flag was stored for a provider. That half described the option working, which is the message being removed, and the boot throw it fed is already covered end to end in test/mesh/failure.test.ts. The default is a different claim and stays: collectProviders throws on anything truthy, so every plain provider recording `false` is what keeps ordinary apps booting. Signed-off-by: Diego Resendez --- src/metadata.ts | 18 +++++++++++------- test/mesh/failure.test.ts | 3 +++ test/metadata.test.ts | 9 ++++++--- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/src/metadata.ts b/src/metadata.ts index 660225a..8e63175 100644 --- a/src/metadata.ts +++ b/src/metadata.ts @@ -15,6 +15,12 @@ export interface ProviderMeta { provides: string; needs: string[]; optional: boolean; + /** + * Always refused. `@Provider`'s options no longer declare `export`, so TypeScript rejects it at + * the decorator and this can only be true for a JavaScript caller. It is still recorded so that + * caller reaches `collectProviders`' boot error, which names the provider and the replacement, + * rather than having the option silently ignored. + */ export: boolean; } /** Metadata attached by `@Step`: what it provides, what it needs, and its visibility. */ @@ -58,18 +64,16 @@ const K = { }; /** Marks a class as a provider: a lazily-built dependency addressable by its `provides` key. */ -export function Provider(opts: { - provides: string; - needs?: string[]; - optional?: boolean; - export?: boolean; -}): ClassDecorator { +export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean }): ClassDecorator { return (target) => { const meta: ProviderMeta = { provides: opts.provides, needs: opts.needs ?? [], optional: opts.optional ?? false, - export: opts.export ?? false, + // Read through a cast because the options type deliberately does not offer `export`: only a + // `@Step` or a route is exportable, and the option's only behaviour was to throw at boot. + // A JavaScript caller can still pass it, and recording it is what routes them to that error. + export: (opts as { export?: boolean }).export ?? false, }; Reflect.defineMetadata(K.provider, meta, target); }; diff --git a/test/mesh/failure.test.ts b/test/mesh/failure.test.ts index 4333874..8d78c46 100644 --- a/test/mesh/failure.test.ts +++ b/test/mesh/failure.test.ts @@ -124,6 +124,9 @@ describe('mesh link failure', () => { describe('provider export', () => { it('refuses to boot when a provider is exported over the mesh', async () => { + // `as any` is load-bearing, not laziness: `export` is not in `@Provider`'s options type, so a + // TypeScript caller cannot write this at all. The cast is how the test reaches the runtime + // backstop that a JavaScript caller would hit. @Provider({ provides: 'db', needs: [], export: true } as any) class Db { provide() { diff --git a/test/metadata.test.ts b/test/metadata.test.ts index f41546e..7293a74 100644 --- a/test/metadata.test.ts +++ b/test/metadata.test.ts @@ -67,12 +67,15 @@ describe('HEAD and OPTIONS decorators', () => { }); describe('mesh export flags', () => { - it('providers/steps carry export (default false)', () => { - @Provider({ provides: 'config', export: true }) class C { provide() { return {}; } } + it('steps carry export, and a provider defaults to not exported', () => { @Step({ provides: 'auth', export: true }) class A { run() { return {}; } } @Provider({ provides: 'priv' }) class P { provide() { return {}; } } - expect(getProviderMeta(C)!.export).toBe(true); expect(getStepMeta(A)!.export).toBe(true); + // No `export: true` case for a provider: the option is gone from `@Provider`'s type, and its + // only behaviour is the boot throw that `test/mesh/failure.test.ts` covers end to end — + // asserting it is *stored* here would assert the option works. The default is a different + // claim and still load-bearing: `collectProviders` throws on anything truthy, so every plain + // provider recording `false` is what keeps ordinary apps booting. expect(getProviderMeta(P)!.export).toBe(false); }); From 727987286b235c4ceeeab941097ed19872977f22 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 17:37:06 -0500 Subject: [PATCH 13/18] refactor(graph): the missing-dependency note is a string, not a callback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit topoSort, finalizeGraph, assertNeedsSatisfiable and finalize all threaded a `(key: string) => string`, and no caller ever read `key` — the one producer, in prepareGraph, is `() => ...`. The note names which teapots did not connect, which does not vary by token, so the parameter was machinery for a customization nothing asked for. Signed-off-by: Diego Resendez --- src/app/index.ts | 10 +++++----- src/graph.ts | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index fdacab7..b486129 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -221,7 +221,7 @@ export function createApp(opts: { let remoteRoutes: RouteDef[] = []; const meshLinks: Link[] = []; - const finalize = (missingNote?: (key: string) => string): void => { + const finalize = (missingNote?: string): void => { ({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote)); booted = true; }; @@ -244,7 +244,7 @@ export function createApp(opts: { // 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. const meshNote = spliced.absent.length - ? () => ` — these teapots did not connect, so their exports are absent: ${spliced.absent.join(', ')}` + ? ` — these teapots did not connect, so their exports are absent: ${spliced.absent.join(', ')}` : undefined; finalize(meshNote); } @@ -667,7 +667,7 @@ function finalizeGraph( registry: Registry, logger: Logger, warnDepth: number | false = DEEP_GRAPH_WARN, - missingNote?: (key: string) => string, + missingNote?: string, ): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } { const { providerNodes, stepNodes, routePlans } = registry; const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params'], missingNote); @@ -711,7 +711,7 @@ function assertNeedsSatisfiable( routePlans: RoutePlan[], providerNodes: GraphNode[], stepNodes: GraphNode[], - missingNote?: (key: string) => string, + missingNote?: string, ): void { const producedKeys = new Set([ ...providerNodes.flatMap((node) => node.provides), @@ -744,7 +744,7 @@ function assertNeedsSatisfiable( const scope = missingNote ? 'local or connected mesh' : 'local or mesh'; throw new Error( `handler '${plan.handlerName}' needs '${need}' but nothing (${scope}) provides it` + - `${hint ? ` — did you mean '${hint}'?` : ''}${missingNote?.(need) ?? ''}`, + `${hint ? ` — did you mean '${hint}'?` : ''}${missingNote ?? ''}`, ); } } diff --git a/src/graph.ts b/src/graph.ts index 66c8d4d..14fd57b 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -43,7 +43,7 @@ export interface GraphNode { } /** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */ -export function topoSort(nodes: GraphNode[], seedKeys: string[], note?: (key: string) => string): GraphNode[] { +export function topoSort(nodes: GraphNode[], seedKeys: string[], note = ''): GraphNode[] { const producedBy = new Map(); for (const node of nodes) for (const key of node.provides) producedBy.set(key, node); @@ -51,7 +51,7 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[], note?: (key: st for (const node of nodes) { for (const key of node.needs) { if (!seedKeys.includes(key) && !producedBy.has(key)) { - throw new Error(`missing dependency: ${key} needed by ${node.name}${note?.(key) ?? ''}`); + throw new Error(`missing dependency: ${key} needed by ${node.name}${note}`); } } } From e69f604053bec72fa81c84f3fd9302ba04f2189e Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 17:37:24 -0500 Subject: [PATCH 14/18] docs(mesh): record the scopes->steps rename as an exception to the bump rule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The bump rule in protocol.ts says renaming a field earns a protocol bump, and this branch renamed the manifest's `scopes` to `steps` at v1 without one. The argument for that lived only in the CHANGELOG, so the rule as written read as simply broken to anyone who found it from the code. The exception is now stated where the rule is, with the three conditions it rests on: mesh is alpha, every app using it is gated behind `experimental: true`, and both peers ship out of this repo, so no deployed pair can be split across the rename. It retires with the first mesh release that drops `experimental`. Two other stale pointers go with it. The bootTimeoutMs JSDoc said `0` restores "the old behaviour of a single attempt", which now reads as restoring a boot that failed — it is only the attempt count, and the way to make a teapot's absence fatal is a local `@needs` on one of its tokens. And the reconnect plan's step 4 still pointed at invalidateRemoteBindings, which this branch deleted; it gets a dated note in the same shape as the degrade plan's D6. Signed-off-by: Diego Resendez --- docs/plans/2026-08-18-mesh-reconnect-plan.md | 6 ++++++ src/app/types.ts | 4 +++- src/mesh/protocol.ts | 8 ++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/docs/plans/2026-08-18-mesh-reconnect-plan.md b/docs/plans/2026-08-18-mesh-reconnect-plan.md index ca91795..e9da086 100644 --- a/docs/plans/2026-08-18-mesh-reconnect-plan.md +++ b/docs/plans/2026-08-18-mesh-reconnect-plan.md @@ -85,6 +85,12 @@ not a wait for `timeoutMs`. 3. **Manifest comparison.** Capture the contributed set at boot, compare per D4, reuse `compilePattern(...).shape` for routes. Refusal logs the missing token or route by name. 4. **`invalidateRemoteBindings(link)`** per D8, called on successful reconnect. + + **Note, 2026-09-06:** this no longer exists. When the mesh stopped exporting providers, the + remote app-scope binding went with it, and `invalidateRemoteBindings`, the `rebind` array and the + `onReconnect` callback went with that — there is no cached value left to invalidate, so a + reconnected link is simply usable again on the next RPC. The rest of this plan shipped as + written; only this step has no counterpart in the code. 5. **Config**: `mesh: { reconnect?: boolean | { initialDelayMs?, maxDelayMs? }, onManifestChange?: 'refuse' }`. Reconnect defaults **on**. Validate at boot like the other mesh options. 6. **Tests.** Reconnect after the teapot returns; refuse when a token disappears, with the message diff --git a/src/app/types.ts b/src/app/types.ts index 1483896..e597582 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -145,7 +145,9 @@ export interface MeshConfig { * one of its tokens still fails the boot, naming it. A permanent refusal — a wrong secret, a * protocol mismatch — fails at once without spending the grace. * - * `0` restores the old behaviour of a single attempt. + * `0` means one attempt and no grace. That is the attempt count boot used to have, and nothing + * more: exhausting it no longer fails the boot, so a single unreachable teapot still warns and + * starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens. */ bootTimeoutMs?: number; } diff --git a/src/mesh/protocol.ts b/src/mesh/protocol.ts index 85d082f..2af6f86 100644 --- a/src/mesh/protocol.ts +++ b/src/mesh/protocol.ts @@ -18,6 +18,14 @@ * * Bumping per change would make the number mean "work happened" rather than "we are * incompatible", which is the one thing it is here to say. + * + * **One exception has been taken, and its terms are the point.** The manifest's `scopes` field was + * renamed to `steps` at v1 — a rename, which the first rule above would otherwise cover — without a + * bump. It was allowed because there is no deployed pair the rename could split: mesh is alpha, + * every app using it is gated behind `experimental: true`, and both peers ship out of this one + * repo, so a teacup and a teapot are always on the same version. Each of those three has to hold + * for the exception to; the first mesh release that drops `experimental` retires it, and a rename + * after that earns a bump like any other. */ export const MESH_PROTOCOL_VERSION = 1; From 8ef7c3ee14188ba6c4a7efe83e26187e75107b1b Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 17:37:26 -0500 Subject: [PATCH 15/18] fix(mesh): validate the manifest's route entries, not just its steps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit decode is the mesh's trust boundary, and the steps array gained a per-element check on this branch while the routes array beside it kept only its Array.isArray. A peer sending `{ method: 5, pattern: {} }` got past decode and died in compilePattern as a boot TypeError — it failed closed, so nothing was exposed, but the error blamed green-tea for what was a malformed frame from the other side. Both fields reach compilePattern, so both are checked. Signed-off-by: Diego Resendez --- src/mesh/protocol.ts | 7 +++++++ test/mesh/protocol.test.ts | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/mesh/protocol.ts b/src/mesh/protocol.ts index 2af6f86..54d1a78 100644 --- a/src/mesh/protocol.ts +++ b/src/mesh/protocol.ts @@ -88,6 +88,9 @@ export type Frame = const isString = (value: unknown): value is string => typeof value === 'string'; const isNumber = (value: unknown): boolean => typeof value === 'number'; const isObject = (value: unknown): boolean => typeof value === 'object' && value !== null; +/** A manifest route entry: both fields reach `compilePattern`, so both must really be strings. */ +const isRouteEntry = (value: unknown): boolean => + isObject(value) && isString((value as RouteEntry).method) && isString((value as RouteEntry).pattern); /** Rejects a frame whose fields don't match its `type` tag. `bad` always throws. */ type ShapeCheck = (frame: Record, bad: (why: string) => never) => void; @@ -108,6 +111,10 @@ const SHAPE: Record = { // Array.isArray above already guarantees this, but TS does not carry that narrowing through a // `never`-typed callback parameter — the cast is safe, not a bypass. if (!(frame.steps as unknown[]).every(isString)) bad('every step must be a string'); + // Checked for the same reason steps are: past `decode` a route entry goes straight to + // `compilePattern`, where a non-string `pattern` dies as a boot `TypeError` about a peer's + // frame — a failure that reads like a green-tea bug rather than a malformed manifest. + if (!(frame.routes as unknown[]).every(isRouteEntry)) bad('every route must have a string method and pattern'); }, 'rpc-req': (frame, bad) => { if (!isString(frame.id)) bad('id must be a string'); diff --git a/test/mesh/protocol.test.ts b/test/mesh/protocol.test.ts index 67323a8..e15e24f 100644 --- a/test/mesh/protocol.test.ts +++ b/test/mesh/protocol.test.ts @@ -38,6 +38,18 @@ describe('protocol codec', () => { ); }); + it('rejects a manifest whose routes array contains a malformed entry', () => { + // Not a hole that was open — `compilePattern` would have thrown downstream — but it threw a + // `TypeError` at boot instead of naming the peer's frame as the malformed thing it is. + const routes = [{ method: 5, pattern: {} }]; + expect(() => decode(JSON.stringify({ type: 'manifest', v: V, steps: [], routes }))).toThrow( + /every route must have a string method and pattern/, + ); + expect(() => decode(JSON.stringify({ type: 'manifest', v: V, steps: [], routes: ['GET /x'] }))).toThrow( + /every route must have a string method and pattern/, + ); + }); + it('throws on malformed json', () => { expect(() => decode('{not json')).toThrow(); }); From 6e050197b6faef77933ba6e740c06894f56cb86b Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 17:37:32 -0500 Subject: [PATCH 16/18] test(mesh): drop the buildRemote case its neighbour already subsumes 'turns every manifest step into a lazy remote node' built the same thing as the test directly below it and asserted less about it: one step token instead of two, no assertion on what the RPC was called with. Two tests covering one behaviour, one of them strictly weaker. Signed-off-by: Diego Resendez --- test/mesh/teacup.test.ts | 9 --------- 1 file changed, 9 deletions(-) diff --git a/test/mesh/teacup.test.ts b/test/mesh/teacup.test.ts index 0920194..a5023ec 100644 --- a/test/mesh/teacup.test.ts +++ b/test/mesh/teacup.test.ts @@ -9,15 +9,6 @@ const fakeLink = (calls: any[]): Link => ({ }); describe('teacup buildRemote', () => { - it('turns every manifest step into a lazy remote node', async () => { - const link = { manifest: { steps: ['auth'], routes: [] }, rpc: async () => ({ ok: true }) } as any; - const { steps, routes } = buildRemote(link); - - expect(routes).toEqual([]); - expect(steps.map((s: any) => s.name)).toEqual(['auth']); - expect(await steps[0].run({})).toEqual({ auth: { ok: true } }); - }); - it('makes a step node per manifest token, with RPC runners returning merge objects', async () => { const calls: any[] = []; const { steps } = buildRemote(fakeLink(calls)); From 249fc00f8001bd56e302f03d753a9b0fab444561 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 17:50:18 -0500 Subject: [PATCH 17/18] fix(mesh): name the teapot in the boot log a later 404 points back to A route the absent teapot would have exported 404s, and that is the right status: nothing was ever registered for a manifest that never arrived, so there is no path to serve. But a bare 404 is indistinguishable from a typo in the path, and the boot log is the only place the two are told apart. It could not tell them apart either. The give-up warning relied on the error's own message to identify the teapot, which holds for a refusal -- `mesh handshake failed: ` -- but not for an unreachable one, where the error is a socket error that may carry no url at all. So the url is passed in now, and every line of the boot-connect story names it: the retries, the refusal, and the give-up. The give-up line also says no manifest was ever exchanged, which is the fact that explains the 404. Signed-off-by: Diego Resendez --- src/app/index.ts | 16 +++++++++------- test/mesh/boot-retry.test.ts | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index b486129..c5194fe 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -775,6 +775,7 @@ async function connectUntilDeadline( mesh: MeshConfig, bus: Bus, logger: Logger, + url: string, attempt: () => Promise, ): Promise { const budgetMs = mesh.bootTimeoutMs ?? mesh.timeoutMs ?? 30_000; @@ -793,7 +794,7 @@ async function connectUntilDeadline( // thirty seconds. Retrying a wrong secret only spends the deploy's patience to reach the // identical error, so it fails now. if (isPermanentRefusal(error)) { - logger.error(`mesh: the teapot refused this peer, which retrying cannot fix — ${(error as Error).message}`); + logger.error(`mesh: teapot ${url} refused this peer, which retrying cannot fix — ${(error as Error).message}`); throw error; } @@ -804,17 +805,18 @@ async function connectUntilDeadline( // at all — its routes 404 and a local `needs` on its tokens still fails in finalize(). if (remaining <= 0) { logger.warn( - `mesh: teapot unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` + - `(${(error as Error).message}) — starting without it. It sent no manifest, so none of ` + - `its steps or routes are in this graph: its routes 404, and the boot still fails if ` + - `anything local needs one of its tokens.`, + `mesh: teapot ${url} unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` + + `(${(error as Error).message}) — starting without it. No manifest was ever exchanged, ` + + `so none of its steps or routes are in this graph: its routes 404 like any path that ` + + `was never registered, and the boot still fails if anything local needs one of its ` + + `tokens. This line is what a later 404 on one of its routes points back to.`, ); return undefined; } bus.emit('mesh:boot:retry', { name: `attempt ${attempts}`, error }); logger.warn( - `mesh: teapot unreachable (${(error as Error).message}) — retrying, ${remaining}ms of boot budget left`, + `mesh: teapot ${url} unreachable (${(error as Error).message}) — retrying, ${remaining}ms of boot budget left`, ); await new Promise((resolve) => setTimeout(resolve, Math.min(delay, Math.max(0, remaining)))); delay = Math.min(delay * 2, 5_000); @@ -857,7 +859,7 @@ async function spliceRemoteScopes( try { for (const teapot of mesh.teapots ?? []) { warnIfCleartext(teapot.url, logger); - const link = await connectUntilDeadline(mesh, bus, logger, () => + const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () => connectLink({ url: teapot.url, secret: teapot.secret, diff --git a/test/mesh/boot-retry.test.ts b/test/mesh/boot-retry.test.ts index 3ee4ae1..6100942 100644 --- a/test/mesh/boot-retry.test.ts +++ b/test/mesh/boot-retry.test.ts @@ -191,6 +191,41 @@ describe('mesh boot retry', () => { } }, 15_000); + it('names the teapot in the log a later 404 points back to', async () => { + // A route the absent teapot would have exported 404s, because nothing was ever registered for a + // manifest that never arrived. That is the right status — you cannot serve what was never + // declared — but a bare 404 is indistinguishable from a typo in the path. The boot log is the + // only place the two are told apart, so it has to name *which* teapot and say that no manifest + // was exchanged. The unreachable error itself is a socket error and does not reliably carry + // the url, so the url is passed in rather than scraped out of the message. + const { lines, logger } = collect(); + const teacup = createApp({ + modules: [LocalOnlyModule], + experimental: true, + logger, + mesh: { + teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], + secret: 's', + bootTimeoutMs: 300, + }, + }); + + try { + await teacup.ready(); + const gaveUp = lines.find((line) => line.includes('starting without it')); + + expect(gaveUp).toBeDefined(); + expect(gaveUp).toContain('ws://127.0.0.1:9/x'); + expect(gaveUp).toMatch(/no manifest was ever exchanged/i); + expect(gaveUp).toMatch(/404/); + + // and the retry lines on the way there name it too, so a deploy tailing logs sees which one + expect(lines.some((line) => /retrying/.test(line) && line.includes('ws://127.0.0.1:9/x'))).toBe(true); + } finally { + await teacup.close(); + } + }, 15_000); + it('still fails the boot when a local step needs a token the absent teapot owned', async () => { const teacup = createApp({ modules: [NeedsAuthModule], // a step with needs: ['auth'] From 0ce81b08f3aa527c307d922bf9cf3ccae186a71a Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 6 Sep 2026 18:20:57 -0500 Subject: [PATCH 18/18] test(mesh): cover the teapot dying with an RPC still in flight The three failure tests kill the teapot between requests, so the link is already down when the next one arrives and `rpc` fails before it sends anything. Nothing covered the case that can actually hang: the request is parked on a promise waiting for an `rpc-res` frame that is never coming. `endSession` already handles it -- `rejectAllPending` fails what was waiting with a 503 -- but that line was untested. Stubbing it out leaves all three existing tests green while these two hang until the per-RPC timeout (30s by default) and then answer 504, so the regression this guards against is a request that stalls for half a minute and then reports the wrong cause. Asserts 503 specifically rather than "not 200", since a 504 would mean the timeout caught it instead of the disconnect. Signed-off-by: Diego Resendez --- test/mesh/failure.test.ts | 77 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/test/mesh/failure.test.ts b/test/mesh/failure.test.ts index 8d78c46..200f480 100644 --- a/test/mesh/failure.test.ts +++ b/test/mesh/failure.test.ts @@ -25,6 +25,37 @@ class SvcCtl { @Module({ mountpoint: '/api', steps: [Config, Auth], controllers: [SvcCtl] }) class TeapotModule {} +/** A step slow enough that the teapot can be killed while its RPC is still on the wire. */ +@Step({ provides: 'slow', needs: [], export: true }) +class Slow { + async run() { + await new Promise((resolve) => setTimeout(resolve, 2_000)); + + return { slow: { done: true } }; + } +} +@Route('/svc') +class SlowRouteCtl { + @Get('/slow', { export: true }) + async slow() { + await new Promise((resolve) => setTimeout(resolve, 2_000)); + + return { done: true }; + } +} +@Module({ mountpoint: '/api', steps: [Slow], controllers: [SlowRouteCtl] }) +class SlowTeapotModule {} + +@Route('/local') +class SlowCtl { + @Get('/slow') + slow(@needs('slow') slow: any) { + return { slow }; + } +} +@Module({ mountpoint: '/api', controllers: [SlowCtl] }) +class SlowTeacupModule {} + @Route('/local') class LocalCtl { @Get('/who') @@ -85,6 +116,52 @@ describe('mesh link failure', () => { await teacup.close(); }); + // The tests above kill the teapot *between* requests, so the link is already down when the next + // one arrives and `rpc` fails before it sends anything. These two kill it with the RPC in flight, + // which is the case that can hang: the request is parked on a promise waiting for an `rpc-res` + // frame that is never coming. `endSession` has to reject what was waiting, not just stop + // accepting new work. The assertion is on 503 specifically rather than "not 200" — a 504 would + // mean the per-RPC timeout caught it instead, which is a much slower and much worse answer. + it('answers 503 when the teapot dies with a step RPC still in flight', async () => { + const teapot = createApp({ modules: [SlowTeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const teacup = createApp({ + modules: [SlowTeacupModule], + experimental: true, + mesh: { teapots: [{ url: controlUrl(tServer), secret: SECRET }] }, + }); + + await teacup.ready(); + const inFlight = teacup.fetch(new Request('http://x/api/local/slow')); + await new Promise((r) => setTimeout(r, 100)); // let the rpc-req reach the teapot + await teapot.close(); + + const res = await inFlight; + + expect(res.status).toBe(503); + await teacup.close(); + }, 10_000); + + it('answers 503 when the teapot dies with a proxied route RPC still in flight', async () => { + const teapot = createApp({ modules: [SlowTeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const teacup = createApp({ + modules: [SlowTeacupModule], + experimental: true, + mesh: { teapots: [{ url: controlUrl(tServer), secret: SECRET }] }, + }); + + await teacup.ready(); + const inFlight = teacup.fetch(new Request('http://x/api/svc/slow')); + await new Promise((r) => setTimeout(r, 100)); + await teapot.close(); + + const res = await inFlight; + + expect(res.status).toBe(503); + await teacup.close(); + }, 10_000); + it('answers 503 on an exported step that used to be a cached app-scope provider', async () => { // Superseded by "forbid exporting a provider": `config` used to be an app-scope @Provider, // resolved once and memoised so it kept answering (stale) after the teapot died — a known gap