Open History to see the last commit
1import {
2 DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,
3 UsageLimitSourceError,
4 type UsageLimitSourceConsumeResetCreditInput,
5 type ProviderConsumeResetCreditResult,
6 type ProviderDriverKind,
7 type ServerSettings,
8 UsageLimitSourceConfig,
9 settingsSecretLiteral,
10 type UsageLimitSourceId,
11 type UsageLimitSourceSnapshot,
12} from "@t3tools/contracts";
13import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
14import * as Context from "effect/Context";
15import * as DateTime from "effect/DateTime";
16import * as Duration from "effect/Duration";
17import * as Effect from "effect/Effect";
18import * as Equal from "effect/Equal";
19import * as Layer from "effect/Layer";
20import * as PubSub from "effect/PubSub";
21import * as Ref from "effect/Ref";
22import * as Semaphore from "effect/Semaphore";
23import * as Stream from "effect/Stream";
24
25import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
26import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
27import * as SecretResolverLayer from "../secrets/SecretResolver.ts";
28import { resolveSettingsSecrets } from "../secrets/settingsSecretValue.ts";
29import * as Settings from "../serverSettings.ts";
30import { windowLimitsModel } from "../provider/claudeUsageLimits.ts";
31import { makeCliproxyApi } from "./cliproxyApi.ts";
32
33export class UsageLimitSources extends Context.Service<
34 UsageLimitSources,
35 {
36 readonly current: Effect.Effect<ReadonlyArray<UsageLimitSourceSnapshot>>;
37 readonly streamChanges: Stream.Stream<ReadonlyArray<UsageLimitSourceSnapshot>>;
38 readonly refresh: Effect.Effect<void>;
39 readonly consumeResetCredit: (
40 input: UsageLimitSourceConsumeResetCreditInput,
41 ) => Effect.Effect<ProviderConsumeResetCreditResult, UsageLimitSourceError>;
42 }
43>()("t3/usage/UsageLimitSources") {}
44
45function sourceLabel(id: string, config: UsageLimitSourceConfig): string {
46 if (config.label) return config.label;
47 const fallback = id.trim() || "Usage limit source";
48 try {
49 return new URL(config.url).host || fallback;
50 } catch {
51 return fallback;
52 }
53}
54
55/**
56 * A refused read of one account keeps its last good reading, as provider probes keep their bars
57 * (see ServerProviderUsageLimits); a reading with none to keep stays listed as unreadable.
58 */
59function keepLastGoodReadings(
60 previous: ReadonlyArray<UsageLimitSourceSnapshot>,
61 next: ReadonlyArray<UsageLimitSourceSnapshot>,
62): ReadonlyArray<UsageLimitSourceSnapshot> {
63 return next.map((source) => {
64 // Auth file names can be reused, so only the same hub and login may lend a reading.
65 const before = previous.find(
66 (candidate) => candidate.id === source.id && candidate.endpoint === source.endpoint,
67 );
68 if (!before) return source;
69 return {
70 ...source,
71 accounts: source.accounts.map((account) => {
72 if (account.usageLimits.unavailable?.reason !== "probeFailed") return account;
73 // Without a listed login, a reused auth file name cannot be told apart from the old one.
74 if (account.email === undefined && account.workspaceId === undefined) return account;
75 const last = before.accounts.find(
76 (candidate) =>
77 candidate.id === account.id &&
78 candidate.driver === account.driver &&
79 // Fingerprinted Antigravity readings omit the listed identity, so they are never lent.
80 candidate.usageLimits.credentialFingerprint === undefined &&
81 candidate.email === account.email &&
82 candidate.workspaceId === account.workspaceId,
83 );
84 return last && !last.usageLimits.unavailable ? last : account;
85 }),
86 };
87 });
88}
89
90function missingManagementKey(config: UsageLimitSourceConfig): string {
91 return typeof config.managementKey === "string"
92 ? "No management key configured."
93 : "Could not read the management key from its secret provider.";
94}
95
96/** @public */
97export const make = Effect.gen(function* () {
98 const api = yield* makeCliproxyApi;
99 const settingsService = yield* Settings.ServerSettingsService;
100 const secrets = yield* SecretResolver.SecretResolver;
101 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
102 const readManagementKey = Effect.fn("UsageLimitSources.readManagementKey")(function* (
103 config: UsageLimitSourceConfig,
104 ) {
105 const resolved = yield* resolveSettingsSecrets(secrets, UsageLimitSourceConfig, config);
106 return settingsSecretLiteral(resolved.managementKey);
107 });
108 const stateRef = yield* Ref.make<ReadonlyArray<UsageLimitSourceSnapshot>>([]);
109 const changes = yield* Effect.acquireRelease(
110 PubSub.unbounded<ReadonlyArray<UsageLimitSourceSnapshot>>(),
111 PubSub.shutdown,
112 );
113
114 const readSource = Effect.fn("UsageLimitSources.readSource")(function* (
115 id: UsageLimitSourceId,
116 config: UsageLimitSourceConfig,
117 ) {
118 const checkedAt = DateTime.formatIso(yield* DateTime.now);
119 const url = URL.parse(config.url);
120 const base = {
121 id,
122 kind: config.kind,
123 label: sourceLabel(id, config),
124 ...(url && /^https?:$/.test(url.protocol)
125 ? {
126 origin: url.origin,
127 endpoint: `${url.origin}${url.pathname.replace(/(\/management\.html)?\/*$/i, "")}`,
128 }
129 : {}),
130 checkedAt,
131 } as const;
132 const managementKey = yield* readManagementKey(config);
133 if (managementKey.length === 0) {
134 return { ...base, accounts: [], error: missingManagementKey(config) };
135 }
136 const accounts = yield* api
137 .readAccounts({ url: config.url, managementKey })
138 .pipe(Effect.result);
139 if (accounts._tag === "Failure") {
140 yield* Effect.logDebug("usage limit source read failed", { id, cause: accounts.failure });
141 return { ...base, accounts: [], error: accounts.failure.detail };
142 }
143 return { ...base, accounts: accounts.success };
144 });
145
146 const publish = Effect.fn("UsageLimitSources.publish")(function* (
147 next: ReadonlyArray<UsageLimitSourceSnapshot>,
148 ) {
149 const changed = yield* Ref.modify(stateRef, (previous) =>
150 Equal.equals(previous, next) ? [false, previous] : [true, next],
151 );
152 if (changed) yield* PubSub.publish(changes, next);
153 });
154
155 // Serialize refreshes so slow old-settings reads cannot resurrect removed sources after newer refreshes.
156 const refreshLock = yield* Semaphore.make(1);
157 const refresh = Effect.gen(function* () {
158 const settings = yield* settingsService.getSettings.pipe(
159 Effect.orElseSucceed((): ServerSettings | null => null),
160 );
161 const entries = Object.entries(settings?.usageLimitSources ?? {}).filter(
162 ([, config]) => config.enabled,
163 );
164 const snapshots = yield* Effect.forEach(
165 entries,
166 ([id, config]) => readSource(id as UsageLimitSourceId, config),
167 { concurrency: 4 },
168 );
169 yield* publish(keepLastGoodReadings(yield* Ref.get(stateRef), snapshots));
170 }).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true }));
171
172 // Shares the refresh lock so a stale in-flight read cannot overwrite a redemption.
173 const consumeResetCredit = Effect.fn("UsageLimitSources.consumeResetCredit")(function* (
174 input: UsageLimitSourceConsumeResetCreditInput,
175 ) {
176 const settings = yield* settingsService.getSettings.pipe(
177 Effect.mapError(() => new UsageLimitSourceError({ detail: "Could not read hub settings." })),
178 );
179 const config = settings.usageLimitSources[input.sourceId];
180 if (!config?.enabled) {
181 return yield* new UsageLimitSourceError({
182 detail: "The usage limit source is missing or disabled.",
183 });
184 }
185 const managementKey = yield* readManagementKey(config);
186 if (managementKey.length === 0) {
187 return yield* new UsageLimitSourceError({ detail: missingManagementKey(config) });
188 }
189 const result = yield* api.consume(
190 { url: config.url, managementKey },
191 input.accountId,
192 input.creditId,
193 );
194 // A redemption changes the reading, so a refused re-read must not bring back the one before it.
195 const snapshot = yield* readSource(input.sourceId, config);
196 const previous = yield* Ref.get(stateRef);
197 yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source)));
198 return result;
199 }, refreshLock.withPermits(1));
200
201 yield* settingsService.streamChanges.pipe(
202 Stream.map((settings) => settings.usageLimitSources),
203 Stream.changes,
204 Stream.runForEach(() => refresh),
205 Effect.forkScoped,
206 );
207
208 const interval = settingsService.getSettings.pipe(
209 Effect.map(
210 (settings) => resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
211 ),
212 Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
213 );
214 yield* Effect.forever(
215 interval.pipe(
216 Effect.flatMap((wait) => Effect.sleep(Duration.isPositive(wait) ? wait : "60 seconds")),
217 Effect.andThen(interval),
218 Effect.flatMap((current) =>
219 Duration.isPositive(current)
220 ? backgroundPolicy.shouldRunScopeWork({ type: "provider-status" })
221 : Effect.succeed(false),
222 ),
223 Effect.flatMap((shouldRun) => (shouldRun ? refresh : Effect.void)),
224 Effect.ignoreCause({ log: true }),
225 ),
226 ).pipe(Effect.forkScoped);
227
228 yield* refresh.pipe(Effect.forkScoped);
229
230 return {
231 current: Ref.get(stateRef),
232 consumeResetCredit,
233 refresh,
234 get streamChanges() {
235 return Stream.unwrap(
236 Effect.gen(function* () {
237 const subscription = yield* PubSub.subscribe(changes);
238 const snapshot = yield* Ref.get(stateRef);
239 return Stream.concat(Stream.make(snapshot), Stream.fromSubscription(subscription)).pipe(
240 Stream.changes,
241 );
242 }),
243 );
244 },
245 } satisfies UsageLimitSources["Service"];
246});
247
248export const layer = Layer.effect(UsageLimitSources, make).pipe(
249 Layer.provide(SecretResolverLayer.layer),
250);
251
252/** A hub answers with a usage limit only when every account it routes the driver to is spent. */
253export function hubPoolResetAt(
254 sources: ReadonlyArray<UsageLimitSourceSnapshot>,
255 driver: ProviderDriverKind,
256 model: string | null,
257 now: number,
258): string | null {
259 let earliest: number | null = null;
260 for (const source of sources) {
261 for (const account of source.accounts) {
262 if (account.driver !== driver) continue;
263 // An unread account may be the one still blocked, so its refill is unknown.
264 if (account.usageLimits.unavailable) return null;
265 const spent = account.usageLimits.windows.filter(
266 (window) => window.usedPercent >= 100 && windowLimitsModel(window, model),
267 );
268 if (spent.length === 0) return null;
269 const resets = spent.map((window) => Date.parse(window.resetsAt ?? ""));
270 if (resets.some((reset) => !Number.isFinite(reset))) return null;
271 const recoversAt = Math.max(...resets);
272 if (recoversAt <= now) return null;
273 earliest = earliest === null ? recoversAt : Math.min(earliest, recoversAt);
274 }
275 }
276 return earliest === null ? null : DateTime.formatIso(DateTime.makeUnsafe(earliest));
277}
278
279export class UsageLimitResetFallback extends Context.Reference<{
280 readonly resetAt: (
281 driver: ProviderDriverKind,
282 endpoint: string,
283 model: string | null,
284 ) => Effect.Effect<string | null>;
285}>("t3/usage/UsageLimitResetFallback", {
286 defaultValue: () => ({ resetAt: () => Effect.succeed(null) }),
287}) {}
288
289export const layerResetFallback = Layer.effect(
290 UsageLimitResetFallback,
291 Effect.gen(function* () {
292 const sources = yield* UsageLimitSources;
293 return {
294 resetAt: Effect.fn("UsageLimitResetFallback.resetAt")(function* (driver, endpoint, model) {
295 // Only the hub at the instance's endpoint serves its turns.
296 const atEndpoint = Effect.map(sources.current, (current) =>
297 current.filter((source) => source.origin === endpoint),
298 );
299 if ((yield* atEndpoint).length === 0) return null;
300 // The pool usually ran out after the last poll, so the cached accounts still show room.
301 yield* sources.refresh.pipe(Effect.timeout("5 seconds"), Effect.ignore);
302 return hubPoolResetAt(
303 yield* atEndpoint,
304 driver,
305 model,
306 DateTime.toEpochMillis(yield* DateTime.now),
307 );
308 }),
309 };
310 }),
311);