Open History to see the last commit
1import type { ServerProvider } from "@t3tools/contracts";
2import { Duration, Effect, Equal, Fiber, PubSub, Ref, Scope, Stream } from "effect";
3import * as Semaphore from "effect/Semaphore";
4
5import type { ServerProviderShape } from "./Services/ServerProvider.ts";
6import { ServerSettingsError } from "@t3tools/contracts";
7
8interface ProviderSnapshotState {
9 readonly snapshot: ServerProvider;
10 readonly enrichmentGeneration: number;
11}
12
13export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
14 Settings,
15>(input: {
16 readonly getSettings: Effect.Effect<Settings>;
17 readonly streamSettings: Stream.Stream<Settings>;
18 readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
19 readonly initialSnapshot: (settings: Settings) => ServerProvider;
20 readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
21 readonly enrichSnapshot?: (input: {
22 readonly settings: Settings;
23 readonly snapshot: ServerProvider;
24 readonly getSnapshot: Effect.Effect<ServerProvider>;
25 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
26 }) => Effect.Effect<void>;
27 readonly refreshInterval?: Duration.Input;
28}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
29 const refreshSemaphore = yield* Semaphore.make(1);
30 const changesPubSub = yield* Effect.acquireRelease(
31 PubSub.unbounded<ServerProvider>(),
32 PubSub.shutdown,
33 );
34 const initialSettings = yield* input.getSettings;
35 const initialSnapshot = input.initialSnapshot(initialSettings);
36 const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({
37 snapshot: initialSnapshot,
38 enrichmentGeneration: 0,
39 });
40 const settingsRef = yield* Ref.make(initialSettings);
41 const enrichmentFiberRef = yield* Ref.make<Fiber.Fiber<void, unknown> | null>(null);
42 const scope = yield* Effect.scope;
43
44 const publishEnrichedSnapshot = Effect.fn("publishEnrichedSnapshot")(function* (
45 generation: number,
46 nextSnapshot: ServerProvider,
47 ) {
48 const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
49 if (state.enrichmentGeneration !== generation || Equal.equals(state.snapshot, nextSnapshot)) {
50 return [null, state] as const;
51 }
52 return [
53 nextSnapshot,
54 {
55 ...state,
56 snapshot: nextSnapshot,
57 },
58 ] as const;
59 });
60 if (snapshotToPublish === null) {
61 return;
62 }
63 yield* PubSub.publish(changesPubSub, snapshotToPublish);
64 });
65
66 const restartSnapshotEnrichment = Effect.fn("restartSnapshotEnrichment")(function* (
67 settings: Settings,
68 snapshot: ServerProvider,
69 generation: number,
70 ) {
71 const previousFiber = yield* Ref.getAndSet(enrichmentFiberRef, null);
72 if (previousFiber) {
73 yield* Fiber.interrupt(previousFiber).pipe(Effect.ignore);
74 }
75
76 if (!input.enrichSnapshot) {
77 return;
78 }
79
80 const fiber = yield* input
81 .enrichSnapshot({
82 settings,
83 snapshot,
84 getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
85 publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot),
86 })
87 .pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope));
88
89 yield* Ref.set(enrichmentFiberRef, fiber);
90 });
91
92 const applySnapshotBase = Effect.fn("applySnapshot")(function* (
93 nextSettings: Settings,
94 options?: { readonly forceRefresh?: boolean },
95 ) {
96 const forceRefresh = options?.forceRefresh === true;
97 const previousSettings = yield* Ref.get(settingsRef);
98 if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
99 yield* Ref.set(settingsRef, nextSettings);
100 return yield* Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot));
101 }
102
103 const nextSnapshot = yield* input.checkProvider;
104 const nextGeneration = yield* Ref.modify(snapshotStateRef, (state) => {
105 const generation = input.enrichSnapshot
106 ? state.enrichmentGeneration + 1
107 : state.enrichmentGeneration;
108 return [
109 generation,
110 {
111 snapshot: nextSnapshot,
112 enrichmentGeneration: generation,
113 },
114 ] as const;
115 });
116 yield* Ref.set(settingsRef, nextSettings);
117 yield* PubSub.publish(changesPubSub, nextSnapshot);
118 yield* restartSnapshotEnrichment(nextSettings, nextSnapshot, nextGeneration);
119 return nextSnapshot;
120 });
121 const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
122 refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));
123
124 const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () {
125 const nextSettings = yield* input.getSettings;
126 return yield* applySnapshot(nextSettings, { forceRefresh: true });
127 });
128
129 yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
130 Effect.asVoid(applySnapshot(nextSettings)),
131 ).pipe(Effect.forkScoped);
132
133 yield* Effect.forever(
134 Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
135 Effect.flatMap(() => refreshSnapshot()),
136 Effect.ignoreCause({ log: true }),
137 ),
138 ).pipe(Effect.forkScoped);
139
140 yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(
141 Effect.ignoreCause({ log: true }),
142 Effect.forkScoped,
143 );
144
145 return {
146 getSnapshot: input.getSettings.pipe(
147 Effect.flatMap(applySnapshot),
148 Effect.tapError(Effect.logError),
149 Effect.orDie,
150 ),
151 refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
152 get streamChanges() {
153 return Stream.fromPubSub(changesPubSub);
154 },
155 } satisfies ServerProviderShape;
156});