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