From df01bbfc410e92f0c45f39a17d3724ad460b1f76 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 28 Jun 2026 01:09:47 -0500 Subject: [PATCH] =?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'); + }); +});