Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

managedProvider.ts

382 lines14.9 KB

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