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 invalidateUsageCache?: Effect.Effect<void>;
48 readonly enrichSnapshot?: (input: {
49 readonly settings: Settings;
50 readonly snapshot: ServerProvider;
51 readonly getSnapshot: Effect.Effect<ServerProvider>;
52 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
53 }) => Effect.Effect<void>;
54 readonly refreshInterval?: Duration.Input;
55 readonly refreshOnInterval?: boolean | ((snapshot: ServerProvider) => boolean);
56 readonly checkProviderOnSettingsChange?: (previous: Settings, next: Settings) => boolean;
57}): Effect.fn.Return<
58 ManagedServerProvider,
59 ServerSettingsError,
60 Scope.Scope | ProviderHost.ProviderHost
61> {
62 const host = yield* ProviderHost.ProviderHost;
63 const refreshSemaphore = yield* Semaphore.make(1);
64 const usageRefreshQueued = yield* Ref.make<symbol | null>(null);
65 const changesPubSub = yield* Effect.acquireRelease(
66 PubSub.unbounded<ServerProvider>(),
67 PubSub.shutdown,
68 );
69 const initialSettings = yield* input.getSettings;
70 const initialSnapshot = yield* input.initialSnapshot(initialSettings);
71 const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({
72 snapshot: initialSnapshot,
73 enrichmentGeneration: 0,
74 });
75 const settingsRef = yield* Ref.make(initialSettings);
76 const enrichmentFiberRef = yield* Ref.make<Fiber.Fiber<void, unknown> | null>(null);
77 const scope = yield* Effect.scope;
78
79 const publishEnrichedSnapshot = Effect.fn("publishEnrichedSnapshot")(function* (
80 generation: number,
81 nextSnapshot: ServerProvider,
82 ) {
83 const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
84 if (state.enrichmentGeneration !== generation) {
85 return [null, state] as const;
86 }
87 // Enrichment must not revert usage updates newer than its input snapshot.
88 const merged = withUsageLimits(nextSnapshot, state.snapshot.usageLimits);
89 if (Equal.equals(state.snapshot, merged)) {
90 return [null, state] as const;
91 }
92 return [merged, { ...state, snapshot: merged }] as const;
93 });
94 if (snapshotToPublish === null) {
95 return;
96 }
97 yield* PubSub.publish(changesPubSub, snapshotToPublish);
98 });
99
100 const restartSnapshotEnrichment = Effect.fn("restartSnapshotEnrichment")(function* (
101 settings: Settings,
102 snapshot: ServerProvider,
103 generation: number,
104 ) {
105 const previousFiber = yield* Ref.getAndSet(enrichmentFiberRef, null);
106 if (previousFiber) {
107 yield* Fiber.interrupt(previousFiber).pipe(Effect.ignore);
108 }
109
110 if (!input.enrichSnapshot || !snapshot.enabled) {
111 return;
112 }
113
114 const fiber = yield* input
115 .enrichSnapshot({
116 settings,
117 snapshot,
118 getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
119 publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot),
120 })
121 .pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope));
122
123 yield* Ref.set(enrichmentFiberRef, fiber);
124 });
125
126 const applySnapshotBase = Effect.fn("applySnapshot")(function* (
127 nextSettings: Settings,
128 options?: { readonly forceRefresh?: boolean },
129 ) {
130 const forceRefresh = options?.forceRefresh === true;
131 const previousSettings = yield* Ref.get(settingsRef);
132 if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
133 yield* Ref.set(settingsRef, nextSettings);
134 return yield* Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot));
135 }
136
137 if (
138 !forceRefresh &&
139 input.checkProviderOnSettingsChange?.(previousSettings, nextSettings) === false
140 ) {
141 const state = yield* Ref.get(snapshotStateRef);
142 const nextGeneration = state.enrichmentGeneration + 1;
143 yield* Ref.set(snapshotStateRef, {
144 ...state,
145 enrichmentGeneration: nextGeneration,
146 });
147 yield* Ref.set(settingsRef, nextSettings);
148 yield* restartSnapshotEnrichment(nextSettings, state.snapshot, nextGeneration);
149 return state.snapshot;
150 }
151
152 const probedSnapshot = yield* input.checkProvider;
153 const { snapshot: nextSnapshot, generation: nextGeneration } = yield* Ref.modify(
154 snapshotStateRef,
155 (state) => {
156 const generation = input.enrichSnapshot
157 ? state.enrichmentGeneration + 1
158 : state.enrichmentGeneration;
159 // Failed reads retain limits only for the same account and original workspace.
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 // Providers call this on every token-usage tick, usually without changing the snapshot.
196 const applyUsageLimits: ManagedServerProvider["applyUsageLimits"] = Effect.fnUntraced(
197 function* (update) {
198 const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
199 const usageLimits = applyUsageLimitsUpdate({
200 previous: state.snapshot.usageLimits,
201 update,
202 checkedAt: update.checkedAt,
203 });
204 if (usageLimits === state.snapshot.usageLimits) {
205 return [null, state] as const;
206 }
207 const snapshot = withUsageLimits(state.snapshot, usageLimits);
208 return [snapshot, { ...state, snapshot }] as const;
209 });
210 if (snapshotToPublish !== null) {
211 yield* PubSub.publish(changesPubSub, snapshotToPublish);
212 }
213 },
214 );
215
216 const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () {
217 const nextSettings = yield* input.getSettings;
218 return yield* applySnapshot(nextSettings, { forceRefresh: true });
219 });
220
221 const refreshUsage = Effect.fn("ManagedServerProvider.refreshUsage")(function* () {
222 const { snapshot } = yield* Ref.get(snapshotStateRef);
223 if (
224 !snapshot.enabled ||
225 !snapshot.usageLimits ||
226 snapshot.usageLimits.unavailable?.reason === "unsupported"
227 )
228 return;
229 // An in-flight refresh may have read cached usage, so one refresh waits behind it.
230 const claim = Symbol();
231 const release = Ref.update(usageRefreshQueued, (queued) => (queued === claim ? null : queued));
232 yield* Effect.uninterruptibleMask((restore) =>
233 Ref.modify(usageRefreshQueued, (queued) => [queued !== null, queued ?? claim]).pipe(
234 Effect.flatMap((held) =>
235 held
236 ? Effect.void
237 : restore(
238 refreshSemaphore.withPermits(1)(
239 release.pipe(
240 Effect.andThen(input.invalidateUsageCache ?? Effect.void),
241 Effect.andThen(input.getSettings),
242 Effect.flatMap((settings) =>
243 applySnapshotBase(settings, { forceRefresh: true }),
244 ),
245 ),
246 ),
247 ).pipe(Effect.onInterrupt(() => release)),
248 ),
249 ),
250 );
251 });
252
253 const shouldRefreshOnInterval = Effect.gen(function* () {
254 const state = yield* Ref.get(snapshotStateRef);
255 // A disabled instance has nothing to probe; a periodic check would only
256 // republish a snapshot that differs in checkedAt.
257 if (
258 !state.snapshot.enabled ||
259 input.refreshOnInterval === false ||
260 (typeof input.refreshOnInterval === "function" && !input.refreshOnInterval(state.snapshot))
261 ) {
262 return false;
263 }
264 const instanceId = state.snapshot.instanceId;
265 const [genericDemand, instanceDemand] = yield* Effect.all([
266 host.shouldRunBackgroundWork({ type: "provider-status" }),
267 host.shouldRunBackgroundWork({ type: "provider-status", instanceId }),
268 ]);
269 return genericDemand || instanceDemand;
270 });
271
272 const getRefreshInterval =
273 input.refreshInterval !== undefined
274 ? Effect.succeed(input.refreshInterval)
275 : host.settings.get.pipe(
276 Effect.map(
277 (settings) =>
278 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
279 ),
280 Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
281 );
282
283 const refreshIntervalChanges = yield* Queue.sliding<void>(1);
284 if (input.refreshInterval === undefined) {
285 const serverSettingsChanges = yield* host.settings.subscribe;
286 yield* serverSettingsChanges.pipe(
287 Stream.map((settings) =>
288 Duration.toMillis(
289 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
290 ),
291 ),
292 Stream.changes,
293 Stream.runForEach(() => Queue.offer(refreshIntervalChanges, undefined).pipe(Effect.asVoid)),
294 Effect.forkScoped,
295 );
296 }
297
298 // A failed check must not end this subscription: the next settings change
299 // retries, like the periodic and initial checks below.
300 yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
301 Effect.asVoid(applySnapshot(nextSettings)).pipe(Effect.ignoreCause({ log: true })),
302 ).pipe(Effect.forkScoped);
303
304 yield* Effect.forever(
305 getRefreshInterval.pipe(
306 Effect.flatMap((refreshInterval) =>
307 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - races the interval against a settings-change signal, not a timeout
308 Effect.raceFirst(
309 Effect.sleep(
310 Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0
311 ? "60 seconds"
312 : refreshInterval,
313 ).pipe(Effect.as(true)),
314 Queue.take(refreshIntervalChanges).pipe(Effect.as(false)),
315 ).pipe(
316 Effect.flatMap((intervalElapsed) =>
317 intervalElapsed && Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0
318 ? shouldRefreshOnInterval.pipe(
319 Effect.flatMap((shouldRefresh) =>
320 shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,
321 ),
322 )
323 : Effect.void,
324 ),
325 ),
326 ),
327 Effect.ignoreCause({ log: true }),
328 ),
329 ).pipe(Effect.forkScoped);
330
331 yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(
332 Effect.ignoreCause({ log: true }),
333 Effect.forkScoped,
334 );
335
336 return {
337 resolveMaintenance: input.resolveMaintenance,
338 getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
339 refresh: input
340 .resolveMaintenance({ fresh: true })
341 .pipe(Effect.andThen(refreshSnapshot), Effect.tapError(Effect.logError), Effect.orDie),
342 applyUsageLimits,
343 refreshUsage: refreshUsage(),
344 get streamChanges() {
345 return Stream.fromPubSub(changesPubSub);
346 },
347 } satisfies ManagedServerProvider;
348});