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

UsageLimitSources.ts

275 lines10.3 KB

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