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

DrainableWorker.ts

74 lines2.7 KB

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