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

DrainableWorker.ts

64 lines2.4 KB

1import * as Cause from "effect/Cause";
2import * as Scope from "effect/Scope";
3import * as Effect from "effect/Effect";
4import * as TxQueue from "effect/TxQueue";
5import * as TxRef from "effect/TxRef";
6​
7export interface DrainableWorker<A> {
8 readonly enqueue: (item: A) => Effect.Effect<void>;
9​
10 readonly drain: Effect.Effect<void>;
12​
13/**
14 * A finalizer shuts down the queue and drops queued items, so `drain` resolves after the scope
15 * closes instead of waiting on them. An item that fails or dies is logged and skipped; the worker
16 * keeps processing later items and `drain` still resolves.
17 */
18export const makeDrainableWorker = <A, E, R>(
19 process: (item: A) => Effect.Effect<void, E, R>,
20): Effect.Effect<DrainableWorker<A>, never, Scope.Scope | R> =>
21 Effect.gen(function* () {
22 const outstanding = yield* TxRef.make(0);
23 const queue = yield* Effect.acquireRelease(TxQueue.unbounded<A>(), (queue) =>
24 // Uncount only the dropped items: an item still running uncounts itself,
25 // even when a parallel scope closes it after this finalizer.
26 TxQueue.clear(queue).pipe(
27 Effect.flatMap((dropped) => TxRef.update(outstanding, (n) => n - dropped.length)),
28 Effect.andThen(TxQueue.shutdown(queue)),
29 Effect.tx,
30 ),
31 );
32​
33 yield* TxQueue.take(queue).pipe(
34 Effect.flatMap((a) =>
35 // `suspend` turns a `process` that throws while building its effect
36 // into this item's defect instead of the loop's.
37 Effect.suspend(() => process(a)).pipe(
38 // Only the item's own failure, defect, or interruption lands here and
39 // the loop continues; interrupting the worker fiber still stops it.
40 Effect.catchCause((cause) =>
41 Cause.hasInterruptsOnly(cause)
42 ? Effect.void
43 : Effect.logError("DrainableWorker item failed", cause),
44 ),
45 Effect.ensuring(TxRef.update(outstanding, (n) => n - 1)),
46 ),
47 ),
48 Effect.forever,
49 Effect.forkScoped,
50 );
51​
52 const drain: DrainableWorker<A>["drain"] = TxRef.get(outstanding).pipe(
53 Effect.flatMap((n) => (n > 0 ? Effect.txRetry : Effect.void)),
54 Effect.tx,
55 );
56​
57 const enqueue = (element: A): Effect.Effect<boolean, never, never> =>
58 TxQueue.offer(queue, element).pipe(
59 Effect.tap((offered) => (offered ? TxRef.update(outstanding, (n) => n + 1) : Effect.void)),
60 Effect.tx,
61 );
62​
63 return { enqueue, drain } satisfies DrainableWorker<A>;
64 });