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

UsageService.ts

913 lines35.4 KB

1/**
2 * UsageService - reads every driver's usage history and returns priced usage
3 * buckets.
4 *
5 * Each built-in driver with a `usage` reader contributes its sources, including
6 * work driven outside T3 Code. A `transcripts` reader names JSONL directories
7 * that this service streams itself; a `scan` reader reads its own sources.
8 *
9 * JSONL transcripts are append-only, so parsed records are memoised per file by
10 * `(size, mtime)`. A cold 30-day scan of ~1.4 GB lands around 2-3 seconds; warm
11 * scans only reparse files that changed, and a file that merely grew resumes
12 * from its cached parse position so only the appended bytes are read.
13 *
14 * A scan reader with a slow source (an account API) may answer from its own
15 * cache and mark itself `refreshing` while a background refresh runs;
16 * `awaitRefresh` waits for that refresh instead.
17 *
18 * @module UsageService
19 */
20import * as NodeOS from "node:os";
21​
22import {
23 type ProviderInstanceConfig,
24 ProviderInstanceId,
25 USAGE_CONTRACT_VERSION,
26 type ServerSettings as ServerSettingsValue,
27 type UsageProviderKind,
28 type UsageSource,
29 type UsagePricing,
30 type UsageSummary,
31 type UsageSummaryInput,
32 UsageReadError,
33} from "@t3tools/contracts";
34import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
35import * as Cause from "effect/Cause";
36import * as Clock from "effect/Clock";
37import * as Context from "effect/Context";
38import * as DateTime from "effect/DateTime";
39import * as Deferred from "effect/Deferred";
40import * as Effect from "effect/Effect";
41import * as Exit from "effect/Exit";
42import * as Fiber from "effect/Fiber";
43import * as FileSystem from "effect/FileSystem";
44import * as Layer from "effect/Layer";
45import * as Option from "effect/Option";
46import * as Path from "effect/Path";
47import * as Schema from "effect/Schema";
48import * as Semaphore from "effect/Semaphore";
49import { HttpClient, HttpClientResponse } from "effect/http";
50​
51import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
52import * as ServerConfig from "../config.ts";
53import * as ServerSettings from "../serverSettings.ts";
54import { BUILT_IN_USAGE_DRIVERS, type BuiltInUsageReadersEnv } from "../provider/builtInDrivers.ts";
55import type { ProviderDriver } from "@t3tools/provider-core/server/driver";
56import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
57import type {
58 ProviderUsageInstance,
59 TranscriptUsageFormat,
60 UsageRecord,
61} from "@t3tools/provider-core/server/usage";
62import { resolveModelAliases, UsageAggregator } from "./usageAggregation.ts";
63import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts";
64import {
65 listTranscriptFiles,
66 readDirectoryVolumeId,
67 readTranscriptRecords,
68} from "./usageTranscriptReader.ts";
69import {
70 decodeScanCache,
71 dedupeWithinFile,
72 LEGACY_SCAN_CACHE_FILE_NAME,
73 makeScanCacheWriter,
74 pruneScanCache,
75 SCAN_CACHE_FILE_NAME,
76 type CachedFile,
77 type ScanCache,
78} from "./usageScanCache.ts";
79​
80const LITELLM_RATES_URL =
81 "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
82​
83/** Rates move rarely; a day-old table keeps the page working offline. */
84const RATES_TTL_MS = 24 * 60 * 60 * 1000;
85​
86/** An explicit refresh ignores the TTL, but not a table fetched this recently. */
87const RATES_REFRESH_FLOOR_MS = 60 * 1000;
88​
89/**
90 * Files are filtered by mtime before opening. The slack covers a session whose
91 * last write lands just before local midnight on the window's first day.
92 */
93const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
94const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
95​
96/**
97 * The longest window the UI offers, 90 days, plus its `MTIME_SLACK_MS`, rounded
98 * up. Older entries are pruned.
99 */
100const CACHE_RETENTION_DAYS = 92;
101​
102/** Transcripts parsed at once. More gains little once the disk stays busy. */
103const TRANSCRIPT_READ_CONCURRENCY = 4;
104​
105/** The transcript readers, in driver order. */
106const transcriptReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) =>
107 driver.usage?.kind === "transcripts" ? [{ driver, reader: driver.usage }] : [],
108);
109​
110/** The scan readers, in driver order. */
111const scanReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) =>
112 driver.usage?.kind === "scan" ? [{ driver, reader: driver.usage }] : [],
113);
114​
115/** Transcript formats by provider, for decoding the persisted scan cache. */
116const transcriptFormats = new Map(
117 transcriptReaders.map(({ reader }) => [reader.provider, reader.format] as const),
118);
119​
120/** One transcript directory to scan. */
121interface TranscriptSource {
122 readonly provider: UsageProviderKind;
123 readonly format: TranscriptUsageFormat<unknown>;
124 readonly dir: string;
125 readonly volumeId: string;
126 readonly fileName?: string;
128​
129/** On-disk shape of the rate snapshot. */
130const RatesCacheFile = Schema.Struct({
131 fetchedAtMs: Schema.Number,
132 document: Schema.Unknown,
133});
134const decodeRatesCache = Schema.decodeUnknownEffect(
135 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
136);
137const encodeRatesCache = Schema.encodeEffect(
138 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
139);
140​
141/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */
142const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);
143const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
144const encodeUsageRecordKey = Schema.encodeSync(ScanCacheJson);
145const CachedSource = Schema.Struct({ dir: Schema.String, volumeId: Schema.String });
146​
147/** Whether `a` read a later state of its file than `b`. Transcripts only grow. */
148function isLaterRead(a: CachedFile, b: CachedFile): boolean {
149 return a.mtimeMs > b.mtimeMs || (a.mtimeMs === b.mtimeMs && a.size > b.size);
151​
152/** Providers whose format lets one session's records appear in several files. */
153const sharedSessionProviders: ReadonlySet<UsageProviderKind> = new Set(
154 transcriptReaders.flatMap(({ reader }) =>
155 reader.format.sharedSessionsAcrossFiles ? [reader.provider] : [],
156 ),
157);
158​
159/**
160 * Sessions of `sharedSessionProviders` with records in more than one file,
161 * such as a rollout that moved after it was read. Only these need cross-file
162 * dedupe keys: within one file the occurrence count already keeps every key
163 * unique, so keying the rest would only build and hash a string for each of
164 * their records.
165 */
166function sharedSessions(
167 files: readonly { readonly records: readonly UsageRecord[] }[],
168): ReadonlySet<string> {
169 const firstFile = new Map<string, number>();
170 const shared = new Set<string>();
171 for (const [index, file] of files.entries()) {
172 let previous = "";
173 for (const { provider, sessionId } of file.records) {
174 if (!sharedSessionProviders.has(provider) || sessionId === previous || sessionId.length === 0)
175 continue;
176 previous = sessionId;
177 const first = firstFile.get(sessionId);
178 if (first === undefined) firstFile.set(sessionId, index);
179 else if (first !== index) shared.add(sessionId);
180 }
181 }
182 return shared;
184const decodeCachedSources = Schema.decodeUnknownOption(
185 Schema.Struct({ sources: Schema.Record(Schema.String, CachedSource) }),
186);
187​
188export class UsageService extends Context.Service<
189 UsageService,
190 {
191 readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
192 /** Refetches the rate table ahead of its TTL. See `ensureRates`. */
193 readonly refreshRates: Effect.Effect<UsagePricing>;
194 }
195>()("t3/usage/UsageService") {}
196​
197const EMPTY_PRICING: UsagePricing = {
198 status: "unavailable",
199 source: LITELLM_RATES_URL,
200 fetchedAt: null,
201 knownModels: 0,
202};
203​
204/** Empty summary, for suites that only need the RPC surface to resolve. */
205const layerTest = Layer.succeed(
206 UsageService,
207 UsageService.of({
208 readSummary: (input) =>
209 Effect.succeed({
210 contractVersion: USAGE_CONTRACT_VERSION,
211 readAt: "1970-01-01T00:00:00.000Z",
212 timeZone: input.timeZone,
213 sinceDay: input.sinceDay,
214 untilDay: input.untilDay,
215 buckets: [],
216 sources: [],
217 pricing: EMPTY_PRICING,
218 scanDurationMs: 0,
219 }),
220 refreshRates: Effect.succeed(EMPTY_PRICING),
221 }),
222);
223​
224export const make = Effect.gen(function* () {
225 const fileSystem = yield* FileSystem.FileSystem;
226 const path = yield* Path.Path;
227 const config = yield* ServerConfig.ServerConfig;
228 const settingsService = yield* ServerSettings.ServerSettingsService;
229 const httpClient = yield* HttpClient.HttpClient;
230 const hostEnvironment = yield* HostProcessEnvironment;
231 // The readers yield their own services; scans run them against this context.
232 const readerContext = yield* Effect.context<BuiltInUsageReadersEnv>();
233​
234 const fileCache: ScanCache = new Map();
235 const sourceCache = new Map<string, typeof CachedSource.Type>();
236 let cacheDirty = false;
237 const isWithinDirectory = (filePath: string, dir: string) => {
238 const relative = path.relative(dir, filePath);
239 return relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative);
240 };
241​
242 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
243 const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME);
244 const legacyScanCachePath = path.join(config.stateDir, LEGACY_SCAN_CACHE_FILE_NAME);
245 const writeCacheFile = (filePath: string, contents: string) =>
246 writeFileStringAtomically({ filePath, contents }).pipe(
247 Effect.provideService(FileSystem.FileSystem, fileSystem),
248 Effect.provideService(Path.Path, path),
249 );
250 let rates: RateTable = new Map();
251 let ratesFetchedAtMs: number | null = null;
252 let ratesStatus: UsagePricing["status"] = "unavailable";
253 // One fetch at a time. A burst of refreshes from several clients waits on
254 // the first fetch and then sees a table young enough to skip its own.
255 const ratesLock = yield* Semaphore.make(1);
256​
257 const pricing = (): UsagePricing => ({
258 status: ratesStatus,
259 source: LITELLM_RATES_URL,
260 fetchedAt:
261 ratesFetchedAtMs === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
262 knownModels: rates.size,
263 });
264​
265 /**
266 * Loads the LiteLLM rate table, preferring a fresh copy and falling back to
267 * the on-disk snapshot. With neither, every model reports as unpriced rather
268 * than the page failing. `force` refetches inside the TTL so a model that
269 * LiteLLM added since the last fetch gets priced now.
270 */
271 const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) {
272 const now = yield* Clock.currentTimeMillis;
273 const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS;
274 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return;
275​
276 if (ratesFetchedAtMs === null) {
277 const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(
278 Effect.flatMap((raw) => decodeRatesCache(raw)),
279 Effect.catchCause(() => Effect.succeed(null)),
280 );
281 if (fromDisk !== null) {
282 const parsed = parseRateTable(fromDisk.document);
283 if (parsed.size > 0) {
284 rates = parsed;
285 ratesFetchedAtMs = fromDisk.fetchedAtMs;
286 ratesStatus = "cached";
287 if (now - fromDisk.fetchedAtMs < maxAgeMs) return;
288 }
289 }
290 }
291​
292 const fetched = yield* httpClient.get(LITELLM_RATES_URL).pipe(
293 Effect.flatMap(HttpClientResponse.filterStatusOk),
294 Effect.flatMap((response) => response.json),
295 Effect.timeout(10_000),
296 Effect.catchCause(() => Effect.succeed(null)),
297 );
298 if (fetched === null) {
299 // The refresh failed; whatever we are serving is now past its TTL and
300 // must not keep claiming to be fresh.
301 if (rates.size > 0) ratesStatus = "cached";
302 return;
303 }
304​
305 const parsed = parseRateTable(fetched);
306 if (parsed.size === 0) return;
307​
308 rates = parsed;
309 ratesFetchedAtMs = now;
310 ratesStatus = "fresh";
311​
312 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe(
313 Effect.flatMap((contents) => writeCacheFile(ratesCachePath, contents)),
314 Effect.ignoreCause,
315 );
316 });
317​
318 const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force));
319​
320 const refreshRates = ensureRates(true).pipe(
321 Effect.map(pricing),
322 Effect.withSpan("UsageService.refreshRates"),
323 );
324​
325 // A settings failure must not silently discard custom rates or transcript homes.
326 const readSettings = settingsService.getSettings.pipe(
327 Effect.catchCause(
328 (cause) =>
329 new UsageReadError({
330 reason: "scanFailed",
331 detail: "Server settings could not be read.",
332 cause: Cause.squash(cause),
333 }),
334 ),
335 );
336​
337 /**
338 * Every instance of `driver` with its decoded config, or none when it does
339 * not decode. Disabled accounts still have history. An unconfigured default
340 * slot runs with default config, just as it does in the provider registry.
341 */
342 const usageInstances = <Config>(
343 driver: ProviderDriver<Config, unknown, unknown>,
344 settings: ServerSettingsValue,
345 ): Array<ProviderUsageInstance<Config>> => {
346 const entries: Array<
347 readonly [ProviderInstanceId, Pick<ProviderInstanceConfig, "config" | "environment">, boolean]
348 > = Object.entries(settings.providerInstances)
349 .filter(([, instance]) => instance.driver === driver.driverKind)
350 .map(([id, instance]) => [ProviderInstanceId.make(id), instance, true] as const);
351 if (!Object.hasOwn(settings.providerInstances, driver.driverKind)) {
352 entries.push([ProviderInstanceId.make(driver.driverKind), {}, false]);
353 }
354 const decodeConfig = Schema.decodeUnknownOption(driver.configSchema);
355 return entries.map(([instanceId, instance, configured]) => ({
356 instanceId,
357 config: Option.getOrUndefined(decodeConfig(instance.config ?? {})),
358 environment: mergeProviderInstanceEnvironment(instance.environment, hostEnvironment),
359 configured,
360 }));
361 };
362​
363 /** Resolves every transcript directory the usage readers point at. */
364 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (
365 settings: ServerSettingsValue,
366 retentionCutoffMs: number,
367 ) {
368 const dirs: Array<TranscriptSource> = [];
369 const seen = new Set<string>();
370 for (const { driver, reader } of transcriptReaders) {
371 const { provider, format } = reader;
372 const directories = yield* Effect.forEach(usageInstances(driver, settings), (instance) =>
373 reader.directories(instance),
374 );
375 for (const { dir: directory, fileName } of directories.flat()) {
376 const sourceKey = provider + "\0" + directory;
377 const previous = sourceCache.get(sourceKey);
378 // Keep canonical paths and source fingerprints stable after root cleanup,
379 // including aliases and clients merging pre-cleanup environment summaries.
380 const dir = yield* fileSystem
381 .realPath(directory)
382 .pipe(Effect.orElseSucceed(() => previous?.dir ?? directory));
383 const currentVolumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
384 const hasRetainedHistory = fileCache
385 .entries()
386 .some(
387 ([filePath, entry]) =>
388 entry.provider === provider &&
389 entry.mtimeMs >= retentionCutoffMs &&
390 entry.records.length + entry.tailRecords.length > 0 &&
391 isWithinDirectory(filePath, dir),
392 );
393 // A recreated directory still reports the retained history under its old identity.
394 const volumeId =
395 previous?.dir === dir && (hasRetainedHistory || !currentVolumeId)
396 ? previous.volumeId || currentVolumeId
397 : currentVolumeId;
398 if (previous?.dir !== dir || previous.volumeId !== volumeId) {
399 sourceCache.set(sourceKey, { dir, volumeId });
400 cacheDirty = true;
401 }
402 const key = `${provider}\0${dir}`;
403 if (seen.has(key)) continue;
404 seen.add(key);
405 dirs.push({
406 provider,
407 format,
408 dir,
409 volumeId,
410 ...(fileName === undefined ? {} : { fileName }),
411 });
412 }
413 }
414 return dirs;
415 });
416​
417 /**
418 * Loads the persisted scan cache exactly once per process.
419 *
420 * `Effect.cached` makes concurrent first readers await the same load rather
421 * than each seeing a "loaded" flag set before the read finished and cold
422 * scanning against an empty cache.
423 */
424 const ensureScanCacheLoaded = yield* Effect.cached(
425 Effect.gen(function* () {
426 const readDocument = (filePath: string) =>
427 fileSystem.readFileString(filePath).pipe(
428 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
429 Effect.catchCause(() => Effect.succeed(null)),
430 );
431 let document = yield* readDocument(scanCachePath);
432 if (document === null) {
433 document = yield* readDocument(legacyScanCachePath);
434 // Write the migrated cache to its own file on the next scan.
435 cacheDirty = document !== null;
436 }
437 if (document === null) return;
438 for (const [path, entry] of decodeScanCache(document, transcriptFormats)) {
439 fileCache.set(path, entry);
440 }
441 const sources = decodeCachedSources(document);
442 if (Option.isSome(sources)) {
443 for (const [key, source] of Object.entries(sources.value.sources))
444 sourceCache.set(key, source);
445 }
446 }),
447 );
448​
449 const writeScanCache = makeScanCacheWriter();
450 // Scans with different windows can finish together; serializing the writes
451 // keeps an older snapshot from landing after a newer one.
452 const persistLock = yield* Semaphore.make(1);
453​
454 // The dirty flag is cleared before encoding, so a change while the write is
455 // in flight marks it dirty again. A failed write restores the flag, so the
456 // next persist retries instead of leaving disk stale. A cache we cannot
457 // write is a slower next start, not a failed read.
458 const persistCaches = Effect.gen(function* () {
459 if (cacheDirty) {
460 cacheDirty = false;
461 yield* Effect.sync(() =>
462 writeScanCache(fileCache, { sources: Object.fromEntries(sourceCache) }),
463 ).pipe(
464 Effect.flatMap((contents) => writeCacheFile(scanCachePath, contents)),
465 Effect.catchCause(() =>
466 Effect.sync(() => {
467 cacheDirty = true;
468 }),
469 ),
470 );
471 }
472 }).pipe(persistLock.withPermit, Effect.withSpan("UsageService.persistCaches"));
473​
474 const pendingPersists = new Set<Fiber.Fiber<void>>();
475 /** Writes dirty caches in the background, after the summary that dirtied them answers. */
476 const schedulePersist = Effect.forkDetach(persistCaches).pipe(
477 Effect.map((fiber) => {
478 pendingPersists.add(fiber);
479 fiber.addObserver(() => pendingPersists.delete(fiber));
480 }),
481 );
482 /** Waits for every write scheduled so far, as a restart would need. */
483 const awaitPersisted = Effect.suspend(() => Fiber.awaitAll([...pendingPersists])).pipe(
484 Effect.asVoid,
485 );
486 // A write still running when the service shuts down finishes first, so the
487 // next start does not lose the last scan.
488 yield* Effect.addFinalizer(() => awaitPersisted);
489​
490 /**
491 * Parses one transcript, reusing the cached result when it is unchanged.
492 *
493 * A file that only grew re-parses from the cached position, so an actively
494 * written multi-hundred-megabyte rollout costs its appended bytes per scan
495 * rather than a full re-read. The reader verifies the position's guard bytes
496 * and silently restarts from byte 0 when they no longer match.
497 *
498 * A fresh parse comes back as `update` for the caller to cache, with the
499 * entry it was built from. Reads run concurrently, and the caller stores
500 * updates in walk order rather than completion order: saved records of
501 * deleted transcripts aggregate in cache order, where the first copy of a
502 * duplicate wins.
503 */
504 const readFileRecords = (
505 filePath: string,
506 size: number,
507 mtimeMs: number,
508 provider: UsageProviderKind,
509 format: TranscriptUsageFormat<unknown>,
510 ): Effect.Effect<{
511 readonly records: readonly UsageRecord[];
512 readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
513 }> =>
514 Effect.gen(function* () {
515 const cached = fileCache.get(filePath);
516 // Provider is part of the identity: if both providers were ever pointed
517 // at one directory, a hit parsed by the other parser must not be reused.
518 if (
519 cached &&
520 cached.size === size &&
521 cached.mtimeMs === mtimeMs &&
522 cached.provider === provider
523 ) {
524 return {
525 records:
526 cached.tailRecords.length === 0
527 ? cached.records
528 : [...cached.records, ...cached.tailRecords],
529 };
530 }
531​
532 // Only a strictly grown file may resume. Same size with a new mtime, or
533 // a shrunken file, means rewritten content; re-parse it whole.
534 const resumeFrom =
535 cached !== undefined && cached.provider === provider && size > cached.size
536 ? cached.position
537 : undefined;
538​
539 const parsed = yield* Effect.promise(() =>
540 readTranscriptRecords(filePath, format, resumeFrom),
541 );
542 // A read failure is not an empty transcript: caching it under this
543 // (size, mtime) would silently drop the file's usage until it changes.
544 if (parsed === null)
545 return {
546 records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
547 };
548​
549 // Stored already de-duplicated within the file, which is 99% of all
550 // duplicates. The aggregator still runs the cross-file dedupe pass. One
551 // seen set spans the cached base, the new lines, and the tail so a
552 // resumed parse dedupes exactly like a full one.
553 const base = parsed.resumed && cached !== undefined ? cached.records : [];
554 const seen = new Set<string>();
555 const records = dedupeWithinFile([...base, ...parsed.records], seen);
556 const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);
557​
558 return {
559 records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
560 update: {
561 entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position },
562 replaces: cached,
563 },
564 };
565 });
566​
567 /** One provider directory's walk and parse, before rates are involved. */
568 interface ScannedDir {
569 readonly provider: UsageProviderKind;
570 readonly dir: string;
571 readonly volumeId: string;
572 readonly hostId?: string;
573 readonly status?: UsageSource["status"];
574 readonly message?: string;
575 readonly action?: UsageSource["action"];
576 /** Parsed records per file, or `null` when the directory does not exist. */
577 readonly files:
578 | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
579 | null;
580 /** Answered from a cache while a refresh runs. */
581 readonly refreshing?: true;
582 }
583​
584 const scanTranscriptDir = Effect.fn("UsageService.scanTranscriptDir")(function* (
585 source: TranscriptSource,
586 windowStartMs: number,
587 ) {
588 const { provider, format, dir, volumeId, fileName } = source;
589 const exists = yield* fileSystem
590 .exists(dir)
591 .pipe(Effect.catchCause(() => Effect.succeed(false)));
592 if (!exists) return { provider, dir, volumeId, files: null } satisfies ScannedDir;
593 const files = yield* Effect.promise(() =>
594 listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
595 );
596 // A cold parse waits on disk reads, so a few files in flight read
597 // close to twice as fast. Results keep walk order.
598 const read = yield* Effect.forEach(
599 files,
600 (file) =>
601 readFileRecords(file.path, file.size, file.mtimeMs, provider, format).pipe(
602 Effect.map((result) => ({ path: file.path, ...result })),
603 ),
604 { concurrency: TRANSCRIPT_READ_CONCURRENCY },
605 );
606 const parsedFiles = read.map(({ path, records, update }) => {
607 if (update === undefined) return { path, records };
608 // A scan of another window may have cached its own read of this file
609 // meanwhile. Then keep whichever read saw the later file, so a slower
610 // scan never replaces newer usage with older.
611 const current = fileCache.get(path);
612 if (
613 current === update.replaces ||
614 current === undefined ||
615 !isLaterRead(current, update.entry)
616 ) {
617 fileCache.set(path, update.entry);
618 cacheDirty = true;
619 }
620 return { path, records };
621 });
622 return { provider, dir, volumeId, files: parsedFiles } satisfies ScannedDir;
623 });
624​
625 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
626 windowStartMs: number,
627 settings: ServerSettingsValue,
628 retentionCutoffMs: number,
629 awaitRefresh: boolean,
630 ) {
631 const dirs = yield* resolveTranscriptDirs(settings, retentionCutoffMs).pipe(
632 Effect.provideContext(readerContext),
633 );
634​
635 const scans = Effect.forEach(
636 scanReaders,
637 ({ driver, reader }) =>
638 reader
639 .scan({
640 instances: usageInstances(driver, settings),
641 settings,
642 windowStartMs,
643 retentionCutoffMs,
644 awaitRefresh,
645 })
646 .pipe(
647 Effect.flatMap((sources) =>
648 Effect.forEach(sources, ({ volumeId, ...source }) =>
649 Effect.map(
650 volumeId === undefined
651 ? Effect.promise(() => readDirectoryVolumeId(source.dir))
652 : Effect.succeed(volumeId),
653 (resolved): ScannedDir => ({
654 ...source,
655 provider: reader.provider,
656 volumeId: resolved,
657 }),
658 ),
659 ),
660 ),
661 Effect.provideContext(readerContext),
662 ),
663 { concurrency: "unbounded" },
664 );
665​
666 // Independent sources scan together. Transcript directories go one at a
667 // time, so open files stay at `TRANSCRIPT_READ_CONCURRENCY`. The result
668 // keeps this order, since aggregation keeps the first copy of a duplicate.
669 const [transcripts, scanDirs] = yield* Effect.all(
670 [Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs)), scans],
671 { concurrency: "unbounded" },
672 );
673 const scanned: readonly ScannedDir[] = [...transcripts, ...scanDirs.flat()];
674 return scanned;
675 });
676​
677 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
678 input: UsageSummaryInput,
679 settings: ServerSettingsValue,
680 ) {
681 if (input.sinceDay > input.untilDay) {
682 return yield* new UsageReadError({
683 reason: "invalidWindow",
684 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
685 });
686 }
687​
688 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
689 if (input.resolution === "hour") {
690 const sinceTime =
691 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
692 const untilTime =
693 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
694 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
695 return yield* new UsageReadError({
696 reason: "invalidWindow",
697 detail: "Hourly usage requires valid sinceTime and untilTime instants",
698 });
699 }
700 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
701 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
702 const durationMs = untilTimeMs - sinceTimeMs;
703 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
704 return yield* new UsageReadError({
705 reason: "invalidWindow",
706 detail: "Hourly usage window must be greater than zero and at most 24 hours",
707 });
708 }
709 hourlyWindow = { sinceTimeMs, untilTimeMs };
710 }
711​
712 const startedAtMs = yield* Clock.currentTimeMillis;
713 yield* ensureScanCacheLoaded;
714​
715 const hostId = NodeOS.hostname();
716 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
717 if (Option.isNone(windowStart)) {
718 return yield* new UsageReadError({
719 reason: "invalidWindow",
720 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
721 });
722 }
723 const windowStartMs =
724 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
725​
726 const retentionCutoffMs = startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000;
727​
728 // Pricing only matters once records are aggregated, so the rate table
729 // loads while transcripts stream instead of gating them: a cold rates
730 // fetch on a slow network no longer delays the scan by its own timeout.
731 const [, scannedDirs] = yield* Effect.all(
732 [
733 ensureRates(false),
734 collectDirs(windowStartMs, settings, retentionCutoffMs, input.awaitRefresh === true),
735 ],
736 { concurrency: 2 },
737 );
738​
739 const aggregator = new UsageAggregator({
740 timeZone: input.timeZone,
741 sinceDay: input.sinceDay,
742 untilDay: input.untilDay,
743 resolution: input.resolution ?? "day",
744 ...hourlyWindow,
745 rates,
746 priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
747 modelAliases: resolveModelAliases(settings.usageModelAliases),
748 });
749​
750 const sources: UsageSource[] = [];
751​
752 // Cleanup may remove transcripts, but the usage we already saved still
753 // contributes to its source through the normal aggregation and dedupe
754 // path. Like the walk, skip files last written before the window: they
755 // cannot hold records inside it.
756 const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs);
757 const filesByDir = scannedDirs.map(({ provider, dir, files }) => {
758 const retainedFiles = [...(files ?? [])];
759 const livePaths = new Set(retainedFiles.map((file) => file.path));
760 for (const [filePath, entry] of fileCache) {
761 if (
762 entry.provider !== provider ||
763 entry.mtimeMs < retainedSinceMs ||
764 livePaths.has(filePath) ||
765 !isWithinDirectory(filePath, dir)
766 )
767 continue;
768 retainedFiles.push({ path: filePath, records: [...entry.records, ...entry.tailRecords] });
769 }
770 return retainedFiles;
771 });
772 const crossFileSessions = sharedSessions(filesByDir.flat());
773​
774 for (const [
775 index,
776 { provider, dir, volumeId, files, status, message, action, refreshing, hostId: sourceHostId },
777 ] of scannedDirs.entries()) {
778 let scannedFiles = 0;
779 let skippedFiles = 0;
780 // Distinct per directory. Buckets carry per-cell session counts, but a
781 // session spans days and models, so clients total this figure instead.
782 const sessionIds = new Set<string>();
783​
784 for (const file of filesByDir[index] ?? []) {
785 if (file.records.length === 0) {
786 skippedFiles += 1;
787 continue;
788 }
789 scannedFiles += 1;
790 const eventOccurrences = new Map<string, number>();
791 for (const record of file.records) {
792 let usageRecord = record;
793 if (
794 sharedSessionProviders.has(record.provider) &&
795 crossFileSessions.has(record.sessionId)
796 ) {
797 // Match moved copies without collapsing repeated equal events
798 // within one file (timestamps can have only second precision).
799 // Only sessions seen in several files can have a copy to match.
800 const key = encodeUsageRecordKey([
801 record.provider,
802 record.sessionId,
803 record.timestampMs,
804 record.model,
805 record.totals,
806 ]);
807 const occurrence = (eventOccurrences.get(key) ?? 0) + 1;
808 eventOccurrences.set(key, occurrence);
809 usageRecord = { ...record, dedupeKey: key + ":" + occurrence };
810 }
811 // Only sessions contributing in-window count; the mtime slack can
812 // admit boundary files whose records fall outside the range.
813 if (aggregator.add(usageRecord, dir) && record.sessionId.length > 0) {
814 sessionIds.add(record.sessionId);
815 }
816 }
817 }
818​
819 sources.push({
820 fingerprint: { hostId: sourceHostId ?? hostId, provider, resolvedHomePath: dir, volumeId },
821 // Clients exclude missing sources, so saved records remain an available source.
822 status: files === null && scannedFiles === 0 ? "missing" : (status ?? "ok"),
823 scannedFiles,
824 skippedFiles,
825 malformedRecords: 0,
826 distinctSessions: sessionIds.size,
827 message:
828 message ?? (files === null ? "No transcript directory on this environment." : null),
829 ...(action ? { action } : {}),
830 ...(refreshing ? { refreshing } : {}),
831 });
832 }
833​
834 const pruned = pruneScanCache(fileCache, retentionCutoffMs);
835 if (pruned > 0) cacheDirty = true;
836​
837 const aggregated = aggregator.finish();
838 const readAt = yield* DateTime.now;
839 const finishedAtMs = yield* Clock.currentTimeMillis;
840​
841 return {
842 contractVersion: USAGE_CONTRACT_VERSION,
843 readAt: DateTime.formatIso(readAt),
844 timeZone: input.timeZone,
845 sinceDay: input.sinceDay,
846 untilDay: input.untilDay,
847 buckets: aggregated.buckets,
848 sources,
849 pricing: pricing(),
850 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
851 } satisfies UsageSummary;
852 });
853​
854 /**
855 * In-flight scans by window and settings, so concurrent identical requests (the usage
856 * page open on two clients at once) share one scan instead of racing over
857 * the same corpus twice. Readers read settings of their own, so a scan is
858 * shared only under the same settings snapshot.
859 */
860 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
861​
862 const scanKey = (input: UsageSummaryInput, settings: ServerSettingsValue): string =>
863 JSON.stringify([
864 input.timeZone,
865 input.sinceDay,
866 input.untilDay,
867 input.resolution ?? "day",
868 input.sinceTime ?? null,
869 input.untilTime ?? null,
870 settings,
871 // A waiting read must never share a scan that answers with `refreshing`.
872 input.awaitRefresh === true,
873 ]);
874​
875 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
876 const settings = yield* readSettings;
877 const key = scanKey(input, settings);
878 const deferred = yield* Effect.uninterruptible(
879 Effect.gen(function* () {
880 const existing = inflightScans.get(key);
881 if (existing !== undefined) return existing;
882​
883 // Enrollment and detached-fiber creation must be atomic. Otherwise a
884 // canceled first caller can leave a Deferred with no scan to finish it.
885 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
886 inflightScans.set(key, created);
887 // Detached so one departing client cannot tear the scan out from under
888 // the fibers awaiting it; a finished scan warms the cache either way.
889 // The cache write is registered before the waiters resume, so they
890 // can await it, but its fiber starts after they have the summary.
891 yield* scanSummary(input, settings).pipe(
892 Effect.onExit((exit) =>
893 Effect.sync(() => inflightScans.delete(key)).pipe(
894 Effect.andThen(Exit.isSuccess(exit) ? schedulePersist : Effect.void),
895 Effect.andThen(Deferred.done(created, exit)),
896 ),
897 ),
898 Effect.forkDetach,
899 );
900 return created;
901 }),
902 );
903 // Waiting stays interruptible. The detached scan continues for other
904 // callers and still warms the cache if this caller leaves.
905 return yield* Deferred.await(deferred);
906 });
907​
908 // `awaitPersisted` is outside the service interface: tests use it to restart
909 // against what a previous instance wrote.
910 return { readSummary, refreshRates, awaitPersisted } as const;
911});
912​
913export const layer = Layer.effect(UsageService, make);