Open History to see the last commit
1import * as NodeOS from "node:os";
2
3import {
4 type ProviderInstanceConfig,
5 ProviderInstanceId,
6 USAGE_CONTRACT_VERSION,
7 type ServerSettings as ServerSettingsValue,
8 type UsageProviderKind,
9 type UsageSource,
10 type UsagePricing,
11 type UsageSummary,
12 type UsageSummaryInput,
13 UsageReadError,
14} from "@t3tools/contracts";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import * as Cause from "effect/Cause";
17import * as Clock from "effect/Clock";
18import * as Context from "effect/Context";
19import * as DateTime from "effect/DateTime";
20import * as Deferred from "effect/Deferred";
21import * as Effect from "effect/Effect";
22import * as Exit from "effect/Exit";
23import * as Fiber from "effect/Fiber";
24import * as FileSystem from "effect/FileSystem";
25import * as Layer from "effect/Layer";
26import * as Option from "effect/Option";
27import * as Path from "effect/Path";
28import * as Schema from "effect/Schema";
29import * as Semaphore from "effect/Semaphore";
30import { HttpClient, HttpClientResponse } from "effect/http";
31
32import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
33import * as ServerConfig from "../config.ts";
34import * as ServerSettings from "../serverSettings.ts";
35import { BUILT_IN_USAGE_DRIVERS, type BuiltInUsageReadersEnv } from "../provider/builtInDrivers.ts";
36import type { ProviderDriver } from "@t3tools/provider-core/server/driver";
37import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
38import type {
39 ProviderUsageInstance,
40 TranscriptUsageFormat,
41 UsageRecord,
42} from "@t3tools/provider-core/server/usage";
43import { resolveModelAliases, UsageAggregator } from "./usageAggregation.ts";
44import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts";
45import {
46 listTranscriptFiles,
47 readDirectoryVolumeId,
48 readTranscriptRecords,
49} from "./usageTranscriptReader.ts";
50import {
51 decodeScanCache,
52 dedupeWithinFile,
53 LEGACY_SCAN_CACHE_FILE_NAMES,
54 makeScanCacheWriter,
55 pruneScanCache,
56 SCAN_CACHE_FILE_NAME,
57 type CachedFile,
58 type ScanCache,
59} from "./usageScanCache.ts";
60
61const LITELLM_RATES_URL =
62 "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
63const LITELLM_RATES_API_URL =
64 "https://api.github.com/repos/BerriAI/litellm/contents/model_prices_and_context_window.json?ref=main";
65
66const RATES_TTL_MS = 24 * 60 * 60 * 1000;
67
68const RATES_REFRESH_FLOOR_MS = 60 * 1000;
69
70// mtime slack includes writes just before local midnight on the window's first day.
71const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
72const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
73
74const CACHE_RETENTION_DAYS = 92;
75
76const TRANSCRIPT_READ_CONCURRENCY = 4;
77
78const transcriptReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) =>
79 driver.usage?.kind === "transcripts" ? [{ driver, reader: driver.usage }] : [],
80);
81
82const scanReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) =>
83 driver.usage?.kind === "scan" ? [{ driver, reader: driver.usage }] : [],
84);
85
86const transcriptFormats = new Map(
87 transcriptReaders.map(({ reader }) => [reader.provider, reader.format] as const),
88);
89
90interface TranscriptSource {
91 readonly provider: UsageProviderKind;
92 readonly format: TranscriptUsageFormat<unknown>;
93 readonly dir: string;
94 readonly volumeId: string;
95 readonly fileName?: string;
96}
97
98const RatesCacheFile = Schema.Struct({
99 fetchedAtMs: Schema.Number,
100 document: Schema.Unknown,
101});
102const decodeRatesCache = Schema.decodeUnknownEffect(
103 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
104);
105const encodeRatesCache = Schema.encodeEffect(
106 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
107);
108
109const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);
110const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
111const encodeUsageRecordKey = Schema.encodeSync(ScanCacheJson);
112const CachedSource = Schema.Struct({ dir: Schema.String, volumeId: Schema.String });
113
114function isLaterRead(a: CachedFile, b: CachedFile): boolean {
115 return a.mtimeMs > b.mtimeMs || (a.mtimeMs === b.mtimeMs && a.size > b.size);
116}
117
118const sharedSessionProviders: ReadonlySet<UsageProviderKind> = new Set(
119 transcriptReaders.flatMap(({ reader }) =>
120 reader.format.sharedSessionsAcrossFiles ? [reader.provider] : [],
121 ),
122);
123
124// Only shared sessions need cross-file dedupe; per-file occurrence counts make other keys unique.
125function sharedSessions(
126 files: readonly { readonly records: readonly UsageRecord[] }[],
127): ReadonlySet<string> {
128 const firstFile = new Map<string, number>();
129 const shared = new Set<string>();
130 for (const [index, file] of files.entries()) {
131 let previous = "";
132 for (const { provider, sessionId } of file.records) {
133 if (!sharedSessionProviders.has(provider) || sessionId === previous || sessionId.length === 0)
134 continue;
135 previous = sessionId;
136 const first = firstFile.get(sessionId);
137 if (first === undefined) firstFile.set(sessionId, index);
138 else if (first !== index) shared.add(sessionId);
139 }
140 }
141 return shared;
142}
143const decodeCachedSources = Schema.decodeUnknownOption(
144 Schema.Struct({ sources: Schema.Record(Schema.String, CachedSource) }),
145);
146
147export class UsageService extends Context.Service<
148 UsageService,
149 {
150 readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
151 readonly refreshRates: Effect.Effect<UsagePricing>;
152 }
153>()("t3/usage/UsageService") {}
154
155const EMPTY_PRICING: UsagePricing = {
156 status: "unavailable",
157 source: LITELLM_RATES_URL,
158 fetchedAt: null,
159 knownModels: 0,
160};
161
162const layerTest = Layer.succeed(
163 UsageService,
164 UsageService.of({
165 readSummary: (input) =>
166 Effect.succeed({
167 contractVersion: USAGE_CONTRACT_VERSION,
168 readAt: "1970-01-01T00:00:00.000Z",
169 timeZone: input.timeZone,
170 sinceDay: input.sinceDay,
171 untilDay: input.untilDay,
172 buckets: [],
173 sources: [],
174 pricing: EMPTY_PRICING,
175 scanDurationMs: 0,
176 }),
177 refreshRates: Effect.succeed(EMPTY_PRICING),
178 }),
179);
180
181export const make = Effect.gen(function* () {
182 const fileSystem = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184 const config = yield* ServerConfig.ServerConfig;
185 const settingsService = yield* ServerSettings.ServerSettingsService;
186 const httpClient = yield* HttpClient.HttpClient;
187 const hostEnvironment = yield* HostProcess.Environment;
188 const readerContext = yield* Effect.context<BuiltInUsageReadersEnv>();
189
190 const fileCache: ScanCache = new Map();
191 // Reads from concurrent windows can still hold the original record after it is corrected.
192 const resolvedRecords = new WeakMap<UsageRecord, UsageRecord>();
193 const correctedRecord = (record: UsageRecord) => resolvedRecords.get(record) ?? record;
194 const correctedBatch = (records: readonly UsageRecord[]) =>
195 records.some((record) => resolvedRecords.has(record)) ? records.map(correctedRecord) : records;
196 const sourceCache = new Map<string, typeof CachedSource.Type>();
197 let cacheDirty = false;
198 const isWithinDirectory = (filePath: string, dir: string) => {
199 const relative = path.relative(dir, filePath);
200 return relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative);
201 };
202
203 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
204 const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME);
205 const writeCacheFile = (filePath: string, contents: string) =>
206 writeFileStringAtomically({ filePath, contents }).pipe(
207 Effect.provideService(FileSystem.FileSystem, fileSystem),
208 Effect.provideService(Path.Path, path),
209 );
210 let rates: RateTable = new Map();
211 let ratesFetchedAtMs: number | null = null;
212 let ratesLastFailedAtMs: number | null = null;
213 let ratesStatus: UsagePricing["status"] = "unavailable";
214 const ratesLock = yield* Semaphore.make(1);
215
216 const pricing = (): UsagePricing => ({
217 status: ratesStatus,
218 source: LITELLM_RATES_URL,
219 fetchedAt:
220 ratesFetchedAtMs === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
221 knownModels: rates.size,
222 });
223
224 const fetchRates = (url: string, accept = "application/json") =>
225 httpClient.get(url, { headers: { accept } }).pipe(
226 Effect.flatMap(HttpClientResponse.filterStatusOk),
227 Effect.flatMap((response) => response.json),
228 Effect.map((document) => {
229 const parsed = parseRateTable(document);
230 return parsed.size > 0 ? { document, parsed } : null;
231 }),
232 Effect.timeout(10_000),
233 Effect.catchCause(() => Effect.succeed(null)),
234 );
235
236 const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) {
237 const now = yield* Clock.currentTimeMillis;
238 const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS;
239 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return;
240
241 if (ratesFetchedAtMs === null) {
242 const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(
243 Effect.flatMap((raw) => decodeRatesCache(raw)),
244 Effect.catchCause(() => Effect.succeed(null)),
245 );
246 if (fromDisk !== null) {
247 const parsed = parseRateTable(fromDisk.document);
248 if (parsed.size > 0) {
249 rates = parsed;
250 ratesFetchedAtMs = fromDisk.fetchedAtMs;
251 ratesStatus = "cached";
252 if (now - fromDisk.fetchedAtMs < maxAgeMs) return;
253 }
254 }
255 }
256
257 if (ratesLastFailedAtMs !== null && now - ratesLastFailedAtMs < RATES_REFRESH_FLOOR_MS) return;
258
259 let fetched = yield* fetchRates(LITELLM_RATES_URL);
260 if (fetched === null) {
261 fetched = yield* fetchRates(LITELLM_RATES_API_URL, "application/vnd.github.raw+json");
262 }
263 if (fetched === null) {
264 ratesLastFailedAtMs = yield* Clock.currentTimeMillis;
265 if (rates.size > 0) ratesStatus = "cached";
266 return;
267 }
268
269 rates = fetched.parsed;
270 ratesFetchedAtMs = now;
271 ratesLastFailedAtMs = null;
272 ratesStatus = "fresh";
273
274 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched.document }).pipe(
275 Effect.flatMap((contents) => writeCacheFile(ratesCachePath, contents)),
276 Effect.ignoreCause,
277 );
278 });
279
280 const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force));
281
282 const refreshRates = ensureRates(true).pipe(
283 Effect.map(pricing),
284 Effect.withSpan("UsageService.refreshRates"),
285 );
286
287 const readSettings = settingsService.getSettings.pipe(
288 Effect.catchCause(
289 (cause) =>
290 new UsageReadError({
291 reason: "scanFailed",
292 detail: "Server settings could not be read.",
293 cause: Cause.squash(cause),
294 }),
295 ),
296 );
297
298 const usageInstances = Effect.fn("UsageService.usageInstances")(function* <Config>(
299 driver: ProviderDriver<Config, unknown, unknown>,
300 settings: ServerSettingsValue,
301 ) {
302 const entries: Array<
303 readonly [ProviderInstanceId, Pick<ProviderInstanceConfig, "config" | "environment">, boolean]
304 > = Object.entries(settings.providerInstances)
305 .filter(([, instance]) => instance.driver === driver.driverKind)
306 .map(([id, instance]) => [ProviderInstanceId.make(id), instance, true] as const);
307 if (!Object.hasOwn(settings.providerInstances, driver.driverKind)) {
308 entries.push([ProviderInstanceId.make(driver.driverKind), {}, false]);
309 }
310 const decodeConfig = Schema.decodeUnknownOption(driver.configSchema);
311 return yield* Effect.forEach(
312 entries,
313 Effect.fnUntraced(function* ([instanceId, instance, configured]) {
314 const instanceConfig: ProviderUsageInstance<Config> = {
315 instanceId,
316 config: Option.getOrUndefined(decodeConfig(instance.config ?? {})),
317 environment: yield* mergeProviderInstanceEnvironment(
318 instance.environment,
319 hostEnvironment,
320 ),
321 configured,
322 };
323 return instanceConfig;
324 }),
325 );
326 });
327
328 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (
329 settings: ServerSettingsValue,
330 retentionCutoffMs: number,
331 ) {
332 const dirs: Array<TranscriptSource> = [];
333 const seen = new Set<string>();
334 for (const { driver, reader } of transcriptReaders) {
335 const { provider, format } = reader;
336 const directories = yield* Effect.forEach(
337 yield* usageInstances(driver, settings),
338 (instance) => reader.directories(instance),
339 );
340 for (const { dir: directory, fileName } of directories.flat()) {
341 const sourceKey = provider + "\0" + directory;
342 const previous = sourceCache.get(sourceKey);
343 const dir = yield* fileSystem
344 .realPath(directory)
345 .pipe(Effect.orElseSucceed(() => previous?.dir ?? directory));
346 const currentVolumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
347 const hasRetainedHistory = fileCache
348 .entries()
349 .some(
350 ([filePath, entry]) =>
351 entry.provider === provider &&
352 entry.mtimeMs >= retentionCutoffMs &&
353 (entry.records.length + entry.tailRecords.length > 0 || entry.malformedRecords > 0) &&
354 isWithinDirectory(filePath, dir),
355 );
356 const volumeId =
357 previous?.dir === dir && (hasRetainedHistory || !currentVolumeId)
358 ? previous.volumeId || currentVolumeId
359 : currentVolumeId;
360 if (previous?.dir !== dir || previous.volumeId !== volumeId) {
361 sourceCache.set(sourceKey, { dir, volumeId });
362 cacheDirty = true;
363 }
364 const key = `${provider}\0${dir}`;
365 if (seen.has(key)) continue;
366 seen.add(key);
367 dirs.push({
368 provider,
369 format,
370 dir,
371 volumeId,
372 ...(fileName === undefined ? {} : { fileName }),
373 });
374 }
375 }
376 return dirs;
377 });
378
379 // Share first loads so concurrent readers cannot scan against a still-empty cache.
380 const ensureScanCacheLoaded = yield* Effect.cached(
381 Effect.gen(function* () {
382 const readDocument = (filePath: string) =>
383 fileSystem.readFileString(filePath).pipe(
384 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
385 Effect.catchCause(() => Effect.succeed(null)),
386 );
387 let document = yield* readDocument(scanCachePath);
388 for (const fileName of LEGACY_SCAN_CACHE_FILE_NAMES) {
389 if (document !== null) break;
390 document = yield* readDocument(path.join(config.stateDir, fileName));
391 cacheDirty = document !== null;
392 }
393 if (document === null) return;
394 for (const [path, entry] of decodeScanCache(document, transcriptFormats)) {
395 fileCache.set(path, entry);
396 }
397 const sources = decodeCachedSources(document);
398 if (Option.isSome(sources)) {
399 for (const [key, source] of Object.entries(sources.value.sources))
400 sourceCache.set(key, source);
401 }
402 }),
403 );
404
405 const writeScanCache = makeScanCacheWriter();
406 // Serialize writes so concurrently finished window scans cannot overwrite newer snapshots.
407 const persistLock = yield* Semaphore.make(1);
408
409 // Clear dirty before encoding to retain concurrent changes; restore it on failure for retry.
410 const persistCaches = Effect.gen(function* () {
411 if (cacheDirty) {
412 cacheDirty = false;
413 yield* Effect.sync(() =>
414 writeScanCache(fileCache, { sources: Object.fromEntries(sourceCache) }),
415 ).pipe(
416 Effect.flatMap((contents) => writeCacheFile(scanCachePath, contents)),
417 Effect.catchCause(() =>
418 Effect.sync(() => {
419 cacheDirty = true;
420 }),
421 ),
422 );
423 }
424 }).pipe(persistLock.withPermit, Effect.withSpan("UsageService.persistCaches"));
425
426 const pendingPersists = new Set<Fiber.Fiber<void>>();
427 const schedulePersist = Effect.forkDetach(persistCaches).pipe(
428 Effect.map((fiber) => {
429 pendingPersists.add(fiber);
430 fiber.addObserver(() => pendingPersists.delete(fiber));
431 }),
432 );
433 const awaitPersisted = Effect.suspend(() => Fiber.awaitAll([...pendingPersists])).pipe(
434 Effect.asVoid,
435 );
436 yield* Effect.addFinalizer(() => awaitPersisted);
437
438 /**
439 * Reads run concurrently, and the caller stores updates in walk order rather
440 * than completion order: saved records of deleted transcripts aggregate in
441 * cache order, where the first copy of a duplicate wins.
442 */
443 const readFileRecords = Effect.fn("UsageService.readFileRecords")(function* (
444 filePath: string,
445 size: number,
446 mtimeMs: number,
447 provider: UsageProviderKind,
448 format: TranscriptUsageFormat<unknown>,
449 ): Effect.fn.Return<{
450 readonly records: readonly UsageRecord[];
451 readonly malformedRecords: number;
452 readonly failed?: true;
453 readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
454 }> {
455 const cached = fileCache.get(filePath);
456 // Provider is part of the identity: if both providers were ever pointed
457 // at one directory, a hit parsed by the other parser must not be reused.
458 if (
459 cached &&
460 cached.size === size &&
461 cached.mtimeMs === mtimeMs &&
462 cached.provider === provider
463 ) {
464 return {
465 records:
466 cached.tailRecords.length === 0
467 ? cached.records
468 : [...cached.records, ...cached.tailRecords],
469 malformedRecords: cached.malformedRecords,
470 };
471 }
472
473 // Only a strictly grown file may resume. Same size with a new mtime, or
474 // a shrunken file, means rewritten content; re-parse it whole.
475 const resumeFrom =
476 cached !== undefined && cached.provider === provider && size > cached.size
477 ? cached.position
478 : undefined;
479
480 const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, format, resumeFrom));
481 // A read failure is not an empty transcript: caching it under this
482 // (size, mtime) would silently drop the file's usage until it changes.
483 if (parsed === null)
484 return {
485 records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
486 malformedRecords: cached?.provider === provider ? cached.malformedRecords : 0,
487 failed: true,
488 };
489
490 if (parsed.resumed && cached !== undefined && cached.tailRecords.length > 0) {
491 // Completing a tentative line reparses it. Reuse its saved correction only when the
492 // same usage is emitted again, without putting inferred tiers in the parser state.
493 const reparsed = [...parsed.records, ...parsed.tailRecords];
494 const identity = (record: UsageRecord) =>
495 encodeUsageRecordKey([
496 record.provider,
497 record.sessionId,
498 record.timestampMs,
499 record.model,
500 record.rateModel,
501 record.totals,
502 record.reportedCostUsd,
503 record.dedupeKey,
504 ]);
505 for (const [index, previous] of cached.tailRecords.entries()) {
506 const record = reparsed[index];
507 const corrected = correctedRecord(previous);
508 if (
509 record?.unresolvedServiceTierTurnId !== undefined &&
510 corrected.unresolvedServiceTierTurnId === undefined &&
511 identity(record) === identity(corrected)
512 ) {
513 resolvedRecords.set(record, corrected);
514 }
515 }
516 }
517 const base = parsed.resumed && cached !== undefined ? cached.records : [];
518 const seen = new Set<string>();
519 const records = dedupeWithinFile([...base, ...parsed.records], seen);
520 const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);
521
522 return {
523 records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
524 malformedRecords: parsed.malformedRecords,
525 update: {
526 entry: {
527 size,
528 mtimeMs,
529 provider,
530 records,
531 tailRecords,
532 malformedRecords: parsed.malformedRecords,
533 position: parsed.position,
534 },
535 replaces: cached,
536 },
537 };
538 });
539
540 interface ScannedDir {
541 readonly provider: UsageProviderKind;
542 readonly dir: string;
543 readonly volumeId: string;
544 readonly hostId?: string;
545 readonly status?: UsageSource["status"];
546 readonly message?: string;
547 readonly action?: UsageSource["action"];
548 readonly files:
549 | readonly {
550 readonly path: string;
551 readonly records: readonly UsageRecord[];
552 readonly malformedRecords: number;
553 }[]
554 | null;
555 readonly refreshing?: true;
556 }
557
558 const scanTranscriptDir = Effect.fn("UsageService.scanTranscriptDir")(function* (
559 source: TranscriptSource,
560 windowStartMs: number,
561 ) {
562 const { provider, format, dir, volumeId, fileName } = source;
563 const exists = yield* fileSystem
564 .exists(dir)
565 .pipe(Effect.catchCause(() => Effect.succeed(false)));
566 if (!exists) return { provider, dir, volumeId, files: null } satisfies ScannedDir;
567 const { files, failedPaths } = yield* Effect.promise(() =>
568 listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
569 );
570 const read = yield* Effect.forEach(
571 files,
572 (file) =>
573 readFileRecords(file.path, file.size, file.mtimeMs, provider, format).pipe(
574 Effect.map((result) => ({ path: file.path, ...result })),
575 ),
576 { concurrency: TRANSCRIPT_READ_CONCURRENCY },
577 );
578 const parsedFiles = read.map(({ path, records, malformedRecords, update }) => {
579 if (update === undefined) return { path, records, malformedRecords };
580 // A scan of another window may have cached its own read of this file
581 // meanwhile. Then keep whichever read saw the later file, so a slower
582 // scan never replaces newer usage with older.
583 const current = fileCache.get(path);
584 if (
585 current === update.replaces ||
586 current === undefined ||
587 isLaterRead(update.entry, current)
588 ) {
589 fileCache.set(path, {
590 ...update.entry,
591 records: correctedBatch(update.entry.records),
592 tailRecords: correctedBatch(update.entry.tailRecords),
593 });
594 cacheDirty = true;
595 }
596 return { path, records, malformedRecords };
597 });
598 const unread = failedPaths + read.filter((file) => file.failed).length;
599 return {
600 provider,
601 dir,
602 volumeId,
603 files: parsedFiles,
604 ...(unread > 0
605 ? {
606 status: "partial",
607 message: `${unread} transcript path(s) could not be read; usage may be incomplete.`,
608 }
609 : {}),
610 } satisfies ScannedDir;
611 });
612
613 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
614 windowStartMs: number,
615 settings: ServerSettingsValue,
616 retentionCutoffMs: number,
617 awaitRefresh: boolean,
618 ) {
619 const dirs = yield* resolveTranscriptDirs(settings, retentionCutoffMs).pipe(
620 Effect.provideContext(readerContext),
621 );
622
623 const scans = Effect.forEach(
624 scanReaders,
625 ({ driver, reader }) =>
626 usageInstances(driver, settings)
627 .pipe(
628 Effect.flatMap((instances) =>
629 reader.scan({ instances, settings, windowStartMs, retentionCutoffMs, awaitRefresh }),
630 ),
631 )
632 .pipe(
633 Effect.flatMap((sources) =>
634 Effect.forEach(sources, ({ volumeId, ...source }) =>
635 Effect.map(
636 volumeId === undefined
637 ? Effect.promise(() => readDirectoryVolumeId(source.dir))
638 : Effect.succeed(volumeId),
639 (resolved): ScannedDir => ({
640 ...source,
641 files: source.files?.map((file) => ({ ...file, malformedRecords: 0 })) ?? null,
642 provider: reader.provider,
643 volumeId: resolved,
644 }),
645 ),
646 ),
647 ),
648 Effect.provideContext(readerContext),
649 ),
650 { concurrency: "unbounded" },
651 );
652
653 // Scan independent sources together, directories sequentially to bound open files; preserve order for first-copy dedupe.
654 const [transcripts, scanDirs] = yield* Effect.all(
655 [Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs)), scans],
656 { concurrency: "unbounded" },
657 );
658 const scanned: readonly ScannedDir[] = [...transcripts, ...scanDirs.flat()];
659 return scanned;
660 });
661
662 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
663 input: UsageSummaryInput,
664 settings: ServerSettingsValue,
665 ) {
666 if (input.sinceDay > input.untilDay) {
667 return yield* new UsageReadError({
668 reason: "invalidWindow",
669 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
670 });
671 }
672
673 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
674 if (input.resolution === "hour") {
675 const sinceTime =
676 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
677 const untilTime =
678 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
679 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
680 return yield* new UsageReadError({
681 reason: "invalidWindow",
682 detail: "Hourly usage requires valid sinceTime and untilTime instants",
683 });
684 }
685 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
686 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
687 const durationMs = untilTimeMs - sinceTimeMs;
688 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
689 return yield* new UsageReadError({
690 reason: "invalidWindow",
691 detail: "Hourly usage window must be greater than zero and at most 24 hours",
692 });
693 }
694 hourlyWindow = { sinceTimeMs, untilTimeMs };
695 }
696
697 const startedAtMs = yield* Clock.currentTimeMillis;
698 yield* ensureScanCacheLoaded;
699
700 const hostId = NodeOS.hostname();
701 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
702 if (Option.isNone(windowStart)) {
703 return yield* new UsageReadError({
704 reason: "invalidWindow",
705 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
706 });
707 }
708 const windowStartMs =
709 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
710
711 const retentionCutoffMs = startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000;
712
713 const [, scannedDirs] = yield* Effect.all(
714 [
715 ensureRates(false),
716 collectDirs(windowStartMs, settings, retentionCutoffMs, input.awaitRefresh === true),
717 ],
718 { concurrency: 2 },
719 );
720
721 const aggregator = new UsageAggregator({
722 timeZone: input.timeZone,
723 sinceDay: input.sinceDay,
724 untilDay: input.untilDay,
725 resolution: input.resolution ?? "day",
726 ...hourlyWindow,
727 rates,
728 priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
729 modelAliases: resolveModelAliases(settings.usageModelAliases),
730 });
731
732 const sources: UsageSource[] = [];
733
734 // Deleted transcripts' saved usage still aggregates and deduplicates normally.
735 const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs);
736 const filesByDir = scannedDirs.map(({ provider, dir, files }) => {
737 const retainedFiles = [...(files ?? [])];
738 const livePaths = new Set(retainedFiles.map((file) => file.path));
739 for (const [filePath, entry] of fileCache) {
740 if (
741 entry.provider !== provider ||
742 entry.mtimeMs < retainedSinceMs ||
743 livePaths.has(filePath) ||
744 !isWithinDirectory(filePath, dir)
745 )
746 continue;
747 retainedFiles.push({
748 path: filePath,
749 records: [...entry.records, ...entry.tailRecords],
750 malformedRecords: entry.malformedRecords,
751 });
752 }
753 return retainedFiles;
754 });
755 const windowEndMs =
756 hourlyWindow?.untilTimeMs ??
757 Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS;
758 let resolvedAny = false;
759 for (const { reader } of transcriptReaders) {
760 if (reader.resolveServiceTiers === undefined) continue;
761 const pending = new Set<UsageRecord>();
762 for (const [index, files] of filesByDir.entries()) {
763 if (scannedDirs[index]?.provider !== reader.provider) continue;
764 for (const file of files) {
765 for (const raw of file.records) {
766 const record = correctedRecord(raw);
767 if (
768 record.provider === reader.provider &&
769 record.unresolvedServiceTierTurnId !== undefined &&
770 record.timestampMs >= windowStartMs &&
771 record.timestampMs < windowEndMs
772 ) {
773 pending.add(record);
774 }
775 }
776 }
777 }
778 if (pending.size === 0) continue;
779 const resolved = yield* reader
780 .resolveServiceTiers([...pending])
781 .pipe(Effect.provideContext(readerContext));
782 for (const [record, speed] of resolved) {
783 const { unresolvedServiceTierTurnId: _turnId, ...rest } = record;
784 resolvedRecords.set(record, { ...rest, speed });
785 resolvedAny = true;
786 }
787 }
788 if (resolvedAny) {
789 for (const [filePath, entry] of fileCache) {
790 const records = correctedBatch(entry.records);
791 const tailRecords = correctedBatch(entry.tailRecords);
792 if (records === entry.records && tailRecords === entry.tailRecords) continue;
793 // Update the current entry by identity; a slow resolver cannot restore an older file.
794 fileCache.set(filePath, { ...entry, records, tailRecords });
795 cacheDirty = true;
796 }
797 }
798 const crossFileSessions = sharedSessions(filesByDir.flat());
799
800 for (const [
801 index,
802 { provider, dir, volumeId, files, status, message, action, refreshing, hostId: sourceHostId },
803 ] of scannedDirs.entries()) {
804 let scannedFiles = 0;
805 let skippedFiles = 0;
806 let malformedRecords = 0;
807 // Distinct per directory. Buckets carry per-cell session counts, but a
808 // session spans days and models, so clients total this figure instead.
809 const sessionIds = new Set<string>();
810
811 for (const file of filesByDir[index] ?? []) {
812 malformedRecords += file.malformedRecords;
813 if (file.records.length === 0) {
814 skippedFiles += 1;
815 continue;
816 }
817 scannedFiles += 1;
818 const eventOccurrences = new Map<string, number>();
819 for (const rawRecord of file.records) {
820 const record = correctedRecord(rawRecord);
821 let usageRecord = record;
822 if (
823 sharedSessionProviders.has(record.provider) &&
824 crossFileSessions.has(record.sessionId)
825 ) {
826 // Dedupe moved copies but retain repeated equal events within a file, including second-precision timestamps.
827 const key = encodeUsageRecordKey([
828 record.provider,
829 record.sessionId,
830 record.timestampMs,
831 record.model,
832 record.totals,
833 ]);
834 const occurrence = (eventOccurrences.get(key) ?? 0) + 1;
835 eventOccurrences.set(key, occurrence);
836 usageRecord = { ...record, dedupeKey: key + ":" + occurrence };
837 }
838 if (aggregator.add(usageRecord, dir) && record.sessionId.length > 0) {
839 sessionIds.add(record.sessionId);
840 }
841 }
842 }
843
844 const sourceMessage =
845 message ?? (files === null ? "No transcript directory on this environment." : null);
846 sources.push({
847 fingerprint: { hostId: sourceHostId ?? hostId, provider, resolvedHomePath: dir, volumeId },
848 status:
849 files === null && scannedFiles === 0
850 ? "missing"
851 : malformedRecords > 0
852 ? status === undefined || status === "ok"
853 ? "partial"
854 : status
855 : (status ?? "ok"),
856 scannedFiles,
857 skippedFiles,
858 malformedRecords,
859 distinctSessions: sessionIds.size,
860 message:
861 malformedRecords > 0
862 ? [
863 sourceMessage,
864 `${malformedRecords} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`,
865 ]
866 .filter(Boolean)
867 .join(" ")
868 : sourceMessage,
869 ...(action ? { action } : {}),
870 ...(refreshing ? { refreshing } : {}),
871 });
872 }
873
874 const pruned = pruneScanCache(fileCache, retentionCutoffMs);
875 if (pruned > 0) cacheDirty = true;
876
877 const aggregated = aggregator.finish();
878 const readAt = yield* DateTime.now;
879 const finishedAtMs = yield* Clock.currentTimeMillis;
880
881 return {
882 contractVersion: USAGE_CONTRACT_VERSION,
883 readAt: DateTime.formatIso(readAt),
884 timeZone: input.timeZone,
885 sinceDay: input.sinceDay,
886 untilDay: input.untilDay,
887 buckets: aggregated.buckets,
888 sources,
889 pricing: pricing(),
890 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
891 } satisfies UsageSummary;
892 });
893
894 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
895
896 const scanKey = (input: UsageSummaryInput, settings: ServerSettingsValue): string =>
897 JSON.stringify([
898 input.timeZone,
899 input.sinceDay,
900 input.untilDay,
901 input.resolution ?? "day",
902 input.sinceTime ?? null,
903 input.untilTime ?? null,
904 settings,
905 input.awaitRefresh === true,
906 ]);
907
908 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
909 const settings = yield* readSettings;
910 const key = scanKey(input, settings);
911 const deferred = yield* Effect.uninterruptible(
912 Effect.gen(function* () {
913 const existing = inflightScans.get(key);
914 if (existing !== undefined) return existing;
915
916 // Register and fork atomically so cancellation cannot leave a Deferred without a scan.
917 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
918 inflightScans.set(key, created);
919 // Detach so caller departure cannot cancel shared scans; finished scans warm the cache.
920 // Register writes before releasing waiters, but start writing after delivering their summary.
921 yield* scanSummary(input, settings).pipe(
922 Effect.onExit((exit) =>
923 Effect.sync(() => inflightScans.delete(key)).pipe(
924 Effect.andThen(Exit.isSuccess(exit) ? schedulePersist : Effect.void),
925 Effect.andThen(Deferred.done(created, exit)),
926 ),
927 ),
928 Effect.forkDetach,
929 );
930 return created;
931 }),
932 );
933 return yield* Deferred.await(deferred);
934 });
935
936 return { readSummary, refreshRates, awaitPersisted } as const;
937});
938
939export const layer = Layer.effect(UsageService, make);