Repository navigation
Expand file tree
/
Copy pathkeyed-lock.ts
More file actions
55 lines (52 loc) · 1.46 KB
/
Copy pathkeyed-lock.ts
File metadata and controls
55 lines (52 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { AsyncLocalStorage } from 'node:async_hooks';
type LockFrame = {
locks: Map<string, Promise<unknown>>;
key: string;
active: boolean;
descendants: Set<Promise<void>>;
};
const keyedLockStorage = new AsyncLocalStorage<LockFrame[]>();
export async function withKeyedLock<T>(
locks: Map<string, Promise<unknown>>,
key: string,
task: () => Promise<T>,
): Promise<T> {
const activeLocks = keyedLockStorage.getStore() ?? [];
const held = activeLocks.find(
(entry) => entry.active && entry.locks === locks && entry.key === key,
);
if (held) {
let markSettled!: () => void;
const settled = new Promise<void>((resolve) => {
markSettled = resolve;
});
held.descendants.add(settled);
try {
return await task();
} finally {
held.descendants.delete(settled);
markSettled();
}
}
const previous = locks.get(key) ?? Promise.resolve();
const current = previous
.catch(() => {})
.then(async () => {
const frame: LockFrame = { locks, key, active: true, descendants: new Set() };
try {
return await keyedLockStorage.run(
[...activeLocks.filter((entry) => entry.active), frame],
task,
);
} finally {
while (frame.descendants.size > 0) await Promise.all(frame.descendants);
frame.active = false;
}
});
locks.set(key, current);
return current.finally(() => {
if (locks.get(key) === current) {
locks.delete(key);
}
});
}