`bootProviders` was a `for...of` with an `await` inside, so three providers that share nothing took the sum of their latencies rather than the longest one. Measured on the issue's case — three providers, no edges, 200ms each — 616ms before, 210ms after. The graph already knew. `topoSort` proves which nodes cannot constrain each other and then throws that away by returning a flat list; `topoLevels` groups the sorted list back into dependency levels in one forward pass, and boot runs a level with `Promise.all`. Nothing else about the ordering changes: level N is fully registered and warmed before level N+1 starts, which is the same guarantee the sequential walk gave. This is the second thing users get for declaring `needs`/`provides` instead of ordering `app.use` calls by hand. Pruning was the first. An Express app cannot parallelize its middleware because nothing declares what is independent — we have that declaration and were not spending it. Three things had to survive the change, and each has a test: - **Teardown stays deterministic.** Registration follows level order, not completion order, so the registry running in reverse still gives dependants teardown before their dependencies. Following whichever provider settled first would have turned that from a guarantee into luck. - **A failed sibling does not strand the level.** `bootProvider` returns an outcome instead of rejecting, and successful teardowns are registered before any failure is raised — so a boot aborted by a required provider still leaves whatever its siblings opened closeable. Previously they had not started at all; now they may be in flight. - **A provider that threw gets no teardown**, unchanged: it never provided anything, and `dispose()` on a half-constructed one is how a teardown finds a null connection. Behaviour visible to a bus consumer: `boot:provider:start` no longer strictly alternates with `:ok`. A level emits its starts together, then its results. That is the truth about what is happening rather than a change in what is reported. Verified non-vacuous: reverting `src/` fails the overlap assertion and all five `topoLevels` cases, and puts the benchmark back at 616ms. Closes #71 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
127 lines
4.2 KiB
TypeScript
127 lines
4.2 KiB
TypeScript
function levenshtein(a: string, b: string): number {
|
|
const aLen = a.length,
|
|
bLen = b.length;
|
|
const matrix: number[][] = Array.from({ length: aLen + 1 }, () => Array(bLen + 1).fill(0));
|
|
for (let i = 0; i <= aLen; i++) matrix[i][0] = i;
|
|
for (let j = 0; j <= bLen; j++) matrix[0][j] = j;
|
|
|
|
for (let i = 1; i <= aLen; i++)
|
|
for (let j = 1; j <= bLen; j++) {
|
|
matrix[i][j] = Math.min(
|
|
matrix[i - 1][j] + 1,
|
|
matrix[i][j - 1] + 1,
|
|
matrix[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),
|
|
);
|
|
}
|
|
|
|
return matrix[aLen][bLen];
|
|
}
|
|
|
|
/** Returns the candidate within edit distance 2 of `token`, for "did you mean?" hints. */
|
|
export function nearest(token: string, candidates: Iterable<string>): string | undefined {
|
|
let best: string | undefined;
|
|
let bestDistance = 3; // only suggest edit distance <= 2
|
|
|
|
for (const candidate of candidates) {
|
|
const distance = levenshtein(token, candidate);
|
|
|
|
if (distance < bestDistance) {
|
|
bestDistance = distance;
|
|
best = candidate;
|
|
}
|
|
}
|
|
|
|
return best;
|
|
}
|
|
|
|
/** A node in the dependency graph: what it provides, what it needs, and where it came from. */
|
|
export interface GraphNode {
|
|
name: string;
|
|
needs: string[];
|
|
provides: string[];
|
|
origin: string;
|
|
}
|
|
|
|
/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */
|
|
export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
|
|
const producedBy = new Map<string, GraphNode>();
|
|
for (const node of nodes) for (const key of node.provides) producedBy.set(key, node);
|
|
|
|
// validate dependencies exist
|
|
for (const node of nodes) {
|
|
for (const key of node.needs) {
|
|
if (!seedKeys.includes(key) && !producedBy.has(key)) {
|
|
throw new Error(`missing dependency: ${key} needed by ${node.name}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
const ordered: GraphNode[] = [];
|
|
const state = new Map<GraphNode, 'visiting' | 'done'>();
|
|
|
|
const visit = (node: GraphNode, trail: string[]): void => {
|
|
const visitState = state.get(node);
|
|
if (visitState === 'done') return;
|
|
if (visitState === 'visiting') throw new Error(`cycle detected: ${[...trail, node.name].join(' -> ')}`);
|
|
state.set(node, 'visiting');
|
|
|
|
for (const key of node.needs) {
|
|
const dependency = producedBy.get(key);
|
|
if (dependency && dependency !== node) visit(dependency, [...trail, node.name]);
|
|
}
|
|
|
|
state.set(node, 'done');
|
|
ordered.push(node);
|
|
};
|
|
|
|
for (const node of nodes) visit(node, []);
|
|
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<string, GraphNode>();
|
|
for (const node of ordered) for (const key of node.provides) producedBy.set(key, node);
|
|
const depthOf = new Map<GraphNode, number>();
|
|
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<string, GraphNode>();
|
|
for (const node of ordered) for (const key of node.provides) producedBy.set(key, node);
|
|
const inClosure = new Set<GraphNode>();
|
|
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((node) => inClosure.has(node));
|
|
}
|