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