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
55function missingManagementKey(config: UsageLimitSourceConfig): string {
56 return typeof config.managementKey === "string"
57 ? "No management key configured."
58 : "Could not read the management key from its secret provider.";
59}
60
61/** @public */
62export const make = Effect.gen(function* () {
63 const api = yield* makeCliproxyApi;
64 const settingsService = yield* Settings.ServerSettingsService;
65 const secrets = yield* SecretResolver.SecretResolver;
66 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
67 const readManagementKey = Effect.fn("UsageLimitSources.readManagementKey")(function* (
68 config: UsageLimitSourceConfig,
69 ) {
70 const resolved = yield* resolveSettingsSecrets(secrets, UsageLimitSourceConfig, config);
71 return settingsSecretLiteral(resolved.managementKey);
72 });
73 const stateRef = yield* Ref.make<ReadonlyArray<UsageLimitSourceSnapshot>>([]);
74 const changes = yield* Effect.acquireRelease(
75 PubSub.unbounded<ReadonlyArray<UsageLimitSourceSnapshot>>(),
76 PubSub.shutdown,
77 );
78
79 const readSource = Effect.fn("UsageLimitSources.readSource")(function* (
80 id: UsageLimitSourceId,
81 config: UsageLimitSourceConfig,
82 ) {
83 const checkedAt = DateTime.formatIso(yield* DateTime.now);
84 const url = URL.parse(config.url);
85 const base = {
86 id,
87 kind: config.kind,
88 label: sourceLabel(id, config),
89 ...(url && /^https?:$/.test(url.protocol) ? { origin: url.origin } : {}),
90 checkedAt,
91 } as const;
92 const managementKey = yield* readManagementKey(config);
93 if (managementKey.length === 0) {
94 return { ...base, accounts: [], error: missingManagementKey(config) };
95 }
96 const accounts = yield* api
97 .readAccounts({ url: config.url, managementKey })
98 .pipe(Effect.result);
99 if (accounts._tag === "Failure") {
100 yield* Effect.logDebug("usage limit source read failed", { id, cause: accounts.failure });
101 return { ...base, accounts: [], error: accounts.failure.detail };
102 }
103 return { ...base, accounts: accounts.success };
104 });
105
106 const publish = Effect.fn("UsageLimitSources.publish")(function* (
107 next: ReadonlyArray<UsageLimitSourceSnapshot>,
108 ) {
109 const changed = yield* Ref.modify(stateRef, (previous) =>
110 Equal.equals(previous, next) ? [false, previous] : [true, next],
111 );
112 if (changed) yield* PubSub.publish(changes, next);
113 });
114
115 // Serialize refreshes so slow old-settings reads cannot resurrect removed sources after newer refreshes.
116 const refreshLock = yield* Semaphore.make(1);
117 const refresh = Effect.gen(function* () {
118 const settings = yield* settingsService.getSettings.pipe(
119 Effect.orElseSucceed((): ServerSettings | null => null),
120 );
121 const entries = Object.entries(settings?.usageLimitSources ?? {}).filter(
122 ([, config]) => config.enabled,
123 );
124 const snapshots = yield* Effect.forEach(
125 entries,
126 ([id, config]) => readSource(id as UsageLimitSourceId, config),
127 { concurrency: 4 },
128 );
129 yield* publish(snapshots);
130 }).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true }));
131
132 // Shares the refresh lock so a stale in-flight read cannot overwrite a redemption.
133 const consumeResetCredit = Effect.fn("UsageLimitSources.consumeResetCredit")(function* (
134 input: UsageLimitSourceConsumeResetCreditInput,
135 ) {
136 const settings = yield* settingsService.getSettings.pipe(
137 Effect.mapError(() => new UsageLimitSourceError({ detail: "Could not read hub settings." })),
138 );
139 const config = settings.usageLimitSources[input.sourceId];
140 if (!config?.enabled) {
141 return yield* new UsageLimitSourceError({
142 detail: "The usage limit source is missing or disabled.",
143 });
144 }
145 const managementKey = yield* readManagementKey(config);
146 if (managementKey.length === 0) {
147 return yield* new UsageLimitSourceError({ detail: missingManagementKey(config) });
148 }
149 const result = yield* api.consume(
150 { url: config.url, managementKey },
151 input.accountId,
152 input.creditId,
153 );
154 const snapshot = yield* readSource(input.sourceId, config);
155 const previous = yield* Ref.get(stateRef);
156 yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source)));
157 return result;
158 }, refreshLock.withPermits(1));
159
160 yield* settingsService.streamChanges.pipe(
161 Stream.map((settings) => settings.usageLimitSources),
162 Stream.changes,
163 Stream.runForEach(() => refresh),
164 Effect.forkScoped,
165 );
166
167 const interval = settingsService.getSettings.pipe(
168 Effect.map(
169 (settings) => resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
170 ),
171 Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
172 );
173 yield* Effect.forever(
174 interval.pipe(
175 Effect.flatMap((wait) => Effect.sleep(Duration.isPositive(wait) ? wait : "60 seconds")),
176 Effect.andThen(interval),
177 Effect.flatMap((current) =>
178 Duration.isPositive(current)
179 ? backgroundPolicy.shouldRunScopeWork({ type: "provider-status" })
180 : Effect.succeed(false),
181 ),
182 Effect.flatMap((shouldRun) => (shouldRun ? refresh : Effect.void)),
183 Effect.ignoreCause({ log: true }),
184 ),
185 ).pipe(Effect.forkScoped);
186
187 yield* refresh.pipe(Effect.forkScoped);
188
189 return {
190 current: Ref.get(stateRef),
191 consumeResetCredit,
192 refresh,
193 get streamChanges() {
194 return Stream.unwrap(
195 Effect.gen(function* () {
196 const subscription = yield* PubSub.subscribe(changes);
197 const snapshot = yield* Ref.get(stateRef);
198 return Stream.concat(Stream.make(snapshot), Stream.fromSubscription(subscription)).pipe(
199 Stream.changes,
200 );
201 }),
202 );
203 },
204 } satisfies UsageLimitSources["Service"];
205});
206
207export const layer = Layer.effect(UsageLimitSources, make).pipe(
208 Layer.provide(SecretResolverLayer.layer),
209);
210
211/** A hub answers with a usage limit only when every account it routes the driver to is spent. */
212export function hubPoolResetAt(
213 sources: ReadonlyArray<UsageLimitSourceSnapshot>,
214 driver: ProviderDriverKind,
215 model: string | null,
216 now: number,
217): string | null {
218 let earliest: number | null = null;
219 for (const source of sources) {
220 for (const account of source.accounts) {
221 if (account.driver !== driver) continue;
222 // An unread account may be the one still blocked, so its refill is unknown.
223 if (account.usageLimits.unavailable) return null;
224 const spent = account.usageLimits.windows.filter(
225 (window) => window.usedPercent >= 100 && windowLimitsModel(window, model),
226 );
227 if (spent.length === 0) return null;
228 const resets = spent.map((window) => Date.parse(window.resetsAt ?? ""));
229 if (resets.some((reset) => !Number.isFinite(reset))) return null;
230 const recoversAt = Math.max(...resets);
231 if (recoversAt <= now) return null;
232 earliest = earliest === null ? recoversAt : Math.min(earliest, recoversAt);
233 }
234 }
235 return earliest === null ? null : DateTime.formatIso(DateTime.makeUnsafe(earliest));
236}
237
238export class UsageLimitResetFallback extends Context.Reference<{
239 readonly resetAt: (
240 driver: ProviderDriverKind,
241 endpoint: string,
242 model: string | null,
243 ) => Effect.Effect<string | null>;
244}>("t3/usage/UsageLimitResetFallback", {
245 defaultValue: () => ({ resetAt: () => Effect.succeed(null) }),
246}) {}
247
248export const layerResetFallback = Layer.effect(
249 UsageLimitResetFallback,
250 Effect.gen(function* () {
251 const sources = yield* UsageLimitSources;
252 return {
253 resetAt: Effect.fn("UsageLimitResetFallback.resetAt")(function* (driver, endpoint, model) {
254 // Only the hub at the instance's endpoint serves its turns.
255 const atEndpoint = Effect.map(sources.current, (current) =>
256 current.filter((source) => source.origin === endpoint),
257 );
258 if ((yield* atEndpoint).length === 0) return null;
259 // The pool usually ran out after the last poll, so the cached accounts still show room.
260 yield* sources.refresh.pipe(Effect.timeout("5 seconds"), Effect.ignore);
261 return hubPoolResetAt(
262 yield* atEndpoint,
263 driver,
264 model,
265 DateTime.toEpochMillis(yield* DateTime.now),
266 );
267 }),
268 };
269 }),
270);