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

UsageLimitSources.test.ts

308 lines9.8 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​
178const NOW = Date.parse("2026-11-13T12:00:00.000Z");
179const at = (hours: number) => DateTime.formatIso(DateTime.makeUnsafe(NOW + hours * 3_600_000));
180const spent = (id: string, hours: number): ServerProviderUsageWindow => ({
181 id,
182 kind: "weekly",
183 label: id,
184 usedPercent: 100,
185 resetsAt: at(hours),
186});
187const hub = (
188 accounts: ReadonlyArray<{
189 driver?: string;
190 windows?: ReadonlyArray<ServerProviderUsageWindow>;
191 unavailable?: true;
192 }>,
193): UsageLimitSourceSnapshot => ({
194 id: UsageLimitSourceId.make("hub"),
195 kind: "cliproxy",
196 label: "hub",
197 checkedAt: at(0),
198 accounts: accounts.map((account, index) => ({
199 id: `account-${index}`,
200 driver: ProviderDriverKind.make(account.driver ?? "claudeAgent"),
201 usageLimits: {
202 checkedAt: at(0),
203 windows: account.windows ?? [],
204 ...(account.unavailable ? { unavailable: { reason: "probeFailed" as const } } : {}),
205 },
206 })),
207});
208​
209it.each([
210 {
211 name: "earliest refill when every account is spent, each at its latest spent window",
212 accounts: [
213 { windows: [spent("five_hour", 1), spent("seven_day", 3)] },
214 { windows: [spent("five_hour", 2)] },
215 { driver: "codex", windows: [] },
216 ],
217 model: "claude-haiku-5-5",
218 expected: at(2),
219 },
220 {
221 name: "unknown while an account still has room",
222 accounts: [{ windows: [spent("five_hour", 1)] }, { windows: [] }],
223 model: "claude-haiku-5-5",
224 expected: null,
225 },
226 {
227 name: "unknown while an account could not be read",
228 accounts: [{ windows: [spent("five_hour", 1)] }, { unavailable: true as const }],
229 model: "claude-haiku-5-5",
230 expected: null,
231 },
232 {
233 name: "unknown when a spent window has no reset or already reset",
234 accounts: [{ windows: [{ ...spent("five_hour", 1), resetsAt: undefined }] }],
235 model: "claude-haiku-5-5",
236 expected: null,
237 },
238 {
239 name: "a model-scoped weekly window blocks only its own model",
240 accounts: [{ windows: [spent("seven_day_fable", 5)] }],
241 model: "claude-haiku-5-5",
242 expected: null,
243 },
244 {
245 name: "a model-scoped weekly window blocks its own model",
246 accounts: [{ windows: [spent("seven_day_fable", 5)] }],
247 model: "claude-fable-5-2",
248 expected: at(5),
249 },
250 {
251 name: "no account of the driver",
252 accounts: [{ driver: "codex", windows: [spent("five_hour", 1)] }],
253 model: "claude-haiku-5-5",
254 expected: null,
255 },
256])("hub pool reset: $name", ({ accounts, model, expected }) => {
257 expect(
258 UsageLimitSources.hubPoolResetAt(
259 [hub(accounts)],
260 ProviderDriverKind.make("claudeAgent"),
261 model,
262 NOW,
263 ),
264 ).toBe(expected);
265});
266​
267it.effect("the reset fallback refreshes its hub, and a stalled hub cannot hold the failure", () =>
268 Effect.gen(function* () {
269 yield* TestClock.setTime(NOW);
270 const roomLeft = { ...hub([{ windows: [spent("five_hour", 2)] }]), origin: "http://hub.test" };
271 const cached = {
272 ...roomLeft,
273 accounts: roomLeft.accounts.map((account) => ({
274 ...account,
275 usageLimits: {
276 ...account.usageLimits,
277 windows: account.usageLimits.windows.map((window) => ({ ...window, usedPercent: 99 })),
278 },
279 })),
280 };
281 let current: ReadonlyArray<UsageLimitSourceSnapshot> = [cached];
282 let refresh: Effect.Effect<void> = Effect.sync(() => {
283 current = [roomLeft];
284 });
285 const lookup = UsageLimitSources.UsageLimitResetFallback.pipe(
286 Effect.flatMap((fallback) =>
287 fallback.resetAt(ProviderDriverKind.make("claudeAgent"), "http://hub.test", null),
288 ),
289 Effect.provide(
290 UsageLimitSources.layerResetFallback.pipe(
291 Layer.provide(
292 Layer.mock(UsageLimitSources.UsageLimitSources)({
293 current: Effect.sync(() => current),
294 refresh: Effect.suspend(() => refresh),
295 }),
296 ),
297 ),
298 ),
299 );
300 // The last poll saw room; the account was spent after it.
301 expect(yield* lookup).toBe(at(2));
302 current = [cached];
303 refresh = Effect.never;
304 const stalled = yield* Effect.forkChild(lookup);
305 yield* TestClock.adjust("5 seconds");
306 expect(yield* Fiber.join(stalled)).toBeNull();
307 }),
308);