feat(di): a read-only events token, and framework names nobody can take

Three things that turned out to be one decision.

## `@needs('events')`

`app.bus` is public and `Bus` is an exported type, but the bus was not a graph token, so
`@needs('bus')` failed at boot. There is a good reason for the difference — putting the
`Bus` in the graph hands `emit` to every node and turns a one-way observation channel into
something anything can forge events on — and it was written down nowhere, inferable only
by reading `provideBuiltins` and noticing what is absent.

The read-only half is a token now: `events`, bound to `{ on }`, the same narrowing plugins
already get. `@needs('events')` works the way `@needs('logger')` does, which is the
symmetry a reader expects, and `emit` still belongs to nobody.

A plugin remains the right home for observation and the docs say so, because it gets
`on` and `onShutdown` *together*. The token gives the subscribe half alone: a `@Provider`
that subscribes should release in `dispose()` — `on()` returns its own unsubscribe — and a
`@Step` should not subscribe at all, since it runs per request and would add a listener
each time.

## The boot error teaches it

Documenting it prevents the mistake for a reader; it does nothing for the person typing
`@needs('bus')`, which is who the issue was about. That need now fails with what it should
have used and why, rather than the generic "nothing provides it" plus a nearest-match that
has nothing near enough to suggest.

## Framework names are reserved

**Behaviour change.** Builtins were registered with `if (!runners.has(name))`, so a
provider called `logger` silently replaced the framework's own and every `@needs('logger')`
in the app got something that was not the logger core writes to — a divergence you
discover from a log line that never appeared. `logger`, `rooms`, `events` and `bus` are
reserved now, enforced in `setRunner`, which is the single point modules, plugins and mesh
exports all register through. Taking one is a boot error naming it.

`bus` is reserved without being provided, so `@needs('bus')` cannot resolve to whatever a
user happened to call `bus` and be wrong in silence.

This replaces a test that asserted the old shadowing as a feature.

Closes #67.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-09-01 10:57:47 -05:00
1 parent c00f714aa8
commit 1e76921d49
7 files changed
+307 -18

No files matched your search

