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

UsageLimitSources.ts

185 lines7.4 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​
63/** @public Service construction is part of the canonical Effect module API. */
64export const make = Effect.gen(function* () {
65 const api = yield* makeCliproxyApi;
66 const settingsService = yield* ServerSettingsService;
67 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
68 const stateRef = yield* Ref.make<ReadonlyArray<UsageLimitSourceSnapshot>>([]);
69 const changes = yield* Effect.acquireRelease(
70 PubSub.unbounded<ReadonlyArray<UsageLimitSourceSnapshot>>(),
71 PubSub.shutdown,
72 );
73​
74 const readSource = Effect.fn("UsageLimitSources.readSource")(function* (
75 id: UsageLimitSourceId,
76 config: UsageLimitSourceConfig,
77 ) {
78 const checkedAt = DateTime.formatIso(yield* DateTime.now);
79 const base = { id, kind: config.kind, label: sourceLabel(id, config), checkedAt } as const;
80 if (config.managementKey.length === 0) {
81 return { ...base, accounts: [], error: "No management key configured." };
82 }
83 const accounts = yield* api.readAccounts(config).pipe(Effect.result);
84 if (accounts._tag === "Failure") {
85 yield* Effect.logDebug("usage limit source read failed", { id, cause: accounts.failure });
86 return { ...base, accounts: [], error: accounts.failure.detail };
87 }
88 return { ...base, accounts: accounts.success };
89 });
90​
91 const publish = (next: ReadonlyArray<UsageLimitSourceSnapshot>) =>
92 Effect.gen(function* () {
93 const changed = yield* Ref.modify(stateRef, (previous) =>
94 Equal.equals(previous, next) ? [false, previous] : [true, next],
95 );
96 if (changed) yield* PubSub.publish(changes, next);
97 });
98​
99 // One refresh at a time: a slow hub read started before a settings change
100 // must not publish after the change's own refresh and resurrect a removed
101 // source. Callers queue behind the in-flight run and see current settings.
102 const refreshLock = yield* Semaphore.make(1);
103 const refresh = Effect.gen(function* () {
104 const settings = yield* settingsService.getSettings.pipe(
105 Effect.orElseSucceed((): ServerSettings | null => null),
106 );
107 const entries = Object.entries(settings?.usageLimitSources ?? {}).filter(
108 ([, config]) => config.enabled,
109 );
110 const snapshots = yield* Effect.forEach(
111 entries,
112 ([id, config]) => readSource(id as UsageLimitSourceId, config),
113 { concurrency: 4 },
114 );
115 yield* publish(snapshots);
116 }).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true }));
117​
118 // Shares the refresh lock so a stale in-flight read cannot overwrite a redemption.
119 const consumeResetCredit = (input: UsageLimitSourceConsumeResetCreditInput) =>
120 Effect.gen(function* () {
121 const settings = yield* settingsService.getSettings.pipe(
122 Effect.mapError(
123 () => new UsageLimitSourceError({ detail: "Could not read hub settings." }),
124 ),
125 );
126 const config = settings.usageLimitSources[input.sourceId];
127 if (!config?.enabled || !config.managementKey) {
128 return yield* new UsageLimitSourceError({
129 detail: "The usage limit source is missing or disabled.",
130 });
131 }
132 const result = yield* api.consume(config, input.accountId, input.creditId);
133 const snapshot = yield* readSource(input.sourceId, config);
134 const previous = yield* Ref.get(stateRef);
135 yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source)));
136 return result;
137 }).pipe(refreshLock.withPermits(1));
138​
139 // Settings edits re-read straight away so a new hub shows up without
140 // waiting for the interval, and a removed one leaves the list.
141 yield* settingsService.streamChanges.pipe(
142 Stream.map((settings) => settings.usageLimitSources),
143 Stream.changes,
144 Stream.runForEach(() => refresh),
145 Effect.forkScoped,
146 );
147​
148 const interval = settingsService.getSettings.pipe(
149 Effect.map(
150 (settings) => resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
151 ),
152 Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
153 );
154 yield* Effect.forever(
155 interval.pipe(
156 Effect.flatMap((wait) =>
157 Effect.sleep(Duration.toMillis(Duration.fromInputUnsafe(wait)) <= 0 ? "60 seconds" : wait),
158 ),
159 Effect.andThen(backgroundPolicy.shouldRunScopeWork({ type: "provider-status" })),
160 Effect.flatMap((shouldRun) => (shouldRun ? refresh : Effect.void)),
161 Effect.ignoreCause({ log: true }),
162 ),
163 ).pipe(Effect.forkScoped);
164​
165 yield* refresh.pipe(Effect.forkScoped);
166​
167 return {
168 current: Ref.get(stateRef),
169 consumeResetCredit,
170 refresh,
171 get streamChanges() {
172 return Stream.unwrap(
173 Effect.gen(function* () {
174 const subscription = yield* PubSub.subscribe(changes);
175 const snapshot = yield* Ref.get(stateRef);
176 return Stream.concat(Stream.make(snapshot), Stream.fromSubscription(subscription)).pipe(
177 Stream.changes,
178 );
179 }),
180 );
181 },
182 } satisfies UsageLimitSources["Service"];
183});
184​
185export const layer = Layer.effect(UsageLimitSources, make);