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

UsageService.ts

1,315 lines50.7 KB

1import {
2 defaultInstanceIdForDriver,
3 ProviderInstanceId,
4 resolveProviderInstanceEnabled,
5 type UsageAccessRequest,
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 { formatMalformedUsageWarning } from "@t3tools/shared/usageFormat";
34import * as ServerConfig from "../config.ts";
35import * as ServerSettings from "../serverSettings.ts";
36import { BUILT_IN_USAGE_DRIVERS, type BuiltInUsageReadersEnv } from "../provider/builtInDrivers.ts";
37import type { ProviderDriver } from "@t3tools/provider-core/server/driver";
38import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
39import type {
40 ProviderUsageInstance,
41 TranscriptUsageFormat,
42 UsageRecord,
43} from "@t3tools/provider-core/server/usage";
44import {
45 canonicalModelFilter,
46 resolveModelAliases,
47 usageTimestampFilter,
48 UsageAggregator,
49} from "./usageAggregation.ts";
50import {
51 createOverrideRateTable,
52 isUnlistedModel,
53 parseRateTable,
54 type RateTable,
55} from "./usagePricing.ts";
56import {
57 DESKTOP_HOST_SCOPE_ENV,
58 listTranscriptFiles,
59 readDirectoryVolumeId,
60 readPhysicalSourceId,
61 readTranscriptRecords,
62} from "./usageTranscriptReader.ts";
63import {
64 decodeScanCache,
65 dedupeWithinFile,
66 LEGACY_SCAN_CACHE_FILE_NAMES,
67 makeScanCacheWriter,
68 pruneScanCache,
69 SCAN_CACHE_FILE_NAME,
70 type CachedFile,
71 type ScanCache,
72} from "./usageScanCache.ts";
73​
74const LITELLM_RATES_URL =
75 "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
76const LITELLM_RATES_API_URL =
77 "https://api.github.com/repos/BerriAI/litellm/contents/model_prices_and_context_window.json?ref=main";
78​
79const RATES_TTL_MS = 24 * 60 * 60 * 1000;
80​
81const RATES_REFRESH_FLOOR_MS = 60 * 1000;
82​
83// mtime slack includes writes just before local midnight on the window's first day.
84const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
85const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
86​
87const STALE_TEMP_DIRECTORY_MS = 60 * 60 * 1000;
88​
89const TRANSCRIPT_READ_CONCURRENCY = 4;
90​
91const transcriptReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) =>
92 driver.usage?.kind === "transcripts" ? [{ driver, reader: driver.usage }] : [],
93);
94​
95const scanReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) =>
96 driver.usage?.kind === "scan" ? [{ driver, reader: driver.usage }] : [],
97);
98​
99const providerRateModels = new Map(
100 BUILT_IN_USAGE_DRIVERS.flatMap(({ usage }) =>
101 usage?.rateModel === undefined ? [] : [[usage.provider, usage.rateModel] as const],
102 ),
103);
104​
105const transcriptFormats = new Map(
106 transcriptReaders.map(({ reader }) => [reader.provider, reader.format] as const),
107);
108​
109interface TranscriptSource {
110 readonly provider: UsageProviderKind;
111 readonly format: TranscriptUsageFormat<unknown>;
112 readonly dir: string;
113 readonly volumeId: string;
114 readonly physicalSourceId?: string;
115 readonly fileName?: string;
117​
118const RatesCacheFile = Schema.Struct({
119 fetchedAtMs: Schema.Number,
120 document: Schema.Unknown,
121});
122const decodeRatesCache = Schema.decodeUnknownEffect(Schema.fromJsonString(RatesCacheFile));
123const encodeRatesCache = Schema.encodeEffect(Schema.fromJsonString(RatesCacheFile));
124​
125const ScanCacheJson = Schema.fromJsonString(Schema.Unknown);
126const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
127const encodeUsageRecordKey = Schema.encodeSync(ScanCacheJson);
128const CachedSource = Schema.Struct({ dir: Schema.String, volumeId: Schema.String });
129​
130function isLaterRead(a: CachedFile, b: CachedFile): boolean {
131 return a.mtimeMs > b.mtimeMs || (a.mtimeMs === b.mtimeMs && a.size > b.size);
133​
134const sharedSessionProviders: ReadonlySet<UsageProviderKind> = new Set(
135 transcriptReaders.flatMap(({ reader }) =>
136 reader.format.sharedSessionsAcrossFiles ? [reader.provider] : [],
137 ),
138);
139​
140// Only shared sessions need cross-file dedupe; per-file occurrence counts make other keys unique.
141function sharedSessions(
142 files: readonly { readonly records: readonly UsageRecord[] }[],
143): ReadonlySet<string> {
144 const firstFile = new Map<string, number>();
145 const shared = new Set<string>();
146 for (const [index, file] of files.entries()) {
147 let previous = "";
148 for (const { provider, sessionId } of file.records) {
149 if (!sharedSessionProviders.has(provider) || sessionId === previous || sessionId.length === 0)
150 continue;
151 previous = sessionId;
152 const first = firstFile.get(sessionId);
153 if (first === undefined) firstFile.set(sessionId, index);
154 else if (first !== index) shared.add(sessionId);
155 }
156 }
157 return shared;
159const decodeCachedSources = Schema.decodeUnknownOption(
160 Schema.Struct({
161 sources: Schema.Record(Schema.String, CachedSource),
162 coveredSince: Schema.optional(Schema.Record(Schema.String, Schema.Number)),
163 }),
164);
165​
166export class UsageService extends Context.Service<
167 UsageService,
168 {
169 readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
170 readonly refreshRates: Effect.Effect<UsagePricing>;
171 }
172>()("t3/usage/UsageService") {}
173​
174export const make = Effect.gen(function* () {
175 const fileSystem = yield* FileSystem.FileSystem;
176 const path = yield* Path.Path;
177 const config = yield* ServerConfig.ServerConfig;
178 const settingsService = yield* ServerSettings.ServerSettingsService;
179 const httpClient = yield* HttpClient.HttpClient;
180 const hostEnvironment = yield* HostProcess.Environment;
181 const hostPlatform = yield* HostProcess.Platform;
182 const hostScope = hostEnvironment[DESKTOP_HOST_SCOPE_ENV]?.trim();
183 // A mount or a directory's on-disk name does not change under a running server.
184 // A miss is not cached: the directory may not exist yet.
185 const physicalSourceIds = new Map<string, Promise<string | undefined>>();
186 const physicalSourceId = (dir: string) =>
187 Effect.promise(() => {
188 const cached = physicalSourceIds.get(dir);
189 if (cached !== undefined) return cached;
190 const id = readPhysicalSourceId(dir, hostScope, hostPlatform);
191 physicalSourceIds.set(dir, id);
192 void id.then((resolved) => {
193 if (resolved === undefined && physicalSourceIds.get(dir) === id) {
194 physicalSourceIds.delete(dir);
195 }
196 });
197 return id;
198 });
199 const hostname = yield* HostProcess.Hostname;
200 const readerContext = yield* Effect.context<BuiltInUsageReadersEnv>();
201​
202 const fileCache: ScanCache = new Map();
203 // Reads from concurrent windows can still hold the original record after it is corrected.
204 const resolvedRecords = new WeakMap<UsageRecord, UsageRecord>();
205 const correctedRecord = (record: UsageRecord) => resolvedRecords.get(record) ?? record;
206 const correctedBatch = (records: readonly UsageRecord[]) =>
207 records.some((record) => resolvedRecords.has(record)) ? records.map(correctedRecord) : records;
208 const sourceCache = new Map<string, typeof CachedSource.Type>();
209 // Earliest window start a complete scan read each transcript directory from.
210 const coveredSince = new Map<string, number>();
211 const coverageKey = (source: TranscriptSource) => `${source.provider}\0${source.dir}`;
212 let cacheDirty = false;
213 const cover = (source: TranscriptSource, windowStartMs: number) => {
214 if ((coveredSince.get(coverageKey(source)) ?? Infinity) <= windowStartMs) return;
215 coveredSince.set(coverageKey(source), windowStartMs);
216 cacheDirty = true;
217 };
218 const isWithinDirectory = (filePath: string, dir: string) => {
219 const relative = path.relative(dir, filePath);
220 return relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative);
221 };
222​
223 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
224 const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME);
225 const writeCacheFile = (filePath: string, contents: string | Iterable<string>) =>
226 writeFileStringAtomically({ filePath, contents }).pipe(
227 Effect.provideService(FileSystem.FileSystem, fileSystem),
228 Effect.provideService(Path.Path, path),
229 );
230 const hostIdPath = path.join(config.baseDir, "usage-host-id");
231 const explicitHostId = hostEnvironment["T3CODE_HOST_ID"]?.trim();
232 const hostId =
233 explicitHostId ||
234 (yield* fileSystem.readFileString(hostIdPath).pipe(
235 Effect.catchIf(
236 (error) => error.reason._tag === "NotFound",
237 () =>
238 Effect.scoped(
239 Effect.gen(function* () {
240 yield* fileSystem.makeDirectory(config.baseDir, { recursive: true });
241 const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
242 directory: config.baseDir,
243 prefix: "usage-host-id.",
244 });
245 const tempFile = path.join(tempDirectory, "identity");
246 yield* fileSystem.writeFileString(tempFile, `${hostname}\n`);
247 // Publish complete contents without replacing another initializer's identity.
248 yield* fileSystem.link(tempFile, hostIdPath).pipe(
249 Effect.catchIf(
250 (error) => error.reason._tag === "AlreadyExists",
251 () => Effect.void,
252 ),
253 );
254 return yield* fileSystem.readFileString(hostIdPath);
255 }),
256 ),
257 ),
258 Effect.map((value) => value.trim() || hostname),
259 Effect.orElseSucceed(() => hostname),
260 ));
261 let rates: RateTable = new Map();
262 let ratesFetchedAtMs: number | null = null;
263 let ratesLastFailedAtMs: number | null = null;
264 let ratesStatus: UsagePricing["status"] = "unavailable";
265 const ratesLock = yield* Semaphore.make(1);
266​
267 const pricing = (): UsagePricing => ({
268 status: ratesStatus,
269 source: LITELLM_RATES_URL,
270 fetchedAt:
271 ratesFetchedAtMs === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
272 knownModels: rates.size,
273 });
274​
275 const fetchRates = (url: string, accept = "application/json") =>
276 httpClient.get(url, { headers: { accept } }).pipe(
277 Effect.flatMap(HttpClientResponse.filterStatusOk),
278 Effect.flatMap((response) => response.json),
279 Effect.map((document) => {
280 const parsed = parseRateTable(document);
281 return parsed.size > 0 ? { document, parsed } : null;
282 }),
283 Effect.timeout(10_000),
284 Effect.catchCause(() => Effect.succeed(null)),
285 );
286​
287 // Outside ratesLock, which a slow fetch holds: a provisional answer prices with these.
288 const loadSavedRates = yield* Effect.cached(
289 fileSystem.readFileString(ratesCachePath).pipe(
290 Effect.flatMap((raw) => decodeRatesCache(raw)),
291 Effect.map((saved) => {
292 const parsed = parseRateTable(saved.document);
293 if (parsed.size === 0) return;
294 rates = parsed;
295 ratesFetchedAtMs = saved.fetchedAtMs;
296 ratesStatus = "cached";
297 }),
298 Effect.ignoreCause,
299 ),
300 );
301​
302 const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) {
303 const now = yield* Clock.currentTimeMillis;
304 const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS;
305 yield* loadSavedRates;
306 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return;
307 if (ratesLastFailedAtMs !== null && now - ratesLastFailedAtMs < RATES_REFRESH_FLOOR_MS) return;
308​
309 let fetched = yield* fetchRates(LITELLM_RATES_URL);
310 if (fetched === null) {
311 fetched = yield* fetchRates(LITELLM_RATES_API_URL, "application/vnd.github.raw+json");
312 }
313 if (fetched === null) {
314 ratesLastFailedAtMs = yield* Clock.currentTimeMillis;
315 if (rates.size > 0) ratesStatus = "cached";
316 return;
317 }
318​
319 rates = fetched.parsed;
320 ratesFetchedAtMs = now;
321 ratesLastFailedAtMs = null;
322 ratesStatus = "fresh";
323​
324 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched.document }).pipe(
325 Effect.flatMap((contents) => writeCacheFile(ratesCachePath, contents)),
326 Effect.ignoreCause,
327 );
328 });
329​
330 const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force));
331​
332 // Rates are kept for RATES_TTL_MS, so a model released after the table was fetched would stay unpriced
333 // that long. A scan that meets a model the table does not list refetches early: once per model against
334 // a fresh table, with loadRates keeping RATES_REFRESH_FLOOR_MS between attempts.
335 const checkedUnlistedModels = new Set<string>();
336 const refreshForUnlistedModels = Effect.fn("UsageService.refreshForUnlistedModels")(function* (
337 models: ReadonlySet<string>,
338 ) {
339 const unlisted = [...models].filter(
340 (model) => !checkedUnlistedModels.has(model) && isUnlistedModel(rates, model),
341 );
342 if (unlisted.length === 0) return;
343 yield* ensureRates(true);
344 const now = yield* Clock.currentTimeMillis;
345 // A failed fetch leaves the models unchecked, so a later scan tries again.
346 if (ratesFetchedAtMs === null || now - ratesFetchedAtMs >= RATES_REFRESH_FLOOR_MS) return;
347 for (const model of unlisted) checkedUnlistedModels.add(model);
348 });
349​
350 const refreshRates = ensureRates(true).pipe(
351 Effect.map(pricing),
352 Effect.withSpan("UsageService.refreshRates"),
353 );
354​
355 const readSettings = settingsService.getSettings.pipe(
356 Effect.catchCause(
357 (cause) =>
358 new UsageReadError({
359 reason: "scanFailed",
360 detail: "Server settings could not be read.",
361 cause: Cause.squash(cause),
362 }),
363 ),
364 );
365​
366 // Only enabled instances, and only those the user allowed; the rest are never read.
367 const usageInstances = Effect.fn("UsageService.usageInstances")(function* <Config>(
368 driver: ProviderDriver<Config, unknown, unknown>,
369 settings: ServerSettingsValue,
370 access: "allowed" | "unasked" = "allowed",
371 ) {
372 const entries = Object.entries(settings.providerInstances).filter(
373 ([, instance]) => instance.driver === driver.driverKind,
374 );
375 const defaultId = defaultInstanceIdForDriver(driver.driverKind);
376 if (
377 driver.metadata.hasDefaultInstance !== false &&
378 !Object.hasOwn(settings.providerInstances, defaultId)
379 ) {
380 entries.push([defaultId, { driver: driver.driverKind }]);
381 }
382 const decodeConfig = Schema.decodeUnknownOption(driver.configSchema);
383 return yield* Effect.forEach(
384 entries.filter(
385 ([, instance]) =>
386 resolveProviderInstanceEnabled(instance) &&
387 (access === "allowed"
388 ? instance.usageAccess === "allowed"
389 : instance.usageAccess === undefined),
390 ),
391 Effect.fnUntraced(function* ([id, instance]) {
392 const instanceConfig: ProviderUsageInstance<Config> = {
393 instanceId: ProviderInstanceId.make(id),
394 config: Option.getOrUndefined(decodeConfig(instance.config ?? {})),
395 environment: yield* mergeProviderInstanceEnvironment(
396 instance.environment,
397 hostEnvironment,
398 ),
399 configured: Object.hasOwn(settings.providerInstances, id),
400 };
401 return instanceConfig;
402 }),
403 );
404 });
405​
406 // Enabled instances nobody has answered for yet. Finding a transcript folder only resolves paths.
407 const accessRequests = Effect.fn("UsageService.accessRequests")(function* (
408 settings: ServerSettingsValue,
409 ) {
410 const requests: Array<UsageAccessRequest> = [];
411 for (const driver of BUILT_IN_USAGE_DRIVERS) {
412 const reader = driver.usage;
413 if (reader === undefined) continue;
414 for (const instance of yield* usageInstances(driver, settings, "unasked")) {
415 const paths =
416 reader.kind === "transcripts"
417 ? (yield* reader.directories(instance, { awaitRefresh: false })).flatMap((entry) =>
418 entry.refreshing ? [] : [entry.dir],
419 )
420 : [];
421 requests.push({
422 instanceId: instance.instanceId,
423 driver: driver.driverKind,
424 provider: reader.provider,
425 paths,
426 });
427 }
428 }
429 return requests;
430 });
431​
432 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (
433 settings: ServerSettingsValue,
434 retentionCutoffMs: number,
435 awaitRefresh: boolean,
436 ) {
437 const dirs: Array<TranscriptSource> = [];
438 const pending: Array<ScannedDir> = [];
439 const seen = new Set<string>();
440 for (const { driver, reader } of transcriptReaders) {
441 const { provider, format } = reader;
442 const directories = yield* Effect.forEach(
443 yield* usageInstances(driver, settings),
444 (instance) => reader.directories(instance, { awaitRefresh }),
445 );
446 for (const { dir: directory, fileName, refreshing } of directories.flat()) {
447 if (refreshing) {
448 const key = `${provider}\0${directory}`;
449 if (seen.has(key)) continue;
450 seen.add(key);
451 pending.push({ provider, dir: directory, volumeId: "", files: [], refreshing });
452 continue;
453 }
454 const sourceKey = provider + "\0" + directory;
455 const previous = sourceCache.get(sourceKey);
456 const dir = yield* fileSystem
457 .realPath(directory)
458 .pipe(Effect.orElseSucceed(() => previous?.dir ?? directory));
459 const currentVolumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
460 const hasRetainedHistory = fileCache
461 .entries()
462 .some(
463 ([filePath, entry]) =>
464 entry.provider === provider &&
465 entry.mtimeMs >= retentionCutoffMs &&
466 (entry.records.length + entry.tailRecords.length > 0 ||
467 entry.malformedRecords.length > 0) &&
468 isWithinDirectory(filePath, dir),
469 );
470 const volumeId =
471 previous?.dir === dir && (hasRetainedHistory || !currentVolumeId)
472 ? previous.volumeId || currentVolumeId
473 : currentVolumeId;
474 if (previous?.dir !== dir || previous.volumeId !== volumeId) {
475 sourceCache.set(sourceKey, { dir, volumeId });
476 cacheDirty = true;
477 }
478 const key = `${provider}\0${dir}`;
479 if (seen.has(key)) continue;
480 seen.add(key);
481 const sourceId = yield* physicalSourceId(dir);
482 dirs.push({
483 provider,
484 format,
485 dir,
486 volumeId,
487 ...(sourceId === undefined ? {} : { physicalSourceId: sourceId }),
488 ...(fileName === undefined ? {} : { fileName }),
489 });
490 }
491 }
492 return { dirs, pending };
493 });
494​
495 // Share first loads so concurrent readers cannot scan against a still-empty cache.
496 const ensureScanCacheLoaded = yield* Effect.cached(
497 Effect.gen(function* () {
498 const readDocument = (filePath: string) =>
499 fileSystem.readFileString(filePath).pipe(
500 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
501 Effect.catchCause(() => Effect.succeed(null)),
502 );
503 let document = yield* readDocument(scanCachePath);
504 const current = document !== null;
505 for (const fileName of LEGACY_SCAN_CACHE_FILE_NAMES) {
506 if (document !== null) break;
507 document = yield* readDocument(path.join(config.stateDir, fileName));
508 cacheDirty = document !== null;
509 }
510 if (document === null) return;
511 const decoded = decodeScanCache(document, transcriptFormats);
512 for (const [path, entry] of decoded) fileCache.set(path, entry);
513 const saved = (document as { readonly files?: unknown }).files;
514 const complete =
515 typeof saved === "object" && saved !== null && Object.keys(saved).length === decoded.size;
516 const sources = decodeCachedSources(document);
517 if (Option.isSome(sources)) {
518 for (const [key, source] of Object.entries(sources.value.sources))
519 sourceCache.set(key, source);
520 // Coverage describes the saved files, so it needs every one, in this version's format.
521 if (current && complete && fileCache.size > 0) {
522 for (const [key, since] of Object.entries(sources.value.coveredSince ?? {}))
523 coveredSince.set(key, since);
524 }
525 }
526 }),
527 );
528​
529 const writeScanCache = makeScanCacheWriter();
530 // Serialize writes so concurrently finished window scans cannot overwrite newer snapshots.
531 const persistLock = yield* Semaphore.make(1);
532​
533 // The saved cache supersedes older versions. Temp folders an aborted write left behind are
534 // removed once idle for an hour, so a write in progress from another server survives.
535 let supersededFilesRemoved = false;
536 const removeSupersededCacheFiles = Effect.gen(function* () {
537 for (const fileName of LEGACY_SCAN_CACHE_FILE_NAMES) {
538 yield* fileSystem.remove(path.join(config.stateDir, fileName)).pipe(Effect.ignore);
539 }
540 const tempPrefixes = [SCAN_CACHE_FILE_NAME, ...LEGACY_SCAN_CACHE_FILE_NAMES].map(
541 (fileName) => `${fileName}.`,
542 );
543 const staleBeforeMs = (yield* Clock.currentTimeMillis) - STALE_TEMP_DIRECTORY_MS;
544 for (const name of yield* fileSystem.readDirectory(config.stateDir)) {
545 if (!tempPrefixes.some((prefix) => name.startsWith(prefix))) continue;
546 const tempPath = path.join(config.stateDir, name);
547 yield* fileSystem.stat(tempPath).pipe(
548 Effect.flatMap((info) => {
549 const mtimeMs = Option.getOrUndefined(info.mtime)?.getTime();
550 return info.type === "Directory" && mtimeMs !== undefined && mtimeMs <= staleBeforeMs
551 ? fileSystem.remove(tempPath, { recursive: true })
552 : Effect.void;
553 }),
554 Effect.ignore,
555 );
556 }
557 }).pipe(Effect.ignore);
558​
559 // Clear dirty before encoding to retain concurrent changes; restore it on failure for retry.
560 const persistCaches = Effect.gen(function* () {
561 if (cacheDirty) {
562 cacheDirty = false;
563 yield* Effect.sync(() =>
564 writeScanCache(fileCache, {
565 sources: Object.fromEntries(sourceCache),
566 coveredSince: Object.fromEntries(coveredSince),
567 }),
568 ).pipe(
569 Effect.flatMap((contents) => writeCacheFile(scanCachePath, contents)),
570 Effect.andThen(
571 Effect.suspend(() => {
572 if (supersededFilesRemoved) return Effect.void;
573 supersededFilesRemoved = true;
574 return removeSupersededCacheFiles;
575 }),
576 ),
577 Effect.catchCause(() =>
578 Effect.sync(() => {
579 cacheDirty = true;
580 }),
581 ),
582 );
583 }
584 }).pipe(persistLock.withPermit, Effect.withSpan("UsageService.persistCaches"));
585​
586 const pendingPersists = new Set<Fiber.Fiber<void>>();
587 const schedulePersist = Effect.forkDetach(persistCaches).pipe(
588 Effect.map((fiber) => {
589 pendingPersists.add(fiber);
590 fiber.addObserver(() => pendingPersists.delete(fiber));
591 }),
592 );
593 const awaitPersisted = Effect.suspend(() => Fiber.awaitAll([...pendingPersists])).pipe(
594 Effect.asVoid,
595 );
596 yield* Effect.addFinalizer(() => awaitPersisted);
597​
598 /**
599 * Reads run concurrently, and the caller stores updates in walk order rather
600 * than completion order: saved records of deleted transcripts aggregate in
601 * cache order, where the first copy of a duplicate decides its bucket. Untraced: a scan
602 * reads thousands of files, so scanTranscriptDir records the counts instead.
603 */
604 const readFileRecords = Effect.fnUntraced(function* (
605 filePath: string,
606 size: number,
607 mtimeMs: number,
608 provider: UsageProviderKind,
609 format: TranscriptUsageFormat<unknown>,
610 ): Effect.fn.Return<{
611 readonly records: readonly UsageRecord[];
612 readonly malformedRecords: readonly number[];
613 readonly failed?: true;
614 readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
615 }> {
616 const cached = fileCache.get(filePath);
617 // Provider is part of the identity: if both providers were ever pointed
618 // at one directory, a hit parsed by the other parser must not be reused.
619 if (
620 cached &&
621 cached.size === size &&
622 cached.mtimeMs === mtimeMs &&
623 cached.provider === provider
624 ) {
625 return {
626 records:
627 cached.tailRecords.length === 0
628 ? cached.records
629 : [...cached.records, ...cached.tailRecords],
630 malformedRecords: cached.malformedRecords,
631 };
632 }
633​
634 // Only a strictly grown file may resume. Same size with a new mtime, or
635 // a shrunken file, means rewritten content; re-parse it whole.
636 const resumeFrom =
637 cached !== undefined && cached.provider === provider && size > cached.size
638 ? cached.position
639 : undefined;
640​
641 const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, format, resumeFrom));
642 // A read failure is not an empty transcript: caching it under this
643 // (size, mtime) would silently drop the file's usage until it changes.
644 if (parsed === null)
645 return {
646 records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
647 malformedRecords: cached?.provider === provider ? cached.malformedRecords : [],
648 failed: true,
649 };
650​
651 const identity = (record: UsageRecord) =>
652 encodeUsageRecordKey([
653 record.provider,
654 record.sessionId,
655 record.timestampMs,
656 record.model,
657 record.rateModel,
658 record.totals,
659 record.reportedCostUsd,
660 record.dedupeKey,
661 ]);
662 if (!parsed.resumed && cached !== undefined && cached.provider === provider) {
663 // A whole-file re-parse re-emits saved requests unresolved. Keep their saved tier
664 // corrections, since the history that resolved them may no longer be available.
665 // Equal requests keep their own corrections by matching occurrences in order.
666 const saved = new Map<string, UsageRecord[]>();
667 for (const previous of [...cached.records, ...cached.tailRecords]) {
668 const corrected = correctedRecord(previous);
669 const key = identity(corrected);
670 const occurrences = saved.get(key);
671 if (occurrences === undefined) saved.set(key, [corrected]);
672 else occurrences.push(corrected);
673 }
674 for (const record of [...parsed.records, ...parsed.tailRecords]) {
675 const corrected = saved.get(identity(record))?.shift();
676 if (
677 record.unresolvedServiceTierTurnId !== undefined &&
678 corrected !== undefined &&
679 corrected.unresolvedServiceTierTurnId === undefined
680 ) {
681 resolvedRecords.set(record, corrected);
682 }
683 }
684 }
685 if (parsed.resumed && cached !== undefined && cached.tailRecords.length > 0) {
686 // Completing a tentative line reparses it. Reuse its saved correction only when the
687 // same usage is emitted again, without putting inferred tiers in the parser state.
688 const reparsed = [...parsed.records, ...parsed.tailRecords];
689 for (const [index, previous] of cached.tailRecords.entries()) {
690 const record = reparsed[index];
691 const corrected = correctedRecord(previous);
692 if (
693 record?.unresolvedServiceTierTurnId !== undefined &&
694 corrected.unresolvedServiceTierTurnId === undefined &&
695 identity(record) === identity(corrected)
696 ) {
697 resolvedRecords.set(record, corrected);
698 }
699 }
700 }
701 const base = parsed.resumed && cached !== undefined ? cached.records : [];
702 const records = dedupeWithinFile([...base, ...parsed.records]);
703 const tailRecords = parsed.tailRecords;
704​
705 return {
706 records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
707 malformedRecords: parsed.malformedRecords,
708 update: {
709 entry: {
710 size,
711 mtimeMs,
712 provider,
713 records,
714 tailRecords,
715 malformedRecords: parsed.malformedRecords,
716 position: parsed.position,
717 },
718 replaces: cached,
719 },
720 };
721 });
722​
723 interface ScannedDir {
724 readonly provider: UsageProviderKind;
725 readonly dir: string;
726 readonly volumeId: string;
727 readonly physicalSourceId?: string;
728 readonly hostId?: string;
729 readonly status?: UsageSource["status"];
730 readonly message?: string;
731 readonly files:
732 | readonly {
733 readonly path: string;
734 readonly records: readonly UsageRecord[];
735 readonly malformedRecords: readonly number[];
736 }[]
737 | null;
738 /** Every transcript path the walk listed, in walk order, whatever its mtime. */
739 readonly walked?: readonly string[];
740 readonly refreshing?: true;
741 }
742​
743 const scanTranscriptDir = Effect.fn("UsageService.scanTranscriptDir")(function* (
744 source: TranscriptSource,
745 windowStartMs: number,
746 fromMemory: boolean,
747 ) {
748 const { provider, format, dir, volumeId, physicalSourceId, fileName } = source;
749 const identity = {
750 provider,
751 dir,
752 volumeId,
753 ...(physicalSourceId === undefined ? {} : { physicalSourceId }),
754 };
755 const exists = yield* fileSystem
756 .exists(dir)
757 .pipe(Effect.catchCause(() => Effect.succeed(false)));
758 if (!exists) {
759 cover(source, windowStartMs);
760 return { ...identity, files: null } satisfies ScannedDir;
761 }
762 // scanSummary aggregates the saved files, as it does for a deleted directory.
763 if (fromMemory) return { ...identity, files: [] } satisfies ScannedDir;
764 const { files, walked, failedPaths } = yield* Effect.promise(() =>
765 listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
766 );
767 const read = yield* Effect.forEach(
768 files,
769 (file) =>
770 readFileRecords(file.path, file.size, file.mtimeMs, provider, format).pipe(
771 Effect.map((result) => ({ path: file.path, ...result })),
772 ),
773 { concurrency: TRANSCRIPT_READ_CONCURRENCY },
774 );
775 const parsedFiles = read.map(({ path, records, malformedRecords, update }) => {
776 if (update === undefined) return { path, records, malformedRecords };
777 // A scan of another window may have cached its own read of this file
778 // meanwhile. Then keep whichever read saw the later file, so a slower
779 // scan never replaces newer usage with older.
780 const current = fileCache.get(path);
781 if (
782 current === update.replaces ||
783 current === undefined ||
784 isLaterRead(update.entry, current)
785 ) {
786 fileCache.set(path, {
787 ...update.entry,
788 records: correctedBatch(update.entry.records),
789 tailRecords: correctedBatch(update.entry.tailRecords),
790 });
791 cacheDirty = true;
792 }
793 return { path, records, malformedRecords };
794 });
795 const livePaths = new Set(files.map((file) => file.path));
796 for (const file of read) {
797 if (file.failed || !file.path.endsWith(".jsonl.zst")) continue;
798 const originalPath = file.path.slice(0, -4);
799 // A successfully read archive replaces the original's saved records and diagnostics.
800 if (!livePaths.has(originalPath) && fileCache.delete(originalPath)) cacheDirty = true;
801 }
802 const unread = failedPaths + read.filter((file) => file.failed).length;
803 if (unread === 0) cover(source, windowStartMs);
804 yield* Effect.annotateCurrentSpan({
805 "usage.files": files.length,
806 "usage.files_parsed": read.filter((file) => file.update !== undefined).length,
807 });
808 return {
809 ...identity,
810 files: parsedFiles,
811 walked,
812 ...(unread > 0
813 ? {
814 status: "partial",
815 message: `${unread} transcript path(s) could not be read; usage may be incomplete.`,
816 }
817 : {}),
818 } satisfies ScannedDir;
819 });
820​
821 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
822 { dirs, pending }: Effect.Success<ReturnType<typeof resolveTranscriptDirs>>,
823 windowStartMs: number,
824 settings: ServerSettingsValue,
825 retentionCutoffMs: number,
826 awaitRefresh: boolean,
827 fromMemory: boolean,
828 ) {
829 const scans = Effect.forEach(
830 scanReaders,
831 ({ driver, reader }) =>
832 usageInstances(driver, settings).pipe(
833 Effect.flatMap((instances) =>
834 reader.scan({ instances, settings, windowStartMs, retentionCutoffMs, awaitRefresh }),
835 ),
836 Effect.flatMap((sources) =>
837 Effect.forEach(sources, ({ volumeId, ...source }) =>
838 Effect.map(
839 // A reader's own volumeId names a remote account, not a local directory.
840 volumeId === undefined
841 ? Effect.all([
842 Effect.promise(() => readDirectoryVolumeId(source.dir)),
843 physicalSourceId(source.dir),
844 ])
845 : Effect.succeed<[string, string | undefined]>([volumeId, undefined]),
846 ([resolved, sourceId]): ScannedDir => ({
847 ...source,
848 files: source.files?.map((file) => ({ ...file, malformedRecords: [] })) ?? null,
849 provider: reader.provider,
850 volumeId: resolved,
851 ...(sourceId === undefined ? {} : { physicalSourceId: sourceId }),
852 }),
853 ),
854 ),
855 ),
856 Effect.provideContext(readerContext),
857 ),
858 { concurrency: "unbounded" },
859 );
860​
861 // Scan independent sources together, directories sequentially to bound open files; keep order, since the first copy decides a duplicate's bucket.
862 const [transcripts, scanDirs] = yield* Effect.all(
863 [Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs, fromMemory)), scans],
864 { concurrency: "unbounded" },
865 );
866 const scanned: readonly ScannedDir[] = [...transcripts, ...pending, ...scanDirs.flat()];
867 return scanned;
868 });
869​
870 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
871 input: UsageSummaryInput,
872 settings: ServerSettingsValue,
873 provisional: boolean,
874 ) {
875 if (input.sinceDay > input.untilDay) {
876 return yield* new UsageReadError({
877 reason: "invalidWindow",
878 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
879 });
880 }
881​
882 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
883 if (input.resolution === "hour") {
884 const sinceTime =
885 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
886 const untilTime =
887 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
888 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
889 return yield* new UsageReadError({
890 reason: "invalidWindow",
891 detail: "Hourly usage requires valid sinceTime and untilTime instants",
892 });
893 }
894 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
895 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
896 const durationMs = untilTimeMs - sinceTimeMs;
897 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
898 return yield* new UsageReadError({
899 reason: "invalidWindow",
900 detail: "Hourly usage window must be greater than zero and at most 24 hours",
901 });
902 }
903 hourlyWindow = { sinceTimeMs, untilTimeMs };
904 }
905​
906 const startedAtMs = yield* Clock.currentTimeMillis;
907 yield* ensureScanCacheLoaded;
908​
909 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
910 if (Option.isNone(windowStart)) {
911 return yield* new UsageReadError({
912 reason: "invalidWindow",
913 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
914 });
915 }
916 const windowStartMs =
917 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
918​
919 const retentionCutoffMs =
920 settings.usageHistoryRetentionDays === "unlimited"
921 ? 0
922 : Math.max(0, startedAtMs - settings.usageHistoryRetentionDays * 24 * 60 * 60 * 1000);
923​
924 const inWindow = usageTimestampFilter({ ...input, ...hourlyWindow });
925 const windowEndMs =
926 hourlyWindow?.untilTimeMs ??
927 Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS;
928​
929 const awaitRefresh = input.awaitRefresh === true;
930 const collect = Effect.gen(function* () {
931 const resolved = yield* resolveTranscriptDirs(settings, retentionCutoffMs, awaitRefresh).pipe(
932 Effect.provideContext(readerContext),
933 );
934 // A window no complete scan has read would show partial totals, so every directory must cover it.
935 // Saved files are keyed by path, so two providers reading one directory keep only one parse.
936 const fromMemory =
937 provisional &&
938 resolved.dirs.length > 0 &&
939 new Set(resolved.dirs.map((source) => source.dir)).size === resolved.dirs.length &&
940 resolved.dirs.every(
941 (source) => (coveredSince.get(coverageKey(source)) ?? Infinity) <= windowStartMs,
942 );
943 const [, scanned] = yield* Effect.all(
944 [
945 fromMemory ? loadSavedRates : provisional ? ensureRates(false) : Effect.void,
946 collectDirs(
947 resolved,
948 windowStartMs,
949 settings,
950 retentionCutoffMs,
951 awaitRefresh,
952 fromMemory,
953 ),
954 ],
955 { concurrency: 2 },
956 );
957 return { scannedDirs: scanned, fromMemory };
958 });
959 const [{ scannedDirs, fromMemory }] = yield* Effect.all(
960 [collect, provisional ? Effect.void : ensureRates(false)],
961 { concurrency: 2 },
962 );
963​
964 const priceOverrides = createOverrideRateTable(settings.usagePriceOverrides);
965 const modelAliases = resolveModelAliases(settings.usageModelAliases);
966 const sources: UsageSource[] = [];
967​
968 // Deleted transcripts' saved usage still aggregates and deduplicates normally.
969 const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs);
970 // Saved paths are files below a scanned root, so their folder decides; folders repeat thousands of times.
971 const withinDir = (dir: string) => {
972 const foldersWithin = new Map<string, boolean>();
973 return (filePath: string) => {
974 const folder = path.dirname(filePath);
975 let within = foldersWithin.get(folder);
976 if (within === undefined) {
977 within = isWithinDirectory(folder, dir);
978 foldersWithin.set(folder, within);
979 }
980 return within;
981 };
982 };
983 const filesByDir = scannedDirs.map(({ provider, dir, files }) => {
984 const retainedFiles = [...(files ?? [])];
985 const livePaths = new Set(retainedFiles.map((file) => file.path));
986 const isRetained = withinDir(dir);
987 for (const [filePath, entry] of fileCache) {
988 if (
989 entry.provider !== provider ||
990 entry.mtimeMs < retainedSinceMs ||
991 livePaths.has(filePath) ||
992 !isRetained(filePath)
993 )
994 continue;
995 retainedFiles.push({
996 path: filePath,
997 records:
998 entry.tailRecords.length === 0
999 ? entry.records
1000 : [...entry.records, ...entry.tailRecords],
1001 malformedRecords: entry.malformedRecords,
1002 });
1004 return retainedFiles.flatMap((file) => {
1005 // A keyed copy outside the window still claims its key, so a later copy is not counted.
1006 const records = file.records.filter(
1007 (record) => record.dedupeKey !== null || inWindow(record.timestampMs),
1008 );
1009 const malformedRecords = file.malformedRecords.filter(inWindow);
1010 return records.length === 0 && malformedRecords.length === 0
1011 ? []
1012 : [{ ...file, records, malformedRecords }];
1013 });
1014 });
1015 // Usage two transcripts share counts in the first one, so saved files take the order an exact
1016 // scan reads them in: walked files in walk order, then the directory's deleted files.
1017 for (const { provider, dir, walked } of fromMemory ? [] : scannedDirs) {
1018 if (walked === undefined) continue;
1019 const within = withinDir(dir);
1020 const saved = [...fileCache.keys()];
1021 const members = new Set(
1022 saved.filter(
1023 (filePath) => fileCache.get(filePath)!.provider === provider && within(filePath),
1024 ),
1025 );
1026 if (members.size < 2) continue;
1027 const listed = new Set(walked);
1028 const target = [
1029 ...walked.filter((filePath) => members.has(filePath)),
1030 ...saved.filter((filePath) => members.has(filePath) && !listed.has(filePath)),
1031 ];
1032 let next = 0;
1033 const ordered = saved.map((filePath) => (members.has(filePath) ? target[next++]! : filePath));
1034 if (ordered.every((filePath, index) => filePath === saved[index])) continue;
1035 const entries = new Map(fileCache);
1036 fileCache.clear();
1037 for (const filePath of ordered) fileCache.set(filePath, entries.get(filePath)!);
1038 cacheDirty = true;
1040​
1041 // The models priced below, as UsageAggregator resolves them: an alias replaces rateModel.
1042 const rateModels = new Set<string>();
1043 for (const files of filesByDir) {
1044 for (const file of files) {
1045 for (const record of file.records) {
1046 const alias = modelAliases.get(record.model);
1047 const model = alias ?? record.model;
1048 if (priceOverrides.has(model.trim())) continue;
1049 rateModels.add(alias === undefined ? (record.rateModel ?? model) : model);
1053 // A saved answer prices with saved rates and the full scan after it refetches.
1054 if (!fromMemory) yield* refreshForUnlistedModels(rateModels);
1055​
1056 const summaryPricing = pricing();
1057​
1058 const aggregator = new UsageAggregator({
1059 timeZone: input.timeZone,
1060 sinceDay: input.sinceDay,
1061 untilDay: input.untilDay,
1062 resolution: input.resolution ?? "day",
1063 ...hourlyWindow,
1064 rates,
1065 priceOverrides,
1066 modelAliases,
1067 rateModel: (provider, model) => providerRateModels.get(provider)?.(model),
1068 ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }),
1069 });
1070​
1071 let resolvedAny = false;
1072 for (const { reader } of transcriptReaders) {
1073 if (reader.resolveServiceTiers === undefined || fromMemory) continue;
1074 const pending = new Set<UsageRecord>();
1075 for (const [index, files] of filesByDir.entries()) {
1076 if (scannedDirs[index]?.provider !== reader.provider) continue;
1077 for (const file of files) {
1078 for (const raw of file.records) {
1079 const record = correctedRecord(raw);
1080 if (
1081 record.provider === reader.provider &&
1082 record.unresolvedServiceTierTurnId !== undefined &&
1083 record.timestampMs >= windowStartMs &&
1084 record.timestampMs < windowEndMs
1085 ) {
1086 pending.add(record);
1091 if (pending.size === 0) continue;
1092 const resolved = yield* reader
1093 .resolveServiceTiers([...pending])
1094 .pipe(Effect.provideContext(readerContext));
1095 for (const [record, speed] of resolved) {
1096 const { unresolvedServiceTierTurnId: _turnId, ...rest } = record;
1097 resolvedRecords.set(record, { ...rest, speed });
1098 resolvedAny = true;
1101 if (resolvedAny) {
1102 for (const [filePath, entry] of fileCache) {
1103 const records = correctedBatch(entry.records);
1104 const tailRecords = correctedBatch(entry.tailRecords);
1105 if (records === entry.records && tailRecords === entry.tailRecords) continue;
1106 // Update the current entry by identity; a slow resolver cannot restore an older file.
1107 fileCache.set(filePath, { ...entry, records, tailRecords });
1108 cacheDirty = true;
1111 const crossFileSessions = sharedSessions(filesByDir.flat());
1112​
1113 for (const [
1114 index,
1116 provider,
1117 dir,
1118 volumeId,
1119 physicalSourceId,
1120 files,
1121 status,
1122 message,
1123 refreshing,
1124 hostId: sourceHostId,
1125 },
1126 ] of scannedDirs.entries()) {
1127 let scannedFiles = 0;
1128 let skippedFiles = 0;
1129 let malformedRecords = 0;
1130 // Distinct per directory. Buckets carry per-cell session counts, but a
1131 // session spans days and models, so clients total this figure instead.
1132 const sessionIds = new Set<string>();
1133 let counted = false;
1134​
1135 for (const file of filesByDir[index] ?? []) {
1136 malformedRecords += file.malformedRecords.length;
1137 if (file.records.length === 0) {
1138 skippedFiles += 1;
1139 continue;
1141 scannedFiles += 1;
1142 const eventOccurrences = new Map<string, number>();
1143 for (const rawRecord of file.records) {
1144 const record = correctedRecord(rawRecord);
1145 let usageRecord = record;
1146 if (
1147 sharedSessionProviders.has(record.provider) &&
1148 crossFileSessions.has(record.sessionId)
1149 ) {
1150 // Dedupe moved copies but retain repeated equal events within a file, including second-precision timestamps.
1151 const key = encodeUsageRecordKey([
1152 record.provider,
1153 record.sessionId,
1154 record.timestampMs,
1155 record.model,
1156 record.totals,
1157 ]);
1158 const occurrence = (eventOccurrences.get(key) ?? 0) + 1;
1159 eventOccurrences.set(key, occurrence);
1160 usageRecord = { ...record, dedupeKey: key + ":" + occurrence };
1162 if (aggregator.add(usageRecord, dir)) {
1163 counted = true;
1164 if (record.sessionId.length > 0) sessionIds.add(record.sessionId);
1168​
1169 const sourceMessage =
1170 message ?? (files === null ? "No transcript directory on this environment." : null);
1171 sources.push({
1172 fingerprint: {
1173 hostId: sourceHostId ?? hostId,
1174 provider,
1175 resolvedHomePath: dir,
1176 volumeId,
1177 ...(physicalSourceId === undefined ? {} : { physicalSourceId }),
1178 },
1179 status:
1180 files === null && scannedFiles === 0
1181 ? "missing"
1182 : malformedRecords > 0
1183 ? status === undefined || status === "ok"
1184 ? "partial"
1185 : status
1186 : (status ?? "ok"),
1187 scannedFiles,
1188 skippedFiles,
1189 malformedRecords,
1190 distinctSessions: sessionIds.size,
1191 message:
1192 malformedRecords > 0
1193 ? [sourceMessage, formatMalformedUsageWarning(malformedRecords)]
1194 .filter(Boolean)
1195 .join(" ")
1196 : sourceMessage,
1197 // A saved answer misses what changed since its scan, so the client must ask again. An
1198 // empty source stays unmarked: it would only flash a loading row.
1199 ...(refreshing || (fromMemory && counted && transcriptFormats.has(provider))
1200 ? { refreshing: true }
1201 : {}),
1202 });
1204​
1205 yield* settingsService
1206 .withSettingsSnapshot((currentSettings) =>
1207 Effect.sync(() => {
1208 if (settings.usageHistoryRetentionDays === currentSettings.usageHistoryRetentionDays) {
1209 const pruned = pruneScanCache(fileCache, retentionCutoffMs);
1210 if (pruned > 0) {
1211 cacheDirty = true;
1212 // Pruned files are no longer saved, so nothing before the cutoff stays covered.
1213 for (const [key, since] of coveredSince) {
1214 if (since < retentionCutoffMs) coveredSince.set(key, retentionCutoffMs);
1218 }),
1220 .pipe(
1221 Effect.catchCause((cause) =>
1222 Effect.logWarning("failed to read settings before pruning the usage cache", { cause }),
1223 ),
1224 );
1225​
1226 const aggregated = aggregator.finish();
1227 const readAt = yield* DateTime.now;
1228 const finishedAtMs = yield* Clock.currentTimeMillis;
1229​
1230 const summary = {
1231 contractVersion: USAGE_CONTRACT_VERSION,
1232 readAt: DateTime.formatIso(readAt),
1233 timeZone: input.timeZone,
1234 sinceDay: input.sinceDay,
1235 untilDay: input.untilDay,
1236 buckets: aggregated.buckets,
1237 sources,
1238 pricing: summaryPricing,
1239 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
1240 ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }),
1241 accessRequests: yield* accessRequests(settings).pipe(Effect.provideContext(readerContext)),
1242 } satisfies UsageSummary;
1243 return { summary, fromMemory };
1244 });
1245​
1246 const readWindow = Effect.fn("UsageService.readWindow")(function* (
1247 input: UsageSummaryInput,
1248 settings: ServerSettingsValue,
1249 provisional: boolean,
1250 ) {
1251 const { summary, fromMemory } = yield* scanSummary(input, settings, provisional);
1252 // With nothing marked refreshing the client would keep a saved answer as final.
1253 return fromMemory && !summary.sources.some((source) => source.refreshing === true)
1254 ? (yield* scanSummary(input, settings, false)).summary
1255 : summary;
1256 });
1257​
1258 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
1259​
1260 const scanKey = (
1261 input: UsageSummaryInput,
1262 settings: ServerSettingsValue,
1263 provisional: boolean,
1264 ): string =>
1265 JSON.stringify([
1266 input.timeZone,
1267 input.sinceDay,
1268 input.untilDay,
1269 input.resolution ?? "day",
1270 input.sinceTime ?? null,
1271 input.untilTime ?? null,
1272 settings,
1273 input.awaitRefresh === true,
1274 provisional,
1275 input.modelFilter ?? null,
1276 ]);
1277​
1278 const readSummary = Effect.fn("UsageService.readSummary")(function* (
1279 requested: UsageSummaryInput,
1280 ) {
1281 const { modelFilter: requestedFilter, ...unfiltered } = requested;
1282 const modelFilter = canonicalModelFilter(requestedFilter);
1283 const input = modelFilter === undefined ? unfiltered : { ...unfiltered, modelFilter };
1284 const settings = yield* readSettings;
1285 const provisional = input.provisional === true && input.awaitRefresh !== true;
1286 const key = scanKey(input, settings, provisional);
1287 const deferred = yield* Effect.uninterruptible(
1288 Effect.gen(function* () {
1289 const existing = inflightScans.get(key);
1290 if (existing !== undefined) return existing;
1291​
1292 // Register and fork atomically so cancellation cannot leave a Deferred without a scan.
1293 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
1294 inflightScans.set(key, created);
1295 // Detach so caller departure cannot cancel shared scans; finished scans warm the cache.
1296 // Register writes before releasing waiters, but start writing after delivering their summary.
1297 yield* readWindow(input, settings, provisional).pipe(
1298 Effect.onExit((exit) =>
1299 Effect.sync(() => inflightScans.delete(key)).pipe(
1300 Effect.andThen(Exit.isSuccess(exit) ? schedulePersist : Effect.void),
1301 Effect.andThen(Deferred.done(created, exit)),
1302 ),
1303 ),
1304 Effect.forkDetach,
1305 );
1306 return created;
1307 }),
1308 );
1309 return yield* Deferred.await(deferred);
1310 });
1311​
1312 return { readSummary, refreshRates, awaitPersisted } as const;
1313});
1314​
1315export const layer = Layer.effect(UsageService, make);