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

UsageLimitSources.test.ts

409 lines13.3 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import { expect, it } from "@effect/vitest";
3import {
4 ProviderDriverKind,
5 SecretProviderId,
6 ServerConfigStreamEvent,
7 UsageLimitSourceId,
8 type ServerProviderUsageWindow,
9 type UsageLimitSourceSnapshot,
10} from "@t3tools/contracts";
11import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Fiber from "effect/Fiber";
15import * as Layer from "effect/Layer";
16import * as Schema from "effect/Schema";
17import * as Stream from "effect/Stream";
18import * as TestClock from "effect/testing/TestClock";
19import { HttpClient, HttpClientResponse } from "effect/http";
20​
21import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
22import * as ServerSettings from "../serverSettings.ts";
23import * as UsageLimitSources from "./UsageLimitSources.ts";
24​
25const encodeConfigEvent = Schema.encodeSync(ServerConfigStreamEvent);
26​
27it.effect("keeps malformed source URLs encodable for config subscribers", () =>
28 Effect.gen(function* () {
29 const sources = yield* UsageLimitSources.make;
30 yield* sources.refresh;
31 const snapshots = yield* sources.current;
32 expect(snapshots.map((source) => source.label)).toEqual([
33 "local-hub",
34 "opaque-hub",
35 "Named hub",
36 "hub.test:8317",
37 "Usage limit source",
38 ]);
39 // Only an http(s) hub URL names an endpoint an agent can be sent to.
40 expect(snapshots.map((source) => source.origin)).toEqual([
41 undefined,
42 undefined,
43 undefined,
44 "https://hub.test:8317",
45 undefined,
46 ]);
47 expect(snapshots[3]?.endpoint).toBe("https://hub.test:8317/team-a");
48 expect(() =>
49 encodeConfigEvent({
50 version: 1,
51 type: "usageLimitSourcesUpdated",
52 payload: { sources: snapshots },
53 }),
54 ).not.toThrow();
55 expect(snapshots.every((source) => source.error === "No management key configured.")).toBe(
56 true,
57 );
58 }).pipe(
59 Effect.provide([
60 Layer.succeed(SecretResolver.SecretResolver, {
61 label: (provider) => Effect.succeed(provider),
62 read: (references) => Effect.succeed(references.map(() => undefined)),
63 invalidate: () => Effect.void,
64 }),
65 ServerSettings.layerTest({
66 usageLimitSources: {
67 [UsageLimitSourceId.make("local-hub")]: {
68 kind: "cliproxy",
69 url: "localhost:8317",
70 managementKey: "",
71 enabled: true,
72 },
73 [UsageLimitSourceId.make("opaque-hub")]: {
74 kind: "cliproxy",
75 url: "file:///tmp/hub",
76 managementKey: "",
77 enabled: true,
78 },
79 [UsageLimitSourceId.make("named-hub")]: {
80 kind: "cliproxy",
81 url: "localhost:8317",
82 label: "Named hub",
83 managementKey: "",
84 enabled: true,
85 },
86 [UsageLimitSourceId.make("valid-hub")]: {
87 kind: "cliproxy",
88 url: "https://hub.test:8317/team-a/management.html",
89 managementKey: "",
90 enabled: true,
91 },
92 [UsageLimitSourceId.make(" ")]: {
93 kind: "cliproxy",
94 url: "localhost:8317",
95 managementKey: "",
96 enabled: true,
97 },
98 },
99 }),
100 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
101 shouldRunScopeWork: () => Effect.succeed(false),
102 }),
103 Layer.succeed(
104 HttpClient.HttpClient,
105 HttpClient.make(() => Effect.die("Unexpected network request")),
106 ),
107 NodeCrypto.layer,
108 ]),
109 ),
110);
111​
112it.effect("reads a management key from its secret provider", () => {
113 const authorizations: Array<string | undefined> = [];
114 const keySource = (reference: string) => ({
115 provider: SecretProviderId.make("homelab"),
116 reference,
117 });
118 return Effect.gen(function* () {
119 const sources = yield* UsageLimitSources.make;
120 const snapshots = yield* sources.streamChanges.pipe(
121 Stream.filter((next) => next.length > 0),
122 Stream.runHead,
123 Effect.flatMap(Effect.fromOption),
124 );
125 expect(snapshots.map(({ id, error }) => ({ id, error }))).toEqual([
126 { id: "resolved-hub", error: undefined },
127 {
128 id: "unresolved-hub",
129 error: "Could not read the management key from its secret provider.",
130 },
131 ]);
132 expect(authorizations).toEqual(["Bearer resolved-key"]);
133 }).pipe(
134 Effect.provide([
135 ServerSettings.layerTest({
136 usageLimitSources: {
137 [UsageLimitSourceId.make("resolved-hub")]: {
138 kind: "cliproxy",
139 url: "https://resolved.test",
140 managementKey: keySource("cliproxy#key"),
141 enabled: true,
142 },
143 [UsageLimitSourceId.make("unresolved-hub")]: {
144 kind: "cliproxy",
145 url: "https://unresolved.test",
146 managementKey: keySource("missing#key"),
147 enabled: true,
148 },
149 },
150 }),
151 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
152 shouldRunScopeWork: () => Effect.succeed(false),
153 }),
154 Layer.succeed(SecretResolver.SecretResolver, {
155 label: (provider) => Effect.succeed(provider),
156 read: (references) =>
157 Effect.succeed(
158 references.map((reference) =>
159 reference.reference === "cliproxy#key" ? "resolved-key" : undefined,
160 ),
161 ),
162 invalidate: () => Effect.void,
163 }),
164 Layer.succeed(
165 HttpClient.HttpClient,
166 HttpClient.make((request) =>
167 Effect.sync(() => {
168 authorizations.push(request.headers.authorization);
169 return HttpClientResponse.fromWeb(request, Response.json({ files: [] }));
170 }),
171 ),
172 ),
173 NodeCrypto.layer,
174 ]),
175 );
176});
177​
178it.effect("keeps an account's last good reading when the hub's next read of it is refused", () => {
179 let refused = true;
180 let workspace = "account-a";
181 let listsIdentity = true;
182 const readAccount = Effect.gen(function* () {
183 const sources = yield* UsageLimitSources.make;
184 return Effect.gen(function* () {
185 yield* sources.refresh;
186 const [source] = yield* sources.current;
187 return source?.accounts[0]?.usageLimits;
188 });
189 });
190 return Effect.gen(function* () {
191 const read = yield* readAccount;
192 // Nothing to keep yet: the account stays listed as unreadable.
193 expect(yield* read).toMatchObject({ windows: [], unavailable: { reason: "probeFailed" } });
194 refused = false;
195 const good = yield* read;
196 expect(good?.windows.map((window) => window.usedPercent)).toEqual([78]);
197 expect(good?.unavailable).toBeUndefined();
198 refused = true;
199 expect(yield* read).toEqual(good);
200 // The same auth file now holds another login, whose reading is unknown.
201 workspace = "account-b";
202 expect(yield* read).toMatchObject({ windows: [], unavailable: { reason: "probeFailed" } });
203 // A file that lists no login cannot show whether the next one is the same.
204 listsIdentity = false;
205 refused = false;
206 yield* read;
207 refused = true;
208 expect(yield* read).toMatchObject({ windows: [], unavailable: { reason: "probeFailed" } });
209 }).pipe(
210 Effect.provide([
211 ServerSettings.layerTest({
212 usageLimitSources: {
213 [UsageLimitSourceId.make("hub")]: {
214 kind: "cliproxy",
215 url: "http://hub.test:8317",
216 managementKey: "management-secret",
217 enabled: true,
218 },
219 },
220 }),
221 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
222 shouldRunScopeWork: () => Effect.succeed(false),
223 }),
224 Layer.succeed(SecretResolver.SecretResolver, {
225 label: (provider) => Effect.succeed(provider),
226 read: (references) => Effect.succeed(references.map(() => undefined)),
227 invalidate: () => Effect.void,
228 }),
229 Layer.succeed(
230 HttpClient.HttpClient,
231 HttpClient.make((request) =>
232 Effect.sync(() => {
233 if (new URL(request.url).pathname.endsWith("/auth-files")) {
234 return HttpClientResponse.fromWeb(
235 request,
236 Response.json({
237 files: [
238 {
239 id: "first.json",
240 auth_index: "a",
241 provider: "codex",
242 ...(listsIdentity
243 ? {
244 email: "first@example.com",
245 id_token: { chatgpt_account_id: workspace },
246 }
247 : {}),
248 },
249 ],
250 }),
251 );
252 }
253 const usage = {
254 plan_type: "pro",
255 rate_limit: {
256 secondary_window: {
257 used_percent: 78,
258 reset_at: 4070908800,
259 limit_window_seconds: 604800,
260 },
261 },
262 };
263 return HttpClientResponse.fromWeb(
264 request,
265 Response.json(
266 refused
267 ? { status_code: 429, body: "{}" }
268 : { status_code: 200, body: JSON.stringify(usage) },
269 ),
270 );
271 }),
272 ),
273 ),
274 NodeCrypto.layer,
275 ]),
276 );
277});
278​
279const NOW = Date.parse("2026-11-13T12:00:00.000Z");
280const at = (hours: number) => DateTime.formatIso(DateTime.makeUnsafe(NOW + hours * 3_600_000));
281const spent = (id: string, hours: number): ServerProviderUsageWindow => ({
282 id,
283 kind: "weekly",
284 label: id,
285 usedPercent: 100,
286 resetsAt: at(hours),
287});
288const hub = (
289 accounts: ReadonlyArray<{
290 driver?: string;
291 windows?: ReadonlyArray<ServerProviderUsageWindow>;
292 unavailable?: true;
293 }>,
294): UsageLimitSourceSnapshot => ({
295 id: UsageLimitSourceId.make("hub"),
296 kind: "cliproxy",
297 label: "hub",
298 checkedAt: at(0),
299 accounts: accounts.map((account, index) => ({
300 id: `account-${index}`,
301 driver: ProviderDriverKind.make(account.driver ?? "claudeAgent"),
302 usageLimits: {
303 checkedAt: at(0),
304 windows: account.windows ?? [],
305 ...(account.unavailable ? { unavailable: { reason: "probeFailed" as const } } : {}),
306 },
307 })),
308});
309​
310it.each([
311 {
312 name: "earliest refill when every account is spent, each at its latest spent window",
313 accounts: [
314 { windows: [spent("five_hour", 1), spent("seven_day", 3)] },
315 { windows: [spent("five_hour", 2)] },
316 { driver: "codex", windows: [] },
317 ],
318 model: "claude-haiku-5-5",
319 expected: at(2),
320 },
321 {
322 name: "unknown while an account still has room",
323 accounts: [{ windows: [spent("five_hour", 1)] }, { windows: [] }],
324 model: "claude-haiku-5-5",
325 expected: null,
326 },
327 {
328 name: "unknown while an account could not be read",
329 accounts: [{ windows: [spent("five_hour", 1)] }, { unavailable: true as const }],
330 model: "claude-haiku-5-5",
331 expected: null,
332 },
333 {
334 name: "unknown when a spent window has no reset or already reset",
335 accounts: [{ windows: [{ ...spent("five_hour", 1), resetsAt: undefined }] }],
336 model: "claude-haiku-5-5",
337 expected: null,
338 },
339 {
340 name: "a model-scoped weekly window blocks only its own model",
341 accounts: [{ windows: [spent("seven_day_fable", 5)] }],
342 model: "claude-haiku-5-5",
343 expected: null,
344 },
345 {
346 name: "a model-scoped weekly window blocks its own model",
347 accounts: [{ windows: [spent("seven_day_fable", 5)] }],
348 model: "claude-fable-5-2",
349 expected: at(5),
350 },
351 {
352 name: "no account of the driver",
353 accounts: [{ driver: "codex", windows: [spent("five_hour", 1)] }],
354 model: "claude-haiku-5-5",
355 expected: null,
356 },
357])("hub pool reset: $name", ({ accounts, model, expected }) => {
358 expect(
359 UsageLimitSources.hubPoolResetAt(
360 [hub(accounts)],
361 ProviderDriverKind.make("claudeAgent"),
362 model,
363 NOW,
364 ),
365 ).toBe(expected);
366});
367​
368it.effect("the reset fallback refreshes its hub, and a stalled hub cannot hold the failure", () =>
369 Effect.gen(function* () {
370 yield* TestClock.setTime(NOW);
371 const roomLeft = { ...hub([{ windows: [spent("five_hour", 2)] }]), origin: "http://hub.test" };
372 const cached = {
373 ...roomLeft,
374 accounts: roomLeft.accounts.map((account) => ({
375 ...account,
376 usageLimits: {
377 ...account.usageLimits,
378 windows: account.usageLimits.windows.map((window) => ({ ...window, usedPercent: 99 })),
379 },
380 })),
381 };
382 let current: ReadonlyArray<UsageLimitSourceSnapshot> = [cached];
383 let refresh: Effect.Effect<void> = Effect.sync(() => {
384 current = [roomLeft];
385 });
386 const lookup = UsageLimitSources.UsageLimitResetFallback.pipe(
387 Effect.flatMap((fallback) =>
388 fallback.resetAt(ProviderDriverKind.make("claudeAgent"), "http://hub.test", null),
389 ),
390 Effect.provide(
391 UsageLimitSources.layerResetFallback.pipe(
392 Layer.provide(
393 Layer.mock(UsageLimitSources.UsageLimitSources)({
394 current: Effect.sync(() => current),
395 refresh: Effect.suspend(() => refresh),
396 }),
397 ),
398 ),
399 ),
400 );
401 // The last poll saw room; the account was spent after it.
402 expect(yield* lookup).toBe(at(2));
403 current = [cached];
404 refresh = Effect.never;
405 const stalled = yield* Effect.forkChild(lookup);
406 yield* TestClock.adjust("5 seconds");
407 expect(yield* Fiber.join(stalled)).toBeNull();
408 }),
409);