Open History to see the last commit
1import {
2 DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,
3 type ServerProvider,
4 ServerSettingsError,
5} from "@t3tools/contracts";
6import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Equal from "effect/Equal";
10import * as Fiber from "effect/Fiber";
11import * as PubSub from "effect/PubSub";
12import * as Queue from "effect/Queue";
13import * as Ref from "effect/Ref";
14import * as Scope from "effect/Scope";
15import * as Stream from "effect/Stream";
16import * as Semaphore from "effect/Semaphore";
17
18import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
19import { ServerSettingsService } from "../serverSettings.ts";
20import type { ServerProviderShape } from "./Services/ServerProvider.ts";
21
22interface ProviderSnapshotState {
23 readonly snapshot: ServerProvider;
24 readonly enrichmentGeneration: number;
25}
26
27export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
28 Settings,
29>(input: {
30 readonly maintenanceCapabilities: ServerProviderShape["maintenanceCapabilities"];
31 readonly getSettings: Effect.Effect<Settings, ServerSettingsError>;
32 readonly streamSettings: Stream.Stream<Settings>;
33 readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
34 readonly initialSnapshot: (settings: Settings) => Effect.Effect<ServerProvider>;
35 readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
36 readonly enrichSnapshot?: (input: {
37 readonly settings: Settings;
38 readonly snapshot: ServerProvider;
39 readonly getSnapshot: Effect.Effect<ServerProvider>;
40 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
41 }) => Effect.Effect<void>;
42 readonly refreshInterval?: Duration.Input;
43 readonly refreshOnInterval?: boolean;
44 readonly checkProviderOnSettingsChange?: (previous: Settings, next: Settings) => boolean;
45}): Effect.fn.Return<
46 ServerProviderShape,
47 ServerSettingsError,
48 Scope.Scope | BackgroundPolicy.BackgroundPolicy | ServerSettingsService
49> {
50 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
51 const serverSettings = yield* ServerSettingsService;
52 const refreshSemaphore = yield* Semaphore.make(1);
53 const changesPubSub = yield* Effect.acquireRelease(
54 PubSub.unbounded<ServerProvider>(),
55 PubSub.shutdown,
56 );
57 const initialSettings = yield* input.getSettings;
58 const initialSnapshot = yield* input.initialSnapshot(initialSettings);
59 const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({
60 snapshot: initialSnapshot,
61 enrichmentGeneration: 0,
62 });
63 const settingsRef = yield* Ref.make(initialSettings);
64 const enrichmentFiberRef = yield* Ref.make<Fiber.Fiber<void, unknown> | null>(null);
65 const scope = yield* Effect.scope;
66
67 const publishEnrichedSnapshot = Effect.fn("publishEnrichedSnapshot")(function* (
68 generation: number,
69 nextSnapshot: ServerProvider,
70 ) {
71 const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
72 if (state.enrichmentGeneration !== generation || Equal.equals(state.snapshot, nextSnapshot)) {
73 return [null, state] as const;
74 }
75 return [
76 nextSnapshot,
77 {
78 ...state,
79 snapshot: nextSnapshot,
80 },
81 ] as const;
82 });
83 if (snapshotToPublish === null) {
84 return;
85 }
86 yield* PubSub.publish(changesPubSub, snapshotToPublish);
87 });
88
89 const restartSnapshotEnrichment = Effect.fn("restartSnapshotEnrichment")(function* (
90 settings: Settings,
91 snapshot: ServerProvider,
92 generation: number,
93 ) {
94 const previousFiber = yield* Ref.getAndSet(enrichmentFiberRef, null);
95 if (previousFiber) {
96 yield* Fiber.interrupt(previousFiber).pipe(Effect.ignore);
97 }
98
99 if (!input.enrichSnapshot) {
100 return;
101 }
102
103 const fiber = yield* input
104 .enrichSnapshot({
105 settings,
106 snapshot,
107 getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
108 publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot),
109 })
110 .pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope));
111
112 yield* Ref.set(enrichmentFiberRef, fiber);
113 });
114
115 const applySnapshotBase = Effect.fn("applySnapshot")(function* (
116 nextSettings: Settings,
117 options?: { readonly forceRefresh?: boolean },
118 ) {
119 const forceRefresh = options?.forceRefresh === true;
120 const previousSettings = yield* Ref.get(settingsRef);
121 if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
122 yield* Ref.set(settingsRef, nextSettings);
123 return yield* Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot));
124 }
125
126 if (
127 !forceRefresh &&
128 input.checkProviderOnSettingsChange?.(previousSettings, nextSettings) === false
129 ) {
130 const state = yield* Ref.get(snapshotStateRef);
131 const nextGeneration = state.enrichmentGeneration + 1;
132 yield* Ref.set(snapshotStateRef, {
133 ...state,
134 enrichmentGeneration: nextGeneration,
135 });
136 yield* Ref.set(settingsRef, nextSettings);
137 yield* restartSnapshotEnrichment(nextSettings, state.snapshot, nextGeneration);
138 return state.snapshot;
139 }
140
141 const nextSnapshot = yield* input.checkProvider;
142 const nextGeneration = yield* Ref.modify(snapshotStateRef, (state) => {
143 const generation = input.enrichSnapshot
144 ? state.enrichmentGeneration + 1
145 : state.enrichmentGeneration;
146 return [
147 generation,
148 {
149 snapshot: nextSnapshot,
150 enrichmentGeneration: generation,
151 },
152 ] as const;
153 });
154 yield* Ref.set(settingsRef, nextSettings);
155 yield* PubSub.publish(changesPubSub, nextSnapshot);
156 yield* restartSnapshotEnrichment(nextSettings, nextSnapshot, nextGeneration);
157 return nextSnapshot;
158 });
159 const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
160 refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));
161
162 const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () {
163 const nextSettings = yield* input.getSettings;
164 return yield* applySnapshot(nextSettings, { forceRefresh: true });
165 });
166
167 const hasProviderStatusDemand = Effect.gen(function* () {
168 const state = yield* Ref.get(snapshotStateRef);
169 const instanceId = state.snapshot.instanceId;
170 const [genericDemand, instanceDemand] = yield* Effect.all([
171 backgroundPolicy.shouldRunScopeWork({ type: "provider-status" }),
172 backgroundPolicy.shouldRunScopeWork({ type: "provider-status", instanceId }),
173 ]);
174 return genericDemand || instanceDemand;
175 });
176
177 const getRefreshInterval =
178 input.refreshInterval !== undefined
179 ? Effect.succeed(input.refreshInterval)
180 : serverSettings.getSettings.pipe(
181 Effect.map(
182 (settings) =>
183 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
184 ),
185 Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
186 );
187
188 const refreshIntervalChanges = yield* Queue.sliding<void>(1);
189 if (input.refreshInterval === undefined) {
190 const serverSettingsChanges = yield* serverSettings.subscribeChanges;
191 yield* serverSettingsChanges.pipe(
192 Stream.map((settings) =>
193 Duration.toMillis(
194 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
195 ),
196 ),
197 Stream.changes,
198 Stream.runForEach(() => Queue.offer(refreshIntervalChanges, undefined).pipe(Effect.asVoid)),
199 Effect.forkScoped,
200 );
201 }
202
203 yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
204 Effect.asVoid(applySnapshot(nextSettings)),
205 ).pipe(Effect.forkScoped);
206
207 yield* Effect.forever(
208 getRefreshInterval.pipe(
209 Effect.flatMap((refreshInterval) =>
210 Effect.raceFirst(
211 Effect.sleep(
212 Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0
213 ? "60 seconds"
214 : refreshInterval,
215 ).pipe(Effect.as(true)),
216 Queue.take(refreshIntervalChanges).pipe(Effect.as(false)),
217 ).pipe(
218 Effect.flatMap((intervalElapsed) =>
219 input.refreshOnInterval !== false &&
220 intervalElapsed &&
221 Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0
222 ? hasProviderStatusDemand.pipe(
223 Effect.flatMap((shouldRefresh) =>
224 shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,
225 ),
226 )
227 : Effect.void,
228 ),
229 ),
230 ),
231 Effect.ignoreCause({ log: true }),
232 ),
233 ).pipe(Effect.forkScoped);
234
235 yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(
236 Effect.ignoreCause({ log: true }),
237 Effect.forkScoped,
238 );
239
240 return {
241 maintenanceCapabilities: input.maintenanceCapabilities,
242 getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
243 refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
244 get streamChanges() {
245 return Stream.fromPubSub(changesPubSub);
246 },
247 } satisfies ServerProviderShape;
248});