Open History to see the last commit
1/**
2 * KeyedCoalescingWorker - A keyed worker that keeps only the latest value per key.
3 *
4 * Enqueues for an active or already-queued key are merged atomically instead of
5 * creating duplicate queued items. `drainKey()` resolves only when that key has
6 * no queued, pending, or active work left.
7 *
8 * @module KeyedCoalescingWorker
9 */
10import * as Scope from "effect/Scope";
11import * as Effect from "effect/Effect";
12import * as TxQueue from "effect/TxQueue";
13import * as TxRef from "effect/TxRef";
14
15export interface KeyedCoalescingWorker<K, V> {
16 readonly enqueue: (key: K, value: V) => Effect.Effect<void>;
17 readonly drainKey: (key: K) => Effect.Effect<void>;
18}
19
20interface KeyedCoalescingWorkerState<K, V> {
21 readonly latestByKey: Map<K, V>;
22 readonly queuedKeys: Set<K>;
23 readonly activeKeys: Set<K>;
24}
25
26export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
27 readonly merge: (current: V, next: V) => V;
28 readonly process: (key: K, value: V) => Effect.Effect<void, E, R>;
29}): Effect.Effect<KeyedCoalescingWorker<K, V>, never, Scope.Scope | R> =>
30 Effect.gen(function* () {
31 const queue = yield* Effect.acquireRelease(TxQueue.unbounded<K>(), TxQueue.shutdown);
32 const stateRef = yield* TxRef.make<KeyedCoalescingWorkerState<K, V>>({
33 latestByKey: new Map(),
34 queuedKeys: new Set(),
35 activeKeys: new Set(),
36 });
37
38 const processKey = (key: K, value: V): Effect.Effect<void, E, R> =>
39 options.process(key, value).pipe(
40 Effect.flatMap(() =>
41 TxRef.modify(stateRef, (state) => {
42 const nextValue = state.latestByKey.get(key);
43 if (nextValue === undefined) {
44 const activeKeys = new Set(state.activeKeys);
45 activeKeys.delete(key);
46 return [null, { ...state, activeKeys }] as const;
47 }
48
49 const latestByKey = new Map(state.latestByKey);
50 latestByKey.delete(key);
51 return [nextValue, { ...state, latestByKey }] as const;
52 }).pipe(Effect.tx),
53 ),
54 Effect.flatMap((nextValue) =>
55 nextValue === null ? Effect.void : processKey(key, nextValue),
56 ),
57 );
58
59 const cleanupFailedKey = (key: K): Effect.Effect<void> =>
60 TxRef.modify(stateRef, (state) => {
61 const activeKeys = new Set(state.activeKeys);
62 activeKeys.delete(key);
63
64 if (state.latestByKey.has(key) && !state.queuedKeys.has(key)) {
65 const queuedKeys = new Set(state.queuedKeys);
66 queuedKeys.add(key);
67 return [true, { ...state, activeKeys, queuedKeys }] as const;
68 }
69
70 return [false, { ...state, activeKeys }] as const;
71 }).pipe(
72 Effect.tx,
73 Effect.flatMap((shouldRequeue) =>
74 shouldRequeue ? TxQueue.offer(queue, key) : Effect.void,
75 ),
76 );
77
78 yield* TxQueue.take(queue).pipe(
79 Effect.flatMap((key) =>
80 TxRef.modify(stateRef, (state) => {
81 const queuedKeys = new Set(state.queuedKeys);
82 queuedKeys.delete(key);
83
84 const value = state.latestByKey.get(key);
85 if (value === undefined) {
86 return [null, { ...state, queuedKeys }] as const;
87 }
88
89 const latestByKey = new Map(state.latestByKey);
90 latestByKey.delete(key);
91 const activeKeys = new Set(state.activeKeys);
92 activeKeys.add(key);
93
94 return [
95 { key, value } as const,
96 { ...state, latestByKey, queuedKeys, activeKeys },
97 ] as const;
98 }).pipe(Effect.tx),
99 ),
100 Effect.flatMap((item) =>
101 item === null
102 ? Effect.void
103 : processKey(item.key, item.value).pipe(
104 Effect.catchCause(() => cleanupFailedKey(item.key)),
105 ),
106 ),
107 Effect.forever,
108 Effect.forkScoped,
109 );
110
111 const enqueue: KeyedCoalescingWorker<K, V>["enqueue"] = (key, value) =>
112 TxRef.modify(stateRef, (state) => {
113 const latestByKey = new Map(state.latestByKey);
114 const existing = latestByKey.get(key);
115 latestByKey.set(key, existing === undefined ? value : options.merge(existing, value));
116
117 if (state.queuedKeys.has(key) || state.activeKeys.has(key)) {
118 return [false, { ...state, latestByKey }] as const;
119 }
120
121 const queuedKeys = new Set(state.queuedKeys);
122 queuedKeys.add(key);
123 return [true, { ...state, latestByKey, queuedKeys }] as const;
124 }).pipe(
125 Effect.flatMap((shouldOffer) => (shouldOffer ? TxQueue.offer(queue, key) : Effect.void)),
126 Effect.tx,
127 Effect.asVoid,
128 );
129
130 const drainKey: KeyedCoalescingWorker<K, V>["drainKey"] = (key) =>
131 TxRef.get(stateRef).pipe(
132 Effect.tap((state) =>
133 state.latestByKey.has(key) || state.queuedKeys.has(key) || state.activeKeys.has(key)
134 ? Effect.txRetry
135 : Effect.void,
136 ),
137 Effect.asVoid,
138 Effect.tx,
139 );
140
141 return { enqueue, drainKey } satisfies KeyedCoalescingWorker<K, V>;
142 });