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