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

serverUsage.test.ts

263 lines9.3 KB

1import {
2 DEFAULT_SERVER_SETTINGS,
3 EnvironmentId,
4 UsageDay,
5 USAGE_CONTRACT_VERSION,
6 WS_METHODS,
7 type ServerConfig,
8 type ServerConfigStreamEvent,
9 type ServerSettings,
10 type UsageSummary,
11 type UsageSummaryInput,
12} from "@t3tools/contracts";
13import { expect, it } from "@effect/vitest";
14import * as Deferred from "effect/Deferred";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Queue from "effect/Queue";
19import * as Stream from "effect/Stream";
20import * as SubscriptionRef from "effect/SubscriptionRef";
21import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
22​
23import {
24 AVAILABLE_CONNECTION_STATE,
25 PrimaryConnectionTarget,
26 type PreparedConnection,
27 type SupervisorConnectionState,
28} from "../connection/model.ts";
29import * as EnvironmentRegistry from "../connection/registry.ts";
30import * as EnvironmentSupervisor from "../connection/supervisor.ts";
31import * as Persistence from "../platform/persistence.ts";
32import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
33import type { RpcSession } from "../rpc/session.ts";
34import { createServerEnvironmentAtoms } from "./server.ts";
35​
36const TARGET = new PrimaryConnectionTarget({
37 environmentId: EnvironmentId.make("usage-environment"),
38 label: "Usage environment",
39 httpBaseUrl: "https://environment.example.test",
40 wsBaseUrl: "wss://environment.example.test",
41});
42​
43const INPUT: UsageSummaryInput = {
44 sinceDay: UsageDay.make("2026-09-01"),
45 untilDay: UsageDay.make("2026-09-04"),
46 timeZone: "UTC",
47};
48​
49const CONFIG = {
50 settings: DEFAULT_SERVER_SETTINGS,
51 environment: { serverVersion: "0.0.1", capabilities: {} },
52} as ServerConfig;
53​
54const makeHarness = Effect.fn("ServerUsageTest.makeHarness")(function* (
55 beforeRead: (request: number) => Effect.Effect<void> = () => Effect.void,
56) {
57 const events = yield* Queue.unbounded<ServerConfigStreamEvent>();
58 let settings = DEFAULT_SERVER_SETTINGS;
59 let requests = 0;
60 const client = {
61 [WS_METHODS.subscribeServerConfig]: () =>
62 Stream.concat(
63 Stream.make({ version: 1 as const, type: "snapshot" as const, config: CONFIG }),
64 Stream.fromQueue(events),
65 ),
66 [WS_METHODS.serverGetUsageSummary]: (input: UsageSummaryInput) =>
67 Effect.gen(function* () {
68 requests += 1;
69 const price = settings.usagePriceOverrides["custom-model"]?.inputCostPerMillionTokens ?? 0;
70 yield* beforeRead(requests);
71 return {
72 contractVersion: USAGE_CONTRACT_VERSION,
73 readAt: "2026-09-04T12:00:00Z",
74 ...input,
75 buckets: [
76 {
77 day: input.sinceDay,
78 provider: "codex",
79 model: "custom-model",
80 totals: {
81 uncachedInputTokens: 1_000_000,
82 cachedInputTokens: 0,
83 cacheCreationTokens: 0,
84 outputTokens: 0,
85 reasoningTokens: 0,
86 },
87 costUsd: price,
88 cacheSavingsUsd: 0,
89 costSource: price === 0 ? "unpriced" : "modelPriced",
90 records: 1,
91 unpricedRecords: price === 0 ? 1 : 0,
92 sessions: 1,
93 },
94 ],
95 sources: [],
96 pricing: { status: "unavailable", source: "test", fetchedAt: null, knownModels: 0 },
97 scanDurationMs: 0,
98 } satisfies UsageSummary;
99 }),
100 } as unknown as WsRpcProtocolClient;
101 const session: RpcSession = {
102 client,
103 initialConfig: Effect.succeed(CONFIG),
104 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
105 ready: Effect.void,
106 probe: Effect.void,
107 closed: Effect.never,
108 };
109 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
110 target: TARGET,
111 state: yield* SubscriptionRef.make<SupervisorConnectionState>({
112 ...AVAILABLE_CONNECTION_STATE,
113 phase: "connected",
114 }),
115 session: yield* SubscriptionRef.make(Option.some(session)),
116 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
117 connect: Effect.void,
118 disconnect: Effect.void,
119 retryNow: Effect.void,
120 });
121 const environments = EnvironmentRegistry.EnvironmentRegistry.of({
122 run: (_environmentId, effect) =>
123 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
124 followStream: (_environmentId, stream) =>
125 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
126 } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
127 const cache = Persistence.EnvironmentCacheStore.of({
128 loadShell: () => Effect.succeedNone,
129 saveShell: () => Effect.void,
130 loadThread: () => Effect.succeedNone,
131 saveThread: () => Effect.void,
132 removeThread: () => Effect.void,
133 loadServerConfig: () => Effect.succeedNone,
134 saveServerConfig: () => Effect.void,
135 loadVcsRefs: () => Effect.succeedNone,
136 saveVcsRefs: () => Effect.void,
137 removeVcsRefs: () => Effect.void,
138 clearVcsRefs: () => Effect.void,
139 clear: () => Effect.void,
140 });
141 const runtime = Atom.runtime(
142 Layer.merge(
143 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environments),
144 Layer.succeed(Persistence.EnvironmentCacheStore, cache),
145 ),
146 );
147 const initialConfigValueAtom = Atom.make(CONFIG);
148 const atoms = createServerEnvironmentAtoms(runtime, {
149 initialConfigValueAtom: () => initialConfigValueAtom,
150 });
151 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
152 Effect.sync(() => registry.dispose()),
153 );
154 const updateSettings = Effect.fn("ServerUsageTest.updateSettings")(function* (
155 next: ServerSettings,
156 ) {
157 settings = next;
158 yield* Queue.offer(events, {
159 version: 1,
160 type: "settingsUpdated",
161 payload: { settings },
162 });
163 yield* AtomRegistry.toStream(registry, atoms.settingsValueAtom(TARGET.environmentId)).pipe(
164 Stream.filter((current) => current === next),
165 Stream.runHead,
166 );
167 });
168 return {
169 registry,
170 requests: () => requests,
171 updateSettings,
172 summary: (input = INPUT) => atoms.usageSummary({ environmentId: TARGET.environmentId, input }),
173 };
174});
175​
176function waitForCost<E>(
177 registry: AtomRegistry.AtomRegistry,
178 atom: Atom.Atom<AsyncResult.AsyncResult<UsageSummary, E>>,
179 cost: number,
180) {
181 return AtomRegistry.toStream(registry, atom).pipe(
182 Stream.filter(
183 (result) =>
184 AsyncResult.isSuccess(result) &&
185 !result.waiting &&
186 result.value.buckets[0]?.costUsd === cost,
187 ),
188 Stream.runHead,
189 );
191​
192it.effect("refreshes cached usage windows only when override prices change", () =>
193 Effect.scoped(
194 Effect.gen(function* () {
195 const harness = yield* makeHarness();
196 const current = harness.summary();
197 const previous = harness.summary({ ...INPUT, sinceDay: UsageDay.make("2026-08-01") });
198 const unmountCurrent = harness.registry.mount(current);
199 const unmountPrevious = harness.registry.mount(previous);
200 yield* waitForCost(harness.registry, current, 0);
201 yield* waitForCost(harness.registry, previous, 0);
202 unmountPrevious();
203 expect(harness.requests()).toBe(2);
204​
205 const prices = {
206 "custom-model": { inputCostPerMillionTokens: 3, outputCostPerMillionTokens: 9 },
207 "other-model": { inputCostPerMillionTokens: 1, outputCostPerMillionTokens: 2 },
208 };
209 yield* harness.updateSettings({ ...DEFAULT_SERVER_SETTINGS, usagePriceOverrides: prices });
210 yield* waitForCost(harness.registry, current, 3);
211 yield* waitForCost(harness.registry, previous, 3);
212 expect(harness.requests()).toBe(4);
213​
214 yield* harness.updateSettings({
215 ...DEFAULT_SERVER_SETTINGS,
216 usagePriceOverrides: {
217 "other-model": { outputCostPerMillionTokens: 2, inputCostPerMillionTokens: 1 },
218 "custom-model": { outputCostPerMillionTokens: 9, inputCostPerMillionTokens: 3 },
219 },
220 });
221 yield* harness.updateSettings({
222 ...DEFAULT_SERVER_SETTINGS,
223 usagePriceOverrides: prices,
224 defaultTheme: "custom-theme",
225 });
226 yield* harness.updateSettings(DEFAULT_SERVER_SETTINGS);
227 yield* waitForCost(harness.registry, current, 0);
228 yield* waitForCost(harness.registry, previous, 0);
229 expect(harness.requests()).toBe(6);
230 unmountCurrent();
231 }),
232 ),
233);
234​
235it.effect("restarts a pending usage read after a price change", () =>
236 Effect.scoped(
237 Effect.gen(function* () {
238 const started = yield* Deferred.make<void>();
239 const interrupted = yield* Deferred.make<void>();
240 const harness = yield* makeHarness((request) =>
241 request === 1
242 ? Deferred.succeed(started, undefined).pipe(
243 Effect.andThen(Effect.never),
244 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
245 )
246 : Effect.void,
247 );
248 const summary = harness.summary();
249 const unmount = harness.registry.mount(summary);
250 yield* Deferred.await(started);
251 yield* harness.updateSettings({
252 ...DEFAULT_SERVER_SETTINGS,
253 usagePriceOverrides: {
254 "custom-model": { inputCostPerMillionTokens: 5, outputCostPerMillionTokens: 10 },
255 },
256 });
257 yield* waitForCost(harness.registry, summary, 5);
258 yield* Deferred.await(interrupted);
259 expect(harness.requests()).toBe(2);
260 unmount();
261 }),
262 ),
263);