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

UsageLimitSources.ts

169 lines6.6 KB

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