test: build plugins as named objects

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-09-16 22:27:15 -05:00
1 parent 3fc761ce16
commit b3152aac45
6 files changed
+107 -63

No files matched your search

+6 -3
View File
@@ -66,9 +66,12 @@ describe('app.upgrade', () => {
it('emits request:step:enter/leave for ws steps, like HTTP routes do', async () => { it('emits request:step:enter/leave for ws steps, like HTTP routes do', async () => {
const seen: string[] = []; const seen: string[] = [];
const logger = (api: any) => { const logger = {
api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`)); name: 'ws-step-logger',
api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`)); mount: (api: any) => {
api.bus.on('request:step:enter', (p: any) => seen.push(`enter:${p.name}`));
api.bus.on('request:step:leave', (p: any) => seen.push(`leave:${p.name}`));
},
}; };
const wsApp = createApp({ modules: [Tagged], plugins: [logger] }); const wsApp = createApp({ modules: [Tagged], plugins: [logger] });
const { socket, inbound, sent } = fakeSocket(); const { socket, inbound, sent } = fakeSocket();
+32 -23
View File
@@ -56,7 +56,10 @@ test('ready() is a no-op on a non-mesh app, so one protocol works for both', asy
test('a logger plugin observes step:enter without mutating the chain', async () => { test('a logger plugin observes step:enter without mutating the chain', async () => {
const seen: string[] = []; const seen: string[] = [];
const logger = (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name)); const logger = {
name: 'step-logger',
mount: (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name)),
};
const app = createApp({ modules: [ApiModule], plugins: [logger] }); const app = createApp({ modules: [ApiModule], plugins: [logger] });
const server = await app.listen(0); const server = await app.listen(0);
const port = (server.address() as any).port; const port = (server.address() as any).port;
@@ -256,17 +259,20 @@ describe('per-route subgraph slicing', () => {
it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => { it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => {
// NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add. // NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add.
const ran: string[] = []; const ran: string[] = [];
const observer = (api: any) => const observer = {
api.scope.add({ name: 'side-effect-observer',
kind: 'step', mount: (api: any) =>
name: 'obs', api.scope.add({
needs: [], kind: 'step',
provides: [], name: 'obs',
run: () => { needs: [],
ran.push('obs'); provides: [],
return {}; run: () => {
}, ran.push('obs');
}); return {};
},
}),
};
@Route('/') @Route('/')
class Ctl { class Ctl {
@Get('/free') free() { @Get('/free') free() {
@@ -285,17 +291,20 @@ describe('per-route subgraph slicing', () => {
it('an always-run observer step receives its declared needs even when the route does not need them', async () => { it('an always-run observer step receives its declared needs even when the route does not need them', async () => {
let seen: any; let seen: any;
const observer = (api: any) => const observer = {
api.scope.add({ name: 'audit-observer',
kind: 'step', mount: (api: any) =>
name: 'audit', api.scope.add({
needs: ['user'], kind: 'step',
provides: [], name: 'audit',
run: (ctx: any) => { needs: ['user'],
seen = ctx.user; provides: [],
return {}; run: (ctx: any) => {
}, seen = ctx.user;
}); return {};
},
}),
};
@Step({ provides: 'user', needs: [] }) @Step({ provides: 'user', needs: [] })
class Auth { class Auth {
run() { run() {
+5 -2
View File
@@ -22,8 +22,11 @@ describe('reaching the bus', () => {
const fromOutside: string[] = []; const fromOutside: string[] = [];
const fromPlugin: string[] = []; const fromPlugin: string[] = [];
const observer: Plugin = (api) => { const observer: Plugin = {
api.bus.on('request:end', (e) => fromPlugin.push(e.route ?? '')); name: 'bus-observer',
mount(api) {
api.bus.on('request:end', (e) => fromPlugin.push(e.route ?? ''));
},
}; };
@Module({ mountpoint: '/', controllers: [Ctl] }) @Module({ mountpoint: '/', controllers: [Ctl] })
+28 -15
View File
@@ -10,9 +10,12 @@ test('plugin can observe via bus.on and add to its own scope', () => {
const added: string[] = []; const added: string[] = [];
const scope: ScopeApi = { add: (n) => added.push(n.name) }; const scope: ScopeApi = { add: (n) => added.push(n.name) };
const logger: Plugin = (api) => { const logger: Plugin = {
api.bus.on('request:step:enter', () => {}); name: 'logger',
api.scope.add({ kind: 'step', name: 'log', needs: [], provides: [], run: () => ({}) }); mount(api) {
api.bus.on('request:step:enter', () => {});
api.scope.add({ kind: 'step', name: 'log', needs: [], provides: [], run: () => ({}) });
},
}; };
const mounted = vi.fn(); const mounted = vi.fn();
@@ -26,8 +29,11 @@ test('plugin can observe via bus.on and add to its own scope', () => {
test('plugin api does NOT expose bus.emit', () => { test('plugin api does NOT expose bus.emit', () => {
const bus = new Bus(); const bus = new Bus();
const scope: ScopeApi = { add: () => {} }; const scope: ScopeApi = { add: () => {} };
const plugin: Plugin = (api) => { const plugin: Plugin = {
expect((api.bus as any).emit).toBeUndefined(); name: 'emit-probe',
mount(api) {
expect((api.bus as any).emit).toBeUndefined();
},
}; };
mountPlugin(plugin, bus, scope, noTeardown()); mountPlugin(plugin, bus, scope, noTeardown());
}); });
@@ -35,8 +41,11 @@ test('plugin api does NOT expose bus.emit', () => {
test('plugin can register a teardown, and it reaches the registry', () => { test('plugin can register a teardown, and it reaches the registry', () => {
const bus = new Bus(); const bus = new Bus();
const registered: TeardownFn[] = []; const registered: TeardownFn[] = [];
const plugin: Plugin = (api) => { const plugin: Plugin = {
api.onShutdown(() => {}); name: 'teardown-registrar',
mount(api) {
api.onShutdown(() => {});
},
}; };
mountPlugin(plugin, bus, { add: () => {} }, (fn) => registered.push(fn)); mountPlugin(plugin, bus, { add: () => {} }, (fn) => registered.push(fn));
@@ -44,22 +53,26 @@ test('plugin can register a teardown, and it reaches the registry', () => {
expect(registered).toHaveLength(1); expect(registered).toHaveLength(1);
}); });
// D3's no-break guarantee, asserted rather than assumed: `Plugin`'s signature did not change, so a // A plugin that opens nothing registers nothing: `onShutdown` is opt-in, and the teardown registry
// plugin written before this capability existed must mount and behave exactly as it did. // stays empty rather than collecting no-ops. (The shape guarantee this test used to assert went
test('a plugin that never calls onShutdown behaves exactly as before', () => { // away with the move to `{ name, mount }` — see CHANGELOG, Breaking.)
test('a plugin that never calls onShutdown registers no teardown', () => {
const bus = new Bus(); const bus = new Bus();
const added: string[] = []; const added: string[] = [];
const registered: TeardownFn[] = []; const registered: TeardownFn[] = [];
const legacy: Plugin = (api) => { const quiet: Plugin = {
api.bus.on('stream:open', () => {}); name: 'quiet',
api.scope.add({ kind: 'provider', name: 'thing', needs: [], provides: ['thing'], run: () => ({}) }); mount(api) {
api.bus.on('stream:open', () => {});
api.scope.add({ kind: 'provider', name: 'thing', needs: [], provides: ['thing'], run: () => ({}) });
},
}; };
const mounted = vi.fn(); const mounted = vi.fn();
bus.on('plugin:mounted', mounted); bus.on('plugin:mounted', mounted);
mountPlugin(legacy, bus, { add: (n) => added.push(n.name) }, (fn) => registered.push(fn)); mountPlugin(quiet, bus, { add: (n) => added.push(n.name) }, (fn) => registered.push(fn));
expect(added).toEqual(['thing']); expect(added).toEqual(['thing']);
expect(mounted).toHaveBeenCalled(); expect(mounted).toHaveBeenCalledWith(expect.objectContaining({ name: 'quiet' }));
expect(registered).toHaveLength(0); expect(registered).toHaveLength(0);
}); });
+26 -14
View File
@@ -17,11 +17,14 @@ class Ctl {
describe('shutdown teardown', () => { describe('shutdown teardown', () => {
it('awaits a plugin onShutdown before close() resolves', async () => { it('awaits a plugin onShutdown before close() resolves', async () => {
const order: string[] = []; const order: string[] = [];
const plugin: Plugin = (api) => { const plugin: Plugin = {
api.onShutdown(async () => { name: 'slow-teardown',
await new Promise((r) => setTimeout(r, 20)); mount(api) {
order.push('plugin torn down'); api.onShutdown(async () => {
}); await new Promise((r) => setTimeout(r, 20));
order.push('plugin torn down');
});
},
}; };
@Module({ mountpoint: '/', controllers: [Ctl] }) @Module({ mountpoint: '/', controllers: [Ctl] })
@@ -135,11 +138,14 @@ describe('shutdown teardown', () => {
it('logs a failing teardown, runs the rest, and still resolves', async () => { it('logs a failing teardown, runs the rest, and still resolves', async () => {
const logger = silentLogger(); const logger = silentLogger();
const closed: string[] = []; const closed: string[] = [];
const plugin: Plugin = (api) => { const plugin: Plugin = {
api.onShutdown(() => { name: 'failing-teardown',
throw new Error('teardown boom'); mount(api) {
}); api.onShutdown(() => {
api.onShutdown(() => void closed.push('survivor')); throw new Error('teardown boom');
});
api.onShutdown(() => void closed.push('survivor'));
},
}; };
@Module({ mountpoint: '/', controllers: [Ctl] }) @Module({ mountpoint: '/', controllers: [Ctl] })
@@ -153,8 +159,11 @@ describe('shutdown teardown', () => {
}); });
it('does not let a hanging teardown push close() past its deadline', async () => { it('does not let a hanging teardown push close() past its deadline', async () => {
const plugin: Plugin = (api) => { const plugin: Plugin = {
api.onShutdown(() => new Promise<void>(() => {})); // never settles name: 'hanging-teardown',
mount(api) {
api.onShutdown(() => new Promise<void>(() => {})); // never settles
},
}; };
@Module({ mountpoint: '/', controllers: [Ctl] }) @Module({ mountpoint: '/', controllers: [Ctl] })
@@ -199,8 +208,11 @@ describe('shutdown teardown', () => {
it('drains only once when close() is called twice', async () => { it('drains only once when close() is called twice', async () => {
let runs = 0; let runs = 0;
const plugin: Plugin = (api) => { const plugin: Plugin = {
api.onShutdown(() => void runs++); name: 'counting-teardown',
mount(api) {
api.onShutdown(() => void runs++);
},
}; };
@Module({ mountpoint: '/', controllers: [Ctl] }) @Module({ mountpoint: '/', controllers: [Ctl] })
+10 -6
View File
@@ -26,8 +26,8 @@ const prometheusText: TransformerFn = (value) => ({
body: String(value), body: String(value),
}); });
// A plugin split into named functions rather than one inline arrow: `Plugin` alone types the // A plugin split into named functions rather than one inline `mount`: `Plugin` types the object,
// arrow, and nothing typed its argument. // and `PluginApi`/`ScopeApi`/`ScopeNode` type what the pieces receive.
function subscribe(api: PluginApi): void { function subscribe(api: PluginApi): void {
api.bus.on('request:end', () => {}); api.bus.on('request:end', () => {});
api.onShutdown(flush); api.onShutdown(flush);
@@ -40,9 +40,12 @@ function contribute(scope: ScopeApi): void {
scope.add(node); scope.add(node);
} }
const metricsPlugin: Plugin = (api) => { const metricsPlugin: Plugin = {
subscribe(api); name: 'metrics',
contribute(api.scope); mount(api) {
subscribe(api);
contribute(api.scope);
},
}; };
// createApp({ hooks }) — declared as a value, which is the point of the option. // createApp({ hooks }) — declared as a value, which is the point of the option.
@@ -59,7 +62,8 @@ const encoder: StreamEncoder = {
test('every extension point is typeable from the package barrel', () => { test('every extension point is typeable from the package barrel', () => {
expect(prometheusText('x').body).toBe('x'); expect(prometheusText('x').body).toBe('x');
expect(typeof metricsPlugin).toBe('function'); expect(typeof metricsPlugin.mount).toBe('function');
expect(metricsPlugin.name).toBe('metrics');
expect(hooks).toHaveLength(1); expect(hooks).toHaveLength(1);
expect(renderError(new Error('boom'), {} as never)?.status).toBe(500); expect(renderError(new Error('boom'), {} as never)?.status).toBe(500);
expect(encoder.encode(1)).toBe('1'); expect(encoder.encode(1)).toBe('1');