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 | ((snapshot: ServerProvider) => 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 must not revert usage updates newer than its input snapshot.
86 const merged = withUsageLimits(nextSnapshot, state.snapshot.usageLimits);
87 if (Equal.equals(state.snapshot, merged)) {
88 return [null, state] as const;
89 }
90 return [merged, { ...state, snapshot: merged }] as const;
91 });
92 if (snapshotToPublish === null) {
93 return;
94 }
95 yield* PubSub.publish(changesPubSub, snapshotToPublish);
96 });
97
98 const restartSnapshotEnrichment = Effect.fn("restartSnapshotEnrichment")(function* (
99 settings: Settings,
100 snapshot: ServerProvider,
101 generation: number,
102 ) {
103 const previousFiber = yield* Ref.getAndSet(enrichmentFiberRef, null);
104 if (previousFiber) {
105 yield* Fiber.interrupt(previousFiber).pipe(Effect.ignore);
106 }
107
108 if (!input.enrichSnapshot || !snapshot.enabled) {
109 return;
110 }
111
112 const fiber = yield* input
113 .enrichSnapshot({
114 settings,
115 snapshot,
116 getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
117 publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot),
118 })
119 .pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope));
120
121 yield* Ref.set(enrichmentFiberRef, fiber);
122 });
123
124 const applySnapshotBase = Effect.fn("applySnapshot")(function* (
125 nextSettings: Settings,
126 options?: { readonly forceRefresh?: boolean },
127 ) {
128 const forceRefresh = options?.forceRefresh === true;
129 const previousSettings = yield* Ref.get(settingsRef);
130 if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
131 yield* Ref.set(settingsRef, nextSettings);
132 return yield* Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot));
133 }
134
135 if (
136 !forceRefresh &&
137 input.checkProviderOnSettingsChange?.(previousSettings, nextSettings) === false
138 ) {
139 const state = yield* Ref.get(snapshotStateRef);
140 const nextGeneration = state.enrichmentGeneration + 1;
141 yield* Ref.set(snapshotStateRef, {
142 ...state,
143 enrichmentGeneration: nextGeneration,
144 });
145 yield* Ref.set(settingsRef, nextSettings);
146 yield* restartSnapshotEnrichment(nextSettings, state.snapshot, nextGeneration);
147 return state.snapshot;
148 }
149
150 const probedSnapshot = yield* input.checkProvider;
151 const { snapshot: nextSnapshot, generation: nextGeneration } = yield* Ref.modify(
152 snapshotStateRef,
153 (state) => {
154 const generation = input.enrichSnapshot
155 ? state.enrichmentGeneration + 1
156 : state.enrichmentGeneration;
157 // Failed reads retain limits only for the same account and original workspace.
158 const previous = state.snapshot.auth;
159 const differs = (a: string | undefined, b: string | undefined) =>
160 a !== undefined && b !== undefined && a !== b;
161 const switchedAccount =
162 differs(probedSnapshot.auth.email?.toLowerCase(), previous.email?.toLowerCase()) ||
163 (probedSnapshot.auth.workspaceId !== undefined &&
164 probedSnapshot.auth.workspaceId !== previous.workspaceId);
165 const usageLimits = switchedAccount
166 ? probedSnapshot.usageLimits
167 : resolveUsageLimitsAfterProbe({
168 published: state.snapshot.usageLimits,
169 probed: probedSnapshot.usageLimits,
170 });
171 const workspaceId =
172 usageLimits === probedSnapshot.usageLimits ? undefined : state.snapshot.auth.workspaceId;
173 const snapshot = withUsageLimits(
174 workspaceId && !probedSnapshot.auth.workspaceId
175 ? { ...probedSnapshot, auth: { ...probedSnapshot.auth, workspaceId } }
176 : probedSnapshot,
177 usageLimits,
178 );
179 return [
180 { snapshot, generation },
181 { snapshot, enrichmentGeneration: generation },
182 ] as const;
183 },
184 );
185 yield* Ref.set(settingsRef, nextSettings);
186 yield* PubSub.publish(changesPubSub, nextSnapshot);
187 yield* restartSnapshotEnrichment(nextSettings, nextSnapshot, nextGeneration);
188 return nextSnapshot;
189 });
190 const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
191 refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));
192
193 // Providers call this on every token-usage tick, usually without changing the snapshot.
194 const applyUsageLimits: ManagedServerProvider["applyUsageLimits"] = Effect.fnUntraced(
195 function* (update) {
196 const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
197 const usageLimits = applyUsageLimitsUpdate({
198 previous: state.snapshot.usageLimits,
199 update,
200 checkedAt: update.checkedAt,
201 });
202 if (usageLimits === state.snapshot.usageLimits) {
203 return [null, state] as const;
204 }
205 const snapshot = withUsageLimits(state.snapshot, usageLimits);
206 return [snapshot, { ...state, snapshot }] as const;
207 });
208 if (snapshotToPublish !== null) {
209 yield* PubSub.publish(changesPubSub, snapshotToPublish);
210 }
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 shouldRefreshOnInterval = Effect.gen(function* () {
220 const state = yield* Ref.get(snapshotStateRef);
221 // A disabled instance has nothing to probe; a periodic check would only
222 // republish a snapshot that differs in checkedAt.
223 if (
224 !state.snapshot.enabled ||
225 input.refreshOnInterval === false ||
226 (typeof input.refreshOnInterval === "function" && !input.refreshOnInterval(state.snapshot))
227 ) {
228 return false;
229 }
230 const instanceId = state.snapshot.instanceId;
231 const [genericDemand, instanceDemand] = yield* Effect.all([
232 host.shouldRunBackgroundWork({ type: "provider-status" }),
233 host.shouldRunBackgroundWork({ type: "provider-status", instanceId }),
234 ]);
235 return genericDemand || instanceDemand;
236 });
237
238 const getRefreshInterval =
239 input.refreshInterval !== undefined
240 ? Effect.succeed(input.refreshInterval)
241 : host.settings.get.pipe(
242 Effect.map(
243 (settings) =>
244 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
245 ),
246 Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
247 );
248
249 const refreshIntervalChanges = yield* Queue.sliding<void>(1);
250 if (input.refreshInterval === undefined) {
251 const serverSettingsChanges = yield* host.settings.subscribe;
252 yield* serverSettingsChanges.pipe(
253 Stream.map((settings) =>
254 Duration.toMillis(
255 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
256 ),
257 ),
258 Stream.changes,
259 Stream.runForEach(() => Queue.offer(refreshIntervalChanges, undefined).pipe(Effect.asVoid)),
260 Effect.forkScoped,
261 );
262 }
263
264 yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
265 Effect.asVoid(applySnapshot(nextSettings)),
266 ).pipe(Effect.forkScoped);
267
268 yield* Effect.forever(
269 getRefreshInterval.pipe(
270 Effect.flatMap((refreshInterval) =>
271 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - races the interval against a settings-change signal, not a timeout
272 Effect.raceFirst(
273 Effect.sleep(
274 Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0
275 ? "60 seconds"
276 : refreshInterval,
277 ).pipe(Effect.as(true)),
278 Queue.take(refreshIntervalChanges).pipe(Effect.as(false)),
279 ).pipe(
280 Effect.flatMap((intervalElapsed) =>
281 intervalElapsed && Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0
282 ? shouldRefreshOnInterval.pipe(
283 Effect.flatMap((shouldRefresh) =>
284 shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,
285 ),
286 )
287 : Effect.void,
288 ),
289 ),
290 ),
291 Effect.ignoreCause({ log: true }),
292 ),
293 ).pipe(Effect.forkScoped);
294
295 yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(
296 Effect.ignoreCause({ log: true }),
297 Effect.forkScoped,
298 );
299
300 return {
301 resolveMaintenance: input.resolveMaintenance,
302 getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
303 refresh: input
304 .resolveMaintenance({ fresh: true })
305 .pipe(Effect.andThen(refreshSnapshot), Effect.tapError(Effect.logError), Effect.orDie),
306 applyUsageLimits,
307 get streamChanges() {
308 return Stream.fromPubSub(changesPubSub);
309 },
310 } satisfies ManagedServerProvider;
311});