fix(bus): emit step events for ws and mesh routes
Steps were executed by three separate hand-rolled loops: runPipeline (HTTP), buildWsRoutes (ws) and resolveScope (mesh). Only the HTTP one emitted request:step:enter/leave, so a logging plugin silently observed nothing on ws routes — a gap in a documented public API, not just redundancy. Route every transport through a single runSteps() so observability is uniform by construction rather than by remembering to copy the emit calls. Also fixes the plugins guide, which documented a request:step:exit event that has never existed (the bus emits request:step:leave). Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
4 files changed
+71
-24
No files matched your search
+12
-15
@@ -3,7 +3,7 @@ import { Bus } from '../bus';
|
|||||||
import { Container } from '../container';
|
import { Container } from '../container';
|
||||||
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
|
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
|
||||||
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
|
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
|
||||||
import { runPipeline, PipelineStep } from '../pipeline';
|
import { runPipeline, runSteps, PipelineStep } from '../pipeline';
|
||||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
||||||
import type { HttpOptions } from '../http';
|
import type { HttpOptions } from '../http';
|
||||||
import { buildFetch } from '../http/web';
|
import { buildFetch } from '../http/web';
|
||||||
@@ -606,15 +606,13 @@ function buildMeshControl(
|
|||||||
|
|
||||||
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
|
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
|
||||||
// context is intentionally `any`: providers and steps merge arbitrary keys into it
|
// context is intentionally `any`: providers and steps merge arbitrary keys into it
|
||||||
let context: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers };
|
const seed: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers };
|
||||||
|
|
||||||
for (const provider of orderedProviders)
|
for (const provider of orderedProviders)
|
||||||
if (container.has(provider.name)) Object.assign(context, await container.resolve(provider.name));
|
if (container.has(provider.name)) Object.assign(seed, await container.resolve(provider.name));
|
||||||
|
|
||||||
for (const step of orderedSteps) {
|
const steps = orderedSteps.map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! }));
|
||||||
const runner = runners.get(step.name)!;
|
const context = await runSteps(steps, seed, bus);
|
||||||
context = { ...context, ...(await runner(context)) };
|
|
||||||
}
|
|
||||||
|
|
||||||
return context[name];
|
return context[name];
|
||||||
};
|
};
|
||||||
@@ -788,7 +786,7 @@ function openApiRoute(openapi: () => unknown): RouteDef {
|
|||||||
|
|
||||||
/** Compiles every ws/negotiate route plan into a WebSocket route that seeds context and runs its steps + handler. */
|
/** Compiles every ws/negotiate route plan into a WebSocket route that seeds context and runs its steps + handler. */
|
||||||
function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[] {
|
function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[] {
|
||||||
const { providedSeed, planSteps } = deps;
|
const { providedSeed, planSteps, bus } = deps;
|
||||||
|
|
||||||
return routePlans
|
return routePlans
|
||||||
.filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate')
|
.filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate')
|
||||||
@@ -798,8 +796,9 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[
|
|||||||
const provided = await providedSeed(plan);
|
const provided = await providedSeed(plan);
|
||||||
// ws upgrades carry the neutral WsRequest (protocol/ip pre-derived by the runtime adapter);
|
// ws upgrades carry the neutral WsRequest (protocol/ip pre-derived by the runtime adapter);
|
||||||
// trustProxy derivation for ws is out of scope here
|
// trustProxy derivation for ws is out of scope here
|
||||||
// context is intentionally `any`: each step merges arbitrary keys into it
|
const context = await runSteps(
|
||||||
let context: any = {
|
planSteps(plan),
|
||||||
|
{
|
||||||
...provided,
|
...provided,
|
||||||
req,
|
req,
|
||||||
params,
|
params,
|
||||||
@@ -810,11 +809,9 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[
|
|||||||
abort,
|
abort,
|
||||||
protocol: req.protocol,
|
protocol: req.protocol,
|
||||||
ip: req.ip,
|
ip: req.ip,
|
||||||
};
|
},
|
||||||
|
bus,
|
||||||
for (const step of planSteps(plan)) {
|
);
|
||||||
context = { ...context, ...(await step.run(context)) };
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await plan.run(context);
|
const result = await plan.run(context);
|
||||||
if (!isAsyncIterable(result)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
|
if (!isAsyncIterable(result)) throw new Error(`@Ws handler '${plan.handlerName}' must return an AsyncIterable`);
|
||||||
|
|||||||
+20
-7
@@ -40,6 +40,25 @@ export function isStreamResult(result: PipelineResult): result is StreamResult {
|
|||||||
return 'stream' in result;
|
return 'stream' in result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run `steps` in order, merging each step's output into the context and emitting
|
||||||
|
* `request:step:enter`/`leave` on the bus. The single place steps are executed — every
|
||||||
|
* transport (HTTP, ws, mesh) goes through here so observability is uniform by construction.
|
||||||
|
*/
|
||||||
|
export async function runSteps(steps: PipelineStep[], seed: Record<string, unknown>, bus: Bus): Promise<any> {
|
||||||
|
// context is intentionally `any`: each step merges arbitrary keys into the accumulator
|
||||||
|
let context: any = seed;
|
||||||
|
|
||||||
|
for (const step of steps) {
|
||||||
|
bus.emit('request:step:enter', { name: step.name, scope: step.origin });
|
||||||
|
const output = await step.run(context);
|
||||||
|
context = { ...context, ...output };
|
||||||
|
bus.emit('request:step:leave', { name: step.name, scope: step.origin });
|
||||||
|
}
|
||||||
|
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run `steps` in order over a context seeded from `seed`, then invoke `handler`.
|
* Run `steps` in order over a context seeded from `seed`, then invoke `handler`.
|
||||||
* An async-iterable handler result becomes a stream; anything else is run through `transformer`.
|
* An async-iterable handler result becomes a stream; anything else is run through `transformer`.
|
||||||
@@ -59,13 +78,7 @@ export async function runPipeline(args: {
|
|||||||
let context: any = { ...seed };
|
let context: any = { ...seed };
|
||||||
|
|
||||||
try {
|
try {
|
||||||
for (const step of steps) {
|
context = await runSteps(steps, context, bus);
|
||||||
bus.emit('request:step:enter', { name: step.name, scope: step.origin });
|
|
||||||
const output = await step.run(context);
|
|
||||||
context = { ...context, ...output };
|
|
||||||
bus.emit('request:step:leave', { name: step.name, scope: step.origin });
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await handler(context);
|
const result = await handler(context);
|
||||||
const streaming = isAsyncIterable(result);
|
const streaming = isAsyncIterable(result);
|
||||||
const contract = TRANSPORT_RETURN[transport];
|
const contract = TRANSPORT_RETURN[transport];
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
import { describe, it, expect } from 'vitest';
|
||||||
import { createApp, Route, Ws, Module, ctx } from '../src/index';
|
import { createApp, Route, Ws, Module, ctx, Step, needs } from '../src/index';
|
||||||
import { channel } from '../src/channel';
|
import { channel } from '../src/channel';
|
||||||
import type { WsSocket, WsRequest } from '../src/http/ws-core';
|
import type { WsSocket, WsRequest } from '../src/http/ws-core';
|
||||||
|
|
||||||
@@ -16,6 +16,24 @@ class Rt {
|
|||||||
class M {}
|
class M {}
|
||||||
const app = createApp({ modules: [M] });
|
const app = createApp({ modules: [M] });
|
||||||
|
|
||||||
|
@Step({ provides: 'tag' })
|
||||||
|
class Tagger {
|
||||||
|
run() {
|
||||||
|
return { tag: 't' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Route('/tagged')
|
||||||
|
class TaggedCtl {
|
||||||
|
@Ws('/echo')
|
||||||
|
echo(@needs('tag') tag: string, @ctx() { inbound }: any) {
|
||||||
|
return (async function* () {
|
||||||
|
for await (const msg of inbound) yield `${tag}:${msg}`;
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', steps: [Tagger], controllers: [TaggedCtl] })
|
||||||
|
class Tagged {}
|
||||||
|
|
||||||
function fakeSocket() {
|
function fakeSocket() {
|
||||||
const inbound = channel<unknown>();
|
const inbound = channel<unknown>();
|
||||||
const ac = new AbortController();
|
const ac = new AbortController();
|
||||||
@@ -46,6 +64,25 @@ describe('app.upgrade', () => {
|
|||||||
expect(sent).toEqual(['echo:hi']);
|
expect(sent).toEqual(['echo:hi']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('emits request:step:enter/leave for ws steps, like HTTP routes do', async () => {
|
||||||
|
const seen: string[] = [];
|
||||||
|
const logger = (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 { socket, inbound, sent } = fakeSocket();
|
||||||
|
const req: WsRequest = { url: '/tagged/echo', headers: {}, protocol: 'http', ip: '' };
|
||||||
|
const run = wsApp.upgrade(req, socket);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
inbound.push('hi');
|
||||||
|
inbound.close();
|
||||||
|
await run;
|
||||||
|
|
||||||
|
expect(sent).toEqual(['t:hi']);
|
||||||
|
expect(seen).toEqual(['enter:tag', 'leave:tag']);
|
||||||
|
});
|
||||||
|
|
||||||
it('closes 1008 on an unknown ws path', async () => {
|
it('closes 1008 on an unknown ws path', async () => {
|
||||||
const { socket } = fakeSocket();
|
const { socket } = fakeSocket();
|
||||||
let closedCode: number | undefined;
|
let closedCode: number | undefined;
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ mesh activity without touching the pipeline itself:
|
|||||||
```typescript
|
```typescript
|
||||||
api.bus.on('boot:provider:ready', (p: any) => { /* ... */ });
|
api.bus.on('boot:provider:ready', (p: any) => { /* ... */ });
|
||||||
api.bus.on('request:step:enter', (p: any) => { /* ... */ });
|
api.bus.on('request:step:enter', (p: any) => { /* ... */ });
|
||||||
api.bus.on('request:step:exit', (p: any) => { /* ... */ });
|
api.bus.on('request:step:leave', (p: any) => { /* ... */ });
|
||||||
```
|
```
|
||||||
|
|
||||||
The full event vocabulary:
|
The full event vocabulary:
|
||||||
|
|||||||
Reference in new issue
Block a user