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

serverUsage.test.ts

336 lines11.5 KB

1import {
2 DEFAULT_SERVER_SETTINGS,
3 EnvironmentId,
4 UsageDay,
5 UsageReadError,
6 USAGE_CONTRACT_VERSION,
7 WS_METHODS,
8 type ServerConfig,
9 type ServerConfigStreamEvent,
10 ServerSettings,
11 type UsageSource,
12 type UsageSummary,
13 type UsageSummaryInput,
14} from "@t3tools/contracts";
15import { expect, it } from "@effect/vitest";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Queue from "effect/Queue";
21import * as Result from "effect/Result";
22import * as Schema from "effect/Schema";
23import * as Stream from "effect/Stream";
24import * as SubscriptionRef from "effect/SubscriptionRef";
25import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
26​
27import {
28 AVAILABLE_CONNECTION_STATE,
29 PrimaryConnectionTarget,
30 type PreparedConnection,
31 type SupervisorConnectionState,
32} from "../connection/model.ts";
33import * as EnvironmentRegistry from "../connection/registry.ts";
34import * as EnvironmentSupervisor from "../connection/supervisor.ts";
35import * as Persistence from "../platform/persistence.ts";
36import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
37import type { RpcSession } from "../rpc/session.ts";
38import { createServerEnvironmentAtoms } from "./server.ts";
39​
40const TARGET = new PrimaryConnectionTarget({
41 environmentId: EnvironmentId.make("usage-environment"),
42 label: "Usage environment",
43 httpBaseUrl: "https://environment.example.test",
44 wsBaseUrl: "wss://environment.example.test",
45});
46​
47const INPUT: UsageSummaryInput = {
48 sinceDay: UsageDay.make("2026-09-01"),
49 untilDay: UsageDay.make("2026-09-04"),
50 timeZone: "UTC",
51};
52​
53const CONFIG = {
54 settings: DEFAULT_SERVER_SETTINGS,
55 environment: { serverVersion: "0.0.1", capabilities: {} },
56} as ServerConfig;
57​
58const PRICING = { status: "unavailable" as const, source: "test", fetchedAt: null, knownModels: 0 };
59​
60const cursorSource = (refreshing: boolean): UsageSource => ({
61 fingerprint: {
62 hostId: "cursor.com",
63 provider: "cursor",
64 resolvedHomePath: "cursor-account:abc",
65 volumeId: "abc",
66 },
67 status: "ok",
68 scannedFiles: 1,
69 skippedFiles: 0,
70 malformedRecords: 0,
71 distinctSessions: 1,
72 message: null,
73 ...(refreshing ? { refreshing: true as const } : {}),
74});
75​
76const sameServerSettings = Schema.toEquivalence(ServerSettings);
77​
78const makeHarness = Effect.fn("ServerUsageTest.makeHarness")(function* (
79 beforeRead: (
80 request: number,
81 input: UsageSummaryInput,
82 ) => Effect.Effect<void, UsageReadError> = () => Effect.void,
83 sources: (input: UsageSummaryInput) => readonly UsageSource[] = () => [],
84) {
85 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
86 let settings = DEFAULT_SERVER_SETTINGS;
87 let requests = 0;
88 const inputs: UsageSummaryInput[] = [];
89 const client = {
90 [WS_METHODS.serverRefreshUsageRates]: () => Effect.succeed(PRICING),
91 [WS_METHODS.subscribeServerConfig]: () =>
92 Stream.concat(
93 Stream.make({ version: 1 as const, type: "snapshot" as const, config: CONFIG }),
94 Stream.fromQueue(events),
95 ),
96 [WS_METHODS.serverGetUsageSummary]: (input: UsageSummaryInput) =>
97 Effect.gen(function* () {
98 requests += 1;
99 inputs.push(input);
100 const price = settings.usagePriceOverrides["custom-model"]?.inputCostPerMillionTokens ?? 0;
101 yield* beforeRead(requests, input);
102 return {
103 contractVersion: USAGE_CONTRACT_VERSION,
104 readAt: "2026-09-04T12:00:00Z",
105 ...input,
106 buckets: [
107 {
108 day: input.sinceDay,
109 provider: "codex",
110 model: "custom-model",
111 totals: {
112 uncachedInputTokens: 1_000_000,
113 cachedInputTokens: 0,
114 cacheCreationTokens: 0,
115 outputTokens: 0,
116 reasoningTokens: 0,
117 },
118 costUsd: price,
119 cacheSavingsUsd: 0,
120 costSource: price === 0 ? "unpriced" : "modelPriced",
121 records: 1,
122 unpricedRecords: price === 0 ? 1 : 0,
123 sessions: 1,
124 },
125 ],
126 sources: sources(input),
127 pricing: PRICING,
128 scanDurationMs: 0,
129 } satisfies UsageSummary;
130 }),
131 } as unknown as WsRpcProtocolClient;
132 const session: RpcSession = {
133 client,
134 initialConfig: Effect.succeed(CONFIG),
135 subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input),
136 ready: Effect.void,
137 probe: Effect.void,
138 inboundFrames: Effect.succeed(0),
139 awaitingReply: Effect.succeed(false),
140 closed: Effect.never,
141 };
142 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
143 target: TARGET,
144 state: yield* SubscriptionRef.make<SupervisorConnectionState>({
145 ...AVAILABLE_CONNECTION_STATE,
146 phase: "connected",
147 }),
148 session: yield* SubscriptionRef.make(Option.some(session)),
149 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
150 connect: Effect.void,
151 disconnect: Effect.void,
152 retryNow: Effect.void,
153 });
154 const environments = EnvironmentRegistry.EnvironmentRegistry.of({
155 run: (_environmentId, effect) =>
156 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
157 followStream: (_environmentId, stream) =>
158 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
159 } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
160 const cache = Persistence.EnvironmentCacheStore.of({
161 loadShell: () => Effect.succeedNone,
162 saveShell: () => Effect.void,
163 loadThread: () => Effect.succeedNone,
164 saveThread: () => Effect.void,
165 removeThread: () => Effect.void,
166 loadServerConfig: () => Effect.succeedNone,
167 saveServerConfig: () => Effect.void,
168 loadVcsRefs: () => Effect.succeedNone,
169 saveVcsRefs: () => Effect.void,
170 removeVcsRefs: () => Effect.void,
171 clearVcsRefs: () => Effect.void,
172 clear: () => Effect.void,
173 });
174 const runtime = Atom.runtime(
175 Layer.merge(
176 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environments),
177 Layer.succeed(Persistence.EnvironmentCacheStore, cache),
178 ),
179 );
180 const initialConfigValueAtom = Atom.make(CONFIG);
181 const atoms = createServerEnvironmentAtoms(runtime, {
182 initialConfigValueAtom: () => initialConfigValueAtom,
183 });
184 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
185 Effect.sync(() => registry.dispose()),
186 );
187 const updateSettings = Effect.fn("ServerUsageTest.updateSettings")(function* (
188 next: ServerSettings,
189 ) {
190 settings = next;
191 yield* Queue.offer(events, {
192 version: 1,
193 type: "settingsUpdated",
194 payload: { settings },
195 });
196 // An equal settings document keeps the previous object, so match on content.
197 yield* AtomRegistry.toStream(registry, atoms.settingsValueAtom(TARGET.environmentId)).pipe(
198 Stream.filter((current) => current !== null && sameServerSettings(current, next)),
199 Stream.runHead,
200 );
201 });
202 return {
203 registry,
204 atoms,
205 requests: () => requests,
206 inputs: () => inputs,
207 updateSettings,
208 summary: (input = INPUT) => atoms.usageSummary({ environmentId: TARGET.environmentId, input }),
209 };
210});
211​
212function settledSummary<E>(
213 registry: AtomRegistry.AtomRegistry,
214 atom: Atom.Atom<AsyncResult.AsyncResult<UsageSummary, E>>,
215) {
216 return AtomRegistry.toStream(registry, atom).pipe(
217 Stream.filterMap((result) =>
218 AsyncResult.isSuccess(result) && !result.waiting
219 ? Result.succeed(result.value)
220 : Result.failVoid,
221 ),
222 Stream.runHead,
223 Effect.map(Option.getOrThrow),
224 );
226​
227const makeRefreshingHarness = Effect.fn("ServerUsageTest.makeRefreshingHarness")(function* (
228 followUp: Effect.Effect<void, UsageReadError>,
229) {
230 const followUpStarted = yield* Deferred.make<void>();
231 const harness = yield* makeHarness(
232 (_request, input) =>
233 input.awaitRefresh === true
234 ? Deferred.succeed(followUpStarted, undefined).pipe(Effect.andThen(followUp))
235 : Effect.void,
236 // The saved answer differs from the plain one, so a test can tell which was kept.
237 (input) => [
238 {
239 ...cursorSource(input.awaitRefresh !== true),
240 ...(input.provisional === true ? { scannedFiles: 0 } : {}),
241 },
242 ],
243 );
244 return { ...harness, followUpStarted };
245});
246​
247function waitForCost<E>(
248 registry: AtomRegistry.AtomRegistry,
249 atom: Atom.Atom<AsyncResult.AsyncResult<UsageSummary, E>>,
250 cost: number,
251) {
252 return AtomRegistry.toStream(registry, atom).pipe(
253 Stream.filter(
254 (result) =>
255 AsyncResult.isSuccess(result) &&
256 !result.waiting &&
257 result.value.buckets[0]?.costUsd === cost,
258 ),
259 Stream.runHead,
260 );
262​
263it.effect("restarts a pending usage read after a price change", () =>
264 Effect.gen(function* () {
265 const started = yield* Deferred.make<void>();
266 const interrupted = yield* Deferred.make<void>();
267 const harness = yield* makeHarness((request) =>
268 request === 1
269 ? Deferred.succeed(started, undefined).pipe(
270 Effect.andThen(Effect.never),
271 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
272 )
273 : Effect.void,
274 );
275 const summary = harness.summary();
276 const unmount = harness.registry.mount(summary);
277 yield* Deferred.await(started);
278 yield* harness.updateSettings({
279 ...DEFAULT_SERVER_SETTINGS,
280 usagePriceOverrides: {
281 "custom-model": { inputCostPerMillionTokens: 5, outputCostPerMillionTokens: 10 },
282 },
283 });
284 yield* waitForCost(harness.registry, summary, 5);
285 yield* Deferred.await(interrupted);
286 expect(harness.requests()).toBe(2);
287 unmount();
288 }),
289);
290​
291it.effect("keeps the cached usage summary when the awaited refresh fails", () =>
292 Effect.gen(function* () {
293 const harness = yield* makeRefreshingHarness(
294 Effect.fail(new UsageReadError({ reason: "scanFailed", detail: "Cursor is down" })),
295 );
296 const summary = harness.summary();
297 const unmount = harness.registry.mount(summary);
298 expect((yield* settledSummary(harness.registry, summary)).sources).toEqual([
299 cursorSource(true),
300 ]);
301 expect(AsyncResult.isSuccess(harness.registry.get(summary))).toBe(true);
302 // The saved answer is followed by a plain read before the one that waits for Cursor.
303 expect(
304 harness.inputs().map(({ provisional, awaitRefresh }) => ({ provisional, awaitRefresh })),
305 ).toEqual([
306 { provisional: true, awaitRefresh: undefined },
307 { provisional: undefined, awaitRefresh: undefined },
308 { provisional: undefined, awaitRefresh: true },
309 ]);
310 // With figures on screen, a refresh reads them exactly instead of asking for saved ones.
311 yield* harness.updateSettings({
312 ...DEFAULT_SERVER_SETTINGS,
313 usagePriceOverrides: {
314 "custom-model": { inputCostPerMillionTokens: 5, outputCostPerMillionTokens: 10 },
315 },
316 });
317 yield* waitForCost(harness.registry, summary, 5);
318 expect(harness.inputs()[3]?.provisional).toBeUndefined();
319 unmount();
320 }),
321);
322​
323it.effect("reads usage in full when the saved answer cannot be read", () =>
324 Effect.gen(function* () {
325 const harness = yield* makeHarness((_request, input) =>
326 input.provisional === true
327 ? Effect.fail(new UsageReadError({ reason: "scanFailed", detail: "saved scan unreadable" }))
328 : Effect.void,
329 );
330 const summary = harness.summary();
331 const unmount = harness.registry.mount(summary);
332 yield* settledSummary(harness.registry, summary);
333 expect(harness.inputs().map(({ provisional }) => provisional)).toEqual([true, undefined]);
334 unmount();
335 }),
336);