10 Commits
Author SHA1 Message Date
chrnx 0ce81b08f3 test(mesh): cover the teapot dying with an RPC still in flight
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 31s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 15s
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 <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx 249fc00f80 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: <url>` -- 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 <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx 6e050197b6 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 <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx 8ef7c3ee14 fix(mesh): validate the manifest's route entries, not just its steps
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 <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx e69f604053 docs(mesh): record the scopes->steps rename as an exception to the bump rule
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 <diego.resendez@zero-oneit.com>
2026-09-12 15:40:26 -05:00
chrnx 727987286b refactor(graph): the missing-dependency note is a string, not a callback
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 <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx bff8778112 refactor(mesh): @Provider's options no longer advertise export
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 <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx 1bcaa463f2 fix(mesh): a rejected first connect no longer leaks a retry supervisor
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 <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx f5d4d0cd74 docs(mesh): an absent teapot 404s, it does not 503
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 <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
chrnx 03132b2048 docs(mesh): steps and routes are what a teapot exports
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 <diego.resendez@zero-oneit.com>
2026-09-12 15:40:25 -05:00
18 changed files with 358 additions and 59 deletions

No files matched your search

+59
View File
@@ -6,6 +6,65 @@ 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 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. 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.
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
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 ## [26.9.0-beta.1] - 2026-09-04
### Added ### Added
+2
View File
@@ -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. **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 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. **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 ## Docs & development
@@ -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 (`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. 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 ## Tasks
1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without 1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without
@@ -85,6 +85,12 @@ not a wait for `timeoutMs`.
3. **Manifest comparison.** Capture the contributed set at boot, compare per D4, reuse 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. `compilePattern(...).shape` for routes. Refusal logs the missing token or route by name.
4. **`invalidateRemoteBindings(link)`** per D8, called on successful reconnect. 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' }`. 5. **Config**: `mesh: { reconnect?: boolean | { initialDelayMs?, maxDelayMs? }, onManifestChange?: 'refuse' }`.
Reconnect defaults **on**. Validate at boot like the other mesh options. 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 6. **Tests.** Reconnect after the teapot returns; refuse when a token disappears, with the message
+36 -20
View File
@@ -221,7 +221,7 @@ export function createApp(opts: {
let remoteRoutes: RouteDef[] = []; let remoteRoutes: RouteDef[] = [];
const meshLinks: Link[] = []; const meshLinks: Link[] = [];
const finalize = (missingNote?: (key: string) => string): void => { const finalize = (missingNote?: string): void => {
({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote)); ({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote));
booted = true; booted = true;
}; };
@@ -244,7 +244,7 @@ export function createApp(opts: {
// Without this the error is `missing dependency: auth needed by getUser` and says nothing // Without this the error is `missing dependency: auth needed by getUser` and says nothing
// about the teapot that was away — which is the actual cause every time it is the cause. // about the teapot that was away — which is the actual cause every time it is the cause.
const meshNote = spliced.absent.length 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; : undefined;
finalize(meshNote); finalize(meshNote);
} }
@@ -667,7 +667,7 @@ function finalizeGraph(
registry: Registry, registry: Registry,
logger: Logger, logger: Logger,
warnDepth: number | false = DEEP_GRAPH_WARN, warnDepth: number | false = DEEP_GRAPH_WARN,
missingNote?: (key: string) => string, missingNote?: string,
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } { ): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
const { providerNodes, stepNodes, routePlans } = registry; const { providerNodes, stepNodes, routePlans } = registry;
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params'], missingNote); const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params'], missingNote);
@@ -699,12 +699,19 @@ function finalizeGraph(
return { orderedProviders, orderedSteps }; 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( function assertNeedsSatisfiable(
routePlans: RoutePlan[], routePlans: RoutePlan[],
providerNodes: GraphNode[], providerNodes: GraphNode[],
stepNodes: GraphNode[], stepNodes: GraphNode[],
missingNote?: (key: string) => string, missingNote?: string,
): void { ): void {
const producedKeys = new Set<string>([ const producedKeys = new Set<string>([
...providerNodes.flatMap((node) => node.provides), ...providerNodes.flatMap((node) => node.provides),
@@ -737,7 +744,7 @@ function assertNeedsSatisfiable(
const scope = missingNote ? 'local or connected mesh' : 'local or mesh'; const scope = missingNote ? 'local or connected mesh' : 'local or mesh';
throw new Error( throw new Error(
`handler '${plan.handlerName}' needs '${need}' but nothing (${scope}) provides it` + `handler '${plan.handlerName}' needs '${need}' but nothing (${scope}) provides it` +
`${hint ? ` — did you mean '${hint}'?` : ''}${missingNote?.(need) ?? ''}`, `${hint ? ` — did you mean '${hint}'?` : ''}${missingNote ?? ''}`,
); );
} }
} }
@@ -748,23 +755,27 @@ function assertNeedsSatisfiable(
* *
* The grace exists because "the container is thirty seconds behind" and "the teapot does not * 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. * 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 * 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 * 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. * 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 * Exhausting the budget returns `undefined` rather than throwing (D4 keeps the one exception: a
* does). Every export a teapot makes is now lazy — a request-scope step or a proxied route — so * permanent refusal still does). Every export a teapot makes is lazy now — a request-scope step or
* nothing needs it resolved by boot; an absent teapot only costs a 503 on the requests that need * a proxied route — so nothing needed this link resolved by boot, and a teacup that refuses to
* it, and a teacup that refuses to start would take down the half of itself that never did. * 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( async function connectUntilDeadline(
mesh: MeshConfig, mesh: MeshConfig,
bus: Bus, bus: Bus,
logger: Logger, logger: Logger,
url: string,
attempt: () => Promise<Link>, attempt: () => Promise<Link>,
): Promise<Link | undefined> { ): Promise<Link | undefined> {
const budgetMs = mesh.bootTimeoutMs ?? mesh.timeoutMs ?? 30_000; const budgetMs = mesh.bootTimeoutMs ?? mesh.timeoutMs ?? 30_000;
@@ -783,24 +794,29 @@ async function connectUntilDeadline(
// thirty seconds. Retrying a wrong secret only spends the deploy's patience to reach the // thirty seconds. Retrying a wrong secret only spends the deploy's patience to reach the
// identical error, so it fails now. // identical error, so it fails now.
if (isPermanentRefusal(error)) { 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; throw error;
} }
// The budget is a grace for a co-deploy, not a requirement. Every export is a lazy step or a // 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 // proxied route now, so nothing needed this link resolved by boot, and a teacup that refuses
// teacup that refuses to start takes down the half of itself that never needed the teapot. // 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) { if (remaining <= 0) {
logger.warn( logger.warn(
`mesh: teapot unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` + `mesh: teapot ${url} 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. 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; return undefined;
} }
bus.emit('mesh:boot:retry', { name: `attempt ${attempts}`, error }); bus.emit('mesh:boot:retry', { name: `attempt ${attempts}`, error });
logger.warn( 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)))); await new Promise((resolve) => setTimeout(resolve, Math.min(delay, Math.max(0, remaining))));
delay = Math.min(delay * 2, 5_000); delay = Math.min(delay * 2, 5_000);
@@ -843,7 +859,7 @@ async function spliceRemoteScopes(
try { try {
for (const teapot of mesh.teapots ?? []) { for (const teapot of mesh.teapots ?? []) {
warnIfCleartext(teapot.url, logger); warnIfCleartext(teapot.url, logger);
const link = await connectUntilDeadline(mesh, bus, logger, () => const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () =>
connectLink({ connectLink({
url: teapot.url, url: teapot.url,
secret: teapot.secret, secret: teapot.secret,
+11 -5
View File
@@ -136,12 +136,18 @@ export interface MeshConfig {
* so 30s). Attempts use the same backoff as reconnection. * 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 * 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 * has not settled — should not fail a deploy, and this is the grace for that. When the deadline
* genuinely absent still fails the boot when the deadline passes, because a provider the graph * passes the teacup warns and starts anyway: every export is a step or a proxied route, so
* depends on is not optional: booting without it would only move the failure to the first * nothing needed that link resolved by boot.
* request, where it is somebody else's 503 instead of your deploy's error.
* *
* `0` restores the old behaviour of a single attempt. * 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` 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; bootTimeoutMs?: number;
} }
+2 -2
View File
@@ -43,7 +43,7 @@ export interface GraphNode {
} }
/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */ /** 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<string, GraphNode>(); const producedBy = new Map<string, GraphNode>();
for (const node of nodes) for (const key of node.provides) producedBy.set(key, node); 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 node of nodes) {
for (const key of node.needs) { for (const key of node.needs) {
if (!seedKeys.includes(key) && !producedBy.has(key)) { 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}`);
} }
} }
} }
+17 -2
View File
@@ -499,10 +499,25 @@ export function connectLink(args: {
} }
}; };
return openSession(sessionArgs(() => endSession(0))).then((session) => { return openSession(sessionArgs(() => endSession(0))).then(
(session) => {
link.manifest = session.manifest; link.manifest = session.manifest;
adopt(session); 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;
},
);
} }
+15
View File
@@ -18,6 +18,14 @@
* *
* Bumping per change would make the number mean "work happened" rather than "we are * 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. * 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; export const MESH_PROTOCOL_VERSION = 1;
@@ -80,6 +88,9 @@ export type Frame =
const isString = (value: unknown): value is string => typeof value === 'string'; const isString = (value: unknown): value is string => typeof value === 'string';
const isNumber = (value: unknown): boolean => typeof value === 'number'; const isNumber = (value: unknown): boolean => typeof value === 'number';
const isObject = (value: unknown): boolean => typeof value === 'object' && value !== null; 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. */ /** Rejects a frame whose fields don't match its `type` tag. `bad` always throws. */
type ShapeCheck = (frame: Record<string, unknown>, bad: (why: string) => never) => void; type ShapeCheck = (frame: Record<string, unknown>, bad: (why: string) => never) => void;
@@ -100,6 +111,10 @@ const SHAPE: Record<Frame['type'], ShapeCheck> = {
// Array.isArray above already guarantees this, but TS does not carry that narrowing through a // 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. // `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'); 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) => { 'rpc-req': (frame, bad) => {
if (!isString(frame.id)) bad('id must be a string'); if (!isString(frame.id)) bad('id must be a string');
+11 -7
View File
@@ -15,6 +15,12 @@ export interface ProviderMeta {
provides: string; provides: string;
needs: string[]; needs: string[];
optional: boolean; 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; export: boolean;
} }
/** Metadata attached by `@Step`: what it provides, what it needs, and its visibility. */ /** 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. */ /** Marks a class as a provider: a lazily-built dependency addressable by its `provides` key. */
export function Provider(opts: { export function Provider(opts: { provides: string; needs?: string[]; optional?: boolean }): ClassDecorator {
provides: string;
needs?: string[];
optional?: boolean;
export?: boolean;
}): ClassDecorator {
return (target) => { return (target) => {
const meta: ProviderMeta = { const meta: ProviderMeta = {
provides: opts.provides, provides: opts.provides,
needs: opts.needs ?? [], needs: opts.needs ?? [],
optional: opts.optional ?? false, 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); Reflect.defineMetadata(K.provider, meta, target);
}; };
+1 -1
View File
@@ -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. // 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 // Bun's ws lifecycle differs from Deno's — its socket events land on a server-level handler
+2 -2
View File
@@ -112,7 +112,7 @@ Deno.test('interop: a Deno teacup consumes a Node teapot', async () => {
try { try {
const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } })); const res = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
assertEquals(res.status, 200); 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(), { assertEquals(await res.json(), {
config: { region: 'mx', runtime: 'node' }, config: { region: 'mx', runtime: 'node' },
auth: { token: 'abc' }, auth: { token: 'abc' },
@@ -140,7 +140,7 @@ Deno.test('interop: a Node teacup consumes a Deno teapot', async () => {
try { try {
const result = await firstJsonLine(node); const result = await firstJsonLine(node);
assertEquals(result.ok, true); 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.config, { region: 'mx', runtime: 'deno' });
assertEquals(result.body.auth, { token: 'abc' }); assertEquals(result.body.auth, { token: 'abc' });
} finally { } finally {
+1 -1
View File
@@ -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. // 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, // This is the test that makes "mesh runs off Node" a fact rather than an intention. It covers,
+90 -7
View File
@@ -43,6 +43,16 @@ class NeedsAuth {
@Module({ mountpoint: '/api', steps: [NeedsAuth] }) @Module({ mountpoint: '/api', steps: [NeedsAuth] })
class NeedsAuthModule {} class NeedsAuthModule {}
/** A free port, taken by opening and immediately closing a server on port 0. */
const freePort = async (): Promise<number> =>
new Promise<number>((resolve) => {
const probe = net.createServer();
probe.listen(0, () => {
const { port } = probe.address() as { port: number };
probe.close(() => resolve(port));
});
});
const collect = () => { const collect = () => {
const lines: string[] = []; const lines: string[] = [];
return { lines, logger: { debug() {}, info() {}, warn: (m: string) => lines.push(m), error: (m: string) => lines.push(m) } }; 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', () => { describe('mesh boot retry', () => {
it('waits for a teapot that starts late, rather than failing the deploy', async () => { it('waits for a teapot that starts late, rather than failing the deploy', async () => {
const port = await new Promise<number>((resolve) => { const port = await freePort();
const probe = net.createServer();
probe.listen(0, () => {
const { port: p } = probe.address() as { port: number };
probe.close(() => resolve(p));
});
});
const { lines, logger } = collect(); const { lines, logger } = collect();
const teacup = createApp({ const teacup = createApp({
@@ -187,6 +191,41 @@ describe('mesh boot retry', () => {
} }
}, 15_000); }, 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 () => { it('still fails the boot when a local step needs a token the absent teapot owned', async () => {
const teacup = createApp({ const teacup = createApp({
modules: [NeedsAuthModule], // a step with needs: ['auth'] modules: [NeedsAuthModule], // a step with needs: ['auth']
@@ -205,6 +244,50 @@ describe('mesh boot retry', () => {
} }
}, 15_000); }, 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 () => { it('bootTimeoutMs: 0 makes one attempt, as before', async () => {
const { lines, logger } = collect(); const { lines, logger } = collect();
const teacup = createApp({ const teacup = createApp({
+80
View File
@@ -25,6 +25,37 @@ class SvcCtl {
@Module({ mountpoint: '/api', steps: [Config, Auth], controllers: [SvcCtl] }) @Module({ mountpoint: '/api', steps: [Config, Auth], controllers: [SvcCtl] })
class TeapotModule {} 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') @Route('/local')
class LocalCtl { class LocalCtl {
@Get('/who') @Get('/who')
@@ -85,6 +116,52 @@ describe('mesh link failure', () => {
await teacup.close(); 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 () => { 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, // 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 // resolved once and memoised so it kept answering (stale) after the teapot died — a known gap
@@ -124,6 +201,9 @@ describe('mesh link failure', () => {
describe('provider export', () => { describe('provider export', () => {
it('refuses to boot when a provider is exported over the mesh', async () => { 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) @Provider({ provides: 'db', needs: [], export: true } as any)
class Db { class Db {
provide() { provide() {
+12
View File
@@ -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', () => { it('throws on malformed json', () => {
expect(() => decode('{not json')).toThrow(); expect(() => decode('{not json')).toThrow();
}); });
-9
View File
@@ -9,15 +9,6 @@ const fakeLink = (calls: any[]): Link => ({
}); });
describe('teacup buildRemote', () => { 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 () => { it('makes a step node per manifest token, with RPC runners returning merge objects', async () => {
const calls: any[] = []; const calls: any[] = [];
const { steps } = buildRemote(fakeLink(calls)); const { steps } = buildRemote(fakeLink(calls));
+6 -3
View File
@@ -67,12 +67,15 @@ describe('HEAD and OPTIONS decorators', () => {
}); });
describe('mesh export flags', () => { describe('mesh export flags', () => {
it('providers/steps carry export (default false)', () => { it('steps carry export, and a provider defaults to not exported', () => {
@Provider({ provides: 'config', export: true }) class C { provide() { return {}; } }
@Step({ provides: 'auth', export: true }) class A { run() { return {}; } } @Step({ provides: 'auth', export: true }) class A { run() { return {}; } }
@Provider({ provides: 'priv' }) class P { provide() { return {}; } } @Provider({ provides: 'priv' }) class P { provide() { return {}; } }
expect(getProviderMeta(C)!.export).toBe(true);
expect(getStepMeta(A)!.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); expect(getProviderMeta(P)!.export).toBe(false);
}); });