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_NAME,
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 legacyScanCachePath = path.join(config.stateDir, LEGACY_SCAN_CACHE_FILE_NAME);
208 const writeCacheFile = (filePath: string, contents: string) =>
209 writeFileStringAtomically({ filePath, contents }).pipe(
210 Effect.provideService(FileSystem.FileSystem, fileSystem),
211 Effect.provideService(Path.Path, path),
212 );
213 let rates: RateTable = new Map();
214 let ratesFetchedAtMs: number | null = null;
215 let ratesLastFailedAtMs: number | null = null;
216 let ratesStatus: UsagePricing["status"] = "unavailable";
217 const ratesLock = yield* Semaphore.make(1);
218
219 const pricing = (): UsagePricing => ({
220 status: ratesStatus,
221 source: LITELLM_RATES_URL,
222 fetchedAt:
223 ratesFetchedAtMs === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
224 knownModels: rates.size,
225 });
226
227 const fetchRates = (url: string, accept = "application/json") =>
228 httpClient.get(url, { headers: { accept } }).pipe(
229 Effect.flatMap(HttpClientResponse.filterStatusOk),
230 Effect.flatMap((response) => response.json),
231 Effect.map((document) => {
232 const parsed = parseRateTable(document);
233 return parsed.size > 0 ? { document, parsed } : null;
234 }),
235 Effect.timeout(10_000),
236 Effect.catchCause(() => Effect.succeed(null)),
237 );
238
239 const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) {
240 const now = yield* Clock.currentTimeMillis;
241 const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS;
242 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return;
243
244 if (ratesFetchedAtMs === null) {
245 const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(
246 Effect.flatMap((raw) => decodeRatesCache(raw)),
247 Effect.catchCause(() => Effect.succeed(null)),
248 );
249 if (fromDisk !== null) {
250 const parsed = parseRateTable(fromDisk.document);
251 if (parsed.size > 0) {
252 rates = parsed;
253 ratesFetchedAtMs = fromDisk.fetchedAtMs;
254 ratesStatus = "cached";
255 if (now - fromDisk.fetchedAtMs < maxAgeMs) return;
256 }
257 }
258 }
259
260 if (ratesLastFailedAtMs !== null && now - ratesLastFailedAtMs < RATES_REFRESH_FLOOR_MS) return;
261
262 let fetched = yield* fetchRates(LITELLM_RATES_URL);
263 if (fetched === null) {
264 fetched = yield* fetchRates(LITELLM_RATES_API_URL, "application/vnd.github.raw+json");
265 }
266 if (fetched === null) {
267 ratesLastFailedAtMs = yield* Clock.currentTimeMillis;
268 if (rates.size > 0) ratesStatus = "cached";
269 return;
270 }
271
272 rates = fetched.parsed;
273 ratesFetchedAtMs = now;
274 ratesLastFailedAtMs = null;
275 ratesStatus = "fresh";
276
277 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched.document }).pipe(
278 Effect.flatMap((contents) => writeCacheFile(ratesCachePath, contents)),
279 Effect.ignoreCause,
280 );
281 });
282
283 const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force));
284
285 const refreshRates = ensureRates(true).pipe(
286 Effect.map(pricing),
287 Effect.withSpan("UsageService.refreshRates"),
288 );
289
290 const readSettings = settingsService.getSettings.pipe(
291 Effect.catchCause(
292 (cause) =>
293 new UsageReadError({
294 reason: "scanFailed",
295 detail: "Server settings could not be read.",
296 cause: Cause.squash(cause),
297 }),
298 ),
299 );
300
301 const usageInstances = Effect.fn("UsageService.usageInstances")(function* <Config>(
302 driver: ProviderDriver<Config, unknown, unknown>,
303 settings: ServerSettingsValue,
304 ) {
305 const entries: Array<
306 readonly [ProviderInstanceId, Pick<ProviderInstanceConfig, "config" | "environment">, boolean]
307 > = Object.entries(settings.providerInstances)
308 .filter(([, instance]) => instance.driver === driver.driverKind)
309 .map(([id, instance]) => [ProviderInstanceId.make(id), instance, true] as const);
310 if (!Object.hasOwn(settings.providerInstances, driver.driverKind)) {
311 entries.push([ProviderInstanceId.make(driver.driverKind), {}, false]);
312 }
313 const decodeConfig = Schema.decodeUnknownOption(driver.configSchema);
314 return yield* Effect.forEach(
315 entries,
316 Effect.fnUntraced(function* ([instanceId, instance, configured]) {
317 const instanceConfig: ProviderUsageInstance<Config> = {
318 instanceId,
319 config: Option.getOrUndefined(decodeConfig(instance.config ?? {})),
320 environment: yield* mergeProviderInstanceEnvironment(
321 instance.environment,
322 hostEnvironment,
323 ),
324 configured,
325 };
326 return instanceConfig;
327 }),
328 );
329 });
330
331 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (
332 settings: ServerSettingsValue,
333 retentionCutoffMs: number,
334 ) {
335 const dirs: Array<TranscriptSource> = [];
336 const seen = new Set<string>();
337 for (const { driver, reader } of transcriptReaders) {
338 const { provider, format } = reader;
339 const directories = yield* Effect.forEach(
340 yield* usageInstances(driver, settings),
341 (instance) => reader.directories(instance),
342 );
343 for (const { dir: directory, fileName } of directories.flat()) {
344 const sourceKey = provider + "\0" + directory;
345 const previous = sourceCache.get(sourceKey);
346 const dir = yield* fileSystem
347 .realPath(directory)
348 .pipe(Effect.orElseSucceed(() => previous?.dir ?? directory));
349 const currentVolumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
350 const hasRetainedHistory = fileCache
351 .entries()
352 .some(
353 ([filePath, entry]) =>
354 entry.provider === provider &&
355 entry.mtimeMs >= retentionCutoffMs &&
356 entry.records.length + entry.tailRecords.length > 0 &&
357 isWithinDirectory(filePath, dir),
358 );
359 const volumeId =
360 previous?.dir === dir && (hasRetainedHistory || !currentVolumeId)
361 ? previous.volumeId || currentVolumeId
362 : currentVolumeId;
363 if (previous?.dir !== dir || previous.volumeId !== volumeId) {
364 sourceCache.set(sourceKey, { dir, volumeId });
365 cacheDirty = true;
366 }
367 const key = `${provider}\0${dir}`;
368 if (seen.has(key)) continue;
369 seen.add(key);
370 dirs.push({
371 provider,
372 format,
373 dir,
374 volumeId,
375 ...(fileName === undefined ? {} : { fileName }),
376 });
377 }
378 }
379 return dirs;
380 });
381
382 /**
383 * `Effect.cached` makes concurrent first readers await the same load rather
384 * than each seeing a "loaded" flag set before the read finished and cold
385 * scanning against an empty cache.
386 */
387 const ensureScanCacheLoaded = yield* Effect.cached(
388 Effect.gen(function* () {
389 const readDocument = (filePath: string) =>
390 fileSystem.readFileString(filePath).pipe(
391 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
392 Effect.catchCause(() => Effect.succeed(null)),
393 );
394 let document = yield* readDocument(scanCachePath);
395 if (document === null) {
396 document = yield* readDocument(legacyScanCachePath);
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 failed?: true;
463 readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
464 }> {
465 const cached = fileCache.get(filePath);
466 // Provider is part of the identity: if both providers were ever pointed
467 // at one directory, a hit parsed by the other parser must not be reused.
468 if (
469 cached &&
470 cached.size === size &&
471 cached.mtimeMs === mtimeMs &&
472 cached.provider === provider
473 ) {
474 return {
475 records:
476 cached.tailRecords.length === 0
477 ? cached.records
478 : [...cached.records, ...cached.tailRecords],
479 };
480 }
481
482 // Only a strictly grown file may resume. Same size with a new mtime, or
483 // a shrunken file, means rewritten content; re-parse it whole.
484 const resumeFrom =
485 cached !== undefined && cached.provider === provider && size > cached.size
486 ? cached.position
487 : undefined;
488
489 const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, format, resumeFrom));
490 // A read failure is not an empty transcript: caching it under this
491 // (size, mtime) would silently drop the file's usage until it changes.
492 if (parsed === null)
493 return {
494 records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
495 failed: true,
496 };
497
498 const base = parsed.resumed && cached !== undefined ? cached.records : [];
499 const seen = new Set<string>();
500 const records = dedupeWithinFile([...base, ...parsed.records], seen);
501 const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);
502
503 return {
504 records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
505 update: {
506 entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position },
507 replaces: cached,
508 },
509 };
510 });
511
512 interface ScannedDir {
513 readonly provider: UsageProviderKind;
514 readonly dir: string;
515 readonly volumeId: string;
516 readonly hostId?: string;
517 readonly status?: UsageSource["status"];
518 readonly message?: string;
519 readonly action?: UsageSource["action"];
520 readonly files:
521 | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
522 | null;
523 readonly refreshing?: true;
524 }
525
526 const scanTranscriptDir = Effect.fn("UsageService.scanTranscriptDir")(function* (
527 source: TranscriptSource,
528 windowStartMs: number,
529 ) {
530 const { provider, format, dir, volumeId, fileName } = source;
531 const exists = yield* fileSystem
532 .exists(dir)
533 .pipe(Effect.catchCause(() => Effect.succeed(false)));
534 if (!exists) return { provider, dir, volumeId, files: null } satisfies ScannedDir;
535 const { files, failedPaths } = yield* Effect.promise(() =>
536 listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
537 );
538 const read = yield* Effect.forEach(
539 files,
540 (file) =>
541 readFileRecords(file.path, file.size, file.mtimeMs, provider, format).pipe(
542 Effect.map((result) => ({ path: file.path, ...result })),
543 ),
544 { concurrency: TRANSCRIPT_READ_CONCURRENCY },
545 );
546 const parsedFiles = read.map(({ path, records, update }) => {
547 if (update === undefined) return { path, records };
548 // A scan of another window may have cached its own read of this file
549 // meanwhile. Then keep whichever read saw the later file, so a slower
550 // scan never replaces newer usage with older.
551 const current = fileCache.get(path);
552 if (
553 current === update.replaces ||
554 current === undefined ||
555 !isLaterRead(current, update.entry)
556 ) {
557 fileCache.set(path, update.entry);
558 cacheDirty = true;
559 }
560 return { path, records };
561 });
562 const unread = failedPaths + read.filter((file) => file.failed).length;
563 return {
564 provider,
565 dir,
566 volumeId,
567 files: parsedFiles,
568 ...(unread > 0
569 ? {
570 status: "partial",
571 message: `${unread} transcript path(s) could not be read; usage may be incomplete.`,
572 }
573 : {}),
574 } satisfies ScannedDir;
575 });
576
577 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
578 windowStartMs: number,
579 settings: ServerSettingsValue,
580 retentionCutoffMs: number,
581 awaitRefresh: boolean,
582 ) {
583 const dirs = yield* resolveTranscriptDirs(settings, retentionCutoffMs).pipe(
584 Effect.provideContext(readerContext),
585 );
586
587 const scans = Effect.forEach(
588 scanReaders,
589 ({ driver, reader }) =>
590 usageInstances(driver, settings)
591 .pipe(
592 Effect.flatMap((instances) =>
593 reader.scan({ instances, settings, windowStartMs, retentionCutoffMs, awaitRefresh }),
594 ),
595 )
596 .pipe(
597 Effect.flatMap((sources) =>
598 Effect.forEach(sources, ({ volumeId, ...source }) =>
599 Effect.map(
600 volumeId === undefined
601 ? Effect.promise(() => readDirectoryVolumeId(source.dir))
602 : Effect.succeed(volumeId),
603 (resolved): ScannedDir => ({
604 ...source,
605 provider: reader.provider,
606 volumeId: resolved,
607 }),
608 ),
609 ),
610 ),
611 Effect.provideContext(readerContext),
612 ),
613 { concurrency: "unbounded" },
614 );
615
616 // Independent sources scan together. Transcript directories go one at a
617 // time, so open files stay at `TRANSCRIPT_READ_CONCURRENCY`. The result
618 // keeps this order, since aggregation keeps the first copy of a duplicate.
619 const [transcripts, scanDirs] = yield* Effect.all(
620 [Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs)), scans],
621 { concurrency: "unbounded" },
622 );
623 const scanned: readonly ScannedDir[] = [...transcripts, ...scanDirs.flat()];
624 return scanned;
625 });
626
627 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
628 input: UsageSummaryInput,
629 settings: ServerSettingsValue,
630 ) {
631 if (input.sinceDay > input.untilDay) {
632 return yield* new UsageReadError({
633 reason: "invalidWindow",
634 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
635 });
636 }
637
638 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
639 if (input.resolution === "hour") {
640 const sinceTime =
641 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
642 const untilTime =
643 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
644 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
645 return yield* new UsageReadError({
646 reason: "invalidWindow",
647 detail: "Hourly usage requires valid sinceTime and untilTime instants",
648 });
649 }
650 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
651 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
652 const durationMs = untilTimeMs - sinceTimeMs;
653 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
654 return yield* new UsageReadError({
655 reason: "invalidWindow",
656 detail: "Hourly usage window must be greater than zero and at most 24 hours",
657 });
658 }
659 hourlyWindow = { sinceTimeMs, untilTimeMs };
660 }
661
662 const startedAtMs = yield* Clock.currentTimeMillis;
663 yield* ensureScanCacheLoaded;
664
665 const hostId = NodeOS.hostname();
666 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
667 if (Option.isNone(windowStart)) {
668 return yield* new UsageReadError({
669 reason: "invalidWindow",
670 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
671 });
672 }
673 const windowStartMs =
674 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
675
676 const retentionCutoffMs = startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000;
677
678 const [, scannedDirs] = yield* Effect.all(
679 [
680 ensureRates(false),
681 collectDirs(windowStartMs, settings, retentionCutoffMs, input.awaitRefresh === true),
682 ],
683 { concurrency: 2 },
684 );
685
686 const aggregator = new UsageAggregator({
687 timeZone: input.timeZone,
688 sinceDay: input.sinceDay,
689 untilDay: input.untilDay,
690 resolution: input.resolution ?? "day",
691 ...hourlyWindow,
692 rates,
693 priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
694 modelAliases: resolveModelAliases(settings.usageModelAliases),
695 });
696
697 const sources: UsageSource[] = [];
698
699 // Cleanup may remove transcripts, but the usage we already saved still
700 // contributes to its source through the normal aggregation and dedupe path.
701 const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs);
702 const filesByDir = scannedDirs.map(({ provider, dir, files }) => {
703 const retainedFiles = [...(files ?? [])];
704 const livePaths = new Set(retainedFiles.map((file) => file.path));
705 for (const [filePath, entry] of fileCache) {
706 if (
707 entry.provider !== provider ||
708 entry.mtimeMs < retainedSinceMs ||
709 livePaths.has(filePath) ||
710 !isWithinDirectory(filePath, dir)
711 )
712 continue;
713 retainedFiles.push({ path: filePath, records: [...entry.records, ...entry.tailRecords] });
714 }
715 return retainedFiles;
716 });
717 const crossFileSessions = sharedSessions(filesByDir.flat());
718
719 for (const [
720 index,
721 { provider, dir, volumeId, files, status, message, action, refreshing, hostId: sourceHostId },
722 ] of scannedDirs.entries()) {
723 let scannedFiles = 0;
724 let skippedFiles = 0;
725 // Distinct per directory. Buckets carry per-cell session counts, but a
726 // session spans days and models, so clients total this figure instead.
727 const sessionIds = new Set<string>();
728
729 for (const file of filesByDir[index] ?? []) {
730 if (file.records.length === 0) {
731 skippedFiles += 1;
732 continue;
733 }
734 scannedFiles += 1;
735 const eventOccurrences = new Map<string, number>();
736 for (const record of file.records) {
737 let usageRecord = record;
738 if (
739 sharedSessionProviders.has(record.provider) &&
740 crossFileSessions.has(record.sessionId)
741 ) {
742 // Match moved copies without collapsing repeated equal events
743 // within one file (timestamps can have only second precision).
744 const key = encodeUsageRecordKey([
745 record.provider,
746 record.sessionId,
747 record.timestampMs,
748 record.model,
749 record.totals,
750 ]);
751 const occurrence = (eventOccurrences.get(key) ?? 0) + 1;
752 eventOccurrences.set(key, occurrence);
753 usageRecord = { ...record, dedupeKey: key + ":" + occurrence };
754 }
755 if (aggregator.add(usageRecord, dir) && record.sessionId.length > 0) {
756 sessionIds.add(record.sessionId);
757 }
758 }
759 }
760
761 sources.push({
762 fingerprint: { hostId: sourceHostId ?? hostId, provider, resolvedHomePath: dir, volumeId },
763 status: files === null && scannedFiles === 0 ? "missing" : (status ?? "ok"),
764 scannedFiles,
765 skippedFiles,
766 malformedRecords: 0,
767 distinctSessions: sessionIds.size,
768 message:
769 message ?? (files === null ? "No transcript directory on this environment." : null),
770 ...(action ? { action } : {}),
771 ...(refreshing ? { refreshing } : {}),
772 });
773 }
774
775 const pruned = pruneScanCache(fileCache, retentionCutoffMs);
776 if (pruned > 0) cacheDirty = true;
777
778 const aggregated = aggregator.finish();
779 const readAt = yield* DateTime.now;
780 const finishedAtMs = yield* Clock.currentTimeMillis;
781
782 return {
783 contractVersion: USAGE_CONTRACT_VERSION,
784 readAt: DateTime.formatIso(readAt),
785 timeZone: input.timeZone,
786 sinceDay: input.sinceDay,
787 untilDay: input.untilDay,
788 buckets: aggregated.buckets,
789 sources,
790 pricing: pricing(),
791 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
792 } satisfies UsageSummary;
793 });
794
795 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
796
797 const scanKey = (input: UsageSummaryInput, settings: ServerSettingsValue): string =>
798 JSON.stringify([
799 input.timeZone,
800 input.sinceDay,
801 input.untilDay,
802 input.resolution ?? "day",
803 input.sinceTime ?? null,
804 input.untilTime ?? null,
805 settings,
806 input.awaitRefresh === true,
807 ]);
808
809 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
810 const settings = yield* readSettings;
811 const key = scanKey(input, settings);
812 const deferred = yield* Effect.uninterruptible(
813 Effect.gen(function* () {
814 const existing = inflightScans.get(key);
815 if (existing !== undefined) return existing;
816
817 // Enrollment and detached-fiber creation must be atomic. Otherwise a
818 // canceled first caller can leave a Deferred with no scan to finish it.
819 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
820 inflightScans.set(key, created);
821 // Detached so one departing client cannot tear the scan out from under
822 // the fibers awaiting it; a finished scan warms the cache either way.
823 // The cache write is registered before the waiters resume, so they
824 // can await it, but its fiber starts after they have the summary.
825 yield* scanSummary(input, settings).pipe(
826 Effect.onExit((exit) =>
827 Effect.sync(() => inflightScans.delete(key)).pipe(
828 Effect.andThen(Exit.isSuccess(exit) ? schedulePersist : Effect.void),
829 Effect.andThen(Deferred.done(created, exit)),
830 ),
831 ),
832 Effect.forkDetach,
833 );
834 return created;
835 }),
836 );
837 return yield* Deferred.await(deferred);
838 });
839
840 return { readSummary, refreshRates, awaitPersisted } as const;
841});
842
843export const layer = Layer.effect(UsageService, make);