/** * What the cache did, per call. * * `stats()` only knows totals, so nothing could say which key a request * missed. Each read, write and removal is published here on a * `node:diagnostics_channel`: one property read per call while nothing is * subscribed, and a subscriber needs no import from this package. */ import { channel, subscribe, unsubscribe } from 'node:diagnostics_channel' export const CACHE_OPERATION_CHANNEL = 'stacks:cache:operation' export interface CacheOperation { type: 'hit' | 'miss' | 'write' | 'forget' key: string /** Seconds, on a write that named one. */ ttl?: number /** Milliseconds the backend took to answer, or the fetcher to compute a miss. */ durationMs?: number } // eslint-disable-next-line pickier/no-unused-vars type CacheOperationListener = (operation: CacheOperation) => void export const cacheOperationChannel: ReturnType = channel(CACHE_OPERATION_CHANNEL) /** Observe every cache operation. Returns a function that stops observing. */ export function onCacheOperation(listener: CacheOperationListener): () => void { const handle = (message: unknown): void => listener(message as CacheOperation) subscribe(CACHE_OPERATION_CHANNEL, handle) return () => { unsubscribe(CACHE_OPERATION_CHANNEL, handle) } }