Open History to see the last commit
1/**
2 * UsageService - scans provider transcripts and returns priced usage buckets.
3 *
4 * The scan reads the provider CLIs' own session files rather than T3 Code's
5 * orchestration projections, so usage covers turns driven outside T3 Code too.
6 * This is the approach `ccusage` takes.
7 *
8 * Transcripts are append-only, so parsed records are memoised per file by
9 * `(size, mtime)`. A cold 30-day scan of ~1.4 GB lands around 2-3 seconds; warm
10 * scans only reparse files that changed.
11 *
12 * @module UsageService
13 */
14import * as NodeOS from "node:os";
15
16import {
17 USAGE_CONTRACT_VERSION,
18 type UsageProviderKind,
19 type UsageSource,
20 type UsageSummary,
21 type UsageSummaryInput,
22 UsageReadError,
23} from "@t3tools/contracts";
24import * as Cause from "effect/Cause";
25import * as Clock from "effect/Clock";
26import * as Context from "effect/Context";
27import * as DateTime from "effect/DateTime";
28import * as Effect from "effect/Effect";
29import * as FileSystem from "effect/FileSystem";
30import * as Layer from "effect/Layer";
31import * as Option from "effect/Option";
32import * as Path from "effect/Path";
33import * as Schema from "effect/Schema";
34import { HttpClient, HttpClientResponse } from "effect/unstable/http";
35
36import { ServerConfig } from "../config.ts";
37import * as ServerSettings from "../serverSettings.ts";
38import { UsageAggregator } from "./usageAggregation.ts";
39import { parseRateTable, type RateTable } from "./usagePricing.ts";
40import {
41 listTranscriptFiles,
42 readDirectoryVolumeId,
43 readTranscriptRecords,
44} from "./usageTranscriptReader.ts";
45import {
46 decodeScanCache,
47 dedupeWithinFile,
48 encodeScanCache,
49 pruneScanCache,
50 type ScanCache,
51} from "./usageScanCache.ts";
52import { resolveUsageTranscriptDirs } from "./usageTranscriptDirs.ts";
53import type { UsageRecord } from "./usageTranscripts.ts";
54
55const LITELLM_RATES_URL =
56 "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
57
58/** Rates move rarely; a day-old table keeps the page working offline. */
59const RATES_TTL_MS = 24 * 60 * 60 * 1000;
60
61/**
62 * Files are filtered by mtime before opening. The slack covers a session whose
63 * last write lands just before local midnight on the window's first day.
64 */
65const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
66const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
67
68/** Longest window the UI offers, plus slack. Older entries are pruned. */
69const CACHE_RETENTION_DAYS = 90;
70
71/** On-disk shape of the rate snapshot. */
72const RatesCacheFile = Schema.Struct({
73 fetchedAtMs: Schema.Number,
74 document: Schema.Unknown,
75});
76const decodeRatesCache = Schema.decodeUnknownEffect(
77 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
78);
79const encodeRatesCache = Schema.encodeEffect(
80 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
81);
82
83/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */
84const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);
85const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
86const encodeScanCacheFile = Schema.encodeEffect(ScanCacheJson);
87
88export class UsageService extends Context.Service<
89 UsageService,
90 {
91 readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
92 }
93>()("t3/usage/UsageService") {}
94
95/** Empty summary, for suites that only need the RPC surface to resolve. */
96export const layerTest = Layer.succeed(
97 UsageService,
98 UsageService.of({
99 readSummary: (input) =>
100 Effect.succeed({
101 contractVersion: USAGE_CONTRACT_VERSION,
102 readAt: "1970-01-01T00:00:00.000Z",
103 timeZone: input.timeZone,
104 sinceDay: input.sinceDay,
105 untilDay: input.untilDay,
106 buckets: [],
107 sources: [],
108 pricing: {
109 status: "unavailable",
110 source: LITELLM_RATES_URL,
111 fetchedAt: null,
112 knownModels: 0,
113 },
114 scanDurationMs: 0,
115 }),
116 }),
117);
118
119export const make = Effect.gen(function* () {
120 const fileSystem = yield* FileSystem.FileSystem;
121 const path = yield* Path.Path;
122 const config = yield* ServerConfig;
123 const settingsService = yield* ServerSettings.ServerSettingsService;
124 const httpClient = yield* HttpClient.HttpClient;
125
126 const fileCache: ScanCache = new Map();
127 let cacheDirty = false;
128
129 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
130 const scanCachePath = path.join(config.stateDir, "usage-scan-cache.json");
131 let rates: RateTable = new Map();
132 let ratesFetchedAtMs: number | null = null;
133 let ratesStatus: UsageSummary["pricing"]["status"] = "unavailable";
134
135 /**
136 * Loads the LiteLLM rate table, preferring a fresh copy and falling back to
137 * the on-disk snapshot. With neither, every model reports as unpriced rather
138 * than the page failing.
139 */
140 const ensureRates = Effect.fn("UsageService.ensureRates")(function* () {
141 const now = yield* Clock.currentTimeMillis;
142 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < RATES_TTL_MS) return;
143
144 if (ratesFetchedAtMs === null) {
145 const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(
146 Effect.flatMap((raw) => decodeRatesCache(raw)),
147 Effect.catchCause(() => Effect.succeed(null)),
148 );
149 if (fromDisk !== null) {
150 const parsed = parseRateTable(fromDisk.document);
151 if (parsed.size > 0) {
152 rates = parsed;
153 ratesFetchedAtMs = fromDisk.fetchedAtMs;
154 ratesStatus = "cached";
155 if (now - fromDisk.fetchedAtMs < RATES_TTL_MS) return;
156 }
157 }
158 }
159
160 const fetched = yield* httpClient.get(LITELLM_RATES_URL).pipe(
161 Effect.flatMap(HttpClientResponse.filterStatusOk),
162 Effect.flatMap((response) => response.json),
163 Effect.timeout(10_000),
164 Effect.catchCause(() => Effect.succeed(null)),
165 );
166 if (fetched === null) {
167 // The refresh failed; whatever we are serving is now past its TTL and
168 // must not keep claiming to be fresh.
169 if (rates.size > 0) ratesStatus = "cached";
170 return;
171 }
172
173 const parsed = parseRateTable(fetched);
174 if (parsed.size === 0) return;
175
176 rates = parsed;
177 ratesFetchedAtMs = now;
178 ratesStatus = "fresh";
179
180 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe(
181 Effect.flatMap((serialized) => fileSystem.writeFileString(ratesCachePath, serialized)),
182 Effect.catchCause(() => Effect.void),
183 );
184 });
185
186 /** Resolves the transcript directory for every configured provider instance. */
187 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* () {
188 // A settings failure must surface as an error: swallowing it here would
189 // present "zero usage from every provider" as a valid answer.
190 const settings = yield* settingsService.getSettings.pipe(
191 Effect.catchCause(
192 (cause) =>
193 new UsageReadError({
194 reason: "scanFailed",
195 // Bounded description; the squashed failure travels as the cause.
196 // Squashed, not the Cause tree: a full tree in a Defect field is
197 // the unbounded wire payload the bounded detail exists to avoid.
198 detail: "Server settings could not be read.",
199 cause: Cause.squash(cause),
200 }),
201 ),
202 );
203
204 return yield* resolveUsageTranscriptDirs(settings);
205 });
206
207 /**
208 * Loads the persisted scan cache exactly once per process.
209 *
210 * `Effect.cached` makes concurrent first readers await the same load rather
211 * than each seeing a "loaded" flag set before the read finished and cold
212 * scanning against an empty cache.
213 */
214 const ensureScanCacheLoaded = yield* Effect.cached(
215 Effect.gen(function* () {
216 const document = yield* fileSystem.readFileString(scanCachePath).pipe(
217 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
218 Effect.catchCause(() => Effect.succeed(null)),
219 );
220 if (document === null) return;
221 for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);
222 }),
223 );
224
225 const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () {
226 if (!cacheDirty) return;
227 // Cleared only after the write lands, so a failed persist is retried on
228 // the next scan instead of leaving disk permanently stale.
229 yield* encodeScanCacheFile(encodeScanCache(fileCache)).pipe(
230 Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)),
231 Effect.map(() => {
232 cacheDirty = false;
233 }),
234 // A cache we cannot write is a slower next start, not a failed read.
235 Effect.catchCause(() => Effect.void),
236 );
237 });
238
239 /** Parses one transcript, reusing the cached result when it is unchanged. */
240 const readFileRecords = (
241 filePath: string,
242 size: number,
243 mtimeMs: number,
244 provider: UsageProviderKind,
245 ): Effect.Effect<readonly UsageRecord[]> =>
246 Effect.gen(function* () {
247 const cached = fileCache.get(filePath);
248 // Provider is part of the identity: if both providers were ever pointed
249 // at one directory, a hit parsed by the other parser must not be reused.
250 if (
251 cached &&
252 cached.size === size &&
253 cached.mtimeMs === mtimeMs &&
254 cached.provider === provider
255 ) {
256 return cached.records;
257 }
258
259 const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, provider));
260 // A read failure is not an empty transcript: caching it under this
261 // (size, mtime) would silently drop the file's usage until it changes.
262 if (parsed === null) return [];
263 // Stored already de-duplicated within the file, which is 99% of all
264 // duplicates. The aggregator still runs the cross-file dedupe pass.
265 const records = dedupeWithinFile(parsed);
266
267 fileCache.set(filePath, { size, mtimeMs, provider, records });
268 cacheDirty = true;
269 return records;
270 });
271
272 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
273 if (input.sinceDay > input.untilDay) {
274 return yield* new UsageReadError({
275 reason: "invalidWindow",
276 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
277 });
278 }
279
280 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
281 if (input.resolution === "hour") {
282 const sinceTime =
283 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
284 const untilTime =
285 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
286 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
287 return yield* new UsageReadError({
288 reason: "invalidWindow",
289 detail: "Hourly usage requires valid sinceTime and untilTime instants",
290 });
291 }
292 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
293 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
294 const durationMs = untilTimeMs - sinceTimeMs;
295 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
296 return yield* new UsageReadError({
297 reason: "invalidWindow",
298 detail: "Hourly usage window must be greater than zero and at most 24 hours",
299 });
300 }
301 hourlyWindow = { sinceTimeMs, untilTimeMs };
302 }
303
304 const startedAtMs = yield* Clock.currentTimeMillis;
305 yield* ensureRates();
306 yield* ensureScanCacheLoaded;
307
308 const hostId = NodeOS.hostname();
309 // The home resolvers ask for `Path` and `FileSystem` themselves; satisfy
310 // them from the instances we already hold so `readSummary` stays context-free.
311 const dirs = yield* resolveTranscriptDirs().pipe(
312 Effect.provideService(Path.Path, path),
313 Effect.provideService(FileSystem.FileSystem, fileSystem),
314 );
315 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
316 if (Option.isNone(windowStart)) {
317 return yield* new UsageReadError({
318 reason: "invalidWindow",
319 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
320 });
321 }
322 const windowStartMs =
323 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
324
325 const aggregator = new UsageAggregator({
326 timeZone: input.timeZone,
327 sinceDay: input.sinceDay,
328 untilDay: input.untilDay,
329 resolution: input.resolution ?? "day",
330 ...hourlyWindow,
331 rates,
332 });
333
334 const sources: UsageSource[] = [];
335 const livePaths = new Set<string>();
336 const walkedRoots: string[] = [];
337
338 for (const { provider, dir } of dirs) {
339 const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
340 const exists = yield* fileSystem
341 .exists(dir)
342 .pipe(Effect.catchCause(() => Effect.succeed(false)));
343
344 if (!exists) {
345 sources.push({
346 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
347 status: "missing",
348 scannedFiles: 0,
349 skippedFiles: 0,
350 malformedRecords: 0,
351 distinctSessions: 0,
352 message: "No transcript directory on this environment.",
353 });
354 continue;
355 }
356
357 walkedRoots.push(dir);
358 const files = yield* Effect.promise(() => listTranscriptFiles(dir, windowStartMs));
359 let scannedFiles = 0;
360 let skippedFiles = 0;
361 // Distinct per directory. Buckets carry per-cell session counts, but a
362 // session spans days and models, so clients total this figure instead.
363 const sessionIds = new Set<string>();
364
365 for (const file of files) {
366 livePaths.add(file.path);
367 const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);
368 if (records.length === 0) {
369 skippedFiles += 1;
370 continue;
371 }
372 scannedFiles += 1;
373 for (const record of records) {
374 // Only sessions that contributed in-window count: the mtime slack
375 // admits boundary files whose records fall outside the range.
376 if (aggregator.add(record) && record.sessionId.length > 0) {
377 sessionIds.add(record.sessionId);
378 }
379 }
380 }
381
382 sources.push({
383 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
384 status: "ok",
385 scannedFiles,
386 skippedFiles,
387 malformedRecords: 0,
388 distinctSessions: sessionIds.size,
389 message: null,
390 });
391 }
392
393 const pruned = pruneScanCache(fileCache, {
394 livePaths,
395 walkedRoots,
396 windowStartMs,
397 retentionCutoffMs: startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000,
398 });
399 if (pruned > 0) cacheDirty = true;
400 yield* persistScanCache();
401
402 const aggregated = aggregator.finish();
403 const readAt = yield* DateTime.now;
404 const finishedAtMs = yield* Clock.currentTimeMillis;
405
406 return {
407 contractVersion: USAGE_CONTRACT_VERSION,
408 readAt: DateTime.formatIso(readAt),
409 timeZone: input.timeZone,
410 sinceDay: input.sinceDay,
411 untilDay: input.untilDay,
412 buckets: aggregated.buckets,
413 sources,
414 pricing: {
415 status: ratesStatus,
416 source: LITELLM_RATES_URL,
417 fetchedAt:
418 ratesFetchedAtMs === null
419 ? null
420 : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
421 knownModels: rates.size,
422 },
423 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
424 } satisfies UsageSummary;
425 });
426
427 return { readSummary } as const;
428});
429
430export const layer = Layer.effect(UsageService, make);