import { DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL, UsageLimitSourceError, type UsageLimitSourceConsumeResetCreditInput, type ProviderConsumeResetCreditResult, type ServerSettings, type UsageLimitSourceConfig, type UsageLimitSourceId, type UsageLimitSourceSnapshot, } from "@t3tools/contracts"; import { normalizeProviderProxyUrl } from "@t3tools/provider-core/server/providerProxy"; import { resolveProxyManagement, type ManagedProxyEndpoint, } from "../providerProxy/effectiveProxy.ts"; import * as ManagedProviderProxy from "../providerProxy/ManagedProviderProxy.ts"; import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Equal from "effect/Equal"; import * as Layer from "effect/Layer"; import * as PubSub from "effect/PubSub"; import * as Ref from "effect/Ref"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; import * as Settings from "../serverSettings.ts"; import { makeCliproxyApi } from "./cliproxyApi.ts"; export class UsageLimitSources extends Context.Service< UsageLimitSources, { readonly current: Effect.Effect>; readonly streamChanges: Stream.Stream>; readonly refresh: Effect.Effect; readonly consumeResetCredit: ( input: UsageLimitSourceConsumeResetCreditInput, ) => Effect.Effect; } >()("t3/usage/UsageLimitSources") {} function sourceLabel(id: string, config: UsageLimitSourceConfig): string { if (config.label) return config.label; const fallback = id.trim() || "Usage limit source"; try { return new URL(config.url).host || fallback; } catch { return fallback; } } export const PROVIDER_PROXY_SOURCE_ID = "provider-proxy" as UsageLimitSourceId; /** The routing proxy reports its accounts without a separate hub entry, unless one already points at it. */ export function effectiveUsageLimitSources( settings: ServerSettings, managedProxy?: ManagedProxyEndpoint, ): Readonly> { const management = resolveProxyManagement(settings, managedProxy); if (management === undefined) return settings.usageLimitSources; const { url, managementKey } = management; const alreadyListed = Object.values(settings.usageLimitSources).some( (source) => source.enabled && source.managementKey !== "" && normalizeProviderProxyUrl(source.url) === url, ); // A hand-written source may already use the synthetic id; it keeps the slot. if (alreadyListed || PROVIDER_PROXY_SOURCE_ID in settings.usageLimitSources) { return settings.usageLimitSources; } return { ...settings.usageLimitSources, [PROVIDER_PROXY_SOURCE_ID]: { kind: "cliproxy", label: "Proxy", url, managementKey, enabled: true, }, }; } /** @public */ export const make = Effect.gen(function* () { const api = yield* makeCliproxyApi; const settingsService = yield* Settings.ServerSettingsService; const managedProxy = yield* ManagedProviderProxy.ManagedProviderProxy; const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; const stateRef = yield* Ref.make>([]); const changes = yield* Effect.acquireRelease( PubSub.unbounded>(), PubSub.shutdown, ); const readSource = Effect.fn("UsageLimitSources.readSource")(function* ( id: UsageLimitSourceId, config: UsageLimitSourceConfig, ) { const checkedAt = DateTime.formatIso(yield* DateTime.now); const base = { id, kind: config.kind, label: sourceLabel(id, config), checkedAt } as const; if (config.managementKey.length === 0) { return { ...base, accounts: [], error: "No management key configured." }; } const accounts = yield* api.readAccounts(config).pipe(Effect.result); if (accounts._tag === "Failure") { yield* Effect.logDebug("usage limit source read failed", { id, cause: accounts.failure }); return { ...base, accounts: [], error: accounts.failure.detail }; } return { ...base, accounts: accounts.success }; }); const publish = Effect.fn("UsageLimitSources.publish")(function* ( next: ReadonlyArray, ) { const changed = yield* Ref.modify(stateRef, (previous) => Equal.equals(previous, next) ? [false, previous] : [true, next], ); if (changed) yield* PubSub.publish(changes, next); }); // Serialize refreshes so slow old-settings reads cannot resurrect removed sources after newer refreshes. const refreshLock = yield* Semaphore.make(1); const refresh = Effect.gen(function* () { const settings = yield* settingsService.getSettings.pipe( Effect.orElseSucceed((): ServerSettings | null => null), ); const endpoint = yield* managedProxy.endpoint; const entries = Object.entries( settings === null ? {} : effectiveUsageLimitSources(settings, endpoint), ).filter(([, config]) => config.enabled); const snapshots = yield* Effect.forEach( entries, ([id, config]) => readSource(id as UsageLimitSourceId, config), { concurrency: 4 }, ); yield* publish(snapshots); }).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true })); // Shares the refresh lock so a stale in-flight read cannot overwrite a redemption. const consumeResetCredit = Effect.fn("UsageLimitSources.consumeResetCredit")(function* ( input: UsageLimitSourceConsumeResetCreditInput, ) { const settings = yield* settingsService.getSettings.pipe( Effect.mapError(() => new UsageLimitSourceError({ detail: "Could not read hub settings." })), ); const config = effectiveUsageLimitSources(settings, yield* managedProxy.endpoint)[ input.sourceId ]; if (!config?.enabled || !config.managementKey) { return yield* new UsageLimitSourceError({ detail: "The usage limit source is missing or disabled.", }); } const result = yield* api.consume(config, input.accountId, input.creditId); const snapshot = yield* readSource(input.sourceId, config); const previous = yield* Ref.get(stateRef); yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source))); return result; }, refreshLock.withPermits(1)); yield* Stream.merge( settingsService.streamChanges.pipe( Stream.map((settings) => effectiveUsageLimitSources(settings)), Stream.changes, ), // Starting makes the managed proxy answer; stopping must drop its accounts. managedProxy.statusChanges.pipe(Stream.drop(1)), ).pipe( Stream.runForEach(() => refresh), Effect.forkScoped, ); const interval = settingsService.getSettings.pipe( Effect.map( (settings) => resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval, ), Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL), ); yield* Effect.forever( interval.pipe( Effect.flatMap((wait) => Effect.sleep(Duration.isPositive(wait) ? wait : "60 seconds")), Effect.andThen(interval), Effect.flatMap((current) => Duration.isPositive(current) ? backgroundPolicy.shouldRunScopeWork({ type: "provider-status" }) : Effect.succeed(false), ), Effect.flatMap((shouldRun) => (shouldRun ? refresh : Effect.void)), Effect.ignoreCause({ log: true }), ), ).pipe(Effect.forkScoped); yield* refresh.pipe(Effect.forkScoped); return { current: Ref.get(stateRef), consumeResetCredit, refresh, get streamChanges() { return Stream.unwrap( Effect.gen(function* () { const subscription = yield* PubSub.subscribe(changes); const snapshot = yield* Ref.get(stateRef); return Stream.concat(Stream.make(snapshot), Stream.fromSubscription(subscription)).pipe( Stream.changes, ); }), ); }, } satisfies UsageLimitSources["Service"]; }); export const layer = Layer.effect(UsageLimitSources, make);