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 = (
455 filePath: string,
456 size: number,
457 mtimeMs: number,
458 provider: UsageProviderKind,
459 format: TranscriptUsageFormat<unknown>,
460 ): Effect.Effect<{
461 readonly records: readonly UsageRecord[];
462 readonly failed?: true;
463 readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
464 }> =>
465 Effect.gen(function* () {
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 };
481 }
482
483 // Only a strictly grown file may resume. Same size with a new mtime, or
484 // a shrunken file, means rewritten content; re-parse it whole.
485 const resumeFrom =
486 cached !== undefined && cached.provider === provider && size > cached.size
487 ? cached.position
488 : undefined;
489
490 const parsed = yield* Effect.promise(() =>
491 readTranscriptRecords(filePath, format, resumeFrom),
492 );
493 // A read failure is not an empty transcript: caching it under this
494 // (size, mtime) would silently drop the file's usage until it changes.
495 if (parsed === null)
496 return {
497 records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
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 update: {
509 entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position },
510 replaces: cached,
511 },
512 };
513 });
514
515 interface ScannedDir {
516 readonly provider: UsageProviderKind;
517 readonly dir: string;
518 readonly volumeId: string;
519 readonly hostId?: string;
520 readonly status?: UsageSource["status"];
521 readonly message?: string;
522 readonly action?: UsageSource["action"];
523 readonly files:
524 | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
525 | null;
526 readonly refreshing?: true;
527 }
528
529 const scanTranscriptDir = Effect.fn("UsageService.scanTranscriptDir")(function* (
530 source: TranscriptSource,
531 windowStartMs: number,
532 ) {
533 const { provider, format, dir, volumeId, fileName } = source;
534 const exists = yield* fileSystem
535 .exists(dir)
536 .pipe(Effect.catchCause(() => Effect.succeed(false)));
537 if (!exists) return { provider, dir, volumeId, files: null } satisfies ScannedDir;
538 const { files, failedPaths } = yield* Effect.promise(() =>
539 listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
540 );
541 const read = yield* Effect.forEach(
542 files,
543 (file) =>
544 readFileRecords(file.path, file.size, file.mtimeMs, provider, format).pipe(
545 Effect.map((result) => ({ path: file.path, ...result })),
546 ),
547 { concurrency: TRANSCRIPT_READ_CONCURRENCY },
548 );
549 const parsedFiles = read.map(({ path, records, update }) => {
550 if (update === undefined) return { path, records };
551 // A scan of another window may have cached its own read of this file
552 // meanwhile. Then keep whichever read saw the later file, so a slower
553 // scan never replaces newer usage with older.
554 const current = fileCache.get(path);
555 if (
556 current === update.replaces ||
557 current === undefined ||
558 !isLaterRead(current, update.entry)
559 ) {
560 fileCache.set(path, update.entry);
561 cacheDirty = true;
562 }
563 return { path, records };
564 });
565 const unread = failedPaths + read.filter((file) => file.failed).length;
566 return {
567 provider,
568 dir,
569 volumeId,
570 files: parsedFiles,
571 ...(unread > 0
572 ? {
573 status: "partial",
574 message: `${unread} transcript path(s) could not be read; usage may be incomplete.`,
575 }
576 : {}),
577 } satisfies ScannedDir;
578 });
579
580 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
581 windowStartMs: number,
582 settings: ServerSettingsValue,
583 retentionCutoffMs: number,
584 awaitRefresh: boolean,
585 ) {
586 const dirs = yield* resolveTranscriptDirs(settings, retentionCutoffMs).pipe(
587 Effect.provideContext(readerContext),
588 );
589
590 const scans = Effect.forEach(
591 scanReaders,
592 ({ driver, reader }) =>
593 usageInstances(driver, settings)
594 .pipe(
595 Effect.flatMap((instances) =>
596 reader.scan({ instances, settings, windowStartMs, retentionCutoffMs, awaitRefresh }),
597 ),
598 )
599 .pipe(
600 Effect.flatMap((sources) =>
601 Effect.forEach(sources, ({ volumeId, ...source }) =>
602 Effect.map(
603 volumeId === undefined
604 ? Effect.promise(() => readDirectoryVolumeId(source.dir))
605 : Effect.succeed(volumeId),
606 (resolved): ScannedDir => ({
607 ...source,
608 provider: reader.provider,
609 volumeId: resolved,
610 }),
611 ),
612 ),
613 ),
614 Effect.provideContext(readerContext),
615 ),
616 { concurrency: "unbounded" },
617 );
618
619 // Independent sources scan together. Transcript directories go one at a
620 // time, so open files stay at `TRANSCRIPT_READ_CONCURRENCY`. The result
621 // keeps this order, since aggregation keeps the first copy of a duplicate.
622 const [transcripts, scanDirs] = yield* Effect.all(
623 [Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs)), scans],
624 { concurrency: "unbounded" },
625 );
626 const scanned: readonly ScannedDir[] = [...transcripts, ...scanDirs.flat()];
627 return scanned;
628 });
629
630 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
631 input: UsageSummaryInput,
632 settings: ServerSettingsValue,
633 ) {
634 if (input.sinceDay > input.untilDay) {
635 return yield* new UsageReadError({
636 reason: "invalidWindow",
637 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
638 });
639 }
640
641 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
642 if (input.resolution === "hour") {
643 const sinceTime =
644 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
645 const untilTime =
646 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
647 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
648 return yield* new UsageReadError({
649 reason: "invalidWindow",
650 detail: "Hourly usage requires valid sinceTime and untilTime instants",
651 });
652 }
653 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
654 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
655 const durationMs = untilTimeMs - sinceTimeMs;
656 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
657 return yield* new UsageReadError({
658 reason: "invalidWindow",
659 detail: "Hourly usage window must be greater than zero and at most 24 hours",
660 });
661 }
662 hourlyWindow = { sinceTimeMs, untilTimeMs };
663 }
664
665 const startedAtMs = yield* Clock.currentTimeMillis;
666 yield* ensureScanCacheLoaded;
667
668 const hostId = NodeOS.hostname();
669 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
670 if (Option.isNone(windowStart)) {
671 return yield* new UsageReadError({
672 reason: "invalidWindow",
673 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
674 });
675 }
676 const windowStartMs =
677 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
678
679 const retentionCutoffMs = startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000;
680
681 const [, scannedDirs] = yield* Effect.all(
682 [
683 ensureRates(false),
684 collectDirs(windowStartMs, settings, retentionCutoffMs, input.awaitRefresh === true),
685 ],
686 { concurrency: 2 },
687 );
688
689 const aggregator = new UsageAggregator({
690 timeZone: input.timeZone,
691 sinceDay: input.sinceDay,
692 untilDay: input.untilDay,
693 resolution: input.resolution ?? "day",
694 ...hourlyWindow,
695 rates,
696 priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
697 modelAliases: resolveModelAliases(settings.usageModelAliases),
698 });
699
700 const sources: UsageSource[] = [];
701
702 // Cleanup may remove transcripts, but the usage we already saved still
703 // contributes to its source through the normal aggregation and dedupe path.
704 const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs);
705 const filesByDir = scannedDirs.map(({ provider, dir, files }) => {
706 const retainedFiles = [...(files ?? [])];
707 const livePaths = new Set(retainedFiles.map((file) => file.path));
708 for (const [filePath, entry] of fileCache) {
709 if (
710 entry.provider !== provider ||
711 entry.mtimeMs < retainedSinceMs ||
712 livePaths.has(filePath) ||
713 !isWithinDirectory(filePath, dir)
714 )
715 continue;
716 retainedFiles.push({ path: filePath, records: [...entry.records, ...entry.tailRecords] });
717 }
718 return retainedFiles;
719 });
720 const crossFileSessions = sharedSessions(filesByDir.flat());
721
722 for (const [
723 index,
724 { provider, dir, volumeId, files, status, message, action, refreshing, hostId: sourceHostId },
725 ] of scannedDirs.entries()) {
726 let scannedFiles = 0;
727 let skippedFiles = 0;
728 // Distinct per directory. Buckets carry per-cell session counts, but a
729 // session spans days and models, so clients total this figure instead.
730 const sessionIds = new Set<string>();
731
732 for (const file of filesByDir[index] ?? []) {
733 if (file.records.length === 0) {
734 skippedFiles += 1;
735 continue;
736 }
737 scannedFiles += 1;
738 const eventOccurrences = new Map<string, number>();
739 for (const record of file.records) {
740 let usageRecord = record;
741 if (
742 sharedSessionProviders.has(record.provider) &&
743 crossFileSessions.has(record.sessionId)
744 ) {
745 // Match moved copies without collapsing repeated equal events
746 // within one file (timestamps can have only second precision).
747 const key = encodeUsageRecordKey([
748 record.provider,
749 record.sessionId,
750 record.timestampMs,
751 record.model,
752 record.totals,
753 ]);
754 const occurrence = (eventOccurrences.get(key) ?? 0) + 1;
755 eventOccurrences.set(key, occurrence);
756 usageRecord = { ...record, dedupeKey: key + ":" + occurrence };
757 }
758 if (aggregator.add(usageRecord, dir) && record.sessionId.length > 0) {
759 sessionIds.add(record.sessionId);
760 }
761 }
762 }
763
764 sources.push({
765 fingerprint: { hostId: sourceHostId ?? hostId, provider, resolvedHomePath: dir, volumeId },
766 status: files === null && scannedFiles === 0 ? "missing" : (status ?? "ok"),
767 scannedFiles,
768 skippedFiles,
769 malformedRecords: 0,
770 distinctSessions: sessionIds.size,
771 message:
772 message ?? (files === null ? "No transcript directory on this environment." : null),
773 ...(action ? { action } : {}),
774 ...(refreshing ? { refreshing } : {}),
775 });
776 }
777
778 const pruned = pruneScanCache(fileCache, retentionCutoffMs);
779 if (pruned > 0) cacheDirty = true;
780
781 const aggregated = aggregator.finish();
782 const readAt = yield* DateTime.now;
783 const finishedAtMs = yield* Clock.currentTimeMillis;
784
785 return {
786 contractVersion: USAGE_CONTRACT_VERSION,
787 readAt: DateTime.formatIso(readAt),
788 timeZone: input.timeZone,
789 sinceDay: input.sinceDay,
790 untilDay: input.untilDay,
791 buckets: aggregated.buckets,
792 sources,
793 pricing: pricing(),
794 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
795 } satisfies UsageSummary;
796 });
797
798 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
799
800 const scanKey = (input: UsageSummaryInput, settings: ServerSettingsValue): string =>
801 JSON.stringify([
802 input.timeZone,
803 input.sinceDay,
804 input.untilDay,
805 input.resolution ?? "day",
806 input.sinceTime ?? null,
807 input.untilTime ?? null,
808 settings,
809 input.awaitRefresh === true,
810 ]);
811
812 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
813 const settings = yield* readSettings;
814 const key = scanKey(input, settings);
815 const deferred = yield* Effect.uninterruptible(
816 Effect.gen(function* () {
817 const existing = inflightScans.get(key);
818 if (existing !== undefined) return existing;
819
820 // Enrollment and detached-fiber creation must be atomic. Otherwise a
821 // canceled first caller can leave a Deferred with no scan to finish it.
822 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
823 inflightScans.set(key, created);
824 // Detached so one departing client cannot tear the scan out from under
825 // the fibers awaiting it; a finished scan warms the cache either way.
826 // The cache write is registered before the waiters resume, so they
827 // can await it, but its fiber starts after they have the summary.
828 yield* scanSummary(input, settings).pipe(
829 Effect.onExit((exit) =>
830 Effect.sync(() => inflightScans.delete(key)).pipe(
831 Effect.andThen(Exit.isSuccess(exit) ? schedulePersist : Effect.void),
832 Effect.andThen(Deferred.done(created, exit)),
833 ),
834 ),
835 Effect.forkDetach,
836 );
837 return created;
838 }),
839 );
840 return yield* Deferred.await(deferred);
841 });
842
843 return { readSummary, refreshRates, awaitPersisted } as const;
844});
845
846export const layer = Layer.effect(UsageService, make);