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

UsageLimitSources.ts

170 lines6.5 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 */
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 = Effect.fn("UsageLimitSources.publish")(function* (
78 next: ReadonlyArray<UsageLimitSourceSnapshot>,
79 ) {
80 const changed = yield* Ref.modify(stateRef, (previous) =>
81 Equal.equals(previous, next) ? [false, previous] : [true, next],
82 );
83 if (changed) yield* PubSub.publish(changes, next);
84 });
85​
86 // Serialize refreshes so slow old-settings reads cannot resurrect removed sources after newer refreshes.
87 const refreshLock = yield* Semaphore.make(1);
88 const refresh = Effect.gen(function* () {
89 const settings = yield* settingsService.getSettings.pipe(
90 Effect.orElseSucceed((): ServerSettings | null => null),
91 );
92 const entries = Object.entries(settings?.usageLimitSources ?? {}).filter(
93 ([, config]) => config.enabled,
94 );
95 const snapshots = yield* Effect.forEach(
96 entries,
97 ([id, config]) => readSource(id as UsageLimitSourceId, config),
98 { concurrency: 4 },
99 );
100 yield* publish(snapshots);
101 }).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true }));
102​
103 // Shares the refresh lock so a stale in-flight read cannot overwrite a redemption.
104 const consumeResetCredit = Effect.fn("UsageLimitSources.consumeResetCredit")(function* (
105 input: UsageLimitSourceConsumeResetCreditInput,
106 ) {
107 const settings = yield* settingsService.getSettings.pipe(
108 Effect.mapError(() => new UsageLimitSourceError({ detail: "Could not read hub settings." })),
109 );
110 const config = settings.usageLimitSources[input.sourceId];
111 if (!config?.enabled || !config.managementKey) {
112 return yield* new UsageLimitSourceError({
113 detail: "The usage limit source is missing or disabled.",
114 });
115 }
116 const result = yield* api.consume(config, input.accountId, input.creditId);
117 const snapshot = yield* readSource(input.sourceId, config);
118 const previous = yield* Ref.get(stateRef);
119 yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source)));
120 return result;
121 }, refreshLock.withPermits(1));
122​
123 yield* settingsService.streamChanges.pipe(
124 Stream.map((settings) => settings.usageLimitSources),
125 Stream.changes,
126 Stream.runForEach(() => refresh),
127 Effect.forkScoped,
128 );
129​
130 const interval = settingsService.getSettings.pipe(
131 Effect.map(
132 (settings) => resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
133 ),
134 Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
135 );
136 yield* Effect.forever(
137 interval.pipe(
138 Effect.flatMap((wait) => Effect.sleep(Duration.isPositive(wait) ? wait : "60 seconds")),
139 Effect.andThen(interval),
140 Effect.flatMap((current) =>
141 Duration.isPositive(current)
142 ? backgroundPolicy.shouldRunScopeWork({ type: "provider-status" })
143 : Effect.succeed(false),
144 ),
145 Effect.flatMap((shouldRun) => (shouldRun ? refresh : Effect.void)),
146 Effect.ignoreCause({ log: true }),
147 ),
148 ).pipe(Effect.forkScoped);
149​
150 yield* refresh.pipe(Effect.forkScoped);
151​
152 return {
153 current: Ref.get(stateRef),
154 consumeResetCredit,
155 refresh,
156 get streamChanges() {
157 return Stream.unwrap(
158 Effect.gen(function* () {
159 const subscription = yield* PubSub.subscribe(changes);
160 const snapshot = yield* Ref.get(stateRef);
161 return Stream.concat(Stream.make(snapshot), Stream.fromSubscription(subscription)).pipe(
162 Stream.changes,
163 );
164 }),
165 );
166 },
167 } satisfies UsageLimitSources["Service"];
168});
169​
170export const layer = Layer.effect(UsageLimitSources, make);