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 <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-09-12 15:40:24 -05:00
1 parent 419ba092d4
commit f6c05a0929
7 files changed
+70 -37

No files matched your search

+4 -4
View File
@@ -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' } });
+10 -1
View File
@@ -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));
+4 -4
View File
@@ -10,13 +10,13 @@
// teapot -> exports scopes, prints {"port":N}, serves until killed
// teacup <controlUrl> -> 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')
+31 -9
View File
@@ -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,
);
});
});
+7 -7
View File
@@ -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();
});
+4 -4
View File
@@ -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')
+10 -8
View File
@@ -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();