Open History to see the last commit
1/**
2 * UsageLimitSources — quota from places this environment cannot run turns
3 * on, today a CLIProxyAPI hub pooling several subscription accounts.
4 *
5 * Each configured `settings.usageLimitSources` entry is polled on the
6 * provider health-check interval and on every settings change, then
7 * published as one snapshot per source over `subscribeServerConfig`. A source
8 * that fails keeps its row with `error` set so the user can see it is
9 * configured but unreachable. Nothing is persisted: like provider status,
10 * this is live state that re-derives on boot.
11 *
12 * @module usage/UsageLimitSources
13 */
14import {
15 DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,
16 type ServerSettings,
17 type UsageLimitSourceConfig,
18 type UsageLimitSourceId,
19 type UsageLimitSourceSnapshot,
20} from "@t3tools/contracts";
21import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
22import type * as Cause from "effect/Cause";
23import * as Context from "effect/Context";
24import * as Data from "effect/Data";
25import * as DateTime from "effect/DateTime";
26import * as Duration from "effect/Duration";
27import * as Effect from "effect/Effect";
28import * as Equal from "effect/Equal";
29import * as Layer from "effect/Layer";
30import * as PubSub from "effect/PubSub";
31import * as Ref from "effect/Ref";
32import * as Semaphore from "effect/Semaphore";
33import type * as Schema from "effect/Schema";
34import * as Stream from "effect/Stream";
35import { HttpClient, type HttpClientError, HttpClientResponse } from "effect/unstable/http";
36
37import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
38import { ServerSettingsService } from "../serverSettings.ts";
39import { cliproxyStatusToAccounts, decodeCliproxyQuotaStatus } from "./cliproxyUsageLimits.ts";
40
41const FETCH_TIMEOUT = "10 seconds";
42const QUOTA_STATUS_PATH = "/v0/management/quota-scheduler/status";
43
44export class UsageLimitSources extends Context.Service<
45 UsageLimitSources,
46 {
47 readonly current: Effect.Effect<ReadonlyArray<UsageLimitSourceSnapshot>>;
48 /** The current set followed by every change, with repeats dropped. */
49 readonly streamChanges: Stream.Stream<ReadonlyArray<UsageLimitSourceSnapshot>>;
50 /** Re-read every source now. Never fails; failures land on the snapshot. */
51 readonly refresh: Effect.Effect<void>;
52 }
53>()("t3/usage/UsageLimitSources") {}
54
55/**
56 * A bounded, client-safe reason for a failed hub read. The exact failure
57 * (which can carry the request URL and response body) goes to the log.
58 */
59function readFailureMessage(
60 error: HttpClientError.HttpClientError | Schema.SchemaError | Cause.TimeoutError | InvalidUrl,
61): string {
62 switch (error._tag) {
63 case "InvalidUrl":
64 return "The hub URL is not valid.";
65 case "TimeoutError":
66 return "The hub did not answer in time.";
67 case "SchemaError":
68 return "The hub answered with an unexpected shape.";
69 case "HttpClientError":
70 return error.reason._tag === "StatusCodeError"
71 ? `The hub refused the request (HTTP ${error.reason.response.status}).`
72 : "The hub could not be reached.";
73 }
74}
75
76class InvalidUrl extends Data.TaggedError("InvalidUrl")<{
77 readonly url: string;
78 readonly cause: unknown;
79}> {}
80
81function sourceLabel(id: string, config: UsageLimitSourceConfig): string {
82 if (config.label) return config.label;
83 try {
84 return new URL(config.url).host;
85 } catch {
86 return id;
87 }
88}
89
90export const make = Effect.gen(function* () {
91 const httpClient = yield* HttpClient.HttpClient;
92 const settingsService = yield* ServerSettingsService;
93 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
94 const stateRef = yield* Ref.make<ReadonlyArray<UsageLimitSourceSnapshot>>([]);
95 const changes = yield* Effect.acquireRelease(
96 PubSub.unbounded<ReadonlyArray<UsageLimitSourceSnapshot>>(),
97 PubSub.shutdown,
98 );
99
100 const readSource = Effect.fn("UsageLimitSources.readSource")(function* (
101 id: UsageLimitSourceId,
102 config: UsageLimitSourceConfig,
103 ) {
104 const checkedAt = DateTime.formatIso(yield* DateTime.now);
105 const base = { id, kind: config.kind, label: sourceLabel(id, config), checkedAt } as const;
106 if (config.managementKey.length === 0) {
107 return { ...base, accounts: [], error: "No management key configured." };
108 }
109 const accounts = yield* Effect.try({
110 try: () => new URL(QUOTA_STATUS_PATH, config.url).toString(),
111 catch: (cause) => new InvalidUrl({ url: config.url, cause }),
112 }).pipe(
113 Effect.flatMap((url) =>
114 httpClient.get(url, { headers: { Authorization: `Bearer ${config.managementKey}` } }),
115 ),
116 Effect.flatMap(HttpClientResponse.filterStatusOk),
117 Effect.flatMap((response) => response.json),
118 Effect.flatMap(decodeCliproxyQuotaStatus),
119 Effect.map((status) => cliproxyStatusToAccounts(status, checkedAt)),
120 Effect.timeout(FETCH_TIMEOUT),
121 Effect.result,
122 );
123 if (accounts._tag === "Failure") {
124 yield* Effect.logDebug("usage limit source read failed", { id, cause: accounts.failure });
125 return { ...base, accounts: [], error: readFailureMessage(accounts.failure) };
126 }
127 return { ...base, accounts: accounts.success };
128 });
129
130 const publish = (next: ReadonlyArray<UsageLimitSourceSnapshot>) =>
131 Effect.gen(function* () {
132 const changed = yield* Ref.modify(stateRef, (previous) =>
133 Equal.equals(previous, next) ? [false, previous] : [true, next],
134 );
135 if (changed) yield* PubSub.publish(changes, next);
136 });
137
138 // One refresh at a time: a slow hub read started before a settings change
139 // must not publish after the change's own refresh and resurrect a removed
140 // source. Callers queue behind the in-flight run and see current settings.
141 const refreshLock = yield* Semaphore.make(1);
142 const refresh = Effect.gen(function* () {
143 const settings = yield* settingsService.getSettings.pipe(
144 Effect.orElseSucceed((): ServerSettings | null => null),
145 );
146 const entries = Object.entries(settings?.usageLimitSources ?? {}).filter(
147 ([, config]) => config.enabled,
148 );
149 const snapshots = yield* Effect.forEach(
150 entries,
151 ([id, config]) => readSource(id as UsageLimitSourceId, config),
152 { concurrency: 4 },
153 );
154 yield* publish(snapshots);
155 }).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true }));
156
157 // Settings edits re-read straight away so a new hub shows up without
158 // waiting for the interval, and a removed one leaves the list.
159 yield* settingsService.streamChanges.pipe(
160 Stream.map((settings) => settings.usageLimitSources),
161 Stream.changes,
162 Stream.runForEach(() => refresh),
163 Effect.forkScoped,
164 );
165
166 const interval = settingsService.getSettings.pipe(
167 Effect.map(
168 (settings) => resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
169 ),
170 Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
171 );
172 yield* Effect.forever(
173 interval.pipe(
174 Effect.flatMap((wait) =>
175 Effect.sleep(Duration.toMillis(Duration.fromInputUnsafe(wait)) <= 0 ? "60 seconds" : wait),
176 ),
177 Effect.andThen(backgroundPolicy.shouldRunScopeWork({ type: "provider-status" })),
178 Effect.flatMap((shouldRun) => (shouldRun ? refresh : Effect.void)),
179 Effect.ignoreCause({ log: true }),
180 ),
181 ).pipe(Effect.forkScoped);
182
183 yield* refresh.pipe(Effect.forkScoped);
184
185 return {
186 current: Ref.get(stateRef),
187 refresh,
188 get streamChanges() {
189 return Stream.unwrap(
190 Effect.gen(function* () {
191 const subscription = yield* PubSub.subscribe(changes);
192 const snapshot = yield* Ref.get(stateRef);
193 return Stream.concat(Stream.make(snapshot), Stream.fromSubscription(subscription)).pipe(
194 Stream.changes,
195 );
196 }),
197 );
198 },
199 } satisfies UsageLimitSources["Service"];
200});
201
202export const layer = Layer.effect(UsageLimitSources, make);