feat(graph)!: fail boot when a token has a second producer (CARD-18, GitHub #35)
topoSort, topoLevels and subgraphFor built their token -> node map with
producedBy.set(key, node), so the last node registered for a token won.
Plugin nodes are registered after module nodes, which let a plugin's
scope.add({ name: 'shadow', provides: ['user'] }) silently replace the
app's own @Provider({ provides: 'user' }) for every route that needed
it. setRunner only rejects duplicate names, and scope.add is the one
path where a name and its tokens differ.
D9 settles it graph-wide: topoSort now throws when a token already has
a producer, naming both nodes and their origins (module:..., plugin,
mesh:<url>, builtin). One check on the whole node set covers every
current and future registration path. It also protects the built-ins
(logger, rooms, events) by rule rather than by registration order.
topoSort runs at finalize, after the mesh splice, so remote steps are
checked too. topoLevels and subgraphFor only ever see nodes topoSort
has already validated, so they keep their plain maps.
overrides replace the runner of an existing token and add no node, so
they are unaffected. Steps that provide nothing (plugin observers) are
not producers. The official plugins (jwt, metrics, rate-limit) pass
their suites against this build.
BREAKING CHANGE: an app whose graph has two nodes providing one token,
e.g. a plugin scope node providing a token a module or built-in
already provides, now fails createApp instead of letting the later
node win.
Refs: GitHub #35
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
6 files changed
+275
-3
No files matched your search
@@ -82,3 +82,33 @@ test('mesh on Bun: a teapot refuses a bad secret over its control channel', asyn
|
||||
tServer.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
// CARD-18 T6 (GitHub #35, D9): a remote step whose token a local node already provides fails the
|
||||
// splice, on Bun as on Node. Today that is the duplicate-name check in `setRunner`, which runs
|
||||
// before the graph-wide one-producer check; this pins that the splice still refuses it.
|
||||
@Step({ provides: 'auth', needs: [] })
|
||||
class LocalAuth {
|
||||
run() {
|
||||
return { auth: { token: 'local' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', steps: [LocalAuth], controllers: [LocalCtl] })
|
||||
class ShadowingTeacupModule {}
|
||||
|
||||
test('mesh on Bun: a remote step colliding with a local token fails the splice', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const tServer = await serveBun(teapot, { port: 0 });
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [ShadowingTeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }], timeoutMs: 1000 },
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(teacup.ready()).rejects.toThrow("duplicate provider/step name 'auth'");
|
||||
} finally {
|
||||
await teacup.close().catch(() => {});
|
||||
tServer.stop(true);
|
||||
}
|
||||
});
|
||||
@@ -106,3 +106,39 @@ Deno.test('mesh on Deno: a teapot refuses a bad secret over its control channel'
|
||||
await t.server.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
// CARD-18 T6 (GitHub #35, D9): a remote step whose token a local node already provides fails the
|
||||
// splice, on Deno as on Node. Today that is the duplicate-name check in `setRunner`, which runs
|
||||
// before the graph-wide one-producer check; this pins that the splice still refuses it.
|
||||
@Step({ provides: 'auth', needs: [] })
|
||||
class LocalAuth {
|
||||
run() {
|
||||
return { auth: { token: 'local' } };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/api', steps: [LocalAuth], controllers: [LocalCtl] })
|
||||
class ShadowingTeacupModule {}
|
||||
|
||||
Deno.test('mesh on Deno: a remote step colliding with a local token fails the splice', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const t = await serve(teapot);
|
||||
|
||||
const teacup = createApp({
|
||||
modules: [ShadowingTeacupModule],
|
||||
experimental: true,
|
||||
mesh: { teapots: [{ url: controlUrl(t.port), secret: SECRET }], timeoutMs: 1000 },
|
||||
});
|
||||
|
||||
try {
|
||||
let message = '';
|
||||
try {
|
||||
await teacup.ready();
|
||||
} catch (err) {
|
||||
message = String((err as Error).message);
|
||||
}
|
||||
assertStringIncludes(message, "duplicate provider/step name 'auth'");
|
||||
} finally {
|
||||
await teacup.close().catch(() => {});
|
||||
await t.server.shutdown();
|
||||
}
|
||||
});
|
||||
@@ -24,6 +24,34 @@ test('throws on cycle', () => {
|
||||
expect(() => topoSort(nodes, [])).toThrow(/cycle detected/);
|
||||
});
|
||||
|
||||
// CARD-18 (GitHub #35, D9): the check is a rule over the whole node set, not an artefact of the
|
||||
// order nodes were registered in — so swapping `provideBuiltins` and `mountPlugins` cannot reopen it.
|
||||
describe('one producer per token', () => {
|
||||
const builtin: GraphNode = { name: 'logger', needs: [], provides: ['logger'], origin: 'builtin' };
|
||||
const plugin: GraphNode = { name: 'fake', needs: [], provides: ['logger'], origin: 'plugin' };
|
||||
|
||||
it.each([
|
||||
['built-in first', [builtin, plugin]],
|
||||
['plugin first', [plugin, builtin]],
|
||||
])('throws naming both producers and origins (%s)', (_, nodes) => {
|
||||
expect(() => topoSort(nodes, [])).toThrow(/token 'logger' is provided twice/);
|
||||
expect(() => topoSort(nodes, [])).toThrow(/'logger' \(builtin\)/);
|
||||
expect(() => topoSort(nodes, [])).toThrow(/'fake' \(plugin\)/);
|
||||
});
|
||||
|
||||
it('names a mesh origin like any other', () => {
|
||||
const local: GraphNode = { name: 'auth', needs: [], provides: ['auth'], origin: 'module:App' };
|
||||
const remote: GraphNode = { name: 'auth-remote', needs: [], provides: ['auth'], origin: 'mesh:ws://t' };
|
||||
expect(() => topoSort([local, remote], [])).toThrow(
|
||||
"token 'auth' is provided twice: by 'auth' (module:App) and by 'auth-remote' (mesh:ws://t)",
|
||||
);
|
||||
});
|
||||
|
||||
it('allows a node to list its own token twice', () => {
|
||||
expect(topoSort([node('a', [], ['a', 'a'])], []).map((n) => n.name)).toEqual(['a']);
|
||||
});
|
||||
});
|
||||
|
||||
const N = (name: string, needs: string[] = []) => ({ name, needs, provides: [name], origin: 'm' });
|
||||
|
||||
describe('subgraphFor', () => {
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// CARD-18 (GitHub #35, D9): every token has at most one producer across modules, plugins, mesh steps
|
||||
// and built-ins. A second producer fails `createApp`, naming both nodes and their origins.
|
||||
import 'reflect-metadata';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
|
||||
import type { Plugin, ScopeNode } from '../src/index';
|
||||
|
||||
@Provider({ provides: 'user' })
|
||||
class User {
|
||||
provide() {
|
||||
return { user: { id: 'real' } };
|
||||
}
|
||||
}
|
||||
|
||||
@Route('/u')
|
||||
class UserCtl {
|
||||
@Get('/me') me(@needs('user') user: unknown) {
|
||||
return { user };
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', providers: [User], controllers: [UserCtl] })
|
||||
class AppModule {}
|
||||
|
||||
/** A plugin that adds one scope node, the way an official plugin would. */
|
||||
const adds = (name: string, node: Omit<ScopeNode, 'run'> & Partial<Pick<ScopeNode, 'run'>>): Plugin => ({
|
||||
name,
|
||||
mount({ scope }) {
|
||||
scope.add({ run: () => Object.fromEntries(node.provides.map((key) => [key, `from ${name}`])), ...node });
|
||||
},
|
||||
});
|
||||
|
||||
describe('one producer per token', () => {
|
||||
it('T1: a plugin node providing a module-provided token fails boot, naming both nodes and origins', () => {
|
||||
const shadow = adds('shadow', { kind: 'provider', name: 'shadow', needs: [], provides: ['user'] });
|
||||
expect(() => createApp({ modules: [AppModule], plugins: [shadow] })).toThrow(
|
||||
"token 'user' is provided twice: by 'user' (module:AppModule) and by 'shadow' (plugin)",
|
||||
);
|
||||
});
|
||||
|
||||
it('T1: a plugin step providing it fails the same way', () => {
|
||||
const shadow = adds('shadow', { kind: 'step', name: 'shadow', needs: [], provides: ['user'] });
|
||||
expect(() => createApp({ modules: [AppModule], plugins: [shadow] })).toThrow(/'user' \(module:AppModule\).*'shadow' \(plugin\)/);
|
||||
});
|
||||
|
||||
it('T2: a plugin node providing a built-in token fails boot instead of losing silently', () => {
|
||||
const fake = adds('fake-logger', { kind: 'provider', name: 'fake-logger', needs: [], provides: ['logger'] });
|
||||
// Plugins mount before the built-ins are registered, so the plugin is the one seen first. The
|
||||
// order the two are reported in is not the point; that both are, with their origins, is.
|
||||
expect(() => createApp({ modules: [AppModule], plugins: [fake] })).toThrow(
|
||||
"token 'logger' is provided twice: by 'fake-logger' (plugin) and by 'logger' (builtin)",
|
||||
);
|
||||
});
|
||||
|
||||
it.each(['rooms', 'events'])('T2: the same holds for the built-in %s', (token) => {
|
||||
const fake = adds('fake', { kind: 'provider', name: 'fake', needs: [], provides: [token] });
|
||||
expect(() => createApp({ modules: [AppModule], plugins: [fake] })).toThrow(`token '${token}' is provided twice`);
|
||||
});
|
||||
|
||||
it('T3: a plugin node providing two tokens, one of them taken, fails naming the taken one', () => {
|
||||
const both = adds('both', { kind: 'provider', name: 'both', needs: [], provides: ['a', 'user'] });
|
||||
expect(() => createApp({ modules: [AppModule], plugins: [both] })).toThrow(/^token 'user' is provided twice/);
|
||||
});
|
||||
|
||||
it('T4: two plugins providing distinct tokens boot', async () => {
|
||||
const a = adds('a', { kind: 'provider', name: 'a', needs: [], provides: ['a'] });
|
||||
const b = adds('b', { kind: 'provider', name: 'b', needs: [], provides: ['b'] });
|
||||
const app = createApp({ modules: [AppModule], plugins: [a, b] });
|
||||
await expect(app.boot()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('two plugin nodes providing the same token fail, naming both', () => {
|
||||
const a = adds('a', { kind: 'step', name: 'a', needs: [], provides: ['shared'] });
|
||||
const b = adds('b', { kind: 'step', name: 'b', needs: [], provides: ['shared'] });
|
||||
expect(() => createApp({ modules: [AppModule], plugins: [a, b] })).toThrow(
|
||||
"token 'shared' is provided twice: by 'a' (plugin) and by 'b' (plugin)",
|
||||
);
|
||||
});
|
||||
|
||||
it('observer steps that provide nothing do not count as producers', async () => {
|
||||
const one = adds('one', { kind: 'step', name: 'one', needs: [], provides: [] });
|
||||
const two = adds('two', { kind: 'step', name: 'two', needs: [], provides: [] });
|
||||
await expect(createApp({ modules: [AppModule], plugins: [one, two] }).boot()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('T5: overrides replace the runner of an existing token, not add a producer', async () => {
|
||||
const app = createApp({ modules: [AppModule], overrides: { user: { id: 1 } } });
|
||||
const res = await app.fetch(new Request('http://x/u/me'));
|
||||
expect(await res.json()).toEqual({ user: { id: 1 } });
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('one producer per token: mesh', () => {
|
||||
const SECRET = 's3cr3t';
|
||||
|
||||
@Step({ provides: 'auth', needs: [], export: true })
|
||||
class RemoteAuth {
|
||||
run() {
|
||||
return { auth: 'remote' };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', steps: [RemoteAuth] })
|
||||
class TeapotModule {}
|
||||
|
||||
@Step({ provides: 'auth', needs: [] })
|
||||
class LocalAuth {
|
||||
run() {
|
||||
return { auth: 'local' };
|
||||
}
|
||||
}
|
||||
@Route('/a')
|
||||
class AuthCtl {
|
||||
@Get('/who') who(@needs('auth') auth: unknown) {
|
||||
return { auth };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', steps: [LocalAuth], controllers: [AuthCtl] })
|
||||
class TeacupModule {}
|
||||
|
||||
it('T6: a remote step whose token a local node provides still fails at splice', async () => {
|
||||
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||
const server = await teapot.listen(0);
|
||||
const url = `ws://127.0.0.1:${(server.address() as any).port}/__mesh__/control`;
|
||||
const teacup = createApp({ modules: [TeacupModule], experimental: true, mesh: { teapots: [{ url, secret: SECRET }] } });
|
||||
|
||||
try {
|
||||
await expect(teacup.ready()).rejects.toThrow("duplicate provider/step name 'auth'");
|
||||
} finally {
|
||||
await teacup.close().catch(() => {});
|
||||
await teapot.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user