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

UsageService.test.ts

128 lines4.6 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import { expect, it } from "@effect/vitest";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as NodeCrypto from "node:crypto";
5import * as NodeFS from "node:fs";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8import { UsageDay, type UsageSummaryInput } from "@t3tools/contracts";
9import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Schema from "effect/Schema";
13import * as TestClock from "effect/testing/TestClock";
14import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
15​
16import * as ServerConfig from "../config.ts";
17import * as ServerSettings from "../serverSettings.ts";
18import * as UsageService from "./UsageService.ts";
19​
20/**
21 * Two tiny documents so the rate table sizes are assertable: two LiteLLM
22 * models and two models.dev go/zen models.
23 */
24const LITELLM_DOC = {
25 "claude-fable-5": { input_cost_per_token: 1e-5, output_cost_per_token: 5e-5 },
26 "claude-opus-5": { input_cost_per_token: 5e-5, output_cost_per_token: 2.5e-4 },
27};
28​
29const MODELS_DEV_DOC = {
30 "opencode-go": {
31 models: { "deepseek-v4-flash": { cost: { input: 0.07, output: 0.14 } } },
32 },
33 opencode: {
34 models: { "deepseek-v4-flash-free": { cost: { input: 0, output: 0 } } },
35 },
36};
37​
38/**
39 * Routes the two rate-table fetches, with the models.dev endpoint failing on
40 * its first call. That makes the two sources refresh on different clocks,
41 * which is the setup the served-table bug needed: LiteLLM refreshes while the
42 * still-fresh models.dev overlay would have been skipped.
43 */
44function makeFakeHttpClient(): {
45 readonly client: HttpClient.HttpClient;
46 readonly modelsDevCalls: () => number;
47} {
48 let modelsDevCalls = 0;
49 const json = (request: HttpClientRequest.HttpClientRequest, body: unknown) =>
50 HttpClientResponse.fromWeb(
51 request,
52 new Response(JSON.stringify(body), {
53 status: 200,
54 headers: { "content-type": "application/json" },
55 }),
56 );
57​
58 return {
59 client: HttpClient.make((request) =>
60 Effect.sync(() => {
61 if (request.url.includes("litellm")) return json(request, LITELLM_DOC);
62 modelsDevCalls += 1;
63 if (modelsDevCalls === 1) {
64 return HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 502 }));
65 }
66 return json(request, MODELS_DEV_DOC);
67 }),
68 ),
69 modelsDevCalls: () => modelsDevCalls,
70 };
72​
73const INPUT: UsageSummaryInput = {
74 sinceDay: Schema.decodeSync(UsageDay)("2026-08-01"),
75 untilDay: Schema.decodeSync(UsageDay)("2026-08-31"),
76 timeZone: "UTC",
77};
78​
79function tempDir(prefix: string): string {
80 const path = NodePath.join(NodeOS.tmpdir(), `${prefix}-${NodeCrypto.randomUUID()}`);
81 NodeFS.mkdirSync(path, { recursive: true });
82 return path;
84​
85it.effect("keeps the models.dev overlay when only the LiteLLM table expires", () => {
86 const { client, modelsDevCalls } = makeFakeHttpClient();
87 // Point every provider transcript home at a path that does not exist so the
88 // scan touches no real data; the assertions only read `knownModels`.
89 const missingHome = tempDir("usage-missing");
90 const base = tempDir("usage-base");
91 const cwd = tempDir("usage-cwd");
92​
93 return Effect.gen(function* () {
94 const usage = yield* UsageService.make;
95​
96 // First scan: LiteLLM loads, models.dev fails -> no overlay yet.
97 const first = yield* usage.readSummary(INPUT);
98 expect(first.pricing.knownModels).toBe(2);
99​
100 // models.dev comes back on the next scan, while LiteLLM is still fresh.
101 yield* TestClock.adjust(Duration.hours(1));
102 const second = yield* usage.readSummary(INPUT);
103 expect(second.pricing.knownModels).toBe(4);
104​
105 // Advance past the LiteLLM TTL (24h) but not the models.dev TTL, so a
106 // fresh LiteLLM copy is served while the models.dev overlay stays cached.
107 yield* TestClock.adjust(Duration.hours(23));
108 const third = yield* usage.readSummary(INPUT);
109 // Regression: before the fix the served table was the LiteLLM copy alone.
110 expect(third.pricing.knownModels).toBe(4);
111 expect(modelsDevCalls()).toBe(2);
112​
113 return true;
114 }).pipe(
115 Effect.provideService(HttpClient.HttpClient, client),
116 Effect.provideService(HostProcessEnvironment, { OPENCODE_DATA_DIR: missingHome }),
117 Effect.provide(ServerConfig.layerTest(cwd, base)),
118 Effect.provide(
119 ServerSettings.layerTest({
120 providers: {
121 codex: { homePath: missingHome },
122 claudeAgent: { homePath: missingHome },
123 },
124 }),
125 ),
126 Effect.provide(NodeServices.layer),
127 );
128});