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 ProviderHost from "./ProviderHost.ts";
19import { applyUsageLimitsUpdate, resolveUsageLimitsAfterProbe } from "./usageLimits.ts";
20import type { ManagedServerProvider } from "./snapshot.ts";
21
22interface ProviderSnapshotState {
23 readonly snapshot: ServerProvider;
24 readonly enrichmentGeneration: number;
25}
26
27function withUsageLimits(
28 snapshot: ServerProvider,
29 usageLimits: ServerProvider["usageLimits"],
30): ServerProvider {
31 if (snapshot.usageLimits === usageLimits) {
32 return snapshot;
33 }
34 const { usageLimits: _previous, ...rest } = snapshot;
35 return usageLimits ? { ...rest, usageLimits } : rest;
36}
37
38export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
39 Settings,
40>(input: {
41 readonly resolveMaintenance: ManagedServerProvider["resolveMaintenance"];
42 readonly getSettings: Effect.Effect<Settings, ServerSettingsError>;
43 readonly streamSettings: Stream.Stream<Settings>;
44 readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
45 readonly initialSnapshot: (settings: Settings) => Effect.Effect<ServerProvider>;
46 readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
47 readonly enrichSnapshot?: (input: {
48 readonly settings: Settings;
49 readonly snapshot: ServerProvider;
50 readonly getSnapshot: Effect.Effect<ServerProvider>;
51 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
52 }) => Effect.Effect<void>;
53 readonly refreshInterval?: Duration.Input;
54 readonly refreshOnInterval?: boolean;
55 readonly checkProviderOnSettingsChange?: (previous: Settings, next: Settings) => boolean;
56}): Effect.fn.Return<
57 ManagedServerProvider,
58 ServerSettingsError,
59 Scope.Scope | ProviderHost.ProviderHost
60> {
61 const host = yield* ProviderHost.ProviderHost;
62 const refreshSemaphore = yield* Semaphore.make(1);
63 const changesPubSub = yield* Effect.acquireRelease(
64 PubSub.unbounded<ServerProvider>(),
65 PubSub.shutdown,
66 );
67 const initialSettings = yield* input.getSettings;
68 const initialSnapshot = yield* input.initialSnapshot(initialSettings);
69 const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({
70 snapshot: initialSnapshot,
71 enrichmentGeneration: 0,
72 });
73 const settingsRef = yield* Ref.make(initialSettings);
74 const enrichmentFiberRef = yield* Ref.make<Fiber.Fiber<void, unknown> | null>(null);
75 const scope = yield* Effect.scope;
76
77 const publishEnrichedSnapshot = Effect.fn("publishEnrichedSnapshot")(function* (
78 generation: number,
79 nextSnapshot: ServerProvider,
80 ) {
81 const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
82 if (state.enrichmentGeneration !== generation) {
83 return [null, state] as const;
84 }
85 // Enrichment derives from the snapshot it was handed; a runtime usage
86 // update that landed since must not be reverted by it.
87 const merged = withUsageLimits(nextSnapshot, state.snapshot.usageLimits);
88 if (Equal.equals(state.snapshot, merged)) {
89 return [null, state] as const;
90 }
91 return [merged, { ...state, snapshot: merged }] as const;
92 });
93 if (snapshotToPublish === null) {
94 return;
95 }
96 yield* PubSub.publish(changesPubSub, snapshotToPublish);
97 });
98
99 const restartSnapshotEnrichment = Effect.fn("restartSnapshotEnrichment")(function* (
100 settings: Settings,
101 snapshot: ServerProvider,
102 generation: number,
103 ) {
104 const previousFiber = yield* Ref.getAndSet(enrichmentFiberRef, null);
105 if (previousFiber) {
106 yield* Fiber.interrupt(previousFiber).pipe(Effect.ignore);
107 }
108
109 if (!input.enrichSnapshot || !snapshot.enabled) {
110 return;
111 }
112
113 const fiber = yield* input
114 .enrichSnapshot({
115 settings,
116 snapshot,
117 getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
118 publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot),
119 })
120 .pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope));
121
122 yield* Ref.set(enrichmentFiberRef, fiber);
123 });
124
125 const applySnapshotBase = Effect.fn("applySnapshot")(function* (
126 nextSettings: Settings,
127 options?: { readonly forceRefresh?: boolean },
128 ) {
129 const forceRefresh = options?.forceRefresh === true;
130 const previousSettings = yield* Ref.get(settingsRef);
131 if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
132 yield* Ref.set(settingsRef, nextSettings);
133 return yield* Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot));
134 }
135
136 if (
137 !forceRefresh &&
138 input.checkProviderOnSettingsChange?.(previousSettings, nextSettings) === false
139 ) {
140 const state = yield* Ref.get(snapshotStateRef);
141 const nextGeneration = state.enrichmentGeneration + 1;
142 yield* Ref.set(snapshotStateRef, {
143 ...state,
144 enrichmentGeneration: nextGeneration,
145 });
146 yield* Ref.set(settingsRef, nextSettings);
147 yield* restartSnapshotEnrichment(nextSettings, state.snapshot, nextGeneration);
148 return state.snapshot;
149 }
150
151 const probedSnapshot = yield* input.checkProvider;
152 const { snapshot: nextSnapshot, generation: nextGeneration } = yield* Ref.modify(
153 snapshotStateRef,
154 (state) => {
155 const generation = input.enrichSnapshot
156 ? state.enrichmentGeneration + 1
157 : state.enrichmentGeneration;
158 // A failed read keeps the last good limits only for the same account,
159 // and they keep the workspace they were read for.
160 const previous = state.snapshot.auth;
161 const differs = (a: string | undefined, b: string | undefined) =>
162 a !== undefined && b !== undefined && a !== b;
163 const switchedAccount =
164 differs(probedSnapshot.auth.email?.toLowerCase(), previous.email?.toLowerCase()) ||
165 (probedSnapshot.auth.workspaceId !== undefined &&
166 probedSnapshot.auth.workspaceId !== previous.workspaceId);
167 const usageLimits = switchedAccount
168 ? probedSnapshot.usageLimits
169 : resolveUsageLimitsAfterProbe({
170 published: state.snapshot.usageLimits,
171 probed: probedSnapshot.usageLimits,
172 });
173 const workspaceId =
174 usageLimits === probedSnapshot.usageLimits ? undefined : state.snapshot.auth.workspaceId;
175 const snapshot = withUsageLimits(
176 workspaceId && !probedSnapshot.auth.workspaceId
177 ? { ...probedSnapshot, auth: { ...probedSnapshot.auth, workspaceId } }
178 : probedSnapshot,
179 usageLimits,
180 );
181 return [
182 { snapshot, generation },
183 { snapshot, enrichmentGeneration: generation },
184 ] as const;
185 },
186 );
187 yield* Ref.set(settingsRef, nextSettings);
188 yield* PubSub.publish(changesPubSub, nextSnapshot);
189 yield* restartSnapshotEnrichment(nextSettings, nextSnapshot, nextGeneration);
190 return nextSnapshot;
191 });
192 const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
193 refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));
194
195 const applyUsageLimits: ManagedServerProvider["applyUsageLimits"] = (update) =>
196 Effect.gen(function* () {
197 const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
198 const usageLimits = applyUsageLimitsUpdate({
199 previous: state.snapshot.usageLimits,
200 update,
201 checkedAt: update.checkedAt,
202 });
203 if (usageLimits === state.snapshot.usageLimits) {
204 return [null, state] as const;
205 }
206 const snapshot = withUsageLimits(state.snapshot, usageLimits);
207 return [snapshot, { ...state, snapshot }] as const;
208 });
209 if (snapshotToPublish !== null) {
210 yield* PubSub.publish(changesPubSub, snapshotToPublish);
211 }
212 });
213
214 const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () {
215 const nextSettings = yield* input.getSettings;
216 return yield* applySnapshot(nextSettings, { forceRefresh: true });
217 });
218
219 const hasProviderStatusDemand = Effect.gen(function* () {
220 const state = yield* Ref.get(snapshotStateRef);
221 const instanceId = state.snapshot.instanceId;
222 const [genericDemand, instanceDemand] = yield* Effect.all([
223 host.shouldRunBackgroundWork({ type: "provider-status" }),
224 host.shouldRunBackgroundWork({ type: "provider-status", instanceId }),
225 ]);
226 return genericDemand || instanceDemand;
227 });
228
229 const getRefreshInterval =
230 input.refreshInterval !== undefined
231 ? Effect.succeed(input.refreshInterval)
232 : host.settings.get.pipe(
233 Effect.map(
234 (settings) =>
235 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
236 ),
237 Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
238 );
239
240 const refreshIntervalChanges = yield* Queue.sliding<void>(1);
241 if (input.refreshInterval === undefined) {
242 const serverSettingsChanges = yield* host.settings.subscribe;
243 yield* serverSettingsChanges.pipe(
244 Stream.map((settings) =>
245 Duration.toMillis(
246 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
247 ),
248 ),
249 Stream.changes,
250 Stream.runForEach(() => Queue.offer(refreshIntervalChanges, undefined).pipe(Effect.asVoid)),
251 Effect.forkScoped,
252 );
253 }
254
255 yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
256 Effect.asVoid(applySnapshot(nextSettings)),
257 ).pipe(Effect.forkScoped);
258
259 yield* Effect.forever(
260 getRefreshInterval.pipe(
261 Effect.flatMap((refreshInterval) =>
262 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - races the interval against a settings-change signal, not a timeout
263 Effect.raceFirst(
264 Effect.sleep(
265 Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0
266 ? "60 seconds"
267 : refreshInterval,
268 ).pipe(Effect.as(true)),
269 Queue.take(refreshIntervalChanges).pipe(Effect.as(false)),
270 ).pipe(
271 Effect.flatMap((intervalElapsed) =>
272 input.refreshOnInterval !== false &&
273 intervalElapsed &&
274 Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0
275 ? hasProviderStatusDemand.pipe(
276 Effect.flatMap((shouldRefresh) =>
277 shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,
278 ),
279 )
280 : Effect.void,
281 ),
282 ),
283 ),
284 Effect.ignoreCause({ log: true }),
285 ),
286 ).pipe(Effect.forkScoped);
287
288 yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(
289 Effect.ignoreCause({ log: true }),
290 Effect.forkScoped,
291 );
292
293 return {
294 resolveMaintenance: input.resolveMaintenance,
295 getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
296 refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
297 applyUsageLimits,
298 get streamChanges() {
299 return Stream.fromPubSub(changesPubSub);
300 },
301 } satisfies ManagedServerProvider;
302});