Open History to see the last commit
1/**
2 * DrainableWorker - A queue-based worker that exposes a `drain()` effect.
3 *
4 * Wraps the common `Queue.unbounded` + `Effect.forever` pattern and adds
5 * a signal that resolves when the queue is empty **and** the current item
6 * has finished processing. This lets tests replace timing-sensitive
7 * `Effect.sleep` calls with deterministic `drain()`.
8 *
9 * @module DrainableWorker
10 */
11import * as Scope from "effect/Scope";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Semaphore from "effect/Semaphore";
15import * as TxQueue from "effect/TxQueue";
16import * as TxRef from "effect/TxRef";
17
18export interface DrainableWorker<A> {
19 /**
20 * Enqueue a work item and track it for `drain()`.
21 *
22 * This wraps `Queue.offer` so drain state is updated atomically with the
23 * enqueue path instead of inferring it from queue internals.
24 */
25 readonly enqueue: (item: A) => Effect.Effect<void>;
26
27 /**
28 * Resolves when the queue is empty and the worker is idle (not processing).
29 */
30 readonly drain: Effect.Effect<void>;
31}
32
33/**
34 * Create drainable FIFO lanes keyed by an item field.
35 *
36 * Lane lookup, creation, and idle cleanup all serialize on a semaphore, so
37 * concurrent enqueues for a not-yet-seen key atomically reserve a single
38 * lane. A plain check-then-create on the lane map would let two fibers both
39 * observe a missing key and each create a lane, splitting the key's FIFO
40 * across lanes.
41 *
42 * Each key gets its own FIFO lane while different keys process concurrently.
43 * `drain` is quiescent: it loops snapshot+drain until no lane holds
44 * unprocessed work offered during the drain (new keys, recreated lanes, or
45 * version-bumped lanes). Idle lanes are
46 * removed once drained so key cardinality stays bounded.
47 *
48 * Callers must handle processing failures before returning: an unhandled failure
49 * stops the lane and leaves queued items undrained.
50 *
51 * @param keyOf - Derives the lane key for an item.
52 * @param process - The effect to run for each queued item.
53 * @returns A `DrainableWorker` with `enqueue` and `drain`.
54 */
55export const makeKeyedDrainableWorker = <A, K, R>(
56 keyOf: (item: A) => K,
57 process: (item: A) => Effect.Effect<void, never, R>,
58): Effect.Effect<DrainableWorker<A>, never, Scope.Scope | R> =>
59 Effect.gen(function* () {
60 const context = yield* Effect.context<R>();
61 const scope = yield* Scope.Scope;
62 const laneLock = yield* Semaphore.make(1);
63 type Entry = {
64 readonly worker: DrainableWorker<A>;
65 readonly scope: Scope.Closeable;
66 version: number;
67 };
68 const entries = new Map<K, Entry>();
69 const processInParentScope = (item: A) =>
70 process(item).pipe(Effect.provide(context), Scope.provide(scope));
71
72 const removeWhenIdle = (key: K, entry: Entry): Effect.Effect<void> =>
73 Effect.gen(function* () {
74 while (true) {
75 const observedVersion = yield* laneLock.withPermit(
76 Effect.sync(() => (entries.get(key) === entry ? entry.version : undefined)),
77 );
78 if (observedVersion === undefined) {
79 return;
80 }
81 yield* entry.worker.drain;
82 const removed = yield* laneLock.withPermit(
83 Effect.sync(() => {
84 if (entries.get(key) !== entry || entry.version !== observedVersion) {
85 return false;
86 }
87 entries.delete(key);
88 return true;
89 }),
90 );
91 if (removed) {
92 yield* Scope.close(entry.scope, Exit.void);
93 return;
94 }
95 }
96 });
97
98 const enqueue = (item: A): Effect.Effect<void> =>
99 laneLock.withPermit(
100 Effect.gen(function* () {
101 const key = keyOf(item);
102 const existing = entries.get(key);
103 if (existing !== undefined) {
104 existing.version += 1;
105 yield* existing.worker.enqueue(item);
106 return;
107 }
108 const laneScope = yield* Scope.fork(scope, "sequential");
109 const worker = yield* makeDrainableWorker(processInParentScope).pipe(
110 Scope.provide(laneScope),
111 );
112 const entry: Entry = { worker, scope: laneScope, version: 1 };
113 entries.set(key, entry);
114 yield* worker.enqueue(item);
115 yield* removeWhenIdle(key, entry).pipe(Effect.forkIn(scope));
116 }),
117 );
118
119 const drain: DrainableWorker<A>["drain"] = Effect.gen(function* () {
120 while (true) {
121 const snapshot = yield* laneLock.withPermit(
122 Effect.sync(() =>
123 Array.from(entries.entries()).map(([key, entry]) => ({
124 key,
125 entry,
126 version: entry.version,
127 })),
128 ),
129 );
130 if (snapshot.length === 0) {
131 return;
132 }
133 yield* Effect.forEach(snapshot, ({ entry }) => entry.worker.drain, {
134 concurrency: "unbounded",
135 discard: true,
136 });
137 const settled = yield* laneLock.withPermit(
138 Effect.sync(() => {
139 const seen = new Map<K, { readonly entry: Entry; readonly version: number }>();
140 for (const { key, entry, version } of snapshot) {
141 seen.set(key, { entry, version });
142 }
143 for (const [key, current] of entries) {
144 const prior = seen.get(key);
145 if (prior === undefined) {
146 return false;
147 }
148 if (current !== prior.entry || current.version !== prior.version) {
149 return false;
150 }
151 }
152 return true;
153 }),
154 );
155 if (settled) {
156 return;
157 }
158 }
159 });
160
161 return { enqueue, drain } satisfies DrainableWorker<A>;
162 });
163
164/**
165 * Create a drainable worker that processes items from an unbounded queue.
166 *
167 * The worker is forked into the current scope and will be interrupted when
168 * the scope closes. A finalizer shuts down the queue.
169 *
170 * @param process - The effect to run for each queued item.
171 * @returns A `DrainableWorker` with `queue` and `drain`.
172 */
173export const makeDrainableWorker = <A, E, R>(
174 process: (item: A) => Effect.Effect<void, E, R>,
175): Effect.Effect<DrainableWorker<A>, never, Scope.Scope | R> =>
176 Effect.gen(function* () {
177 const queue = yield* Effect.acquireRelease(TxQueue.unbounded<A>(), TxQueue.shutdown);
178 const outstanding = yield* TxRef.make(0);
179
180 yield* TxQueue.take(queue).pipe(
181 Effect.tap((a) =>
182 Effect.ensuring(
183 process(a),
184 TxRef.update(outstanding, (n) => n - 1),
185 ),
186 ),
187 Effect.forever,
188 Effect.forkScoped,
189 );
190
191 const drain: DrainableWorker<A>["drain"] = TxRef.get(outstanding).pipe(
192 Effect.tap((n) => (n > 0 ? Effect.txRetry : Effect.void)),
193 Effect.tx,
194 );
195
196 const enqueue = (element: A): Effect.Effect<boolean, never, never> =>
197 TxQueue.offer(queue, element).pipe(
198 Effect.tap(() => TxRef.update(outstanding, (n) => n + 1)),
199 Effect.tx,
200 );
201
202 return { enqueue, drain } satisfies DrainableWorker<A>;
203 });