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 // 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 hasProviderStatusDemand = Effect.gen(function* () {
222 const state = yield* Ref.get(snapshotStateRef);
223 // A disabled instance has nothing to probe; a periodic check would only
224 // republish a snapshot that differs in checkedAt.
225 if (!state.snapshot.enabled) {
226 return false;
227 }
228 const instanceId = state.snapshot.instanceId;
229 const [genericDemand, instanceDemand] = yield* Effect.all([
230 host.shouldRunBackgroundWork({ type: "provider-status" }),
231 host.shouldRunBackgroundWork({ type: "provider-status", instanceId }),
232 ]);
233 return genericDemand || instanceDemand;
234 });
235
236 const getRefreshInterval =
237 input.refreshInterval !== undefined
238 ? Effect.succeed(input.refreshInterval)
239 : host.settings.get.pipe(
240 Effect.map(
241 (settings) =>
242 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
243 ),
244 Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
245 );
246
247 const refreshIntervalChanges = yield* Queue.sliding<void>(1);
248 if (input.refreshInterval === undefined) {
249 const serverSettingsChanges = yield* host.settings.subscribe;
250 yield* serverSettingsChanges.pipe(
251 Stream.map((settings) =>
252 Duration.toMillis(
253 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
254 ),
255 ),
256 Stream.changes,
257 Stream.runForEach(() => Queue.offer(refreshIntervalChanges, undefined).pipe(Effect.asVoid)),
258 Effect.forkScoped,
259 );
260 }
261
262 yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
263 Effect.asVoid(applySnapshot(nextSettings)),
264 ).pipe(Effect.forkScoped);
265
266 yield* Effect.forever(
267 getRefreshInterval.pipe(
268 Effect.flatMap((refreshInterval) =>
269 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - races the interval against a settings-change signal, not a timeout
270 Effect.raceFirst(
271 Effect.sleep(
272 Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0
273 ? "60 seconds"
274 : refreshInterval,
275 ).pipe(Effect.as(true)),
276 Queue.take(refreshIntervalChanges).pipe(Effect.as(false)),
277 ).pipe(
278 Effect.flatMap((intervalElapsed) =>
279 input.refreshOnInterval !== false &&
280 intervalElapsed &&
281 Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0
282 ? hasProviderStatusDemand.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});