Merge pull request 'feat(graph)!: fail boot when a token has a second producer (CARD-18, GitHub #35)' (#143) from feature/fprd-001c-one-producer-per-token into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 26s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 26s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
This commit was merged in pull request #143.
This commit is contained in:
commit
444910b6f0
6 files changed
+274
-3
No files matched your search
@@ -64,6 +64,16 @@ npm treats versions as semver and semver forbids leading zeros.
|
||||
`ctx.ip` on an edge WebSocket is `''`, as it already was on edge HTTP: workerd exposes no peer
|
||||
address. An app behind Cloudflare that keys anything on the WebSocket IP needs
|
||||
`createApp({ trustProxy: true })`.
|
||||
- **A token has one producer: a second one fails `createApp`** (GitHub #35). The graph kept the
|
||||
last node registered for a token, and plugin nodes are registered after module nodes, so a
|
||||
plugin whose `scope.add` provided `user` silently replaced the app's own `@Provider({ provides:
|
||||
'user' })` for every route that needed it. Boot now fails instead, naming both nodes and where
|
||||
they came from: `token 'user' is provided twice: by 'user' (module:AppModule) and by 'shadow'
|
||||
(plugin)`. The rule covers the whole graph (modules, plugins, mesh steps spliced at boot, and
|
||||
the built-ins `logger`, `rooms` and `events`), so a plugin node that provides `logger` under
|
||||
another name fails as well, whatever order things are registered in. `overrides` keep working:
|
||||
they replace the runner of an existing token and add no producer. Observer steps that provide
|
||||
nothing are unaffected. The official plugins already follow name = node name = token.
|
||||
|
||||
### Added
|
||||
|
||||
|
||||
+36
-3
@@ -42,10 +42,43 @@ export interface GraphNode {
|
||||
origin: string;
|
||||
}
|
||||
|
||||
/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */
|
||||
export function topoSort(nodes: GraphNode[], seedKeys: string[], note = ''): GraphNode[] {
|
||||
/**
|
||||
* Maps every token to the one node that produces it; throws when a second node provides a token.
|
||||
*
|
||||
* One producer per token, across modules, plugins, mesh steps and built-ins alike (GitHub #35, D9).
|
||||
* This used to be `producedBy.set(key, node)`, last one wins: plugin nodes are registered after
|
||||
* module nodes, so a plugin's `scope.add` that provided `user` silently replaced the app's own `user`
|
||||
* for every route that needed it. Checking here, on the whole graph, rather than at each place a node
|
||||
* is registered, is what covers every path — current and future — and makes the built-in tokens
|
||||
* (`logger`, `rooms`, `events`) safe by rule instead of by registration order.
|
||||
*/
|
||||
function producers(nodes: GraphNode[]): 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) {
|
||||
const prior = producedBy.get(key);
|
||||
|
||||
if (prior && prior !== node) {
|
||||
throw new Error(
|
||||
`token '${key}' is provided twice: by '${prior.name}' (${prior.origin}) and by '${node.name}' (${node.origin}) — ` +
|
||||
'a token has exactly one producer; rename one of them, or use `overrides` to replace a runner',
|
||||
);
|
||||
}
|
||||
|
||||
producedBy.set(key, node);
|
||||
}
|
||||
}
|
||||
|
||||
return producedBy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Orders nodes so every dependency precedes its dependents; throws on a token with two producers,
|
||||
* missing keys or cycles.
|
||||
*/
|
||||
export function topoSort(nodes: GraphNode[], seedKeys: string[], note = ''): GraphNode[] {
|
||||
const producedBy = producers(nodes);
|
||||
|
||||
// validate dependencies exist
|
||||
for (const node of nodes) {
|
||||
|
||||
@@ -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