@@ -16,7 +16,9 @@ import * as DateTime from "effect/DateTime"; |
16 | 16 | import * as Duration from "effect/Duration"; |
17 | 17 | import * as Effect from "effect/Effect"; |
18 | 18 | import * as Equal from "effect/Equal"; |
| 19 | +import * as FileSystem from "effect/FileSystem"; |
19 | 20 | import * as Layer from "effect/Layer"; |
| 21 | +import * as Path from "effect/Path"; |
20 | 22 | import * as PubSub from "effect/PubSub"; |
21 | 23 | import * as Ref from "effect/Ref"; |
22 | 24 | import * as Semaphore from "effect/Semaphore"; |
@@ -29,6 +31,7 @@ import { resolveSettingsSecrets } from "../secrets/settingsSecretValue.ts"; |
29 | 31 | import * as Settings from "../serverSettings.ts"; |
30 | 32 | import { windowLimitsModel } from "../provider/claudeUsageLimits.ts"; |
31 | 33 | import { makeCliproxyApi } from "./cliproxyApi.ts"; |
| 34 | +import { discoverGatewayOrigins, gatewayOrigin, makeMagpieApi } from "./magpieQuotas.ts"; |
32 | 35 |
|
33 | 36 | export class UsageLimitSources extends Context.Service< |
34 | 37 | UsageLimitSources, |
@@ -61,6 +64,9 @@ function missingManagementKey(config: UsageLimitSourceConfig): string { |
61 | 64 | /** @public */ |
62 | 65 | export const make = Effect.gen(function* () { |
63 | 66 | const api = yield* makeCliproxyApi; |
| 67 | + const magpie = yield* makeMagpieApi; |
| 68 | + const fileSystem = yield* FileSystem.FileSystem; |
| 69 | + const path = yield* Path.Path; |
64 | 70 | const settingsService = yield* Settings.ServerSettingsService; |
65 | 71 | const secrets = yield* SecretResolver.SecretResolver; |
66 | 72 | const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; |
@@ -95,19 +101,78 @@ export const make = Effect.gen(function* () { |
95 | 101 | checkedAt, |
96 | 102 | } as const; |
97 | 103 | const managementKey = yield* readManagementKey(config); |
98 | | - if (managementKey.length === 0) { |
| 104 | + // A Magpie gateway on loopback answers without a key. |
| 105 | + if (config.kind === "cliproxy" && managementKey.length === 0) { |
99 | 106 | return { ...base, accounts: [], error: missingManagementKey(config) }; |
100 | 107 | } |
101 | | - const accounts = yield* api |
102 | | - .readAccounts({ url: config.url, managementKey }) |
103 | | - .pipe(Effect.result); |
| 108 | + const accounts = yield* ( |
| 109 | + config.kind === "magpie" |
| 110 | + ? magpie.readAccounts({ url: config.url, managementKey }) |
| 111 | + : api.readAccounts({ url: config.url, managementKey }) |
| 112 | + ).pipe(Effect.result); |
104 | 113 | if (accounts._tag === "Failure") { |
105 | 114 | yield* Effect.logDebug("usage limit source read failed", { id, cause: accounts.failure }); |
106 | 115 | return { ...base, accounts: [], error: accounts.failure.detail }; |
107 | 116 | } |
108 | 117 | return { ...base, accounts: accounts.success }; |
109 | 118 | }); |
110 | 119 |
|
| 120 | + // Gateways the enabled instances already route through, read without |
| 121 | + // configuration. An origin that does not answer the quotas route is not a |
| 122 | + // Magpie gateway and is dropped quietly; nobody configured it. |
| 123 | + const discoverMagpieSources = Effect.fn("UsageLimitSources.discoverMagpieSources")( |
| 124 | + function* ( |
| 125 | + settings: ServerSettings | null, |
| 126 | + configured: ReadonlyArray<UsageLimitSourceSnapshot>, |
| 127 | + ) { |
| 128 | + if (!settings) return []; |
| 129 | + const explicit = new Set( |
| 130 | + Object.values(settings.usageLimitSources) |
| 131 | + .filter((config) => config.enabled && config.kind === "magpie") |
| 132 | + .map((config) => gatewayOrigin(config.url)), |
| 133 | + ); |
| 134 | + const origins = (yield* discoverGatewayOrigins(settings, process.env).pipe( |
| 135 | + Effect.provideService(FileSystem.FileSystem, fileSystem), |
| 136 | + Effect.provideService(Path.Path, path), |
| 137 | + )).filter((origin) => !explicit.has(origin)); |
| 138 | + const reads = yield* Effect.forEach( |
| 139 | + origins, |
| 140 | + (origin) => |
| 141 | + magpie.readAccounts({ url: origin, managementKey: "" }).pipe( |
| 142 | + Effect.map((accounts) => ({ origin, accounts })), |
| 143 | + Effect.option, |
| 144 | + ), |
| 145 | + { concurrency: 4 }, |
| 146 | + ); |
| 147 | + const checkedAt = DateTime.formatIso(yield* DateTime.now); |
| 148 | + // A forward and the gateway it reaches report the same accounts: show one. |
| 149 | + const seen = new Set(configured.map((source) => accountSet(source.accounts))); |
| 150 | + const discovered: UsageLimitSourceSnapshot[] = []; |
| 151 | + for (const read of reads) { |
| 152 | + if (read._tag === "None") continue; |
| 153 | + const key = accountSet(read.value.accounts); |
| 154 | + if (seen.has(key)) continue; |
| 155 | + seen.add(key); |
| 156 | + discovered.push({ |
| 157 | + id: `magpie:${new URL(read.value.origin).host}` as UsageLimitSourceId, |
| 158 | + kind: "magpie", |
| 159 | + label: "Magpie", |
| 160 | + origin: read.value.origin, |
| 161 | + endpoint: read.value.origin, |
| 162 | + checkedAt, |
| 163 | + accounts: read.value.accounts, |
| 164 | + }); |
| 165 | + } |
| 166 | + return discovered.length > 1 |
| 167 | + ? discovered.map((source) => ({ |
| 168 | + ...source, |
| 169 | + label: `Magpie · ${source.id.slice("magpie:".length)}`, |
| 170 | + })) |
| 171 | + : discovered; |
| 172 | + }, |
| 173 | + Effect.orElseSucceed((): ReadonlyArray<UsageLimitSourceSnapshot> => []), |
| 174 | + ); |
| 175 | + |
111 | 176 | const publish = Effect.fn("UsageLimitSources.publish")(function* ( |
112 | 177 | next: ReadonlyArray<UsageLimitSourceSnapshot>, |
113 | 178 | ) { |
@@ -131,7 +196,7 @@ export const make = Effect.gen(function* () { |
131 | 196 | ([id, config]) => readSource(id as UsageLimitSourceId, config), |
132 | 197 | { concurrency: 4 }, |
133 | 198 | ); |
134 | | - yield* publish(snapshots); |
| 199 | + yield* publish([...snapshots, ...(yield* discoverMagpieSources(settings, snapshots))]); |
135 | 200 | }).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true })); |
136 | 201 |
|
137 | 202 | // Shares the refresh lock so a stale in-flight read cannot overwrite a redemption. |
@@ -142,7 +207,7 @@ export const make = Effect.gen(function* () { |
142 | 207 | Effect.mapError(() => new UsageLimitSourceError({ detail: "Could not read hub settings." })), |
143 | 208 | ); |
144 | 209 | const config = settings.usageLimitSources[input.sourceId]; |
145 | | - if (!config?.enabled) { |
| 210 | + if (!config?.enabled || config.kind !== "cliproxy") { |
146 | 211 | return yield* new UsageLimitSourceError({ |
147 | 212 | detail: "The usage limit source is missing or disabled.", |
148 | 213 | }); |
@@ -209,6 +274,13 @@ export const make = Effect.gen(function* () { |
209 | 274 | } satisfies UsageLimitSources["Service"]; |
210 | 275 | }); |
211 | 276 |
|
| 277 | +function accountSet(accounts: ReadonlyArray<{ readonly id: string }>): string { |
| 278 | + return accounts |
| 279 | + .map((account) => account.id) |
| 280 | + .sort() |
| 281 | + .join("\n"); |
| 282 | +} |
| 283 | + |
212 | 284 | export const layer = Layer.effect(UsageLimitSources, make).pipe( |
213 | 285 | Layer.provide(SecretResolverLayer.layer), |
214 | 286 | ); |
|