The best way to control Claude Code, Codex and more from any computer or phone

main
ts 86 lines 2.71 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as FiberSet from "effect/FiberSet";
3 import * as Ref from "effect/Ref";
4 import type * as Scope from "effect/Scope";
5 import * as Semaphore from "effect/Semaphore";
6
7 export interface KeyedLock<Key> {
8 readonly withLock: <A, E, R>(key: Key, effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
9 readonly activeKeys: Effect.Effect<ReadonlyArray<Key>>;
10 }
11
12 interface LockEntry {
13 readonly semaphore: Semaphore.Semaphore;
14 readonly users: number;
15 }
16
17 /**
18 * Not reentrant: taking a key while already holding it deadlocks.
19 */
20 export const make = Effect.fn("KeyedLock.make")(function* <Key>(): Effect.fn.Return<
21 KeyedLock<Key>
22 > {
23 const locks = yield* Ref.make<ReadonlyMap<Key, LockEntry>>(new Map());
24
25 const acquire = (key: Key) =>
26 Effect.flatMap(Semaphore.make(1), (candidate) =>
27 Ref.modify(locks, (current) => {
28 const existing = current.get(key);
29 const semaphore = existing?.semaphore ?? candidate;
30 const next = new Map(current);
31 next.set(key, { semaphore, users: (existing?.users ?? 0) + 1 });
32 return [semaphore, next] as const;
33 }),
34 );
35
36 const release = (key: Key) =>
37 Ref.update(locks, (current) => {
38 const existing = current.get(key);
39 if (existing === undefined) return current;
40 const next = new Map(current);
41 if (existing.users === 1) {
42 next.delete(key);
43 } else {
44 next.set(key, { ...existing, users: existing.users - 1 });
45 }
46 return next;
47 });
48
49 return {
50 withLock: (key, effect) =>
51 Effect.acquireUseRelease(
52 acquire(key),
53 (semaphore) => semaphore.withPermit(effect),
54 () => release(key),
55 ),
56 activeKeys: Effect.map(Ref.get(locks), (current) => Array.from(current.keys())),
57 } satisfies KeyedLock<Key>;
58 });
59
60 export interface KeyedRunner<Key> {
61 /** Forks `effect` to run once every effect passed earlier for `key` has finished. */
62 readonly run: <R>(
63 key: Key,
64 effect: Effect.Effect<void, never, R>,
65 ) => Effect.Effect<void, never, R>;
66 }
67
68 /**
69 * For a stream consumer whose handler waits on a per-key lock: a busy key delays only its own
70 * later effects. The forked fiber starts immediately, so it queues on the key's FIFO semaphore
71 * before `run` returns; that keeps each key's effects in `run` order.
72 */
73 export const makeRunner = Effect.fn("KeyedLock.makeRunner")(function* <Key>(): Effect.fn.Return<
74 KeyedRunner<Key>,
75 never,
76 Scope.Scope
77 > {
78 const lock = yield* make<Key>();
79 const fibers = yield* FiberSet.make<void, never>();
80 return {
81 run: (key, effect) =>
82 FiberSet.run(fibers, lock.withLock(key, effect), { startImmediately: true }).pipe(
83 Effect.asVoid,
84 ),
85 } satisfies KeyedRunner<Key>;
86 });