Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import { describe, expect, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as Schema from "effect/Schema";
6import * as TestClock from "effect/testing/TestClock";
7import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
8
9import { makeCliproxyApi } from "./cliproxyApi.ts";
10
11const config = {
12 kind: "cliproxy",
13 url: "http://hub.test:8317",
14 managementKey: "management-secret",
15 enabled: true,
16} as const;
17const accounts = [
18 {
19 id: "first.json",
20 auth_index: "a",
21 provider: "codex",
22 email: "first@example.com",
23 id_token: { chatgpt_account_id: "account-a" },
24 },
25 {
26 id: "second.json",
27 auth_index: "b",
28 provider: "codex",
29 email: "second@example.com",
30 id_token: { chatgpt_account_id: "account-b" },
31 },
32];
33const credit = (id: string, expires_at = "2099-01-01T00:00:00Z") => ({
34 id,
35 expires_at,
36 status: "available",
37 reset_type: "codex_rate_limits",
38});
39const RequestBody = Schema.Struct({
40 auth_index: Schema.String,
41 method: Schema.optional(Schema.String),
42 url: Schema.optional(Schema.String),
43 header: Schema.optional(Schema.Record(Schema.String, Schema.String)),
44 data: Schema.optional(Schema.String),
45});
46type RequestBody = typeof RequestBody.Type;
47const decodeRequest = Schema.decodeUnknownSync(Schema.fromJsonString(RequestBody));
48const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
49
50function fixture(
51 options: {
52 accounts?: Array<{
53 id: string;
54 auth_index: string;
55 provider: string;
56 email?: string;
57 disabled?: boolean;
58 project_id?: string;
59 id_token?: { chatgpt_account_id: string; plan_type?: string; chatgpt_plan_type?: string };
60 }>;
61 upstream?: (request: RequestBody) => { status: number; body: unknown };
62 cooldownStatus?: number;
63 models?: (name: string) => Response;
64 } = {},
65) {
66 const requests: Array<{ path: string; body?: RequestBody }> = [];
67 const http = HttpClient.make((request) =>
68 Effect.sync(() => {
69 expect(request.headers.authorization).toBe("Bearer management-secret");
70 const path = new URL(request.url).pathname;
71 const body =
72 request.body._tag === "Uint8Array"
73 ? decodeRequest(new TextDecoder().decode(request.body.body))
74 : undefined;
75 requests.push({ path, ...(body ? { body } : {}) });
76 if (path.endsWith("/auth-files/models"))
77 return HttpClientResponse.fromWeb(
78 request,
79 options.models?.(new URL(request.url).searchParams.get("name")!) ??
80 Response.json({}, { status: 404 }),
81 );
82 if (path.endsWith("/auth-files"))
83 return HttpClientResponse.fromWeb(
84 request,
85 Response.json({ files: options.accounts ?? accounts }),
86 );
87 if (path.endsWith("/reset-quota"))
88 return HttpClientResponse.fromWeb(
89 request,
90 Response.json({}, { status: options.cooldownStatus ?? 200 }),
91 );
92 expect(path).toMatch(/\/v0\/management\/api-call$/);
93 expect(body?.header?.Authorization).toBe("Bearer $TOKEN$");
94 const upstream = options.upstream?.(body!) ?? {
95 status: 200,
96 body: body?.url?.endsWith("/consume")
97 ? { code: "reset" }
98 : body?.url?.endsWith("/rate-limit-reset-credits")
99 ? {
100 credits: [
101 credit("later", "2099-02-01T00:00:00Z"),
102 credit("first"),
103 credit("expired", "2000-01-01T00:00:00Z"),
104 { ...credit("used"), status: "redeemed" },
105 ],
106 }
107 : {
108 plan_type: "pro",
109 rate_limit: {
110 secondary_window: {
111 used_percent: 78,
112 reset_at: 4070908800,
113 limit_window_seconds: 604800,
114 },
115 },
116 },
117 };
118 return HttpClientResponse.fromWeb(
119 request,
120 Response.json({ status_code: upstream.status, body: encodeJson(upstream.body) }),
121 );
122 }),
123 );
124 return {
125 requests,
126 api: makeCliproxyApi.pipe(
127 Effect.provideService(HttpClient.HttpClient, http),
128 Effect.provide(NodeCrypto.layer),
129 ),
130 };
131}
132
133const unreachableHub = (
134 fail: (
135 request: Parameters<Parameters<typeof HttpClient.make>[0]>[0],
136 ) => HttpClientError.HttpClientError,
137) =>
138 makeCliproxyApi.pipe(
139 Effect.provideService(
140 HttpClient.HttpClient,
141 HttpClient.make((request) => Effect.fail(fail(request))),
142 ),
143 Effect.provide(NodeCrypto.layer),
144 );
145
146describe("CLIProxyAPI hub failures", () => {
147 it.effect("names the TLS code when the hub's certificate is not trusted", () =>
148 Effect.gen(function* () {
149 const api = yield* unreachableHub(
150 (request) =>
151 new HttpClientError.HttpClientError({
152 reason: new HttpClientError.TransportError({
153 request,
154 // Node's fetch wraps the TLS error, which carries the code, in a generic TypeError.
155 cause: new TypeError("fetch failed", {
156 cause: Object.assign(new Error("unable to get local issuer certificate"), {
157 code: "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
158 }),
159 }),
160 }),
161 }),
162 );
163 const error = yield* Effect.flip(api.readAccounts(config));
164 expect(error.detail).toContain("UNABLE_TO_GET_ISSUER_CERT_LOCALLY");
165 expect(error.detail).toContain("NODE_EXTRA_CA_CERTS");
166 }),
167 );
168
169 // regression: #18168 Limits hub failures name their TLS, HTTP, or timeout cause
170 it.effect("ignores a transport code that is not a short Node error code", () =>
171 Effect.gen(function* () {
172 const api = yield* unreachableHub(
173 (request) =>
174 new HttpClientError.HttpClientError({
175 reason: new HttpClientError.TransportError({
176 request,
177 cause: Object.assign(new Error("odd"), { code: "X".repeat(200) }),
178 }),
179 }),
180 );
181 const error = yield* Effect.flip(api.readAccounts(config));
182 expect(error.detail).toBe("The hub management request failed.");
183 }),
184 );
185
186 it.effect("names the status, not the body, when the hub rejects the request", () =>
187 Effect.gen(function* () {
188 const test = HttpClient.make((request) =>
189 Effect.succeed(
190 HttpClientResponse.fromWeb(
191 request,
192 Response.json({ error: "management-secret is wrong" }, { status: 401 }),
193 ),
194 ),
195 );
196 const api = yield* makeCliproxyApi.pipe(
197 Effect.provideService(HttpClient.HttpClient, test),
198 Effect.provide(NodeCrypto.layer),
199 );
200 const error = yield* Effect.flip(api.readAccounts(config));
201 expect(error.detail).toContain("401");
202 expect(error.detail).not.toContain("management-secret");
203 }),
204 );
205});
206
207describe("CLIProxyAPI built-in management API", () => {
208 it.effect(
209 "reads both accounts and their earliest unexpired credits without plugin endpoints",
210 () =>
211 Effect.gen(function* () {
212 yield* TestClock.setTime(1788710400000);
213 const test = fixture();
214 const api = yield* test.api;
215 const result = yield* api.readAccounts(config);
216 expect(result.map((account) => account.usageLimits.resetCredits)).toEqual([
217 { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
218 { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
219 ]);
220 expect(result[0]?.usageLimits.windows).toMatchObject([
221 { id: "secondary", usedPercent: 78, kind: "weekly" },
222 ]);
223 const calls = test.requests.filter((request) => request.body?.url);
224 expect(calls.map((request) => request.body?.auth_index).sort()).toEqual([
225 "a",
226 "a",
227 "b",
228 "b",
229 ]);
230 expect(
231 calls.find((request) => request.body?.auth_index === "b")?.body?.header?.[
232 "Chatgpt-Account-Id"
233 ],
234 ).toBe("account-b");
235 }),
236 );
237
238 it.effect("names the models the hub routes to each account, when the hub lists them", () =>
239 Effect.gen(function* () {
240 const test = fixture({
241 accounts: [...accounts, { ...accounts[1]!, id: "third.json", auth_index: "c" }],
242 models: (name) =>
243 name === "first.json"
244 ? Response.json({ models: [{ id: "gpt-5.6-sol" }, { id: " " }] })
245 : name === "third.json"
246 ? Response.json({ models: [] })
247 : Response.json({}, { status: 404 }),
248 });
249 const api = yield* test.api;
250 const result = yield* api.readAccounts(config);
251 expect(result.map((account) => account.models)).toEqual([["gpt-5.6-sol"], undefined, []]);
252 expect(result[1]?.usageLimits.windows).toHaveLength(1);
253 }),
254 );
255
256 it.effect("resolves a missing usage plan from current, then legacy, token plans", () =>
257 Effect.gen(function* () {
258 const test = fixture({
259 accounts: [
260 { ...accounts[0]!, id_token: { chatgpt_account_id: "account-a", plan_type: "free" } },
261 {
262 ...accounts[1]!,
263 id_token: {
264 chatgpt_account_id: "account-b",
265 plan_type: "go",
266 chatgpt_plan_type: "plus",
267 },
268 },
269 {
270 ...accounts[1]!,
271 id: "third.json",
272 auth_index: "c",
273 id_token: { chatgpt_account_id: "account-c", chatgpt_plan_type: "free" },
274 },
275 ],
276 upstream: (request) => ({
277 status: 200,
278 body: {
279 ...(request.auth_index === "a" ? { plan_type: "plus" } : {}),
280 rate_limit: { primary_window: { used_percent: 12 } },
281 },
282 }),
283 });
284 const api = yield* test.api;
285 const result = yield* api.readAccounts(config);
286 expect(result.map((account) => [account.plan, account.usageLimits.windows[0]?.kind])).toEqual(
287 [
288 ["ChatGPT Plus Subscription", "session"],
289 ["ChatGPT Go Subscription", "monthly"],
290 ["ChatGPT Free Subscription", "monthly"],
291 ],
292 );
293 }),
294 );
295
296 it.effect.each([
297 "https://tools.test/cliproxy",
298 "https://tools.test/cliproxy/",
299 "https://tools.test/cliproxy/management.html",
300 "https://tools.test/cliproxy/management.html/",
301 "https://tools.test/cliproxy/MANAGEMENT.HTML",
302 "https://tools.test/cliproxy/management.html?tab=accounts",
303 "https://tools.test/cliproxy/management.html#accounts",
304 "https://tools.test/cliproxy/management.html/?tab=accounts",
305 "https://tools.test/cliproxy/management.html/#accounts",
306 ])("keeps the path of a hub served under a prefix: %s", (url) =>
307 Effect.gen(function* () {
308 const test = fixture();
309 const api = yield* test.api;
310 yield* api.readAccounts({ ...config, url });
311 expect(test.requests.length).toBeGreaterThan(0);
312 expect(
313 test.requests.every((request) => request.path.startsWith("/cliproxy/v0/management/")),
314 ).toBe(true);
315 }),
316 );
317
318 it.effect("preserves a hub path that only ends with the panel filename", () =>
319 Effect.gen(function* () {
320 const test = fixture();
321 const api = yield* test.api;
322 yield* api.readAccounts({ ...config, url: "https://tools.test/team-management.html" });
323 expect(test.requests.length).toBeGreaterThan(0);
324 expect(
325 test.requests.every((request) =>
326 request.path.startsWith("/team-management.html/v0/management/"),
327 ),
328 ).toBe(true);
329 }),
330 );
331
332 it.effect("keeps usage when the credits endpoint fails", () =>
333 Effect.gen(function* () {
334 const test = fixture({
335 upstream: (request) =>
336 request.url?.endsWith("rate-limit-reset-credits")
337 ? { status: 503, body: { token: "do-not-publish" } }
338 : { status: 200, body: { rate_limit: { primary_window: { used_percent: 12 } } } },
339 });
340 const api = yield* test.api;
341 const result = yield* api.readAccounts(config);
342 expect(result[0]?.usageLimits.windows[0]?.usedPercent).toBe(12);
343 expect(result[0]?.usageLimits.resetCredits).toBeUndefined();
344 }),
345 );
346
347 it.effect("isolates a failed account and never publishes upstream error bodies", () =>
348 Effect.gen(function* () {
349 const test = fixture({
350 upstream: (request) =>
351 request.auth_index === "a"
352 ? { status: 401, body: { token: "do-not-publish" } }
353 : {
354 status: 200,
355 body: request.url?.endsWith("rate-limit-reset-credits")
356 ? { credits: [] }
357 : { rate_limit: { primary_window: { used_percent: 12 } } },
358 },
359 });
360 const api = yield* test.api;
361 const result = yield* api.readAccounts(config);
362 expect(result[0]?.usageLimits.unavailable).toEqual({
363 reason: "probeFailed",
364 message: "The provider refused the hub request (HTTP 401).",
365 });
366 expect(result[1]?.usageLimits.windows[0]?.usedPercent).toBe(12);
367 expect(encodeJson(result)).not.toContain("do-not-publish");
368 }),
369 );
370
371 it.effect("maps Claude scoped windows without a scheduler plugin", () =>
372 Effect.gen(function* () {
373 const test = fixture({
374 accounts: [{ ...accounts[0]!, provider: "claude" }],
375 // The usage endpoint answers 429 to requests without a Claude Code user agent.
376 upstream: (request) => ({
377 status: request.header?.["User-Agent"]?.startsWith("claude-code/") ? 200 : 429,
378 body: {
379 five_hour: { utilization: 10, resets_at: null },
380 seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" },
381 limits: [
382 {
383 kind: "weekly_scoped",
384 percent: 80,
385 resets_at: null,
386 scope: { model: { display_name: "Fable" } },
387 },
388 ],
389 },
390 }),
391 });
392 const api = yield* test.api;
393 const result = yield* api.readAccounts(config);
394 expect(
395 result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
396 ).toEqual([
397 ["five_hour", 10],
398 ["seven_day", 50],
399 ["seven_day_fable", 80],
400 ]);
401 }),
402 );
403
404 it.effect.each([
405 {
406 name: "spend budget",
407 budget: {
408 spend: {
409 enabled: true,
410 used: { amount_minor: 4_631, currency: "USD", exponent: 2 },
411 limit: { amount_minor: 50_000, currency: "USD", exponent: 2 },
412 },
413 },
414 },
415 {
416 name: "extra usage",
417 budget: {
418 extra_usage: {
419 is_enabled: true,
420 used_credits: 4_631,
421 monthly_limit: 50_000,
422 utilization: 9,
423 },
424 },
425 },
426 ])("keeps Claude monthly spend from $name beside rolling windows", ({ budget }) =>
427 Effect.gen(function* () {
428 const test = fixture({
429 accounts: [{ ...accounts[0]!, provider: "claude" }],
430 upstream: () => ({
431 status: 200,
432 body: { five_hour: { utilization: 10, resets_at: null }, ...budget },
433 }),
434 });
435 const result = yield* (yield* test.api).readAccounts(config);
436 expect(
437 result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
438 ).toEqual([
439 ["five_hour", 10],
440 ["monthly_spend", expect.closeTo(9.262, 10)],
441 ]);
442 }),
443 );
444
445 it.effect("omits disabled Claude budgets without losing rolling windows", () =>
446 Effect.gen(function* () {
447 const test = fixture({
448 accounts: [{ ...accounts[0]!, provider: "claude" }],
449 upstream: () => ({
450 status: 200,
451 body: {
452 five_hour: { utilization: 10, resets_at: null },
453 spend: { enabled: false, used: null, limit: null },
454 extra_usage: {
455 is_enabled: false,
456 used_credits: null,
457 monthly_limit: null,
458 utilization: null,
459 },
460 },
461 }),
462 });
463 const result = yield* (yield* test.api).readAccounts(config);
464 expect(result[0]?.usageLimits.windows.map((window) => window.id)).toEqual(["five_hour"]);
465 }),
466 );
467
468 it.effect("keeps a Claude account whose window reports no utilization", () =>
469 Effect.gen(function* () {
470 const test = fixture({
471 accounts: [{ ...accounts[0]!, provider: "claude" }],
472 upstream: () => ({
473 status: 200,
474 body: {
475 five_hour: { utilization: null, resets_at: null },
476 seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" },
477 },
478 }),
479 });
480 const result = yield* (yield* test.api).readAccounts(config);
481 expect(result[0]?.usageLimits.unavailable).toBeUndefined();
482 expect(
483 result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
484 ).toEqual([["seven_day", 50]]);
485 }),
486 );
487
488 const antigravitySummary = {
489 buckets: [
490 {
491 bucketId: "gemini-weekly",
492 window: "weekly",
493 remainingFraction: 0.75,
494 resetTime: "2099-01-01T00:00:00Z",
495 },
496 ],
497 };
498
499 it.effect("reads an xAI account as Grok with Grok CLI headers", () =>
500 Effect.gen(function* () {
501 const test = fixture({
502 accounts: [{ id: "xai.json", auth_index: "x", provider: "xai", email: "x@example.com" }],
503 upstream: () => ({
504 status: 200,
505 body: {
506 config: {
507 creditUsagePercent: 40,
508 currentPeriod: { type: "USAGE_PERIOD_TYPE_WEEKLY", end: "2099-01-01T00:00:00Z" },
509 },
510 },
511 }),
512 });
513 const [account] = yield* (yield* test.api).readAccounts(config);
514 expect(account).toMatchObject({ driver: "grok", email: "x@example.com" });
515 expect(account?.usageLimits.windows).toMatchObject([
516 { id: "subscription", kind: "weekly", usedPercent: 40 },
517 ]);
518 const call = test.requests.find((request) => request.body?.url)?.body;
519 expect(call?.method).toBe("GET");
520 expect(call?.url).toBe("https://cli-chat-proxy.grok.com/v1/billing?format=credits");
521 expect(call?.header).toMatchObject({
522 "x-xai-token-auth": "xai-grok-cli",
523 "x-grok-client-version": expect.any(String),
524 "User-Agent": expect.stringMatching(/^grok-cli\//),
525 });
526 }),
527 );
528
529 it.effect("reads an Antigravity summary and keys the account by its Google ID", () =>
530 Effect.gen(function* () {
531 const test = fixture({
532 accounts: [
533 {
534 id: "antigravity-g@example.com.json",
535 auth_index: "g",
536 provider: "antigravity",
537 email: "g@example.com",
538 project_id: "project-7",
539 },
540 ],
541 upstream: (request) => ({
542 status: 200,
543 body: request.url?.endsWith("/userinfo") ? { id: "google-42" } : antigravitySummary,
544 }),
545 });
546 const [account] = yield* (yield* test.api).readAccounts(config);
547 expect(account?.driver).toBe("antigravity");
548 expect(account?.email).toBeUndefined();
549 expect(account?.usageLimits.credentialFingerprint).toBe(
550 // sha256("google-account\0google-42"), as a local Antigravity probe reports it.
551 "136d4952771fd67a3600053f37492cbd05828712e0b1c89ebab03d4c22ab6554",
552 );
553 expect(account?.usageLimits.windows).toMatchObject([
554 { id: "gemini-weekly", kind: "weekly", usedPercent: 25 },
555 ]);
556 const summary = test.requests.find((request) => request.body?.method === "POST")?.body;
557 expect(summary?.url).toBe(
558 "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary",
559 );
560 expect(summary?.data).toBe(encodeJson({ project: "project-7" }));
561 expect(summary).toMatchObject({
562 auth_index: "g",
563 method: "POST",
564 header: {
565 Authorization: "Bearer $TOKEN$",
566 "Content-Type": "application/json",
567 "User-Agent":
568 "antigravity/hub/2.24.0 (aidev_client; os_type=linux; arch=x64; cl=963137146)",
569 },
570 });
571 const identityCalls = test.requests.filter((request) =>
572 request.body?.url?.endsWith("/userinfo"),
573 );
574 expect(identityCalls).toHaveLength(1);
575 expect(identityCalls[0]?.body).toMatchObject({
576 method: "GET",
577 url: "https://www.googleapis.com/oauth2/v2/userinfo",
578 header: { Authorization: "Bearer $TOKEN$" },
579 });
580 }).pipe(
581 Effect.provideService(HostProcess.Platform, "linux"),
582 Effect.provideService(HostProcess.Architecture, "x64"),
583 ),
584 );
585
586 it.effect("keeps Antigravity limits and listing email when its identity read fails", () =>
587 Effect.gen(function* () {
588 const test = fixture({
589 accounts: [
590 {
591 id: "antigravity.json",
592 auth_index: "g",
593 provider: "antigravity",
594 email: "g@example.com",
595 project_id: "project-7",
596 },
597 ],
598 upstream: (request) =>
599 request.url?.endsWith("/userinfo")
600 ? { status: 403, body: { error: "denied" } }
601 : {
602 status: 200,
603 body: antigravitySummary,
604 },
605 });
606 const result = yield* (yield* test.api).readAccounts(config);
607 expect(result).toHaveLength(1);
608 const [account] = result;
609 expect(account).toMatchObject({ driver: "antigravity", email: "g@example.com" });
610 expect(account?.usageLimits.credentialFingerprint).toBeUndefined();
611 expect(account?.usageLimits.unavailable).toBeUndefined();
612 expect(account?.usageLimits.windows).toMatchObject([
613 { id: "gemini-weekly", kind: "weekly", usedPercent: 25 },
614 ]);
615 }),
616 );
617
618 it.effect.each([
619 { name: "a refused xAI call", provider: "xai", status: 403, body: { error: "denied" } },
620 { name: "a malformed xAI answer", provider: "xai", status: 200, body: { config: "x" } },
621 { name: "a refused Antigravity call", provider: "antigravity", status: 401, body: {} },
622 { name: "a malformed Antigravity answer", provider: "antigravity", status: 200, body: [] },
623 { name: "an empty Antigravity summary", provider: "antigravity", status: 200, body: {} },
624 ])("reports $name as unreadable", ({ provider, status, body }) =>
625 Effect.gen(function* () {
626 const test = fixture({
627 accounts: [{ id: `${provider}.json`, auth_index: "a", provider, project_id: "project-7" }],
628 upstream: () => ({ status, body }),
629 });
630 const [account] = yield* (yield* test.api).readAccounts(config);
631 expect(account?.usageLimits.unavailable?.reason).toBe("probeFailed");
632 }),
633 );
634
635 it.effect.each([undefined, "", " "])(
636 "rejects a missing or blank Antigravity project (%s) before upstream calls",
637 (project_id) =>
638 Effect.gen(function* () {
639 const test = fixture({
640 accounts: [
641 {
642 id: "antigravity.json",
643 auth_index: "a",
644 provider: "antigravity",
645 ...(project_id === undefined ? {} : { project_id }),
646 },
647 ],
648 });
649 const [account] = yield* (yield* test.api).readAccounts(config);
650 expect(account?.usageLimits.unavailable?.reason).toBe("probeFailed");
651 expect(test.requests.map((request) => request.path)).not.toContain(
652 "/v0/management/api-call",
653 );
654 }),
655 );
656
657 it.effect("skips accounts of providers the hub table does not know", () =>
658 Effect.gen(function* () {
659 const test = fixture({
660 accounts: [
661 { id: "kiro.json", auth_index: "k", provider: "kiro", email: "k@example.com" },
662 { ...accounts[0]!, provider: "claude" },
663 ],
664 upstream: () => ({ status: 200, body: { five_hour: { utilization: 1, resets_at: null } } }),
665 });
666 const result = yield* (yield* test.api).readAccounts(config);
667 expect(result.map((account) => account.driver)).toEqual(["claudeAgent"]);
668 expect(test.requests.map((request) => request.body?.auth_index)).not.toContain("k");
669 }),
670 );
671
672 it.effect("pins redemption to the displayed credit and clears only that account's cooldown", () =>
673 Effect.gen(function* () {
674 const test = fixture();
675 const api = yield* test.api;
676 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
677 expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
678 const redemptions = test.requests.filter((request) =>
679 request.body?.url?.endsWith("/consume"),
680 );
681 expect(redemptions).toHaveLength(2);
682 expect(redemptions[0]?.body?.data).toBe(redemptions[1]?.body?.data);
683 expect(redemptions[0]?.body?.data).toBe(
684 encodeJson({
685 redeem_request_id: "519d5243-011a-5b7b-91f3-44d85f095705",
686 credit_id: "credit-b",
687 }),
688 );
689 expect(
690 test.requests
691 .filter((request) => request.path.endsWith("/reset-quota"))
692 .map((request) => request.body?.auth_index),
693 ).toEqual(["b", "b"]);
694 }),
695 );
696
697 it.effect("reports redemption success even if cooldown clearing fails", () =>
698 Effect.gen(function* () {
699 const api = yield* fixture({ cooldownStatus: 404 }).api;
700 const result = yield* api.consume(config, "first.json", "credit");
701 expect(result.outcome).toBe("reset");
702 expect(result.warning).toContain("cooldown");
703 }),
704 );
705
706 it.effect("skips disabled accounts and rejects redemption on them", () =>
707 Effect.gen(function* () {
708 const test = fixture({ accounts: [{ ...accounts[0]!, disabled: true }] });
709 const api = yield* test.api;
710 expect(yield* api.readAccounts(config)).toEqual([]);
711 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
712 "Failure",
713 );
714 expect(test.requests.every((request) => request.path.endsWith("/auth-files"))).toBe(true);
715 }),
716 );
717
718 it.effect("keeps the same redemption id after an uncertain upstream failure", () =>
719 Effect.gen(function* () {
720 let attempts = 0;
721 const test = fixture({
722 upstream: () =>
723 ++attempts === 1
724 ? { status: 503, body: {} }
725 : { status: 200, body: { code: "already_redeemed" } },
726 });
727 const api = yield* test.api;
728 expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
729 "Failure",
730 );
731 expect(yield* api.consume(config, "first.json", "credit")).toEqual({
732 outcome: "alreadyRedeemed",
733 });
734 const data = test.requests
735 .filter((request) => request.body?.url?.endsWith("/consume"))
736 .map((request) => request.body?.data);
737 expect(data[0]).toBe(data[1]);
738 expect(test.requests.filter((request) => request.path.endsWith("/reset-quota"))).toHaveLength(
739 1,
740 );
741 }),
742 );
743
744 it.effect("rejects unknown accounts without forwarding a redemption", () =>
745 Effect.gen(function* () {
746 const test = fixture();
747 const api = yield* test.api;
748 const result = yield* api.consume(config, "missing.json", "credit").pipe(Effect.result);
749 expect(result._tag).toBe("Failure");
750 expect(test.requests).toHaveLength(1);
751 }),
752 );
753});