Open History to see the last commit
1/**
2 * UsageService - scans provider transcripts and returns priced usage buckets.
3 *
4 * The scan reads the provider CLIs' own session files (Claude Code, Codex, and
5 * Grok Build) rather than T3 Code's orchestration projections, so usage covers
6 * turns driven outside T3 Code too. This is the approach `ccusage` takes.
7 *
8 * Transcripts are append-only, so parsed records are memoised per file by
9 * `(size, mtime)`. A cold 30-day scan of ~1.4 GB lands around 2-3 seconds; warm
10 * scans only reparse files that changed, and a file that merely grew resumes
11 * from its cached parse position so only the appended bytes are read.
12 *
13 * @module UsageService
14 */
15import * as NodeOS from "node:os";
16
17import {
18 ClaudeSettings,
19 CodexSettings,
20 type ProviderInstanceConfig,
21 USAGE_CONTRACT_VERSION,
22 type ServerSettings as ServerSettingsValue,
23 type UsageProviderKind,
24 type UsageSource,
25 type UsagePricing,
26 type UsageSummary,
27 type UsageSummaryInput,
28 UsageReadError,
29} from "@t3tools/contracts";
30import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
31import * as Cause from "effect/Cause";
32import * as Clock from "effect/Clock";
33import * as Context from "effect/Context";
34import * as DateTime from "effect/DateTime";
35import * as Deferred from "effect/Deferred";
36import * as Effect from "effect/Effect";
37import * as FileSystem from "effect/FileSystem";
38import * as Layer from "effect/Layer";
39import * as Option from "effect/Option";
40import * as Path from "effect/Path";
41import * as Schema from "effect/Schema";
42import * as Semaphore from "effect/Semaphore";
43import { HttpClient, HttpClientResponse } from "effect/unstable/http";
44
45import { ServerConfig } from "../config.ts";
46import { expandHomePath } from "../pathExpansion.ts";
47import * as ServerSettings from "../serverSettings.ts";
48import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
49import { mergeProviderInstanceEnvironment } from "../provider/ProviderInstanceEnvironment.ts";
50import { UsageAggregator } from "./usageAggregation.ts";
51import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts";
52import {
53 listTranscriptFiles,
54 readDirectoryVolumeId,
55 readTranscriptRecords,
56} from "./usageTranscriptReader.ts";
57import {
58 decodeScanCache,
59 dedupeWithinFile,
60 encodeScanCache,
61 pruneScanCache,
62 type ScanCache,
63} from "./usageScanCache.ts";
64import type { UsageRecord } from "./usageTranscripts.ts";
65
66const LITELLM_RATES_URL =
67 "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
68
69/** Rates move rarely; a day-old table keeps the page working offline. */
70const RATES_TTL_MS = 24 * 60 * 60 * 1000;
71
72/** An explicit refresh ignores the TTL, but not a table fetched this recently. */
73const RATES_REFRESH_FLOOR_MS = 60 * 1000;
74
75/**
76 * Files are filtered by mtime before opening. The slack covers a session whose
77 * last write lands just before local midnight on the window's first day.
78 */
79const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
80const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
81
82/** Longest window the UI offers, plus slack. Older entries are pruned. */
83const CACHE_RETENTION_DAYS = 90;
84
85const decodeCodexSettings = Schema.decodeOption(CodexSettings);
86const decodeClaudeSettings = Schema.decodeOption(ClaudeSettings);
87
88/** On-disk shape of the rate snapshot. */
89const RatesCacheFile = Schema.Struct({
90 fetchedAtMs: Schema.Number,
91 document: Schema.Unknown,
92});
93const decodeRatesCache = Schema.decodeUnknownEffect(
94 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
95);
96const encodeRatesCache = Schema.encodeEffect(
97 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
98);
99
100/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */
101const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);
102const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
103const encodeScanCacheFile = Schema.encodeEffect(ScanCacheJson);
104
105export class UsageService extends Context.Service<
106 UsageService,
107 {
108 readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
109 /** Refetches the rate table ahead of its TTL. See `ensureRates`. */
110 readonly refreshRates: Effect.Effect<UsagePricing>;
111 }
112>()("t3/usage/UsageService") {}
113
114const EMPTY_PRICING: UsagePricing = {
115 status: "unavailable",
116 source: LITELLM_RATES_URL,
117 fetchedAt: null,
118 knownModels: 0,
119};
120
121/** Empty summary, for suites that only need the RPC surface to resolve. */
122const layerTest = Layer.succeed(
123 UsageService,
124 UsageService.of({
125 readSummary: (input) =>
126 Effect.succeed({
127 contractVersion: USAGE_CONTRACT_VERSION,
128 readAt: "1970-01-01T00:00:00.000Z",
129 timeZone: input.timeZone,
130 sinceDay: input.sinceDay,
131 untilDay: input.untilDay,
132 buckets: [],
133 sources: [],
134 pricing: EMPTY_PRICING,
135 scanDurationMs: 0,
136 }),
137 refreshRates: Effect.succeed(EMPTY_PRICING),
138 }),
139);
140
141export const make = Effect.gen(function* () {
142 const fileSystem = yield* FileSystem.FileSystem;
143 const path = yield* Path.Path;
144 const config = yield* ServerConfig;
145 const settingsService = yield* ServerSettings.ServerSettingsService;
146 const httpClient = yield* HttpClient.HttpClient;
147 const hostEnvironment = yield* HostProcessEnvironment;
148
149 const fileCache: ScanCache = new Map();
150 let cacheDirty = false;
151
152 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
153 const scanCachePath = path.join(config.stateDir, "usage-scan-cache.json");
154 let rates: RateTable = new Map();
155 let ratesFetchedAtMs: number | null = null;
156 let ratesStatus: UsagePricing["status"] = "unavailable";
157 // One fetch at a time. A burst of refreshes from several clients waits on
158 // the first fetch and then sees a table young enough to skip its own.
159 const ratesLock = yield* Semaphore.make(1);
160
161 const pricing = (): UsagePricing => ({
162 status: ratesStatus,
163 source: LITELLM_RATES_URL,
164 fetchedAt:
165 ratesFetchedAtMs === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
166 knownModels: rates.size,
167 });
168
169 /**
170 * Loads the LiteLLM rate table, preferring a fresh copy and falling back to
171 * the on-disk snapshot. With neither, every model reports as unpriced rather
172 * than the page failing. `force` refetches inside the TTL so a model that
173 * LiteLLM added since the last fetch gets priced now.
174 */
175 const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) {
176 const now = yield* Clock.currentTimeMillis;
177 const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS;
178 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return;
179
180 if (ratesFetchedAtMs === null) {
181 const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(
182 Effect.flatMap((raw) => decodeRatesCache(raw)),
183 Effect.catchCause(() => Effect.succeed(null)),
184 );
185 if (fromDisk !== null) {
186 const parsed = parseRateTable(fromDisk.document);
187 if (parsed.size > 0) {
188 rates = parsed;
189 ratesFetchedAtMs = fromDisk.fetchedAtMs;
190 ratesStatus = "cached";
191 if (now - fromDisk.fetchedAtMs < maxAgeMs) return;
192 }
193 }
194 }
195
196 const fetched = yield* httpClient.get(LITELLM_RATES_URL).pipe(
197 Effect.flatMap(HttpClientResponse.filterStatusOk),
198 Effect.flatMap((response) => response.json),
199 Effect.timeout(10_000),
200 Effect.catchCause(() => Effect.succeed(null)),
201 );
202 if (fetched === null) {
203 // The refresh failed; whatever we are serving is now past its TTL and
204 // must not keep claiming to be fresh.
205 if (rates.size > 0) ratesStatus = "cached";
206 return;
207 }
208
209 const parsed = parseRateTable(fetched);
210 if (parsed.size === 0) return;
211
212 rates = parsed;
213 ratesFetchedAtMs = now;
214 ratesStatus = "fresh";
215
216 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe(
217 Effect.flatMap((serialized) => fileSystem.writeFileString(ratesCachePath, serialized)),
218 Effect.catchCause(() => Effect.void),
219 );
220 });
221
222 const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force));
223
224 const refreshRates = ensureRates(true).pipe(
225 Effect.map(pricing),
226 Effect.withSpan("UsageService.refreshRates"),
227 );
228
229 // A settings failure must not silently discard custom rates or transcript homes.
230 const readSettings = settingsService.getSettings.pipe(
231 Effect.catchCause(
232 (cause) =>
233 new UsageReadError({
234 reason: "scanFailed",
235 detail: "Server settings could not be read.",
236 cause: Cause.squash(cause),
237 }),
238 ),
239 );
240
241 /** Resolves the transcript directory for each provider. */
242 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (
243 settings: ServerSettingsValue,
244 ) {
245 const dirs: Array<{ provider: UsageProviderKind; dir: string; fileName?: string }> = [];
246 const seen = new Set<string>();
247 for (const driver of ["claudeAgent", "codex", "grok"] as const) {
248 // Disabled accounts still have history. Explicit default slots replace
249 // the legacy settings, just as they do in the provider registry.
250 const instances: Array<Pick<ProviderInstanceConfig, "config" | "environment">> =
251 Object.values(settings.providerInstances).filter((instance) => instance.driver === driver);
252 if (!Object.hasOwn(settings.providerInstances, driver)) {
253 instances.push({ config: settings.providers[driver] });
254 }
255 for (const instance of instances) {
256 const environment = mergeProviderInstanceEnvironment(instance.environment, hostEnvironment);
257 const provider = driver === "claudeAgent" ? "claude" : driver;
258 let home: string;
259 if (driver === "codex") {
260 const decoded = decodeCodexSettings(instance.config ?? {});
261 if (Option.isNone(decoded)) continue;
262 const config = decoded.value;
263 const environmentHome = environment.CODEX_HOME?.trim();
264 const layout = yield* resolveCodexHomeLayout(
265 !config.homePath.trim() && !config.shadowHomePath.trim() && environmentHome
266 ? { ...config, homePath: environmentHome }
267 : config,
268 );
269 home = layout.sharedHomePath;
270 } else if (driver === "claudeAgent") {
271 const decoded = decodeClaudeSettings(instance.config ?? {});
272 if (Option.isNone(decoded)) continue;
273 const configured = decoded.value.homePath.trim();
274 home = configured
275 ? expandHomePath(configured)
276 : environment.CLAUDE_CONFIG_DIR?.trim() || path.join(NodeOS.homedir(), ".claude");
277 } else {
278 home = expandHomePath(
279 environment.GROK_HOME?.trim() || path.join(NodeOS.homedir(), ".grok"),
280 );
281 }
282 const directory = path.resolve(home, provider === "claude" ? "projects" : "sessions");
283 // Account aliases and Codex auth overlays can share the same history.
284 const dir = yield* fileSystem
285 .realPath(directory)
286 .pipe(Effect.orElseSucceed(() => directory));
287 const key = `${provider}\0${dir}`;
288 if (seen.has(key)) continue;
289 seen.add(key);
290 dirs.push({ provider, dir, ...(provider === "grok" ? { fileName: "updates.jsonl" } : {}) });
291 }
292 }
293 return dirs;
294 });
295
296 /**
297 * Loads the persisted scan cache exactly once per process.
298 *
299 * `Effect.cached` makes concurrent first readers await the same load rather
300 * than each seeing a "loaded" flag set before the read finished and cold
301 * scanning against an empty cache.
302 */
303 const ensureScanCacheLoaded = yield* Effect.cached(
304 Effect.gen(function* () {
305 const document = yield* fileSystem.readFileString(scanCachePath).pipe(
306 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
307 Effect.catchCause(() => Effect.succeed(null)),
308 );
309 if (document === null) return;
310 for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);
311 }),
312 );
313
314 const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () {
315 if (!cacheDirty) return;
316 // Cleared only after the write lands, so a failed persist is retried on
317 // the next scan instead of leaving disk permanently stale.
318 yield* encodeScanCacheFile(encodeScanCache(fileCache)).pipe(
319 Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)),
320 Effect.map(() => {
321 cacheDirty = false;
322 }),
323 // A cache we cannot write is a slower next start, not a failed read.
324 Effect.catchCause(() => Effect.void),
325 );
326 });
327
328 /**
329 * Parses one transcript, reusing the cached result when it is unchanged.
330 *
331 * A file that only grew re-parses from the cached position, so an actively
332 * written multi-hundred-megabyte rollout costs its appended bytes per scan
333 * rather than a full re-read. The reader verifies the position's guard bytes
334 * and silently restarts from byte 0 when they no longer match.
335 */
336 const readFileRecords = (
337 filePath: string,
338 size: number,
339 mtimeMs: number,
340 provider: UsageProviderKind,
341 ): Effect.Effect<readonly UsageRecord[]> =>
342 Effect.gen(function* () {
343 const cached = fileCache.get(filePath);
344 // Provider is part of the identity: if both providers were ever pointed
345 // at one directory, a hit parsed by the other parser must not be reused.
346 if (
347 cached &&
348 cached.size === size &&
349 cached.mtimeMs === mtimeMs &&
350 cached.provider === provider
351 ) {
352 return cached.tailRecords.length === 0
353 ? cached.records
354 : [...cached.records, ...cached.tailRecords];
355 }
356
357 // Only a strictly grown file may resume. Same size with a new mtime, or
358 // a shrunken file, means rewritten content; re-parse it whole.
359 const resumeFrom =
360 cached !== undefined && cached.provider === provider && size > cached.size
361 ? cached.position
362 : undefined;
363
364 const parsed = yield* Effect.promise(() =>
365 readTranscriptRecords(filePath, provider, resumeFrom),
366 );
367 // A read failure is not an empty transcript: caching it under this
368 // (size, mtime) would silently drop the file's usage until it changes.
369 if (parsed === null) return [];
370
371 // Stored already de-duplicated within the file, which is 99% of all
372 // duplicates. The aggregator still runs the cross-file dedupe pass. One
373 // seen set spans the cached base, the new lines, and the tail so a
374 // resumed parse dedupes exactly like a full one.
375 const base = parsed.resumed && cached !== undefined ? cached.records : [];
376 const seen = new Set<string>();
377 const records = dedupeWithinFile([...base, ...parsed.records], seen);
378 const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);
379
380 fileCache.set(filePath, {
381 size,
382 mtimeMs,
383 provider,
384 records,
385 tailRecords,
386 position: parsed.position,
387 });
388 cacheDirty = true;
389 return tailRecords.length === 0 ? records : [...records, ...tailRecords];
390 });
391
392 /** One provider directory's walk and parse, before rates are involved. */
393 interface ScannedDir {
394 readonly provider: UsageProviderKind;
395 readonly dir: string;
396 readonly volumeId: string;
397 /** Parsed records per file, or `null` when the directory does not exist. */
398 readonly files:
399 | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
400 | null;
401 }
402
403 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
404 windowStartMs: number,
405 settings: ServerSettingsValue,
406 ) {
407 // The home resolvers ask for `Path` themselves; satisfy them from the
408 // instance we already hold so the scan stays context-free.
409 const dirs = yield* resolveTranscriptDirs(settings).pipe(
410 Effect.provideService(Path.Path, path),
411 );
412 const scanned: ScannedDir[] = [];
413 for (const { provider, dir, fileName } of dirs) {
414 const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
415 const exists = yield* fileSystem
416 .exists(dir)
417 .pipe(Effect.catchCause(() => Effect.succeed(false)));
418 if (!exists) {
419 scanned.push({ provider, dir, volumeId, files: null });
420 continue;
421 }
422 const files = yield* Effect.promise(() =>
423 listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
424 );
425 const parsedFiles: { path: string; records: readonly UsageRecord[] }[] = [];
426 for (const file of files) {
427 const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);
428 parsedFiles.push({ path: file.path, records });
429 }
430 scanned.push({ provider, dir, volumeId, files: parsedFiles });
431 }
432 return scanned;
433 });
434
435 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
436 input: UsageSummaryInput,
437 settings: ServerSettingsValue,
438 ) {
439 if (input.sinceDay > input.untilDay) {
440 return yield* new UsageReadError({
441 reason: "invalidWindow",
442 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
443 });
444 }
445
446 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
447 if (input.resolution === "hour") {
448 const sinceTime =
449 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
450 const untilTime =
451 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
452 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
453 return yield* new UsageReadError({
454 reason: "invalidWindow",
455 detail: "Hourly usage requires valid sinceTime and untilTime instants",
456 });
457 }
458 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
459 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
460 const durationMs = untilTimeMs - sinceTimeMs;
461 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
462 return yield* new UsageReadError({
463 reason: "invalidWindow",
464 detail: "Hourly usage window must be greater than zero and at most 24 hours",
465 });
466 }
467 hourlyWindow = { sinceTimeMs, untilTimeMs };
468 }
469
470 const startedAtMs = yield* Clock.currentTimeMillis;
471 yield* ensureScanCacheLoaded;
472
473 const hostId = NodeOS.hostname();
474 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
475 if (Option.isNone(windowStart)) {
476 return yield* new UsageReadError({
477 reason: "invalidWindow",
478 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
479 });
480 }
481 const windowStartMs =
482 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
483
484 // Pricing only matters once records are aggregated, so the rate table
485 // loads while transcripts stream instead of gating them: a cold rates
486 // fetch on a slow network no longer delays the scan by its own timeout.
487 const [, scannedDirs] = yield* Effect.all(
488 [ensureRates(false), collectDirs(windowStartMs, settings)],
489 { concurrency: 2 },
490 );
491
492 const aggregator = new UsageAggregator({
493 timeZone: input.timeZone,
494 sinceDay: input.sinceDay,
495 untilDay: input.untilDay,
496 resolution: input.resolution ?? "day",
497 ...hourlyWindow,
498 rates,
499 priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
500 });
501
502 const sources: UsageSource[] = [];
503 const livePaths = new Set<string>();
504 const walkedRoots: string[] = [];
505
506 for (const { provider, dir, volumeId, files } of scannedDirs) {
507 if (files === null) {
508 sources.push({
509 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
510 status: "missing",
511 scannedFiles: 0,
512 skippedFiles: 0,
513 malformedRecords: 0,
514 distinctSessions: 0,
515 message: "No transcript directory on this environment.",
516 });
517 continue;
518 }
519
520 walkedRoots.push(dir);
521 let scannedFiles = 0;
522 let skippedFiles = 0;
523 // Distinct per directory. Buckets carry per-cell session counts, but a
524 // session spans days and models, so clients total this figure instead.
525 const sessionIds = new Set<string>();
526
527 for (const file of files) {
528 livePaths.add(file.path);
529 if (file.records.length === 0) {
530 skippedFiles += 1;
531 continue;
532 }
533 scannedFiles += 1;
534 for (const record of file.records) {
535 // Only sessions that contributed in-window count: the mtime slack
536 // admits boundary files whose records fall outside the range.
537 if (aggregator.add(record) && record.sessionId.length > 0) {
538 sessionIds.add(record.sessionId);
539 }
540 }
541 }
542
543 sources.push({
544 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
545 status: "ok",
546 scannedFiles,
547 skippedFiles,
548 malformedRecords: 0,
549 distinctSessions: sessionIds.size,
550 message: null,
551 });
552 }
553
554 const pruned = pruneScanCache(fileCache, {
555 livePaths,
556 walkedRoots,
557 windowStartMs,
558 retentionCutoffMs: startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000,
559 });
560 if (pruned > 0) cacheDirty = true;
561 yield* persistScanCache();
562
563 const aggregated = aggregator.finish();
564 const readAt = yield* DateTime.now;
565 const finishedAtMs = yield* Clock.currentTimeMillis;
566
567 return {
568 contractVersion: USAGE_CONTRACT_VERSION,
569 readAt: DateTime.formatIso(readAt),
570 timeZone: input.timeZone,
571 sinceDay: input.sinceDay,
572 untilDay: input.untilDay,
573 buckets: aggregated.buckets,
574 sources,
575 pricing: pricing(),
576 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
577 } satisfies UsageSummary;
578 });
579
580 /**
581 * In-flight scans by window and custom prices, so concurrent identical requests (the usage
582 * page open on two clients at once) share one scan instead of racing over
583 * the same corpus twice.
584 */
585 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
586
587 const scanKey = (
588 input: UsageSummaryInput,
589 priceOverrides: ServerSettingsValue["usagePriceOverrides"],
590 ): string =>
591 JSON.stringify([
592 input.timeZone,
593 input.sinceDay,
594 input.untilDay,
595 input.resolution ?? "day",
596 input.sinceTime ?? null,
597 input.untilTime ?? null,
598 priceOverrides,
599 ]);
600
601 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
602 const settings = yield* readSettings;
603 const key = scanKey(input, settings.usagePriceOverrides);
604 const deferred = yield* Effect.uninterruptible(
605 Effect.gen(function* () {
606 const existing = inflightScans.get(key);
607 if (existing !== undefined) return existing;
608
609 // Enrollment and detached-fiber creation must be atomic. Otherwise a
610 // canceled first caller can leave a Deferred with no scan to finish it.
611 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
612 inflightScans.set(key, created);
613 // Detached so one departing client cannot tear the scan out from under
614 // the fibers awaiting it; a finished scan warms the cache either way.
615 yield* scanSummary(input, settings).pipe(
616 Effect.onExit((exit) =>
617 Effect.sync(() => inflightScans.delete(key)).pipe(
618 Effect.andThen(Deferred.done(created, exit)),
619 ),
620 ),
621 Effect.forkDetach,
622 );
623 return created;
624 }),
625 );
626 // Waiting stays interruptible. The detached scan continues for other
627 // callers and still warms the cache if this caller leaves.
628 return yield* Deferred.await(deferred);
629 });
630
631 return { readSummary, refreshRates } as const;
632});
633
634export const layer = Layer.effect(UsageService, make);