+58 -14
View File
@@ -1,5 +1,5 @@
import type http from 'http';
import { Bus } from '../bus';
import { Bus, type Events } from '../bus';
import { createDefaultLogger, logRequests, type Logger } from '../logger';
import { Container } from '../container';
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
@@ -62,7 +62,7 @@ interface Registry {
exportedProviders: string[];
exportedSteps: string[];
exportedRoutes: RouteEntry[];
setRunner(name: string, runner: Runner): void;
setRunner(name: string, runner: Runner, framework?: boolean): void;
}
/**
@@ -210,7 +210,7 @@ export function createApp(opts: {
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs);
mountPlugins(opts.plugins, bus, registry, teardown);
provideBuiltins(registry, logger);
provideBuiltins(registry, logger, bus);
// For each route, resolve which providers/steps feed it via topo order.
// MVP: every route depends on every declared step + provider in the app graph.
@@ -406,7 +406,12 @@ export function createApp(opts: {
function emptyRegistry(): Registry {
const runners = new Map<string, Runner>(); // node name -> runtime fn
const setRunner = (name: string, runner: Runner) => {
const setRunner = (name: string, runner: Runner, framework = false) => {
if (!framework && RESERVED_TOKENS.has(name))
throw new Error(
`'${name}' is reserved by the framework and cannot be provided by a module, plugin or mesh export — ` +
`rename it. The framework's own '${name}' is what '@needs' resolves to.`,
);
if (runners.has(name))
throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
runners.set(name, runner);
@@ -595,22 +600,46 @@ function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registr
}
/** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */
function provideBuiltins(registry: Registry, logger: Logger): void {
/**
* Token names the framework owns. Declaring one is a boot error, not a silent override.
*
* Builtins used to be registered with `if (!runners.has(name))`, so a provider called `logger`
* quietly replaced the framework's own and every `@needs('logger')` in the app got something else.
* That is the kind of thing that is discovered from a log line that never appeared.
*
* `bus` is reserved without being provided, on purpose. It is not a graph token — putting the `Bus`
* itself in the graph would hand `emit` to every node and turn a one-way observation channel into
* something anything can forge events on. Reserving the name means `@needs('bus')` can say that,
* instead of resolving to whatever a user happened to call `bus` and being wrong in silence.
*/
const RESERVED_TOKENS = new Set(['logger', 'rooms', 'events', 'bus']);
function provideBuiltins(registry: Registry, logger: Logger, bus: Bus): void {
const builtin = (name: string, value: () => Record<string, unknown>): void => {
registry.providerNodes.push({ name, needs: [], provides: [name], origin: 'builtin' });
registry.providerMeta.set(name, { optional: false });
registry.setRunner(name, value, true);
};
// `logger` is registered as an ordinary provider *in addition to* being framework infrastructure,
// so a step or handler reaches it with `@needs('logger')` like any other dependency. It is the
// same object createApp holds, not a second one — core cannot depend on the graph for something
// it must use while the graph is still resolving.
if (!registry.runners.has('logger')) {
registry.providerNodes.push({ name: 'logger', needs: [], provides: ['logger'], origin: 'builtin' });
registry.providerMeta.set('logger', { optional: false });
registry.setRunner('logger', () => ({ logger }));
}
builtin('logger', () => ({ logger }));
if (registry.runners.has('rooms')) return;
const roomsInstance = new Rooms();
registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' });
registry.providerMeta.set('rooms', { optional: false });
registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms
builtin('rooms', () => ({ rooms: roomsInstance }));
// The read-only half of the bus, and only the read-only half: `on`, never `emit`. The same
// narrowing a plugin gets, for the same reason — an observation channel anything can write to is
// not one.
//
// A subscription is not like the other injectables, and the difference is the scope that reaches
// it. A `@Provider` runs once, so subscribing there is fine; a `@Step` runs *per request*, and a
// step that calls `on()` registers a listener on every one of them. `on()` returns its own
// unsubscribe for the provider that wants to clean up in `dispose()` — but a plugin, which gets
// `on` and `onShutdown` together, remains the right home for observation.
builtin('events', () => ({ events: { on: bus.on.bind(bus) } satisfies Events }));
}
// Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling
@@ -668,6 +697,21 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
for (const plan of routePlans) {
for (const need of plan.needs) {
if (allowed.has(need)) continue;
// The generic message plus a nearest-match is right for a typo and useless here: nothing is
// spelled nearly enough like `bus` to suggest, and the reader's mistake is not a typo but a
// reasonable guess about the shape. `@needs('logger')` teaches that framework things are
// graph tokens, so `@needs('bus')` is the next instinct — and the boot error is the first
// news that it is not the same shape. Say why, where they are.
if (need === 'bus') {
throw new Error(
`handler '${plan.handlerName}' needs 'bus' — the Bus is not a graph token, because a node ` +
`that could reach it could also emit, and an observation channel anything can write to ` +
`is not one. Use @needs('events') for the read-only half ({ on }), or write a plugin, ` +
`which gets on() and onShutdown() together and is the right home for observation.`,
);
}
const hint = nearest(need, allowed);
throw new Error(
`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`,
+16
View File
@@ -132,6 +132,22 @@ export interface EventPayload {
*/
export type Correlation = Pick<EventPayload, 'requestId' | 'traceId' | 'route' | 'method' | 'transport'>;
/**
* The read-only half of the {@link Bus}, as `@needs('events')` hands it over.
*
* `on` and deliberately not `emit`: a channel anything can write to is not an observation channel,
* and the framework's own events would stop being trustworthy the moment a node could forge one.
* Plugins get exactly this same narrowing.
*
* `on` returns its own unsubscribe. Use it — a `@Provider` that subscribes should release in
* `dispose()`, and a `@Step` should not subscribe at all, since it runs once per request and would
* add a listener each time. A plugin, which gets `on` and `onShutdown` together, is the home this
* token exists to point at rather than replace.
*/
export interface Events {
on: Bus['on'];
}
/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
export class Bus {
private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>();
+1 -1
View File
@@ -60,7 +60,7 @@ export {
// Bus & flow
export { Bus } from './bus';
export type { LifecycleEvent, EventPayload, Correlation } from './bus';
export type { LifecycleEvent, EventPayload, Correlation, Events } from './bus';
export { flow, Flow } from './flow';
export type { StepFn, CompiledFlow } from './flow';
+12 -1
View File
@@ -14,7 +14,18 @@ export interface ScopeNode {
export interface ScopeApi {
add(node: ScopeNode): void;
}
/** The capabilities handed to a plugin: event subscription, node registration, and teardown. */
/**
* The capabilities handed to a plugin: event subscription, node registration, and teardown.
*
* This is the home for observation, and the reason is the pairing: `bus.on` arrives next to
* `onShutdown`, so whatever a plugin subscribes to it can also release. A graph node can reach the
* same read-only slice through `@needs('events')`, but it gets the subscribe half without the
* unsubscribe half — and a `@Step` reaching it would register a listener per request.
*
* The `Bus` itself is deliberately not here and is not a graph token either: handing over `emit`
* would turn a one-way observation channel into something any node can forge events on.
* `@needs('bus')` fails at boot and says so.
*/
export interface PluginApi {
bus: { on: Bus['on'] };
scope: ScopeApi;
+6 -2
View File
@@ -603,7 +603,11 @@ describe('rooms auto-provide', () => {
expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
s.close();
});
it('a user-declared rooms provider wins (no duplicate-name throw)', () => {
// This used to be allowed, and the user's provider silently replaced the framework's. The same
// held for `logger`, where every `@needs('logger')` in the app then got something that was not
// the logger core writes to — a divergence discovered from a log line that never appeared.
// Framework token names are reserved now, and taking one is a boot error.
it('refuses a user-declared rooms provider instead of silently replacing the built-in', () => {
@Provider({ provides: 'rooms' })
class MyRooms {
provide() {
@@ -618,7 +622,7 @@ describe('rooms auto-provide', () => {
}
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).not.toThrow();
expect(() => createApp({ modules: [M] })).toThrow(/'rooms' is reserved by the framework/);
});
});
+73
View File
@@ -0,0 +1,73 @@
// The three legitimate ways to reach the bus, exercised together in one app.
//
// `bus` became a reserved name and the `Bus` itself is still not a graph token, so this file's job
// is to prove that what closed is only the wrong door: observation from outside, from a plugin and
// from inside the graph all still work, and only `emit` stays where it was.
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp, Route, Get, Module, needs } from '../src/index';
import type { Events, Plugin } from '../src/index';
@Route('/b')
class Ctl {
@Get('/x') x(@needs('events') events: Events) {
// Reaching it per request is allowed; *subscribing* per request is the thing the docs warn
// about, and nothing here does that.
return { hasOn: typeof events.on === 'function' };
}
}
describe('reaching the bus', () => {
it('works from outside, from a plugin and from the graph, all at once', async () => {
const fromOutside: string[] = [];
const fromPlugin: string[] = [];
const observer: Plugin = (api) => {
api.bus.on('request:end', (e) => fromPlugin.push(e.route ?? ''));
};
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [observer] });
// 1. from outside: the public `app.bus`, which keeps `emit` too.
app.bus.on('request:end', (e) => fromOutside.push(e.route ?? ''));
// 3. from the graph: the handler receives `events` and reports its shape.
const res = await app.fetch(new Request('http://x/b/x'));
expect(await res.json()).toEqual({ hasOn: true });
expect(fromOutside).toEqual(['/b/x']);
expect(fromPlugin).toEqual(['/b/x']);
await app.close();
});
it('keeps emit outside the graph and outside plugins, and only there', async () => {
let injected: Events | undefined;
const seen: string[] = [];
@Route('/e')
class Grab {
@Get('/x') x(@needs('events') events: Events) {
injected = events;
return {};
}
}
@Module({ mountpoint: '/', controllers: [Grab] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/x'));
// The graph's slice cannot forge an event...
expect((injected as unknown as { emit?: unknown }).emit).toBeUndefined();
// ...while the application that owns the app still can, which is what `app.bus` is for.
app.bus.on('plugin:mounted', (e) => seen.push(e.name));
app.bus.emit('plugin:mounted', { name: 'from the owner' });
expect(seen).toEqual(['from the owner']);
await app.close();
});
});
+141
View File
@@ -0,0 +1,141 @@
// Framework token names, and the read-only slice of the bus that `@needs` can reach.
//
// Two halves of one decision. The bus is not a graph token — a node that could reach it could also
// `emit`, and an observation channel anything can write to is not one — but `@needs('logger')`
// teaches that framework things *are* graph tokens, so reaching for `@needs('bus')` is the natural
// next move. Documenting that it does not work only reaches a reader; the boot error reaches the
// person writing it. And reserving the names stops a user's own `logger` from quietly becoming the
// one the whole app injects.
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
import type { Events } from '../src/index';
@Route('/r')
class Ctl {
@Get('/x') x() {
return { ok: true };
}
}
describe('reserved framework tokens', () => {
for (const token of ['logger', 'rooms', 'events']) {
it(`refuses a provider that declares '${token}'`, () => {
@Provider({ provides: token })
class Shadow {
provide() {
return { [token]: { mine: true } };
}
}
@Module({ mountpoint: '/', providers: [Shadow], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(
new RegExp(`'${token}' is reserved by the framework`),
);
});
}
it("refuses a step that declares 'bus', a name the framework reserves without providing", () => {
@Step({ provides: 'bus' })
class Shadow {
run() {
return { bus: { mine: true } };
}
}
@Module({ mountpoint: '/', steps: [Shadow], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/'bus' is reserved by the framework/);
});
it('leaves every other name alone', () => {
@Provider({ provides: 'buses' })
class Fine {
provide() {
return { buses: 1 };
}
}
@Module({ mountpoint: '/', providers: [Fine], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).not.toThrow();
});
});
describe("@needs('bus')", () => {
it('fails at boot naming the read-only token and the plugin, not a nearest match', () => {
@Route('/b')
class Bad {
@Get('/x') x(@needs('bus') _bus: unknown) {
return {};
}
}
@Module({ mountpoint: '/', controllers: [Bad] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/the Bus is not a graph token/);
expect(() => createApp({ modules: [M] })).toThrow(/@needs\('events'\)/);
expect(() => createApp({ modules: [M] })).toThrow(/plugin/);
});
});
describe("@needs('events')", () => {
it('hands over on() and nothing else — no emit to forge events with', async () => {
let injected: Events | undefined;
@Route('/e')
class Observer {
@Get('/x') x(@needs('events') events: Events) {
injected = events;
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Observer] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/x'));
expect(typeof injected?.on).toBe('function');
expect(Object.keys(injected!)).toEqual(['on']);
expect((injected as unknown as { emit?: unknown }).emit).toBeUndefined();
});
it('subscribes to the same bus the framework emits on, and hands back an unsubscribe', async () => {
const seen: string[] = [];
@Provider({ provides: 'watcher', needs: ['events'] })
class Watcher {
#off?: () => void;
provide(ctx: { events: Events }) {
this.#off = ctx.events.on('request:end', (e) => seen.push(e.route ?? ''));
return { watcher: true };
}
dispose() {
this.#off?.();
}
}
@Route('/e')
class Observed {
@Get('/y') y(@needs('watcher') _w: unknown) {
return { ok: true };
}
}
@Module({ mountpoint: '/', providers: [Watcher], controllers: [Observed] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/y'));
expect(seen).toEqual(['/e/y']);
// dispose() releases it, which is the half a plugin gets for free with onShutdown. Asserted by
// emitting after close and watching nothing arrive — clearing the array and finding it empty
// would prove only that clearing works.
await app.close();
seen.length = 0;
app.bus.emit('request:end', { name: 'after close', route: '/after' });
expect(seen).toEqual([]);
});
});