Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Ref from "effect/Ref";
3import * as Semaphore from "effect/Semaphore";
4
5export interface KeyedLock<Key> {
6 readonly withLock: <A, E, R>(key: Key, effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
7 readonly activeKeys: Effect.Effect<ReadonlyArray<Key>>;
8}
9
10interface LockEntry {
11 readonly semaphore: Semaphore.Semaphore;
12 readonly users: number;
13}
14
15/**
16 * Not reentrant: taking a key while already holding it deadlocks.
17 */
18export const make = <Key>(): Effect.Effect<KeyedLock<Key>> =>
19 Effect.gen(function* () {
20 const locks = yield* Ref.make<ReadonlyMap<Key, LockEntry>>(new Map());
21
22 const acquire = (key: Key) =>
23 Effect.flatMap(Semaphore.make(1), (candidate) =>
24 Ref.modify(locks, (current) => {
25 const existing = current.get(key);
26 const semaphore = existing?.semaphore ?? candidate;
27 const next = new Map(current);
28 next.set(key, { semaphore, users: (existing?.users ?? 0) + 1 });
29 return [semaphore, next] as const;
30 }),
31 );
32
33 const release = (key: Key) =>
34 Ref.update(locks, (current) => {
35 const existing = current.get(key);
36 if (existing === undefined) return current;
37 const next = new Map(current);
38 if (existing.users === 1) {
39 next.delete(key);
40 } else {
41 next.set(key, { ...existing, users: existing.users - 1 });
42 }
43 return next;
44 });
45
46 return {
47 withLock: (key, effect) =>
48 Effect.acquireUseRelease(
49 acquire(key),
50 (semaphore) => semaphore.withPermit(effect),
51 () => release(key),
52 ),
53 activeKeys: Effect.map(Ref.get(locks), (current) => Array.from(current.keys())),
54 } satisfies KeyedLock<Key>;
55 });