Open History to see the last commit
1import * as Scope from "effect/Scope";
2import * as Effect from "effect/Effect";
3import * as TxQueue from "effect/TxQueue";
4import * as TxRef from "effect/TxRef";
5
6export interface KeyedCoalescingWorker<K, V, R = never> {
7 readonly enqueue: (key: K, value: V) => Effect.Effect<void>;
8 readonly drainKey: (key: K) => Effect.Effect<void>;
9 /**
10 * Waits for the key's in-flight batch, then processes its pending value, including anything
11 * enqueued meanwhile, in the caller's fiber, ignoring failures as the worker does. Unlike
12 * `drainKey`, it never waits for other keys' queued batches.
13 */
14 readonly flushKey: (key: K) => Effect.Effect<void, never, R>;
15}
16
17interface KeyedCoalescingWorkerState<K, V> {
18 readonly latestByKey: Map<K, V>;
19 readonly queuedKeys: Set<K>;
20 readonly activeKeys: Set<K>;
21 /** Queue entries whose batch `flushKey` already took; the dispatcher drops them. */
22 readonly staleEntries: Map<K, number>;
23}
24
25type FlushClaim<V> =
26 | { readonly _tag: "Active" }
27 | { readonly _tag: "Idle" }
28 | { readonly _tag: "Claimed"; readonly value: V };
29
30export const makeKeyedCoalescingWorker = Effect.fn(
31 "KeyedCoalescingWorker.makeKeyedCoalescingWorker",
32)(function* <K, V, E, R>(options: {
33 readonly merge: (current: V, next: V) => V;
34 readonly process: (key: K, value: V) => Effect.Effect<void, E, R>;
35}): Effect.fn.Return<KeyedCoalescingWorker<K, V, R>, never, Scope.Scope | R> {
36 const queue = yield* Effect.acquireRelease(TxQueue.unbounded<K>(), TxQueue.shutdown);
37 const stateRef = yield* TxRef.make<KeyedCoalescingWorkerState<K, V>>({
38 latestByKey: new Map(),
39 queuedKeys: new Set(),
40 activeKeys: new Set(),
41 staleEntries: new Map(),
42 });
43
44 const completeKey = (key: K): Effect.Effect<void> =>
45 TxRef.modify(stateRef, (state) => {
46 const activeKeys = new Set(state.activeKeys);
47 activeKeys.delete(key);
48
49 if (state.latestByKey.has(key) && !state.queuedKeys.has(key)) {
50 const queuedKeys = new Set(state.queuedKeys);
51 queuedKeys.add(key);
52 return [true, { ...state, activeKeys, queuedKeys }] as const;
53 }
54
55 return [false, { ...state, activeKeys }] as const;
56 }).pipe(
57 Effect.flatMap((shouldRequeue) => (shouldRequeue ? TxQueue.offer(queue, key) : Effect.void)),
58 Effect.tx,
59 Effect.asVoid,
60 );
61
62 const runBatch = (key: K, value: V) =>
63 Effect.suspend(() => options.process(key, value)).pipe(
64 Effect.ignoreCause,
65 Effect.ensuring(completeKey(key)),
66 );
67
68 yield* TxQueue.take(queue).pipe(
69 Effect.flatMap((key) =>
70 TxRef.modify(stateRef, (state) => {
71 // A key's stale entries are older than its live one, so they are reached first.
72 const stale = state.staleEntries.get(key) ?? 0;
73 if (stale > 0) {
74 const staleEntries = new Map(state.staleEntries);
75 if (stale === 1) staleEntries.delete(key);
76 else staleEntries.set(key, stale - 1);
77 return [null, { ...state, staleEntries }] as const;
78 }
79
80 const queuedKeys = new Set(state.queuedKeys);
81 queuedKeys.delete(key);
82
83 const value = state.latestByKey.get(key);
84 if (value === undefined) {
85 return [null, { ...state, queuedKeys }] as const;
86 }
87
88 const latestByKey = new Map(state.latestByKey);
89 latestByKey.delete(key);
90 const activeKeys = new Set(state.activeKeys);
91 activeKeys.add(key);
92
93 return [
94 { key, value } as const,
95 { ...state, latestByKey, queuedKeys, activeKeys },
96 ] as const;
97 }).pipe(Effect.tx),
98 ),
99 Effect.flatMap((item) => (item === null ? Effect.void : runBatch(item.key, item.value))),
100 Effect.forever,
101 Effect.forkScoped,
102 );
103
104 const enqueue: KeyedCoalescingWorker<K, V, R>["enqueue"] = (key, value) =>
105 TxRef.modify(stateRef, (state) => {
106 const latestByKey = new Map(state.latestByKey);
107 const existing = latestByKey.get(key);
108 latestByKey.set(key, existing === undefined ? value : options.merge(existing, value));
109
110 if (state.queuedKeys.has(key) || state.activeKeys.has(key)) {
111 return [false, { ...state, latestByKey }] as const;
112 }
113
114 const queuedKeys = new Set(state.queuedKeys);
115 queuedKeys.add(key);
116 return [true, { ...state, latestByKey, queuedKeys }] as const;
117 }).pipe(
118 Effect.flatMap((shouldOffer) => (shouldOffer ? TxQueue.offer(queue, key) : Effect.void)),
119 Effect.tx,
120 Effect.asVoid,
121 );
122
123 const drainKey: KeyedCoalescingWorker<K, V, R>["drainKey"] = (key) =>
124 TxRef.get(stateRef).pipe(
125 Effect.tap((state) =>
126 state.latestByKey.has(key) || state.queuedKeys.has(key) || state.activeKeys.has(key)
127 ? Effect.txRetry
128 : Effect.void,
129 ),
130 Effect.asVoid,
131 Effect.tx,
132 );
133
134 const awaitInactive = (key: K) =>
135 TxRef.get(stateRef).pipe(
136 Effect.tap((state) => (state.activeKeys.has(key) ? Effect.txRetry : Effect.void)),
137 Effect.tx,
138 );
139
140 // A claimed key gives up its queue entry, so output after the flush queues behind other keys.
141 const claimPending = (key: K) =>
142 TxRef.modify(stateRef, (state): [FlushClaim<V>, KeyedCoalescingWorkerState<K, V>] => {
143 if (state.activeKeys.has(key)) return [{ _tag: "Active" }, state];
144 const value = state.latestByKey.get(key);
145 if (value === undefined) return [{ _tag: "Idle" }, state];
146 const latestByKey = new Map(state.latestByKey);
147 latestByKey.delete(key);
148 const activeKeys = new Set(state.activeKeys);
149 activeKeys.add(key);
150 const queuedKeys = new Set(state.queuedKeys);
151 const staleEntries = new Map(state.staleEntries);
152 if (queuedKeys.delete(key)) staleEntries.set(key, (staleEntries.get(key) ?? 0) + 1);
153 return [
154 { _tag: "Claimed", value },
155 { latestByKey, queuedKeys, activeKeys, staleEntries },
156 ];
157 }).pipe(Effect.tx);
158
159 // Only the wait is interruptible: a claimed value is always processed and its key released,
160 // as it would be had the worker taken it.
161 const flushKey: KeyedCoalescingWorker<K, V, R>["flushKey"] = (key) =>
162 Effect.uninterruptibleMask((restore) => {
163 const flush: Effect.Effect<void, never, R> = restore(awaitInactive(key)).pipe(
164 Effect.andThen(claimPending(key)),
165 Effect.flatMap((claim) => {
166 if (claim._tag === "Active") return flush;
167 if (claim._tag === "Idle") return Effect.void;
168 return runBatch(key, claim.value);
169 }),
170 );
171 return flush;
172 });
173
174 return { enqueue, drainKey, flushKey } satisfies KeyedCoalescingWorker<K, V, R>;
175});