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
Addednew 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;
10 + const calls
: string[]
= [];
11 + const first
= lazy(
async ()
=> {
12 + calls.
push(
"first");
13 + await firstFinished;
14 + throw new Error(
"failed");
16 + const second
= lazy(
async ()
=> {
17 + calls.
push(
"second");
20 + const firstAttempt
= first();
21 + assert.
equal(
first(), firstAttempt);
22 + const secondAttempt
= second();
23 + await Promise.
resolve();
24 + assert.
deepEqual(calls, [
"first"]);
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"]);
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;
15 - (promise
??= load().
catch((error
: unknown)
=> {
16 - promise
= undefined;
18 + (promise
??= (()
=> {
19 + const next
= pending.
then(load);
20 + pending
= next.
catch(()
=> {});
21 + return next.
catch((error
: unknown)
=> {
22 + promise
= undefined;