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

DrainableWorker.ts

70 lines2.3 KB

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 TxQueue from "effect/TxQueue";
14import * as TxRef from "effect/TxRef";
15​
16export interface DrainableWorker<A> {
17 /**
18 * Enqueue a work item and track it for `drain()`.
19 *
20 * This wraps `Queue.offer` so drain state is updated atomically with the
21 * enqueue path instead of inferring it from queue internals.
22 */
23 readonly enqueue: (item: A) => Effect.Effect<void>;
24​
25 /**
26 * Resolves when the queue is empty and the worker is idle (not processing).
27 */
28 readonly drain: Effect.Effect<void>;
30​
31/**
32 * Create a drainable worker that processes items from an unbounded queue.
33 *
34 * The worker is forked into the current scope and will be interrupted when
35 * the scope closes. A finalizer shuts down the queue.
36 *
37 * @param process - The effect to run for each queued item.
38 * @returns A `DrainableWorker` with `queue` and `drain`.
39 */
40export const makeDrainableWorker = <A, E, R>(
41 process: (item: A) => Effect.Effect<void, E, R>,
42): Effect.Effect<DrainableWorker<A>, never, Scope.Scope | R> =>
43 Effect.gen(function* () {
44 const queue = yield* Effect.acquireRelease(TxQueue.unbounded<A>(), TxQueue.shutdown);
45 const outstanding = yield* TxRef.make(0);
46​
47 yield* TxQueue.take(queue).pipe(
48 Effect.tap((a) =>
49 Effect.ensuring(
50 process(a),
51 TxRef.update(outstanding, (n) => n - 1),
52 ),
53 ),
54 Effect.forever,
55 Effect.forkScoped,
56 );
57​
58 const drain: DrainableWorker<A>["drain"] = TxRef.get(outstanding).pipe(
59 Effect.tap((n) => (n > 0 ? Effect.txRetry : Effect.void)),
60 Effect.tx,
61 );
62​
63 const enqueue = (element: A): Effect.Effect<boolean, never, never> =>
64 TxQueue.offer(queue, element).pipe(
65 Effect.tap(() => TxRef.update(outstanding, (n) => n + 1)),
66 Effect.tx,
67 );
68​
69 return { enqueue, drain } satisfies DrainableWorker<A>;
70 });