diff --git a/src/app/index.ts b/src/app/index.ts index 926e141..71ae619 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -2,7 +2,7 @@ import type http from 'http'; import { Bus, type Events } from '../bus'; import { createDefaultLogger, logRequests, type Logger } from '../logger'; import { Container } from '../container'; -import { topoSort, subgraphFor, GraphNode, nearest } from '../graph'; +import { topoSort, topoLevels, subgraphFor, GraphNode, nearest } from '../graph'; import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz'; import { runPipeline, runSteps, PipelineStep } from '../pipeline'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; @@ -937,8 +937,41 @@ function applyOverrides(overrides: Record | undefined, registry } } +/** What a provider's boot produced: nothing to say, or the error it failed with. */ +interface BootOutcome { + node: GraphNode; + error?: Error; +} + +/** Boots one provider and registers its value. Never rejects — the caller decides what a failure means. */ +async function bootProvider( + node: GraphNode, + deps: { runners: Map; container: Container; bus: Bus }, +): Promise { + const { runners, container, bus } = deps; + bus.emit('boot:provider:start', { name: node.name, scope: node.origin }); + + try { + const value = await runners.get(node.name)!(await snapshot(container, node.needs)); + container.register(node.name, 'app', () => value); + await container.resolve(node.name); // warm the cache + bus.emit('boot:provider:ok', { name: node.name }); + return { node }; + } catch (error) { + bus.emit('boot:provider:fail', { name: node.name, error }); + return { node, error: error as Error }; + } +} + /** - * Runs app-scoped providers in topo order, caching each result; required failures abort, optional ones warn. + * Runs app-scoped providers level by level — concurrently within a level, sequentially between + * them; required failures abort, optional ones warn. + * + * The topo sort already proved nothing in a level can order anything else in it, so serializing a + * level only ever bought latency: an app paid the sum of its providers' boot times instead of its + * longest chain. Concurrency is the second thing the graph earns its users, after pruning, and the + * one a middleware chain structurally cannot offer. + * * @returns The names of optional providers that failed and are running degraded (unregistered). */ async function bootProviders( @@ -953,40 +986,39 @@ async function bootProviders( logger: Logger; }, ): Promise { - const { runners, container, providerMeta, providerInstances, teardown, bus, logger } = deps; + const { providerMeta, providerInstances, teardown, logger } = deps; const degraded: string[] = []; - for (const node of orderedProviders) { - bus.emit('boot:provider:start', { name: node.name, scope: node.origin }); + for (const level of topoLevels(orderedProviders)) { + // Outcomes rather than rejections: a sibling that throws must not strand the ones that + // succeeded, or a provider that opened a pool would never get its dispose() registered. + const outcomes = await Promise.all(level.map((node) => bootProvider(node, deps))); - try { - const value = await runners.get(node.name)!(await snapshot(container, node.needs)); - container.register(node.name, 'app', () => value); - await container.resolve(node.name); // warm the cache - // Registered here, as it boots, rather than where it was collected. `orderedProviders` is - // topologically sorted, so registration order *is* boot order — and the registry running in - // reverse then gives dependants teardown before their dependencies for free, with no second - // sort to keep in step with this one. - // - // Inside the try on purpose: a provider that threw never provided anything, and calling - // dispose() on a half-constructed one is how a teardown finds a null connection. + // Teardown in level order, not completion order. `orderedProviders` is topologically sorted and + // the registry runs in reverse, which is what gives dependants teardown before their + // dependencies for free — a guarantee that would have become luck if this followed whichever + // provider happened to settle first. Registered before the failure pass so a level that aborts + // the boot still leaves its successful siblings closeable. + // + // Skipped for a failure on purpose: a provider that threw never provided anything, and calling + // dispose() on a half-constructed one is how a teardown finds a null connection. + for (const { node, error } of outcomes) { + if (error) continue; const instance = providerInstances.get(node.name); if (instance?.dispose) teardown.add(() => instance.dispose!()); - bus.emit('boot:provider:ok', { name: node.name }); - } catch (error) { - bus.emit('boot:provider:fail', { name: node.name, error }); + } + + for (const { node, error } of outcomes) { + if (!error) continue; if (!providerMeta.get(node.name)?.optional) { - throw new Error(`provider '${node.name}' failed: ${(error as Error).message}`); + throw new Error(`provider '${node.name}' failed: ${error.message}`); } // optional: warn, leave it unregistered; routes needing it fail at request time // ponytail: full partial-degradation is out of scope (spec §10); warn is enough here degraded.push(node.name); - logger.warn(`optional provider '${node.name}' failed: ${(error as Error).message}`, { - provider: node.name, - error, - }); + logger.warn(`optional provider '${node.name}' failed: ${error.message}`, { provider: node.name, error }); } } diff --git a/src/graph.ts b/src/graph.ts index b576dfd..75e22e4 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -78,6 +78,35 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] { return ordered; } +/** + * Groups an already topo-sorted list into dependency levels: nothing in a level can constrain + * anything else in it, and a level depends only on the levels before it — so a level can run + * concurrently. Needs produced by nothing in `ordered` (seeds, filtered-out kinds) constrain + * nothing and are ignored. + */ +export function topoLevels(ordered: GraphNode[]): GraphNode[][] { + const producedBy = new Map(); + for (const node of ordered) for (const key of node.provides) producedBy.set(key, node); + const depthOf = new Map(); + const levels: GraphNode[][] = []; + + // One forward pass is enough: `ordered` is topologically sorted, so every producer of a node's + // needs already has its depth by the time the node is reached. + for (const node of ordered) { + let depth = 0; + + for (const key of node.needs) { + const producer = producedBy.get(key); + if (producer && producer !== node) depth = Math.max(depth, (depthOf.get(producer) ?? 0) + 1); + } + + depthOf.set(node, depth); + (levels[depth] ??= []).push(node); + } + + return levels; +} + /** Filters `ordered` down to the transitive closure of producers reachable from `needs`. */ export function subgraphFor(needs: string[], ordered: GraphNode[]): GraphNode[] { const producedBy = new Map(); diff --git a/test/boot-concurrency.test.ts b/test/boot-concurrency.test.ts new file mode 100644 index 0000000..d12e4ed --- /dev/null +++ b/test/boot-concurrency.test.ts @@ -0,0 +1,205 @@ +// Independent providers boot concurrently; dependent ones still wait. +// +// The graph already proved which providers cannot constrain each other — that is what the topo +// sort *is*. Booting them one at a time charged every app the sum of its providers' latencies +// instead of its longest chain, for no ordering anyone declared. +// +// Timing is asserted structurally rather than by clock: "all three entered before any left" is +// the same claim as "they overlapped" and does not get flaky on a loaded CI box. +import 'reflect-metadata'; +import { describe, expect, it, vi } from 'vitest'; +import { Get, Module, Provider, Route, type Ctor } from '../src/metadata'; +import { createApp } from '../src/app'; +import type { Logger } from '../src/logger'; + +const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }); +const sleep = (ms: number): Promise => new Promise((r) => setTimeout(r, ms)); + +@Route('/') +class Ctl { + @Get('/ping') ping() { + return { ok: true }; + } +} + +/** Boots the app by serving one request — providers are lazy until something is actually served. */ +async function boot(module: Ctor, logger = silentLogger()): Promise { + const app = createApp({ modules: [module], logger }); + await app.fetch(new Request('http://x/ping')); + await app.close(); +} + +describe('provider boot concurrency', () => { + it('overlaps providers that do not depend on each other', async () => { + const log: string[] = []; + + const independent = (name: string): Ctor => { + @Provider({ provides: name }) + class P { + async provide() { + log.push(`${name}:in`); + await sleep(10); + log.push(`${name}:out`); + return { [name]: name }; + } + } + return P; + }; + + @Module({ mountpoint: '/', controllers: [Ctl], providers: [independent('a'), independent('b'), independent('c')] }) + class M {} + await boot(M); + + // Serial boot gives a:in a:out b:in … — every entry preceded by the previous exit. + expect(log.slice(0, 3)).toEqual(['a:in', 'b:in', 'c:in']); + expect(log).toHaveLength(6); + }); + + it('still waits for a provider its dependant needs', async () => { + const log: string[] = []; + + @Provider({ provides: 'base' }) + class Base { + async provide() { + log.push('base:in'); + await sleep(10); + log.push('base:out'); + return { base: 1 }; + } + } + + @Provider({ provides: 'derived', needs: ['base'] }) + class Derived { + provide(ctx: { base: number }) { + log.push('derived:in'); + return { derived: ctx.base + 1 }; + } + } + + // Declared out of order on purpose: the wait is the graph's doing, not the array's. + @Module({ mountpoint: '/', controllers: [Ctl], providers: [Derived, Base] }) + class M {} + await boot(M); + + expect(log).toEqual(['base:in', 'base:out', 'derived:in']); + }); + + it('gives a dependant every value from its level, not just the one that finished first', async () => { + @Provider({ provides: 'slow' }) + class Slow { + async provide() { + await sleep(15); + return { slow: 'slow' }; + } + } + + @Provider({ provides: 'fast' }) + class Fast { + provide() { + return { fast: 'fast' }; + } + } + + let seen: Record = {}; + @Provider({ provides: 'joined', needs: ['slow', 'fast'] }) + class Joined { + provide(ctx: Record) { + seen = { slow: ctx.slow, fast: ctx.fast }; + return { joined: true }; + } + } + + @Module({ mountpoint: '/', controllers: [Ctl], providers: [Slow, Fast, Joined] }) + class M {} + await boot(M); + + expect(seen).toEqual({ slow: 'slow', fast: 'fast' }); + }); + + it('tears down in reverse boot order even though boot is concurrent', async () => { + const disposed: string[] = []; + + const independent = (name: string, delay: number): Ctor => { + @Provider({ provides: name }) + class P { + async provide() { + await sleep(delay); + return { [name]: name }; + } + dispose() { + disposed.push(name); + } + } + return P; + }; + + // `c` finishes first and `a` last — completion order is the reverse of declaration order, so a + // teardown registered as each one lands would come out in a different order than this. + @Module({ + mountpoint: '/', + controllers: [Ctl], + providers: [independent('a', 20), independent('b', 10), independent('c', 1)], + }) + class M {} + await boot(M); + + expect(disposed).toEqual(['c', 'b', 'a']); + }); + + it('fails the boot on a required provider, and still registers its siblings for teardown', async () => { + const disposed: string[] = []; + + @Provider({ provides: 'ok' }) + class Ok { + async provide() { + await sleep(10); // still in flight when its sibling rejects + return { ok: true }; + } + dispose() { + disposed.push('ok'); + } + } + + @Provider({ provides: 'broken' }) + class Broken { + provide(): never { + throw new Error('no pool'); + } + } + + @Module({ mountpoint: '/', controllers: [Ctl], providers: [Ok, Broken] }) + class M {} + const app = createApp({ modules: [M], logger: silentLogger() }); + + await expect(app.fetch(new Request('http://x/ping'))).rejects.toThrow("provider 'broken' failed: no pool"); + // The sibling booted — it was already in flight — so whatever it opened has to be closeable. + await app.close(); + expect(disposed).toEqual(['ok']); + }); + + it('degrades an optional provider without taking its level down', async () => { + const logger = silentLogger(); + + @Provider({ provides: 'flaky', optional: true }) + class Flaky { + provide(): never { + throw new Error('nope'); + } + } + + @Provider({ provides: 'solid' }) + class Solid { + provide() { + return { solid: true }; + } + } + + @Module({ mountpoint: '/', controllers: [Ctl], providers: [Flaky, Solid] }) + class M {} + const app = createApp({ modules: [M], logger }); + await app.fetch(new Request('http://x/ping')); + + expect(app.degraded()).toEqual(['flaky']); + await app.close(); + }); +}); diff --git a/test/graph.test.ts b/test/graph.test.ts index dc5e825..41cd419 100644 --- a/test/graph.test.ts +++ b/test/graph.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, test } from 'vitest'; -import { topoSort, GraphNode, subgraphFor, nearest } from '../src/graph'; +import { topoSort, topoLevels, GraphNode, subgraphFor, nearest } from '../src/graph'; const node = (name: string, needs: string[], provides: string[]): GraphNode => ({ name, needs, provides, origin: 'test' }); @@ -42,6 +42,34 @@ describe('subgraphFor', () => { }); }); +describe('topoLevels', () => { + const levels = (ordered: GraphNode[]): string[][] => topoLevels(ordered).map((l) => l.map((n) => n.name)); + + it('puts nodes that cannot constrain each other in the same level', () => { + expect(levels([N('a'), N('b'), N('c')])).toEqual([['a', 'b', 'c']]); + }); + + it('pushes a node past every producer it needs, not just its first', () => { + // `late` needs a depth-0 and a depth-1 node, so it belongs at 2 — taking the max, not the first. + const ordered = [N('config'), N('db', ['config']), N('late', ['config', 'db'])]; + expect(levels(ordered)).toEqual([['config'], ['db'], ['late']]); + }); + + it('ignores needs nothing here produces, so a seed does not push a node down a level', () => { + expect(levels([N('a'), N('user', ['req', 'params'])])).toEqual([['a', 'user']]); + }); + + it('leaves no gaps, so every level has something to run', () => { + const ordered = topoSort([N('c', ['b']), N('a'), N('b', ['a']), N('solo')], []); + expect(topoLevels(ordered).every((level) => level.length > 0)).toBe(true); + }); + + it('keeps every node exactly once', () => { + const ordered = topoSort([N('c', ['b']), N('a'), N('b', ['a']), N('solo')], []); + expect(topoLevels(ordered).flat().map((n) => n.name).sort()).toEqual(['a', 'b', 'c', 'solo']); + }); +}); + describe('nearest', () => { it('suggests a close candidate (edit distance <= 2)', () => { expect(nearest('usr', ['user', 'config', 'db'])).toBe('user');