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

DrainableWorker.ts

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