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}): Effect.fn.Return<
44 ServerProviderShape,
45 ServerSettingsError,
46 Scope.Scope | BackgroundPolicy.BackgroundPolicy | ServerSettingsService
47> {
48 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
49 const serverSettings = yield* ServerSettingsService;
50 const refreshSemaphore = yield* Semaphore.make(1);
51 const changesPubSub = yield* Effect.acquireRelease(
52 PubSub.unbounded<ServerProvider>(),
53 PubSub.shutdown,
54 );
55 const initialSettings = yield* input.getSettings;
56 const initialSnapshot = yield* input.initialSnapshot(initialSettings);
57 const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({
58 snapshot: initialSnapshot,
59 enrichmentGeneration: 0,
60 });
61 const settingsRef = yield* Ref.make(initialSettings);
62 const enrichmentFiberRef = yield* Ref.make<Fiber.Fiber<void, unknown> | null>(null);
63 const scope = yield* Effect.scope;
64
65 const publishEnrichedSnapshot = Effect.fn("publishEnrichedSnapshot")(function* (
66 generation: number,
67 nextSnapshot: ServerProvider,
68 ) {
69 const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
70 if (state.enrichmentGeneration !== generation || Equal.equals(state.snapshot, nextSnapshot)) {
71 return [null, state] as const;
72 }
73 return [
74 nextSnapshot,
75 {
76 ...state,
77 snapshot: nextSnapshot,
78 },
79 ] as const;
80 });
81 if (snapshotToPublish === null) {
82 return;
83 }
84 yield* PubSub.publish(changesPubSub, snapshotToPublish);
85 });
86
87 const restartSnapshotEnrichment = Effect.fn("restartSnapshotEnrichment")(function* (
88 settings: Settings,
89 snapshot: ServerProvider,
90 generation: number,
91 ) {
92 const previousFiber = yield* Ref.getAndSet(enrichmentFiberRef, null);
93 if (previousFiber) {
94 yield* Fiber.interrupt(previousFiber).pipe(Effect.ignore);
95 }
96
97 if (!input.enrichSnapshot) {
98 return;
99 }
100
101 const fiber = yield* input
102 .enrichSnapshot({
103 settings,
104 snapshot,
105 getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
106 publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot),
107 })
108 .pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope));
109
110 yield* Ref.set(enrichmentFiberRef, fiber);
111 });
112
113 const applySnapshotBase = Effect.fn("applySnapshot")(function* (
114 nextSettings: Settings,
115 options?: { readonly forceRefresh?: boolean },
116 ) {
117 const forceRefresh = options?.forceRefresh === true;
118 const previousSettings = yield* Ref.get(settingsRef);
119 if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
120 yield* Ref.set(settingsRef, nextSettings);
121 return yield* Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot));
122 }
123
124 const nextSnapshot = yield* input.checkProvider;
125 const nextGeneration = yield* Ref.modify(snapshotStateRef, (state) => {
126 const generation = input.enrichSnapshot
127 ? state.enrichmentGeneration + 1
128 : state.enrichmentGeneration;
129 return [
130 generation,
131 {
132 snapshot: nextSnapshot,
133 enrichmentGeneration: generation,
134 },
135 ] as const;
136 });
137 yield* Ref.set(settingsRef, nextSettings);
138 yield* PubSub.publish(changesPubSub, nextSnapshot);
139 yield* restartSnapshotEnrichment(nextSettings, nextSnapshot, nextGeneration);
140 return nextSnapshot;
141 });
142 const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
143 refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));
144
145 const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () {
146 const nextSettings = yield* input.getSettings;
147 return yield* applySnapshot(nextSettings, { forceRefresh: true });
148 });
149
150 const hasProviderStatusDemand = Effect.gen(function* () {
151 const state = yield* Ref.get(snapshotStateRef);
152 const instanceId = state.snapshot.instanceId;
153 const [genericDemand, instanceDemand] = yield* Effect.all([
154 backgroundPolicy.shouldRunScopeWork({ type: "provider-status" }),
155 backgroundPolicy.shouldRunScopeWork({ type: "provider-status", instanceId }),
156 ]);
157 return genericDemand || instanceDemand;
158 });
159
160 const getRefreshInterval =
161 input.refreshInterval !== undefined
162 ? Effect.succeed(input.refreshInterval)
163 : serverSettings.getSettings.pipe(
164 Effect.map(
165 (settings) =>
166 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
167 ),
168 Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
169 );
170
171 const refreshIntervalChanges = yield* Queue.sliding<void>(1);
172 if (input.refreshInterval === undefined) {
173 const serverSettingsChanges = yield* serverSettings.subscribeChanges;
174 yield* serverSettingsChanges.pipe(
175 Stream.map((settings) =>
176 Duration.toMillis(
177 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
178 ),
179 ),
180 Stream.changes,
181 Stream.runForEach(() => Queue.offer(refreshIntervalChanges, undefined).pipe(Effect.asVoid)),
182 Effect.forkScoped,
183 );
184 }
185
186 yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
187 Effect.asVoid(applySnapshot(nextSettings)),
188 ).pipe(Effect.forkScoped);
189
190 yield* Effect.forever(
191 getRefreshInterval.pipe(
192 Effect.flatMap((refreshInterval) =>
193 Effect.raceFirst(
194 Effect.sleep(
195 Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0
196 ? "60 seconds"
197 : refreshInterval,
198 ).pipe(Effect.as(true)),
199 Queue.take(refreshIntervalChanges).pipe(Effect.as(false)),
200 ).pipe(
201 Effect.flatMap((intervalElapsed) =>
202 intervalElapsed && Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0
203 ? hasProviderStatusDemand.pipe(
204 Effect.flatMap((shouldRefresh) =>
205 shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,
206 ),
207 )
208 : Effect.void,
209 ),
210 ),
211 ),
212 Effect.ignoreCause({ log: true }),
213 ),
214 ).pipe(Effect.forkScoped);
215
216 yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(
217 Effect.ignoreCause({ log: true }),
218 Effect.forkScoped,
219 );
220
221 return {
222 maintenanceCapabilities: input.maintenanceCapabilities,
223 getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
224 refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
225 get streamChanges() {
226 return Stream.fromPubSub(changesPubSub);
227 },
228 } satisfies ServerProviderShape;
229});