Open History to see the last commit
1import {
2 EnvironmentId,
3 UsageDay,
4 USAGE_CONTRACT_VERSION,
5 type UsageSummary,
6} from "@t3tools/contracts";
7import * as Effect from "effect/Effect";
8import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
9import { afterEach, describe, expect, it } from "vite-plus/test";
10
11import type { EnvironmentPresentation } from "../connection/presentation.ts";
12import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
13import { refreshUsage } from "./usage.ts";
14
15const input = {
16 sinceDay: UsageDay.make("2026-09-05"),
17 untilDay: UsageDay.make("2026-09-05"),
18 timeZone: "UTC",
19};
20const pricing = { status: "fresh" as const, source: "test", fetchedAt: null, knownModels: 1 };
21const summary: UsageSummary = {
22 ...input,
23 contractVersion: USAGE_CONTRACT_VERSION,
24 readAt: "2026-09-05T12:00:00Z",
25 buckets: [],
26 sources: [],
27 pricing,
28 scanDurationMs: 1,
29};
30const registries: AtomRegistry.AtomRegistry[] = [];
31afterEach(() => {
32 for (const registry of registries.splice(0)) registry.dispose();
33});
34
35function harness(ids = ["a"]) {
36 const registry = AtomRegistry.make();
37 registries.push(registry);
38 const environments = ids.map((id) => {
39 const environmentId = EnvironmentId.make(id);
40 const rates = Promise.withResolvers<
41 AsyncResult.Success<typeof pricing> | AsyncResult.Failure<never, unknown>
42 >();
43 const scan = Promise.withResolvers<UsageSummary>();
44 const scanStarted = Promise.withResolvers<void>();
45 const presentation = Atom.make({
46 connection: { phase: "connected" },
47 } as EnvironmentPresentation | null);
48 const query = Atom.make(
49 Effect.promise(() => {
50 scanStarted.resolve();
51 return scan.promise;
52 }),
53 );
54 return { environmentId, rates, scan, scanStarted, presentation, query };
55 });
56 function get(environmentId: EnvironmentId) {
57 const environment = environments.find((entry) => entry.environmentId === environmentId);
58 if (!environment) throw new Error(`Unknown environment: ${environmentId}`);
59 return environment;
60 }
61 const options = {
62 registry,
63 environmentIds: environments.map((entry) => entry.environmentId),
64 input,
65 server: {
66 usageSummary: ({ environmentId }: { environmentId: EnvironmentId }) =>
67 get(environmentId).query,
68 refreshUsageRates: {
69 label: "test:rates",
70 run: (
71 _registry: AtomRegistry.AtomRegistry,
72 { environmentId }: { environmentId: EnvironmentId },
73 ) => get(environmentId).rates.promise,
74 },
75 },
76 presentations: {
77 presentationAtom: (environmentId: EnvironmentId) => get(environmentId).presentation,
78 },
79 } satisfies Parameters<typeof refreshUsage>[0];
80 return { registry, environments, refresh: () => refreshUsage(options) };
81}
82
83describe("manual usage refresh", () => {
84 it.each(["success", "failure"])("waits for the rescan after a pricing %s", async (result) => {
85 const {
86 environments: [environment],
87 refresh,
88 } = harness();
89 const entry = environment!;
90 let finished = false;
91 const refreshing = refresh().then(() => {
92 finished = true;
93 });
94 expect(finished).toBe(false);
95 entry.rates.resolve(
96 result === "success"
97 ? AsyncResult.success(pricing)
98 : AsyncResult.fail(new Error("Pricing offline")),
99 );
100 await entry.scanStarted.promise;
101 expect(finished).toBe(false);
102 entry.scan.resolve(summary);
103 await refreshing;
104 expect(finished).toBe(true);
105 });
106
107 it("settles when an environment disconnects during the rescan", async () => {
108 const {
109 registry,
110 environments: [environment],
111 refresh,
112 } = harness();
113 const entry = environment!;
114 const refreshing = refresh();
115 entry.rates.resolve(AsyncResult.success(pricing));
116 await entry.scanStarted.promise;
117 registry.set(entry.presentation, null);
118 await refreshing;
119 });
120
121 it("waits for healthy environments without waiting for a recovering environment", async () => {
122 const { registry, environments, refresh } = harness(["healthy", "recovering"]);
123 const [healthy, recovering] = environments;
124 registry.set(recovering!.presentation, null);
125 let finished = false;
126 const refreshing = refresh().then(() => {
127 finished = true;
128 });
129 for (const entry of environments) entry.rates.resolve(AsyncResult.success(pricing));
130 await healthy!.scanStarted.promise;
131 expect(finished).toBe(false);
132 healthy!.scan.resolve(summary);
133 await refreshing;
134 expect(finished).toBe(true);
135 });
136
137 it("settles when connected state has no usable RPC session", async () => {
138 const {
139 environments: [environment],
140 refresh,
141 } = harness();
142 const entry = environment!;
143 const refreshing = refresh();
144 entry.rates.resolve(
145 AsyncResult.fail(
146 new EnvironmentRpcUnavailableError({
147 environmentId: entry.environmentId,
148 message: "No session",
149 }),
150 ),
151 );
152 await refreshing;
153 });
154
155 it("replaces a scan that started before pricing was refreshed", async () => {
156 const {
157 registry,
158 environments: [environment],
159 refresh,
160 } = harness();
161 const entry = environment!;
162 let reads = 0;
163 const rescanned = Promise.withResolvers<void>();
164 const query = Atom.make(
165 Effect.promise(() => {
166 reads += 1;
167 if (reads > 1) {
168 rescanned.resolve();
169 return Promise.resolve(summary);
170 }
171 return new Promise<UsageSummary>(() => {});
172 }),
173 );
174 entry.query = query;
175 const unmount = registry.mount(query);
176 expect(reads).toBe(1);
177 const refreshing = refresh();
178 entry.rates.resolve(AsyncResult.success(pricing));
179 await rescanned.promise;
180 await refreshing;
181 expect(reads).toBe(2);
182 unmount();
183 });
184});