Open History to see the last commit
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
9import { forkParked, withoutParentSpan } from "../serverActivation.ts";
10
11export class Scheduler extends Context.Service<
12 Scheduler,
13 {
14 readonly register: <E, R>(
15 name: string,
16 runDueWork: Effect.Effect<void, E, R>,
17 ) => Effect.Effect<void, never, R | Scope.Scope>;
18 }
19>()("t3/scheduling/Scheduler") {}
20
21const make = Effect.gen(function* () {
22 const sources = yield* Ref.make(new Map<symbol, Effect.Effect<void>>());
23 const register: Scheduler["Service"]["register"] = Effect.fnUntraced(function* <E, R>(
24 name: string,
25 runDueWork: Effect.Effect<void, E, R>,
26 ) {
27 const scope = yield* Effect.scope;
28 const context = yield* Effect.context<R>();
29 const permit = yield* Semaphore.make(1);
30 const run = runDueWork.pipe(
31 withoutParentSpan,
32 Effect.provideContext(context),
33 Effect.catchCause((cause) =>
34 Cause.hasInterruptsOnly(cause)
35 ? Effect.void
36 : Effect.logWarning("Scheduler source failed", { source: name, cause }),
37 ),
38 permit.withPermitsIfAvailable(1),
39 Effect.forkIn(scope),
40 Effect.asVoid,
41 );
42 const id = Symbol(name);
43 yield* Effect.acquireRelease(
44 Ref.update(sources, (current) => new Map(current).set(id, run)),
45 () =>
46 Ref.update(sources, (current) => {
47 const next = new Map(current);
48 next.delete(id);
49 return next;
50 }),
51 );
52 // Due work waits for startup recovery, which would cancel runs it started.
53 yield* forkParked(run);
54 });
55 const tick = Ref.get(sources).pipe(
56 Effect.flatMap((current) => Effect.forEach(current.values(), (run) => run, { discard: true })),
57 );
58 yield* forkParked(Effect.sleep("5 seconds").pipe(Effect.andThen(tick), Effect.forever));
59 return Scheduler.of({ register });
60});
61
62export const layer = Layer.effect(Scheduler, make);