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 BackgroundPolicy from "../background/BackgroundPolicy.ts";
19import { ServerSettingsService } from "../serverSettings.ts";
20import { applyUsageLimitsUpdate, resolveUsageLimitsAfterProbe } from "./providerUsageLimits.ts";
21import type { ServerProviderShape } from "./Services/ServerProvider.ts";
22
23interface ProviderSnapshotState {
24 readonly snapshot: ServerProvider;
25 readonly enrichmentGeneration: number;
26}
27
28function withUsageLimits(
29 snapshot: ServerProvider,
30 usageLimits: ServerProvider["usageLimits"],
31): ServerProvider {
32 if (snapshot.usageLimits === usageLimits) {
33 return snapshot;
34 }
35 const { usageLimits: _previous, ...rest } = snapshot;
36 return usageLimits ? { ...rest, usageLimits } : rest;
37}
38
39export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
40 Settings,
41>(input: {
42 readonly resolveMaintenance: ServerProviderShape["resolveMaintenance"];
43 readonly getSettings: Effect.Effect<Settings, ServerSettingsError>;
44 readonly streamSettings: Stream.Stream<Settings>;
45 readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
46 readonly initialSnapshot: (settings: Settings) => Effect.Effect<ServerProvider>;
47 readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
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;
56 readonly checkProviderOnSettingsChange?: (previous: Settings, next: Settings) => boolean;
57}): Effect.fn.Return<
58 ServerProviderShape,
59 ServerSettingsError,
60 Scope.Scope | BackgroundPolicy.BackgroundPolicy | ServerSettingsService
61> {
62 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
63 const serverSettings = yield* ServerSettingsService;
64 const refreshSemaphore = yield* Semaphore.make(1);
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 derives from the snapshot it was handed; a runtime usage
88 // update that landed since must not be reverted by it.
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) {
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 const snapshot = withUsageLimits(
161 probedSnapshot,
162 resolveUsageLimitsAfterProbe({
163 published: state.snapshot.usageLimits,
164 probed: probedSnapshot.usageLimits,
165 }),
166 );
167 return [
168 { snapshot, generation },
169 { snapshot, enrichmentGeneration: generation },
170 ] as const;
171 },
172 );
173 yield* Ref.set(settingsRef, nextSettings);
174 yield* PubSub.publish(changesPubSub, nextSnapshot);
175 yield* restartSnapshotEnrichment(nextSettings, nextSnapshot, nextGeneration);
176 return nextSnapshot;
177 });
178 const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
179 refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));
180
181 /**
182 * Runtime usage updates arrive between probes. They patch only
183 * `usageLimits` on whatever snapshot is published and leave the enrichment
184 * generation alone, so an in-flight enrichment still lands.
185 */
186 const applyUsageLimits: ServerProviderShape["applyUsageLimits"] = (update) =>
187 Effect.gen(function* () {
188 const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
189 const usageLimits = applyUsageLimitsUpdate({
190 previous: state.snapshot.usageLimits,
191 update,
192 checkedAt: update.checkedAt,
193 });
194 // `applyUsageLimitsUpdate` hands back the same object when nothing
195 // moved, which is the common case for Codex's per-tick notification.
196 if (usageLimits === state.snapshot.usageLimits) {
197 return [null, state] as const;
198 }
199 const snapshot = withUsageLimits(state.snapshot, usageLimits);
200 return [snapshot, { ...state, snapshot }] as const;
201 });
202 if (snapshotToPublish !== null) {
203 yield* PubSub.publish(changesPubSub, snapshotToPublish);
204 }
205 });
206
207 const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () {
208 const nextSettings = yield* input.getSettings;
209 return yield* applySnapshot(nextSettings, { forceRefresh: true });
210 });
211
212 const hasProviderStatusDemand = Effect.gen(function* () {
213 const state = yield* Ref.get(snapshotStateRef);
214 const instanceId = state.snapshot.instanceId;
215 const [genericDemand, instanceDemand] = yield* Effect.all([
216 backgroundPolicy.shouldRunScopeWork({ type: "provider-status" }),
217 backgroundPolicy.shouldRunScopeWork({ type: "provider-status", instanceId }),
218 ]);
219 return genericDemand || instanceDemand;
220 });
221
222 const getRefreshInterval =
223 input.refreshInterval !== undefined
224 ? Effect.succeed(input.refreshInterval)
225 : serverSettings.getSettings.pipe(
226 Effect.map(
227 (settings) =>
228 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
229 ),
230 Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
231 );
232
233 const refreshIntervalChanges = yield* Queue.sliding<void>(1);
234 if (input.refreshInterval === undefined) {
235 const serverSettingsChanges = yield* serverSettings.subscribeChanges;
236 yield* serverSettingsChanges.pipe(
237 Stream.map((settings) =>
238 Duration.toMillis(
239 resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
240 ),
241 ),
242 Stream.changes,
243 Stream.runForEach(() => Queue.offer(refreshIntervalChanges, undefined).pipe(Effect.asVoid)),
244 Effect.forkScoped,
245 );
246 }
247
248 yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
249 Effect.asVoid(applySnapshot(nextSettings)),
250 ).pipe(Effect.forkScoped);
251
252 yield* Effect.forever(
253 getRefreshInterval.pipe(
254 Effect.flatMap((refreshInterval) =>
255 Effect.raceFirst(
256 Effect.sleep(
257 Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0
258 ? "60 seconds"
259 : refreshInterval,
260 ).pipe(Effect.as(true)),
261 Queue.take(refreshIntervalChanges).pipe(Effect.as(false)),
262 ).pipe(
263 Effect.flatMap((intervalElapsed) =>
264 input.refreshOnInterval !== false &&
265 intervalElapsed &&
266 Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0
267 ? hasProviderStatusDemand.pipe(
268 Effect.flatMap((shouldRefresh) =>
269 shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,
270 ),
271 )
272 : Effect.void,
273 ),
274 ),
275 ),
276 Effect.ignoreCause({ log: true }),
277 ),
278 ).pipe(Effect.forkScoped);
279
280 yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(
281 Effect.ignoreCause({ log: true }),
282 Effect.forkScoped,
283 );
284
285 return {
286 resolveMaintenance: input.resolveMaintenance,
287 getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
288 refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
289 applyUsageLimits,
290 get streamChanges() {
291 return Stream.fromPubSub(changesPubSub);
292 },
293 } satisfies ServerProviderShape;
294});