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

UsageService.ts

832 lines30.0 KB

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