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

UsageService.ts

425 lines15.0 KB

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