repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(the-system): serialize distinct lazy module loads

a50cd3c59640ff2565b0991faa9e2097bdd6afea

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (2)

extensions/the-system/__tests__/lazy.test.ts

Added
new file mode 100644
1 +import assert from "node:assert/strict";
2 +import { it } from "vitest";
3 +import { lazy } from "../lazy.ts";
5 +it("serializes different loads, shares a target, and continues after failure", async () => {
6 + let releaseFirst!: () => void;
7 + const firstFinished = new Promise<void>((resolve) => {
8 + releaseFirst = resolve;
9 + });
10 + const calls: string[] = [];
11 + const first = lazy(async () => {
12 + calls.push("first");
13 + await firstFinished;
14 + throw new Error("failed");
15 + });
16 + const second = lazy(async () => {
17 + calls.push("second");
18 + return 2;
19 + });
20 + const firstAttempt = first();
21 + assert.equal(first(), firstAttempt);
22 + const secondAttempt = second();
23 + await Promise.resolve();
24 + assert.deepEqual(calls, ["first"]);
25 + releaseFirst();
26 + await assert.rejects(firstAttempt, /failed/);
27 + assert.equal(await secondAttempt, 2);
28 + assert.deepEqual(calls, ["first", "second"]);
29 + await assert.rejects(first(), /failed/);
30 + assert.deepEqual(calls, ["first", "second", "first"]);
31 +});

extensions/the-system/lazy.ts

Modified
6 6 * caller receives a partially initialized module whose top-level awaits
7 7 * have not finished and whose imported bindings are still `undefined`.
9 - * Routing every lazy import through one shared promise closes that window.
9 + * Memoize each target and serialize distinct targets, since their shared
10 + * dependencies can also race through jiti's partially initialized cache.
10 11 * A rejected load clears the memo so the next call retries.
13 +let pending: Promise<unknown> = Promise.resolve();
12 15 export function lazy<T>(load: () => Promise<T>): () => Promise<T> {
13 16 let promise: Promise<T> | undefined;
14 17 return () =>
15 - (promise ??= load().catch((error: unknown) => {
16 - promise = undefined;
17 - throw error;
18 - }));
18 + (promise ??= (() => {
19 + const next = pending.then(load);
20 + pending = next.catch(() => {});
21 + return next.catch((error: unknown) => {
22 + promise = undefined;
23 + throw error;
24 + });
25 + })());