From a327352ba0422eb8e60ca9218e3be822dd9db312 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 01:02:43 -0500 Subject: [PATCH 1/6] ci: typecheck, test, and build on push/PR (Gitea Actions, Node 18) Signed-off-by: Diego Resendez --- .gitea/workflows/ci.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .gitea/workflows/ci.yml diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..ba0e6fd --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,18 @@ +name: CI +on: + push: + branches: [develop, main] + pull_request: + branches: [develop, main] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '18' + - run: npm ci + - run: npm run typecheck + - run: npm test + - run: npm run build From ddca3fd74bab2f0dd9b0ac598942dd35749495c8 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 01:05:09 -0500 Subject: [PATCH 2/6] feat: request body-size limit (413) and configurable server timeouts Signed-off-by: Diego Resendez --- src/app.ts | 6 +++--- src/http.ts | 35 ++++++++++++++++++++++++++++------- src/index.ts | 1 + test/http.test.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 73 insertions(+), 10 deletions(-) diff --git a/src/app.ts b/src/app.ts index 7374ac5..f6a415e 100644 --- a/src/app.ts +++ b/src/app.ts @@ -3,7 +3,7 @@ import { Bus } from './bus'; import { Container } from './container'; import { topoSort, GraphNode } from './graph'; import { runPipeline, PipelineStep } from './pipeline'; -import { createHttpServer, parseQuery, RouteDef, WsRouteDef } from './http'; +import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http'; import { isAsyncIterable } from './channel'; import { JsonTransformer } from './transformers'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from './plugin'; @@ -43,7 +43,7 @@ export interface MeshConfig { timeoutMs?: number; } -export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig }): App { +export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits }): App { const bus = new Bus(); const container = new Container(); const extraSteps: ScopeNode[] = []; @@ -279,7 +279,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me }, })); - const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl); + const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits }); server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } }); await new Promise((resolve) => server.listen(port, resolve)); return server; diff --git a/src/http.ts b/src/http.ts index 86b05b4..a0bc495 100644 --- a/src/http.ts +++ b/src/http.ts @@ -2,11 +2,20 @@ import http from 'http'; import { once } from 'events'; import { channel } from './channel'; import { errorToResponse } from './transformers'; +import { HttpError } from './signals'; import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders'; import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline'; import type { Transport } from './metadata'; import type { Bus } from './bus'; +export interface RequestLimits { + maxBodyBytes?: number; // default 1_000_000 + requestTimeoutMs?: number; // default 30_000 + headersTimeoutMs?: number; // default 10_000 + keepAliveTimeoutMs?: number; // default 5_000 +} +export interface HttpOptions { limits?: RequestLimits } + export type RouteHandler = (req: { method: string; url: string; headers: Record; @@ -58,9 +67,14 @@ export function parseQuery(url: string): Record { return out; } -async function readBody(req: http.IncomingMessage): Promise { +async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise { const chunks: Buffer[] = []; - for await (const chunk of req) chunks.push(chunk as Buffer); + let total = 0; + for await (const chunk of req) { + total += (chunk as Buffer).length; + if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large'); + chunks.push(chunk as Buffer); + } if (chunks.length === 0) return undefined; const raw = Buffer.concat(chunks).toString('utf8'); return raw === '' ? undefined : raw; @@ -154,7 +168,10 @@ function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshCo }); } -export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl): http.Server { +export function createHttpServer( + routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions, +): http.Server { + const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000; const server = http.createServer(async (req, res) => { const url = req.url ?? '/'; const path = url.split('?')[0]; @@ -166,10 +183,11 @@ export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [] } let raw: string | undefined; try { - raw = await readBody(req); - } catch { - res.writeHead(500, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ error: 'Internal Server Error' })); + raw = await readBody(req, maxBody); + } catch (error) { + const r = errorToResponse(error); + res.writeHead(r.status, { ...r.headers, connection: 'close' }); + res.end(r.body); return; } let body: unknown = raw; @@ -200,6 +218,9 @@ export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [] res.writeHead(r.status, r.headers); res.end(r.body); }); + server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; + server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; + server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; attachWs(server, wsRoutes, bus, meshControl); return server; } diff --git a/src/index.ts b/src/index.ts index fec76a1..57ed120 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,6 +20,7 @@ export { inbound, abort } from './params'; export { sseEncoder, ndjsonEncoder } from './encoders'; export type { StreamEncoder } from './encoders'; export type { MeshConfig } from './app'; +export type { RequestLimits } from './http'; export { connectLink } from './mesh/link'; export { buildRemote, envelopeFrom } from './mesh/teacup'; export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot'; diff --git a/test/http.test.ts b/test/http.test.ts index cc445d1..f94b407 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -97,3 +97,44 @@ describe('http streaming', () => { server.close(); }); }); + +describe('request hardening', () => { + const getUrl = (s: import('http').Server) => `http://127.0.0.1:${(s.address() as any).port}`; + + it('rejects an over-size body with 413 and does not run the handler', async () => { + let ran = false; + const server = createHttpServer( + [{ method: 'POST', pattern: '/echo', transport: 'buffer', + handler: async () => { ran = true; return { status: 200, headers: {}, body: 'ok' }; } }], + [], undefined, undefined, { limits: { maxBodyBytes: 16 } }, + ); + await new Promise((r) => server.listen(0, r)); + const res = await fetch(`${getUrl(server)}/echo`, { method: 'POST', body: 'x'.repeat(1000) }); + expect(res.status).toBe(413); + expect(ran).toBe(false); + server.close(); + }); + + it('sets the configured server timeouts', async () => { + const server = createHttpServer([], [], undefined, undefined, + { limits: { requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } }); + expect(server.requestTimeout).toBe(12345); + expect(server.headersTimeout).toBe(6789); + expect(server.keepAliveTimeout).toBe(4321); + server.close(); + }); + + it('requestTimeout does NOT kill an in-flight SSE stream (streaming regression)', async () => { + async function* feed() { for (let n = 1; n <= 3; n++) { yield { n }; await new Promise((r) => setTimeout(r, 80)); } } + const server = createHttpServer( + [{ method: 'GET', pattern: '/feed', transport: 'sse', handler: async () => ({ stream: feed() }) }], + [], undefined, undefined, { limits: { requestTimeoutMs: 100 } }, + ); + await new Promise((r) => server.listen(0, r)); + const res = await fetch(`${getUrl(server)}/feed`, { headers: { accept: 'text/event-stream' } }); + const text = await res.text(); + expect(text).toContain('data: {"n":1}'); + expect(text).toContain('data: {"n":3}'); + server.close(); + }); +}); From 68caca2cc1ca24d0f2eb7593e249e3894bf4c1c9 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 01:07:42 -0500 Subject: [PATCH 3/6] feat: graceful shutdown via app.close() force-closing streams and connections Signed-off-by: Diego Resendez --- src/app.ts | 16 +++++++++++++--- src/http.ts | 18 +++++++++++++----- test/app.test.ts | 19 +++++++++++++++++++ 3 files changed, 45 insertions(+), 8 deletions(-) diff --git a/src/app.ts b/src/app.ts index f6a415e..19e7079 100644 --- a/src/app.ts +++ b/src/app.ts @@ -20,6 +20,7 @@ import type { RequestEnvelope, RouteEntry } from './mesh/protocol'; export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string } export interface App { listen(port: number): Promise; + close(): Promise; inspect(routePath: string): InspectLine[]; bus: Bus; } @@ -46,6 +47,8 @@ export interface MeshConfig { export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits }): App { const bus = new Bus(); const container = new Container(); + let server: http.Server | undefined; + const streams = new Set<() => void>(); const extraSteps: ScopeNode[] = []; const scope: ScopeApi = { add: (n) => extraSteps.push(n) }; @@ -279,13 +282,20 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me }, })); - const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits }); + server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams }); server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } }); - await new Promise((resolve) => server.listen(port, resolve)); + await new Promise((resolve) => server!.listen(port, resolve)); return server; }; - return { listen, inspect, bus }; + const close = (): Promise => new Promise((resolve) => { + if (!server) return resolve(); + server.close(() => resolve()); // waits for in-flight buffered to drain + for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves + server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive + }); + + return { listen, close, inspect, bus }; } async function snapshot(c: Container, needs: string[]): Promise> { diff --git a/src/http.ts b/src/http.ts index a0bc495..c4602c0 100644 --- a/src/http.ts +++ b/src/http.ts @@ -14,7 +14,7 @@ export interface RequestLimits { headersTimeoutMs?: number; // default 10_000 keepAliveTimeoutMs?: number; // default 5_000 } -export interface HttpOptions { limits?: RequestLimits } +export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void> } export type RouteHandler = (req: { method: string; url: string; @@ -88,7 +88,7 @@ function pickEncoder(transport: Transport, accept: string): StreamEncoder { async function pipeStream( res: http.ServerResponse, stream: AsyncIterable, encoder: StreamEncoder, - bus?: Bus, name = '', + bus?: Bus, name = '', streams?: Set<() => void>, ): Promise { res.writeHead(200, encoder.headers); bus?.emit('stream:open', { name }); @@ -97,6 +97,8 @@ async function pipeStream( if (encoder.ping) { ping = setInterval(() => res.write(encoder.ping!()), PING_MS); ping.unref?.(); } const stop = () => { if (ping) clearInterval(ping); void Promise.resolve(it.return?.()).catch(() => {}); }; res.on('close', stop); + const closer = () => { try { res.destroy(); } catch { /* */ } }; + streams?.add(closer); const onClose = once(res, 'close'); try { while (true) { @@ -113,6 +115,7 @@ async function pipeStream( if (frame && !res.writableEnded) res.write(frame); } finally { if (ping) clearInterval(ping); + streams?.delete(closer); if (!res.writableEnded && !res.destroyed) res.end(); bus?.emit('stream:close', { name }); } @@ -122,7 +125,9 @@ function loadWss(): any | null { try { return require('ws').WebSocketServer; } catch { return null; } } -function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshControl?: MeshControl): void { +function attachWs( + server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshControl?: MeshControl, streams?: Set<() => void>, +): void { if (wsRoutes.length === 0 && !meshControl) return; const WSS = loadWss(); const wss = WSS ? new WSS({ noServer: true }) : null; @@ -137,6 +142,9 @@ function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshCo if (!route) { socket.destroy(); return; } if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; } wss.handleUpgrade(req, socket, head, async (ws: any) => { + const closer = () => { try { (ws.terminate ?? ws.close).call(ws); } catch { /* */ } }; + streams?.add(closer); + ws.on('close', () => streams?.delete(closer)); const inbound = channel(); const ac = new AbortController(); ws.on('message', (d: Buffer) => inbound.push(d.toString())); @@ -211,7 +219,7 @@ export function createHttpServer( } if (isStreamResult(result)) { const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? '')); - await pipeStream(res, result.stream, encoder, bus, matched.def.pattern); + await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams); return; } const r: ResponseShape = result; @@ -221,6 +229,6 @@ export function createHttpServer( server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; - attachWs(server, wsRoutes, bus, meshControl); + attachWs(server, wsRoutes, bus, meshControl, opts?.streams); return server; } diff --git a/test/app.test.ts b/test/app.test.ts index 250bd36..cb1c6d8 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -153,3 +153,22 @@ describe('app streaming wiring', () => { client.close(); server.close(); }); }); + +describe('graceful shutdown', () => { + it('app.close() stops accepting and resolves, even with an SSE stream open', async () => { + @Route('/') + class Ctl { @Sse('/ticks') ticks() { return (async function* () { yield { t: 1 }; await new Promise((r) => setTimeout(r, 1000)); yield { t: 2 }; })(); } } + @Module({ mountpoint: '/', controllers: [Ctl] }) class M {} + const app = createApp({ modules: [M] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + + const res = await fetch(`http://127.0.0.1:${port}/ticks`, { headers: { accept: 'text/event-stream' } }); + const reader = res.body!.getReader(); + await reader.read(); // first event; stream still open + + await app.close(); // must NOT hang despite the open stream + await expect(fetch(`http://127.0.0.1:${port}/ticks`).then((r) => r.text())).rejects.toThrow(); + reader.cancel().catch(() => {}); + }); +}); From df01bbfc410e92f0c45f39a17d3724ad460b1f76 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 01:09:47 -0500 Subject: [PATCH 4/6] =?UTF-8?q?feat:=20per-route=20subgraph=20slicing=20?= =?UTF-8?q?=E2=80=94=20routes=20run=20only=20their=20needed=20providers/st?= =?UTF-8?q?eps?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- src/app.ts | 10 ++++++++-- src/graph.ts | 15 +++++++++++++++ test/app.test.ts | 39 +++++++++++++++++++++++++++++++++++++++ test/graph.test.ts | 22 ++++++++++++++++++++-- 4 files changed, 82 insertions(+), 4 deletions(-) diff --git a/src/app.ts b/src/app.ts index 19e7079..97afff6 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,7 +1,7 @@ import http from 'http'; import { Bus } from './bus'; import { Container } from './container'; -import { topoSort, GraphNode } from './graph'; +import { topoSort, subgraphFor, GraphNode } from './graph'; import { runPipeline, PipelineStep } from './pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http'; import { isAsyncIterable } from './channel'; @@ -129,7 +129,13 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params']); orderedProviders = ordered.filter((n) => providerNodes.includes(n)); orderedSteps = ordered.filter((n) => stepNodes.includes(n)); - for (const plan of routePlans) { plan.providers = orderedProviders; plan.steps = orderedSteps; } + const alwaysSteps = stepNodes.filter((n) => n.provides.length === 0); // side-effect/observer steps (plugins) + for (const plan of routePlans) { + const closure = subgraphFor(plan.needs, ordered); + plan.providers = closure.filter((n) => providerNodes.includes(n)); + const sliced = new Set([...closure.filter((n) => stepNodes.includes(n)), ...alwaysSteps]); + plan.steps = ordered.filter((n) => stepNodes.includes(n) && sliced.has(n)); // topo order, deduped + } const producedKeys = new Set([ ...providerNodes.flatMap((n) => n.provides), diff --git a/src/graph.ts b/src/graph.ts index 76f3112..7a215a9 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -37,3 +37,18 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { for (const n of nodes) visit(n, []); return ordered; } + +export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] { + const producedBy = new Map(); + for (const n of ordered) for (const k of n.provides) producedBy.set(k, n); + const inClosure = new Set(); + const work = [...needs]; + while (work.length) { + const token = work.pop() as string; + const node = producedBy.get(token); + if (!node || inClosure.has(node)) continue; // no producer = seed/envelope; already-seen = skip + inClosure.add(node); + work.push(...node.needs); + } + return ordered.filter((n) => inClosure.has(n)); +} diff --git a/test/app.test.ts b/test/app.test.ts index cb1c6d8..38e04b9 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -154,6 +154,45 @@ describe('app streaming wiring', () => { }); }); +describe('per-route subgraph slicing', () => { + it('a route that does not @needs a step does not run it', async () => { + const ran: string[] = []; + @Step({ provides: 'tracked', needs: [] }) + class Tracked { run() { ran.push('tracked'); return { tracked: true }; } } + @Route('/') + class Ctl { + @Get('/needs') needs(@needs('tracked') t: any) { return { t }; } + @Get('/free') free() { return { ok: true }; } + } + @Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] }) class M {} + const app = createApp({ modules: [M] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + + await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json()); + expect(ran).toEqual([]); // step did NOT run for /free + await fetch(`http://127.0.0.1:${port}/needs`).then((r) => r.json()); + expect(ran).toEqual(['tracked']); // step ran for /needs + expect(app.inspect('/free').map((l) => l.kind)).toEqual(['handler']); // no step in the chain + server.close(); + }); + + 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. + const ran: string[] = []; + const observer = (api: any) => api.scope.add({ kind: 'step', name: 'obs', needs: [], provides: [], run: () => { ran.push('obs'); return {}; } }); + @Route('/') + class Ctl { @Get('/free') free() { return { ok: true }; } } + @Module({ mountpoint: '/', controllers: [Ctl] }) class M {} + const app = createApp({ modules: [M], plugins: [observer] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json()); + expect(ran).toEqual(['obs']); // ran despite the route @needs-ing nothing + server.close(); + }); +}); + describe('graceful shutdown', () => { it('app.close() stops accepting and resolves, even with an SSE stream open', async () => { @Route('/') diff --git a/test/graph.test.ts b/test/graph.test.ts index f59b92e..a64bb44 100644 --- a/test/graph.test.ts +++ b/test/graph.test.ts @@ -1,5 +1,5 @@ -import { expect, test } from 'vitest'; -import { topoSort, GraphNode } from '../src/graph'; +import { describe, expect, it, test } from 'vitest'; +import { topoSort, GraphNode, subgraphFor } from '../src/graph'; const node = (name: string, needs: string[], provides: string[]): GraphNode => ({ name, needs, provides, origin: 'test' }); @@ -23,3 +23,21 @@ test('throws on cycle', () => { const nodes = [node('a', ['b'], ['a']), node('b', ['a'], ['b'])]; expect(() => topoSort(nodes, [])).toThrow(/cycle detected/); }); + +const N = (name: string, needs: string[] = []) => ({ name, needs, provides: [name], origin: 'm' }); + +describe('subgraphFor', () => { + const ordered = [N('config'), N('db', ['config']), N('user', ['db', 'req']), N('audit', ['db'])]; + it('returns the transitive closure of needs, in the given order', () => { + expect(subgraphFor(['user'], ordered).map((n) => n.name)).toEqual(['config', 'db', 'user']); + }); + it('returns empty for no needs', () => { + expect(subgraphFor([], ordered)).toEqual([]); + }); + it('ignores tokens with no producer (seeds/envelope)', () => { + expect(subgraphFor(['user', 'query', 'req'], ordered).map((n) => n.name)).toEqual(['config', 'db', 'user']); + }); + it('does not pull in unrelated nodes', () => { + expect(subgraphFor(['user'], ordered).map((n) => n.name)).not.toContain('audit'); + }); +}); From 9a5f54a4b3054265cc47d6fdb31f8e7dcaa8bc73 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 01:14:06 -0500 Subject: [PATCH 5/6] docs: document per-route slicing execution and app.close() in quickstart Signed-off-by: Diego Resendez --- docs/quickstart.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/quickstart.md b/docs/quickstart.md index fe412f4..6db7651 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -68,8 +68,18 @@ class ApiModule {} const app = createApp({ modules: [ApiModule] }); await app.listen(3000); // GET /api/users/9 (header x-token) → { "requested": "9", "you": { "id": "...", "name": "Diego" } } + +await app.close(); // graceful shutdown: drains in-flight requests, closes streams + mesh links ``` +> **Per-route execution (important).** Each route runs **only the providers/steps in the transitive +> closure of its handler's `@needs`** — nothing else. A route that doesn't `@needs('user')` does **not** +> run the `Authenticate` step. This means a cross-cutting *enforcement* step (e.g. auth that throws 401) +> only protects routes that actually `@needs` its token. To run something on **every** route regardless +> of needs (logging, audit, a global guard), add it as a **plugin step** via `scope.add({ ..., provides: [] })` — +> steps that produce nothing run unconditionally. Don't rely on a token-providing step to guard routes +> that don't declare it. + ### Argument decorators | Decorator | Reads from | Adds a graph dependency? | From a25c9752a2e61ef804eef311620a8c8b98762fa9 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 01:14:20 -0500 Subject: [PATCH 6/6] fix: always-run observer steps receive their declared needs under slicing Signed-off-by: Diego Resendez --- src/app.ts | 3 ++- test/app.test.ts | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/app.ts b/src/app.ts index 97afff6..3ca3b38 100644 --- a/src/app.ts +++ b/src/app.ts @@ -130,8 +130,9 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me orderedProviders = ordered.filter((n) => providerNodes.includes(n)); orderedSteps = ordered.filter((n) => stepNodes.includes(n)); const alwaysSteps = stepNodes.filter((n) => n.provides.length === 0); // side-effect/observer steps (plugins) + const alwaysNeeds = alwaysSteps.flatMap((n) => n.needs); // pull observers' deps into every route for (const plan of routePlans) { - const closure = subgraphFor(plan.needs, ordered); + const closure = subgraphFor([...plan.needs, ...alwaysNeeds], ordered); plan.providers = closure.filter((n) => providerNodes.includes(n)); const sliced = new Set([...closure.filter((n) => stepNodes.includes(n)), ...alwaysSteps]); plan.steps = ordered.filter((n) => stepNodes.includes(n) && sliced.has(n)); // topo order, deduped diff --git a/test/app.test.ts b/test/app.test.ts index 38e04b9..b1feb59 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -191,6 +191,22 @@ describe('per-route subgraph slicing', () => { expect(ran).toEqual(['obs']); // ran despite the route @needs-ing nothing server.close(); }); + + it('an always-run observer step receives its declared needs even when the route does not need them', async () => { + let seen: any; + const observer = (api: any) => api.scope.add({ kind: 'step', name: 'audit', needs: ['user'], provides: [], run: (ctx: any) => { seen = ctx.user; return {}; } }); + @Step({ provides: 'user', needs: [] }) + class Auth { run() { return { user: { id: 'u1' } }; } } + @Route('/') + class Ctl { @Get('/free') free() { return { ok: true }; } } // does NOT @needs('user') + @Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] }) class M {} + const app = createApp({ modules: [M], plugins: [observer] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json()); + expect(seen).toEqual({ id: 'u1' }); // observer got user, not undefined + server.close(); + }); }); describe('graceful shutdown', () => {