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

UsageLimitSources.ts

184 lines7.3 KB

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 UsageLimitSourceError,
17 type UsageLimitSourceConsumeResetCreditInput,
18 type ProviderConsumeResetCreditResult,
19 type ServerSettings,
20 type UsageLimitSourceConfig,
21 type UsageLimitSourceId,
22 type UsageLimitSourceSnapshot,
23} from "@t3tools/contracts";
24import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
25import * as Context from "effect/Context";
26import * as DateTime from "effect/DateTime";
27import * as Duration from "effect/Duration";
28import * as Effect from "effect/Effect";
29import * as Equal from "effect/Equal";
30import * as Layer from "effect/Layer";
31import * as PubSub from "effect/PubSub";
32import * as Ref from "effect/Ref";
33import * as Semaphore from "effect/Semaphore";
34import * as Stream from "effect/Stream";
35​
36import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
37import { ServerSettingsService } from "../serverSettings.ts";
38import { makeCliproxyApi } from "./cliproxyApi.ts";
39​
40export class UsageLimitSources extends Context.Service<
41 UsageLimitSources,
42 {
43 readonly current: Effect.Effect<ReadonlyArray<UsageLimitSourceSnapshot>>;
44 /** The current set followed by every change, with repeats dropped. */
45 readonly streamChanges: Stream.Stream<ReadonlyArray<UsageLimitSourceSnapshot>>;
46 /** Re-read every source now. Never fails; failures land on the snapshot. */
47 readonly refresh: Effect.Effect<void>;
48 readonly consumeResetCredit: (
49 input: UsageLimitSourceConsumeResetCreditInput,
50 ) => Effect.Effect<ProviderConsumeResetCreditResult, UsageLimitSourceError>;
51 }
52>()("t3/usage/UsageLimitSources") {}
53​
54function sourceLabel(id: string, config: UsageLimitSourceConfig): string {
55 if (config.label) return config.label;
56 try {
57 return new URL(config.url).host;
58 } catch {
59 return id;
60 }
62​
63export const make = Effect.gen(function* () {
64 const api = yield* makeCliproxyApi;
65 const settingsService = yield* ServerSettingsService;
66 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
67 const stateRef = yield* Ref.make<ReadonlyArray<UsageLimitSourceSnapshot>>([]);
68 const changes = yield* Effect.acquireRelease(
69 PubSub.unbounded<ReadonlyArray<UsageLimitSourceSnapshot>>(),
70 PubSub.shutdown,
71 );
72​
73 const readSource = Effect.fn("UsageLimitSources.readSource")(function* (
74 id: UsageLimitSourceId,
75 config: UsageLimitSourceConfig,
76 ) {
77 const checkedAt = DateTime.formatIso(yield* DateTime.now);
78 const base = { id, kind: config.kind, label: sourceLabel(id, config), checkedAt } as const;
79 if (config.managementKey.length === 0) {
80 return { ...base, accounts: [], error: "No management key configured." };
81 }
82 const accounts = yield* api.readAccounts(config).pipe(Effect.result);
83 if (accounts._tag === "Failure") {
84 yield* Effect.logDebug("usage limit source read failed", { id, cause: accounts.failure });
85 return { ...base, accounts: [], error: accounts.failure.detail };
86 }
87 return { ...base, accounts: accounts.success };
88 });
89​
90 const publish = (next: ReadonlyArray<UsageLimitSourceSnapshot>) =>
91 Effect.gen(function* () {
92 const changed = yield* Ref.modify(stateRef, (previous) =>
93 Equal.equals(previous, next) ? [false, previous] : [true, next],
94 );
95 if (changed) yield* PubSub.publish(changes, next);
96 });
97​
98 // One refresh at a time: a slow hub read started before a settings change
99 // must not publish after the change's own refresh and resurrect a removed
100 // source. Callers queue behind the in-flight run and see current settings.
101 const refreshLock = yield* Semaphore.make(1);
102 const refresh = Effect.gen(function* () {
103 const settings = yield* settingsService.getSettings.pipe(
104 Effect.orElseSucceed((): ServerSettings | null => null),
105 );
106 const entries = Object.entries(settings?.usageLimitSources ?? {}).filter(
107 ([, config]) => config.enabled,
108 );
109 const snapshots = yield* Effect.forEach(
110 entries,
111 ([id, config]) => readSource(id as UsageLimitSourceId, config),
112 { concurrency: 4 },
113 );
114 yield* publish(snapshots);
115 }).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true }));
116​
117 // Shares the refresh lock so a stale in-flight read cannot overwrite a redemption.
118 const consumeResetCredit = (input: UsageLimitSourceConsumeResetCreditInput) =>
119 Effect.gen(function* () {
120 const settings = yield* settingsService.getSettings.pipe(
121 Effect.mapError(
122 () => new UsageLimitSourceError({ detail: "Could not read hub settings." }),
123 ),
124 );
125 const config = settings.usageLimitSources[input.sourceId];
126 if (!config?.enabled || !config.managementKey) {
127 return yield* new UsageLimitSourceError({
128 detail: "The usage limit source is missing or disabled.",
129 });
130 }
131 const result = yield* api.consume(config, input.accountId, input.creditId);
132 const snapshot = yield* readSource(input.sourceId, config);
133 const previous = yield* Ref.get(stateRef);
134 yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source)));
135 return result;
136 }).pipe(refreshLock.withPermits(1));
137​
138 // Settings edits re-read straight away so a new hub shows up without
139 // waiting for the interval, and a removed one leaves the list.
140 yield* settingsService.streamChanges.pipe(
141 Stream.map((settings) => settings.usageLimitSources),
142 Stream.changes,
143 Stream.runForEach(() => refresh),
144 Effect.forkScoped,
145 );
146​
147 const interval = settingsService.getSettings.pipe(
148 Effect.map(
149 (settings) => resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
150 ),
151 Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
152 );
153 yield* Effect.forever(
154 interval.pipe(
155 Effect.flatMap((wait) =>
156 Effect.sleep(Duration.toMillis(Duration.fromInputUnsafe(wait)) <= 0 ? "60 seconds" : wait),
157 ),
158 Effect.andThen(backgroundPolicy.shouldRunScopeWork({ type: "provider-status" })),
159 Effect.flatMap((shouldRun) => (shouldRun ? refresh : Effect.void)),
160 Effect.ignoreCause({ log: true }),
161 ),
162 ).pipe(Effect.forkScoped);
163​
164 yield* refresh.pipe(Effect.forkScoped);
165​
166 return {
167 current: Ref.get(stateRef),
168 consumeResetCredit,
169 refresh,
170 get streamChanges() {
171 return Stream.unwrap(
172 Effect.gen(function* () {
173 const subscription = yield* PubSub.subscribe(changes);
174 const snapshot = yield* Ref.get(stateRef);
175 return Stream.concat(Stream.make(snapshot), Stream.fromSubscription(subscription)).pipe(
176 Stream.changes,
177 );
178 }),
179 );
180 },
181 } satisfies UsageLimitSources["Service"];
182});
183​
184export const layer = Layer.effect(UsageLimitSources, make);