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

Scheduler.ts

61 lines2.2 KB

1import * as Cause from "effect/Cause";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Ref from "effect/Ref";
6import * as Scope from "effect/Scope";
7import * as Semaphore from "effect/Semaphore";
8​
9/** Sources load due work from their durable state; registration owns its execution lifetime. */
10export class Scheduler extends Context.Service<
11 Scheduler,
12 {
13 readonly register: <E, R>(
14 name: string,
15 runDueWork: Effect.Effect<void, E, R>,
16 ) => Effect.Effect<void, never, R | Scope.Scope>;
17 }
18>()("t3/scheduling/Scheduler") {}
19​
20const make = Effect.gen(function* () {
21 const sources = yield* Ref.make(new Map<symbol, Effect.Effect<void>>());
22 const register: Scheduler["Service"]["register"] = Effect.fn("Scheduler.register")(function* <
23 E,
24 R,
25 >(name: string, runDueWork: Effect.Effect<void, E, R>) {
26 const scope = yield* Effect.scope;
27 const context = yield* Effect.context<R>();
28 const permit = yield* Semaphore.make(1);
29 const run = runDueWork.pipe(
30 Effect.provideContext(context),
31 Effect.catchCause((cause) =>
32 Cause.hasInterruptsOnly(cause)
33 ? Effect.void
34 : Effect.logWarning("Scheduler source failed", { source: name, cause }),
35 ),
36 permit.withPermitsIfAvailable(1),
37 Effect.forkIn(scope),
38 Effect.asVoid,
39 );
40 const id = Symbol(name);
41 yield* Effect.acquireRelease(
42 Ref.update(sources, (current) => new Map(current).set(id, run)),
43 () =>
44 Ref.update(sources, (current) => {
45 const next = new Map(current);
46 next.delete(id);
47 return next;
48 }),
49 );
50 yield* run;
51 });
52 const tick = Ref.get(sources).pipe(
53 Effect.flatMap((current) => Effect.forEach(current.values(), (run) => run, { discard: true })),
54 );
55 // One clock for all due-work sources. A slow source cannot block another
56 // source or overlap itself, and no extra missed-tick backlog is queued.
57 yield* Effect.sleep("5 seconds").pipe(Effect.andThen(tick), Effect.forever, Effect.forkScoped);
58 return Scheduler.of({ register });
59});
60​
61export const layer = Layer.effect(Scheduler, make);