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

UsageService.ts

1,275 lines49.4 KB

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