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:
7 files changed
+307
-18
No files matched your search
+58
-14
@@ -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
@@ -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
@@ -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
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user