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

UsageLimitSources.test.ts

307 lines9.7 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(() =>
48 encodeConfigEvent({
49 version: 1,
50 type: "usageLimitSourcesUpdated",
51 payload: { sources: snapshots },
52 }),
53 ).not.toThrow();
54 expect(snapshots.every((source) => source.error === "No management key configured.")).toBe(
55 true,
56 );
57 }).pipe(
58 Effect.provide([
59 Layer.succeed(SecretResolver.SecretResolver, {
60 label: (provider) => Effect.succeed(provider),
61 read: (references) => Effect.succeed(references.map(() => undefined)),
62 invalidate: () => Effect.void,
63 }),
64 ServerSettings.layerTest({
65 usageLimitSources: {
66 [UsageLimitSourceId.make("local-hub")]: {
67 kind: "cliproxy",
68 url: "localhost:8317",
69 managementKey: "",
70 enabled: true,
71 },
72 [UsageLimitSourceId.make("opaque-hub")]: {
73 kind: "cliproxy",
74 url: "file:///tmp/hub",
75 managementKey: "",
76 enabled: true,
77 },
78 [UsageLimitSourceId.make("named-hub")]: {
79 kind: "cliproxy",
80 url: "localhost:8317",
81 label: "Named hub",
82 managementKey: "",
83 enabled: true,
84 },
85 [UsageLimitSourceId.make("valid-hub")]: {
86 kind: "cliproxy",
87 url: "https://hub.test:8317",
88 managementKey: "",
89 enabled: true,
90 },
91 [UsageLimitSourceId.make(" ")]: {
92 kind: "cliproxy",
93 url: "localhost:8317",
94 managementKey: "",
95 enabled: true,
96 },
97 },
98 }),
99 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
100 shouldRunScopeWork: () => Effect.succeed(false),
101 }),
102 Layer.succeed(
103 HttpClient.HttpClient,
104 HttpClient.make(() => Effect.die("Unexpected network request")),
105 ),
106 NodeCrypto.layer,
107 ]),
108 ),
109);
110​
111it.effect("reads a management key from its secret provider", () => {
112 const authorizations: Array<string | undefined> = [];
113 const keySource = (reference: string) => ({
114 provider: SecretProviderId.make("homelab"),
115 reference,
116 });
117 return Effect.gen(function* () {
118 const sources = yield* UsageLimitSources.make;
119 const snapshots = yield* sources.streamChanges.pipe(
120 Stream.filter((next) => next.length > 0),
121 Stream.runHead,
122 Effect.flatMap(Effect.fromOption),
123 );
124 expect(snapshots.map(({ id, error }) => ({ id, error }))).toEqual([
125 { id: "resolved-hub", error: undefined },
126 {
127 id: "unresolved-hub",
128 error: "Could not read the management key from its secret provider.",
129 },
130 ]);
131 expect(authorizations).toEqual(["Bearer resolved-key"]);
132 }).pipe(
133 Effect.provide([
134 ServerSettings.layerTest({
135 usageLimitSources: {
136 [UsageLimitSourceId.make("resolved-hub")]: {
137 kind: "cliproxy",
138 url: "https://resolved.test",
139 managementKey: keySource("cliproxy#key"),
140 enabled: true,
141 },
142 [UsageLimitSourceId.make("unresolved-hub")]: {
143 kind: "cliproxy",
144 url: "https://unresolved.test",
145 managementKey: keySource("missing#key"),
146 enabled: true,
147 },
148 },
149 }),
150 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
151 shouldRunScopeWork: () => Effect.succeed(false),
152 }),
153 Layer.succeed(SecretResolver.SecretResolver, {
154 label: (provider) => Effect.succeed(provider),
155 read: (references) =>
156 Effect.succeed(
157 references.map((reference) =>
158 reference.reference === "cliproxy#key" ? "resolved-key" : undefined,
159 ),
160 ),
161 invalidate: () => Effect.void,
162 }),
163 Layer.succeed(
164 HttpClient.HttpClient,
165 HttpClient.make((request) =>
166 Effect.sync(() => {
167 authorizations.push(request.headers.authorization);
168 return HttpClientResponse.fromWeb(request, Response.json({ files: [] }));
169 }),
170 ),
171 ),
172 NodeCrypto.layer,
173 ]),
174 );
175});
176​
177const NOW = Date.parse("2026-11-13T12:00:00.000Z");
178const at = (hours: number) => DateTime.formatIso(DateTime.makeUnsafe(NOW + hours * 3_600_000));
179const spent = (id: string, hours: number): ServerProviderUsageWindow => ({
180 id,
181 kind: "weekly",
182 label: id,
183 usedPercent: 100,
184 resetsAt: at(hours),
185});
186const hub = (
187 accounts: ReadonlyArray<{
188 driver?: string;
189 windows?: ReadonlyArray<ServerProviderUsageWindow>;
190 unavailable?: true;
191 }>,
192): UsageLimitSourceSnapshot => ({
193 id: UsageLimitSourceId.make("hub"),
194 kind: "cliproxy",
195 label: "hub",
196 checkedAt: at(0),
197 accounts: accounts.map((account, index) => ({
198 id: `account-${index}`,
199 driver: ProviderDriverKind.make(account.driver ?? "claudeAgent"),
200 usageLimits: {
201 checkedAt: at(0),
202 windows: account.windows ?? [],
203 ...(account.unavailable ? { unavailable: { reason: "probeFailed" as const } } : {}),
204 },
205 })),
206});
207​
208it.each([
209 {
210 name: "earliest refill when every account is spent, each at its latest spent window",
211 accounts: [
212 { windows: [spent("five_hour", 1), spent("seven_day", 3)] },
213 { windows: [spent("five_hour", 2)] },
214 { driver: "codex", windows: [] },
215 ],
216 model: "claude-haiku-5-5",
217 expected: at(2),
218 },
219 {
220 name: "unknown while an account still has room",
221 accounts: [{ windows: [spent("five_hour", 1)] }, { windows: [] }],
222 model: "claude-haiku-5-5",
223 expected: null,
224 },
225 {
226 name: "unknown while an account could not be read",
227 accounts: [{ windows: [spent("five_hour", 1)] }, { unavailable: true as const }],
228 model: "claude-haiku-5-5",
229 expected: null,
230 },
231 {
232 name: "unknown when a spent window has no reset or already reset",
233 accounts: [{ windows: [{ ...spent("five_hour", 1), resetsAt: undefined }] }],
234 model: "claude-haiku-5-5",
235 expected: null,
236 },
237 {
238 name: "a model-scoped weekly window blocks only its own model",
239 accounts: [{ windows: [spent("seven_day_fable", 5)] }],
240 model: "claude-haiku-5-5",
241 expected: null,
242 },
243 {
244 name: "a model-scoped weekly window blocks its own model",
245 accounts: [{ windows: [spent("seven_day_fable", 5)] }],
246 model: "claude-fable-5-2",
247 expected: at(5),
248 },
249 {
250 name: "no account of the driver",
251 accounts: [{ driver: "codex", windows: [spent("five_hour", 1)] }],
252 model: "claude-haiku-5-5",
253 expected: null,
254 },
255])("hub pool reset: $name", ({ accounts, model, expected }) => {
256 expect(
257 UsageLimitSources.hubPoolResetAt(
258 [hub(accounts)],
259 ProviderDriverKind.make("claudeAgent"),
260 model,
261 NOW,
262 ),
263 ).toBe(expected);
264});
265​
266it.effect("the reset fallback refreshes its hub, and a stalled hub cannot hold the failure", () =>
267 Effect.gen(function* () {
268 yield* TestClock.setTime(NOW);
269 const roomLeft = { ...hub([{ windows: [spent("five_hour", 2)] }]), origin: "http://hub.test" };
270 const cached = {
271 ...roomLeft,
272 accounts: roomLeft.accounts.map((account) => ({
273 ...account,
274 usageLimits: {
275 ...account.usageLimits,
276 windows: account.usageLimits.windows.map((window) => ({ ...window, usedPercent: 99 })),
277 },
278 })),
279 };
280 let current: ReadonlyArray<UsageLimitSourceSnapshot> = [cached];
281 let refresh: Effect.Effect<void> = Effect.sync(() => {
282 current = [roomLeft];
283 });
284 const lookup = UsageLimitSources.UsageLimitResetFallback.pipe(
285 Effect.flatMap((fallback) =>
286 fallback.resetAt(ProviderDriverKind.make("claudeAgent"), "http://hub.test", null),
287 ),
288 Effect.provide(
289 UsageLimitSources.layerResetFallback.pipe(
290 Layer.provide(
291 Layer.mock(UsageLimitSources.UsageLimitSources)({
292 current: Effect.sync(() => current),
293 refresh: Effect.suspend(() => refresh),
294 }),
295 ),
296 ),
297 ),
298 );
299 // The last poll saw room; the account was spent after it.
300 expect(yield* lookup).toBe(at(2));
301 current = [cached];
302 refresh = Effect.never;
303 const stalled = yield* Effect.forkChild(lookup);
304 yield* TestClock.adjust("5 seconds");
305 expect(yield* Fiber.join(stalled)).toBeNull();
306 }),
307);