fix(mesh): refuse to export a value the wire cannot carry, instead of delivering an empty object
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 14s

Exporting a provider whose value was a connection pool produced HTTP 200 and
 on the other side. JSON keeps the shape and discards everything else, so
what arrived was an object that passed every truthiness check and had no
methods — and the failure surfaced as `db.query is not a function` at a call
site arbitrarily far from the export that caused it. Nothing warned, at either
end, at any point.

The teapot now checks before sending, which is the only place the evidence
still exists: past encode() a pool and an empty object are the same bytes.

An allowlist rather than a denylist. Date is refused too — it would arrive as
a string rather than the declared type, which is the same silent difference
wearing a smaller costume. Bounded by a scan budget so a large legitimate
payload is never turned into an error by the cost of checking it.

The constraint this makes visible was never written down anywhere: a mesh
export carries data, never behaviour. Export what the handle produces rather
than the handle. That limit is what makes an 'executable provider' (#50) the
missing shape rather than a nicety.

442 vitest / 12 Deno / 7 Bun / edge / JSR dry run. All 5 new tests verified to
fail against the old code.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-08-18 12:35:48 -05:00
1 parent 1975a7c03f
commit 46342a0aa2
5 files changed
+289

No files matched your search

+16
View File
@@ -43,6 +43,22 @@ npm treats versions as semver and semver forbids leading zeros.
### Fixed
- **A mesh export that carried behaviour arrived as `{}`, with HTTP 200 and no warning.** The wire is
JSON, so a value with methods — a connection pool, a client, a `Map` — lost everything but its
shape in transit. What reached the caller was an object: truthy, passing any `if (db)` check, and
missing every method, so the failure surfaced as `db.query is not a function` at a call site
arbitrarily far from the export that caused it.
A teapot now refuses to send one, on the side that still holds the real value, with a message
naming the token and what sat where: `mesh cannot transport 'db': result.db is a Pool instance`.
The check is an allowlist — primitives, plain objects, arrays — so `Date` is refused too, since it
would arrive as a string rather than the type the caller declared, which is the same silent
difference in a smaller costume. It is bounded by a scan budget, so a large legitimate payload is
never turned into an error by the cost of checking it.
**This is a constraint the documentation never stated:** a mesh export carries *data*, never
behaviour. Export what a handle produces, not the handle.
- **A mesh teacup now reconnects to a teapot that came back.** A dropped link used to stay dead for
the life of the process: every RPC answered 503 until the teacup was restarted, so deploying a
teapot forced a restart of every teacup that depended on it, and boot order became load-bearing.
@@ -0,0 +1,82 @@
# A teapot that may be absent, declared per teapot
**Status:** planned, 2026-08-18
**Depends on:** the boot grace (`bootTimeoutMs`) and the reconnect/refuse work already merged
**Mesh stays alpha.**
## The decision
Strictness is a property of the *teapot*, not of the app. Diego: *"es mejor que los teapots definan
esa estrategia … 503 suena mejor para billing que para authorization."* A payment provider being
away is a degraded checkout; an authorization provider being away is not a degraded anything.
```ts
mesh: {
teapots: [
{ url: billingUrl, secret, expects: ['billing'], onUnreachable: 'degrade' },
{ url: authUrl, secret }, // 'fail' — the default
],
}
```
## Why `expects` is required for `'degrade'`, and not inferred
A teapot that never answered never sent a manifest, so **we do not know what it exported**. Without
that list there is nothing to put in the graph, `@needs('billing')` has no provider, and graph
validation fails the boot anyway — degrading would fail identically, just later.
The tempting shortcut is to placeholder *every unresolved token*. That must not happen: it would
turn a misspelled `needs` into a runtime 503 instead of a boot error, and destroy the property the
framework leads with. `expects` keeps the placeholder set exact, so a typo anywhere else still fails
loudly.
It also pushes the developer to state what a service depends on, which is the same discipline the
graph asks for everywhere else. `createApp` throws when `'degrade'` is set without a non-empty
`expects`, naming the teapot.
## Decisions
**D1 — Placeholders are request-scope, never app-scope.** An app-scope placeholder resolves once at
boot, and throwing there is the very failure we are avoiding. A request-scope node runs per request
and throws `503`, naming the token and the teapot it belongs to.
**D2 — `expects` covers scope tokens only, not routes.** A degraded teapot's exported *routes*
simply do not exist locally, because a route needs a method and a pattern we were never told. A
request for one 404s, which is what an unregistered route does everywhere else. Documented, not
silent.
**D3 — Degraded tokens surface through `app.degraded()`**, the API that already reports optional
providers that failed to boot. A teapot that came up degraded is the same idea, not a parallel one,
and a consumer that already checks `degraded()` before reporting healthy gets this for free. Plus a
boot-time `logger.warn` and a `mesh:boot:degraded` event, for the same reason retries are both
logged and emitted.
**D4 — A degraded link keeps trying in the background.** Reconnection today only covers links that
handshook at least once; this one never did, so it needs its own attempt loop. Without it a degraded
teapot stays degraded until the process restarts, which is the bug this plan exists to avoid, moved.
**D5 — Adoption is the refuse rule again.** When a degraded teapot finally answers, its manifest
must contain everything in `expects`; if it does not, the connection is refused and the placeholders
stay. Same policy, same reason, and it reuses `missingFromManifest` with `expects` as the baseline
instead of a boot manifest.
**D6 — Swapping placeholders for real runners reuses the rebind seam** added for reconnection
(`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.
## Tasks
1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without
`expects`.
2. Placeholder step nodes per D1, registered when the boot grace runs out under `'degrade'`.
3. `degraded()` reporting per D3, plus the warn and the event.
4. Background attempt loop per D4, and adoption per D5/D6.
5. Tests, on all three server runtimes: boots degraded, the token 503s with a message naming it,
the teapot arrives late and the same request then succeeds, a manifest missing `expects` is
refused, and `'degrade'` without `expects` fails at `createApp`.
6. Docs: the mesh guide, `app.degraded()` in the reference, and the event table.
## Size
Comparable to the reconnection work — a background loop, a graph mutation and a runtime swap, on
three runtimes. Not a follow-up to squeeze into another change.
+86
View File
@@ -115,6 +115,92 @@ const SHAPE: Record<Frame['type'], ShapeCheck> = {
},
};
/** How much of a value the transport check walks before it stops looking. */
const TRANSPORT_SCAN_BUDGET = 10_000;
/** Names what a value is, for an error a reader can act on: `Pool`, `Map`, `Date`, `function`. */
function describe(value: unknown): string {
if (typeof value === 'function') return 'a function';
const name = (value as object).constructor?.name;
return name ? `a ${name} instance` : 'an object with no prototype';
}
/**
* Find the first part of `value` that cannot survive the wire, or `undefined` if all of it can.
*
* The wire is JSON, so the mesh transports **data, never behaviour**. Before this check, exporting a
* value with methods — a connection pool, a client, a `Map` — serialized to `{}` and arrived looking
* alive: truthy, an object, and missing every method. The failure then surfaced as
* `db.query is not a function` at the call site, arbitrarily far from the export that caused it.
*
* The rule is an allowlist rather than a denylist, on purpose. `Date` is refused too: it would
* arrive as a string, which is not the type the caller declared and is the same silent difference
* in a smaller costume.
*
* Bounded by a node budget so a large legitimate payload is never turned into an error by the cost
* of checking it — past the budget the value is assumed fine, since the shapes this catches are
* structural and show up immediately.
*/
export function untransportable(value: unknown, path = 'result'): Offender | undefined {
return walk(value, path, { left: TRANSPORT_SCAN_BUDGET });
}
/** What could not cross, and where it sat in the value. */
type Offender = { path: string; what: string };
/** Remaining nodes the scan may visit, shared across the whole walk. */
type Budget = { left: number };
/** Values JSON cannot represent at all, whatever they are nested in. */
function isBehaviour(kind: string): boolean {
return kind === 'function' || kind === 'symbol' || kind === 'bigint';
}
/**
* Whether a container survives the round trip as itself: a plain object or a null-prototype bag.
* Anything else is a class instance whose identity JSON discards — `Pool`, `Map`, `Set`, `Date`.
*/
function isPlainContainer(node: object): boolean {
const proto = Object.getPrototypeOf(node);
return proto === Object.prototype || proto === null;
}
/** Walk labelled children in order, returning the first offender. */
function walkEntries(entries: Array<[string, unknown]>, budget: Budget): Offender | undefined {
for (const [at, item] of entries) {
const found = walk(item, at, budget);
if (found) return found;
}
return undefined;
}
/** One node of the scan: reject behaviour and class instances, otherwise descend. */
function walk(node: unknown, at: string, budget: Budget): Offender | undefined {
if (budget.left-- <= 0 || node === null) return undefined;
const kind = typeof node;
if (isBehaviour(kind)) return { path: at, what: describe(node) };
if (kind !== 'object') return undefined;
if (Array.isArray(node)) {
return walkEntries(
node.map((item, index) => [`${at}[${index}]`, item] as [string, unknown]),
budget,
);
}
if (!isPlainContainer(node as object)) return { path: at, what: describe(node) };
return walkEntries(
Object.entries(node as Record<string, unknown>).map(([key, item]) => [`${at}.${key}`, item] as [string, unknown]),
budget,
);
}
/** Serialize a frame to a JSON wire string. */
export function encode(frame: Frame): string {
return JSON.stringify(frame);
+14
View File
@@ -9,6 +9,7 @@ import { isHttpError } from '../signals';
import {
encode,
decode,
untransportable,
MESH_PROTOCOL_VERSION,
type Manifest,
type RequestEnvelope,
@@ -155,6 +156,19 @@ async function handleRpc(
try {
const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes);
// Checked here, on the side that still holds the real value. Past `encode` the evidence is
// gone: JSON turns a pool into `{}`, which arrives looking alive and fails at the call site.
const offender = untransportable(result);
if (offender) {
const error: any = new Error(
`mesh cannot transport '${name}': ${offender.path} is ${offender.what}. ` +
'The wire is JSON, so a mesh export carries data, never behaviour — export what the ' +
'handle produces rather than the handle.',
);
error.status = 500;
throw error;
}
socket.send(encode({ type: 'rpc-res', id, ok: true, result }));
} catch (err) {
+91
View File
@@ -0,0 +1,91 @@
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Route, Get, Module, needs } from '../../src/index';
import { untransportable } from '../../src/mesh/protocol';
describe('untransportable', () => {
it('passes the shapes JSON actually round-trips', () => {
expect(untransportable({ a: 1, b: 'x', c: true, d: null, e: [1, { f: 2 }] })).toBeUndefined();
expect(untransportable([])).toBeUndefined();
expect(untransportable('plain')).toBeUndefined();
expect(untransportable(Object.create(null))).toBeUndefined();
});
it('names the class whose identity JSON would discard, and where it sits', () => {
class RemotePool {
query() {
return 1;
}
}
expect(untransportable({ db: new RemotePool() })).toEqual({ path: 'result.db', what: 'a RemotePool instance' });
expect(untransportable({ seen: new Map() })).toEqual({ path: 'result.seen', what: 'a Map instance' });
// refused rather than quietly delivered as a string, which is the same silent difference smaller
expect(untransportable({ at: new Date() })).toEqual({ path: 'result.at', what: 'a Date instance' });
});
it('finds behaviour nested in arrays and objects', () => {
expect(untransportable({ list: [1, { run: () => 1 }] })).toEqual({
path: 'result.list[1].run',
what: 'a function',
});
});
it('gives up rather than rejecting a payload too large to check', () => {
const huge: Record<string, unknown> = {};
for (let i = 0; i < 11_000; i++) huge[`k${i}`] = i;
huge.late = () => 1; // past the budget: assumed fine rather than turned into an error
expect(untransportable(huge)).toBeUndefined();
});
});
class Pool {
query(sql: string) {
return `ran:${sql}`;
}
}
@Provider({ provides: 'db', export: true })
class Db {
provide() {
return { db: new Pool() };
}
}
@Module({ mountpoint: '/api', providers: [Db] })
class TeapotModule {}
@Route('/local')
class Ctl {
@Get('/use')
use(@needs('db') db: any) {
return { got: typeof db };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class TeacupModule {}
describe('exporting a handle over the mesh', () => {
it('fails with a message naming the token, instead of delivering an empty object', async () => {
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'x' } });
const server = await teapot.listen(0);
const port = (server.address() as { port: number }).port;
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'x' }] },
});
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/,
);
} finally {
await teacup.close();
await teapot.close();
server.close();
}
});
});