Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

providerMaintenanceCommandCoordinator.ts

80 lines2.6 KB

1import * as Effect from "effect/Effect";
2import * as Ref from "effect/Ref";
3import * as Semaphore from "effect/Semaphore";
4​
5export interface ProviderMaintenanceCommandCoordinatorShape<E> {
6 readonly withCommandLock: <A, R>(input: {
7 readonly targetKey: string;
8 readonly lockKey: string;
9 readonly onQueued?: Effect.Effect<void, E, R>;
10 readonly run: Effect.Effect<A, E, R>;
11 }) => Effect.Effect<A, E, R>;
13​
14export const makeProviderMaintenanceCommandCoordinator = Effect.fn(
15 "makeProviderMaintenanceCommandCoordinator",
16)(function* <E>(input: { readonly makeAlreadyRunningError: (targetKey: string) => E }) {
17 const runningTargetsRef = yield* Ref.make<ReadonlySet<string>>(new Set());
18 const locksRef = yield* Ref.make<ReadonlyMap<string, Semaphore.Semaphore>>(new Map());
19​
20 const acquireTarget = Effect.fn("acquireTarget")(function* (targetKey: string) {
21 return yield* Ref.modify(runningTargetsRef, (runningTargets) => {
22 if (runningTargets.has(targetKey)) {
23 return [false, runningTargets] as const;
24 }
25 const next = new Set(runningTargets);
26 next.add(targetKey);
27 return [true, next] as const;
28 });
29 });
30​
31 const releaseTarget = (targetKey: string) =>
32 Ref.update(runningTargetsRef, (runningTargets) => {
33 const next = new Set(runningTargets);
34 next.delete(targetKey);
35 return next;
36 });
37​
38 const getLock = Effect.fn("getProviderMaintenanceCommandLock")(function* (lockKey: string) {
39 const existing = (yield* Ref.get(locksRef)).get(lockKey);
40 if (existing) {
41 return existing;
42 }
43​
44 const lock = yield* Semaphore.make(1);
45 return yield* Ref.modify(locksRef, (locks) => {
46 const current = locks.get(lockKey);
47 if (current) {
48 return [current, locks] as const;
49 }
50 const next = new Map(locks);
51 next.set(lockKey, lock);
52 return [lock, next] as const;
53 });
54 });
55​
56 const withCommandLock: ProviderMaintenanceCommandCoordinatorShape<E>["withCommandLock"] = ({
57 targetKey,
58 lockKey,
59 onQueued,
60 run,
61 }) =>
62 Effect.gen(function* () {
63 const acquired = yield* acquireTarget(targetKey);
64 if (!acquired) {
65 return yield* Effect.fail(input.makeAlreadyRunningError(targetKey));
66 }
67​
68 return yield* Effect.gen(function* () {
69 const lock = yield* getLock(lockKey);
70 if (onQueued) {
71 yield* onQueued;
72 }
73 return yield* lock.withPermits(1)(run);
74 }).pipe(Effect.ensuring(releaseTarget(targetKey)));
75 });
76​
77 return {
78 withCommandLock,
79 } satisfies ProviderMaintenanceCommandCoordinatorShape<E>;
80});