Skip to main content

cachekit/
metrics.rs

1//! Telemetry: live hit/miss counters, the `X-CacheKit-*` SaaS telemetry
2//! headers built from them, and — behind the `tracing` feature — structured
3//! events for cache operations.
4//!
5//! Counters are owned by a [`CacheKit`](crate::CacheKit) and shared by its
6//! clones; read a snapshot with [`CacheKit::stats`](crate::CacheKit::stats).
7//! At build time the client hands a
8//! [`MetricsProvider`](crate::metrics::MetricsProvider) over those counters to
9//! the backend ([`Backend::attach_metrics`](crate::backend::Backend::attach_metrics)),
10//! so the cachekit.io backends' telemetry headers report real numbers with no
11//! user plumbing. A provider given to the backend's own builder takes
12//! precedence.
13
14use std::sync::atomic::{AtomicU64, Ordering};
15use std::sync::Arc;
16use std::time::Duration;
17
18/// Snapshot of cache hit statistics for one [`CacheKit`](crate::CacheKit)
19/// and all of its clones.
20///
21/// Counts cover the value read path — `get`, `interop_get`, their SWR
22/// variants, and the `SecureCache` equivalents. `exists` and reads that end
23/// in a backend error are not counted.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub struct L1Stats {
26    /// Number of reads served from the L1 in-process cache.
27    pub l1_hits: u64,
28    /// Number of reads served from the L2 backend.
29    pub l2_hits: u64,
30    /// Number of reads that found nothing in either layer.
31    pub misses: u64,
32    /// Whether the L1 cache is enabled on this client.
33    pub l1_enabled: bool,
34}
35
36impl L1Stats {
37    /// Fraction of reads served from L1, in `[0.0, 1.0]` (`0.0` before any read).
38    pub fn l1_hit_rate(&self) -> f64 {
39        let total = self.l1_hits + self.l2_hits + self.misses;
40        if total == 0 {
41            0.0
42        } else {
43            self.l1_hits as f64 / total as f64
44        }
45    }
46}
47
48/// Thread-safe closure that produces an optional [`L1Stats`] snapshot.
49pub type MetricsProvider = Arc<dyn Fn() -> Option<L1Stats> + Send + Sync>;
50
51/// Names of the `X-CacheKit-*` telemetry headers, in the order
52/// [`metrics_headers`] emits them: L1 status, L1 hits, L2 hits, misses, L1 hit
53/// rate.
54pub(crate) const METRICS_HEADER_NAMES: [&str; 5] = [
55    "X-CacheKit-L1-Status",
56    "X-CacheKit-L1-Hits",
57    "X-CacheKit-L2-Hits",
58    "X-CacheKit-Misses",
59    "X-CacheKit-L1-Hit-Rate",
60];
61
62/// Build `X-CacheKit-*` HTTP headers from the current L1 stats provider.
63pub fn metrics_headers(provider: Option<&MetricsProvider>) -> Vec<(&'static str, String)> {
64    metrics_headers_named(provider, &METRICS_HEADER_NAMES)
65}
66
67/// [`metrics_headers`] with the names supplied in [`METRICS_HEADER_NAMES`]
68/// order, so the native CachekitIO backend can pass prebuilt `HeaderName`s
69/// instead of having reqwest parse each name on every request.
70pub(crate) fn metrics_headers_named<N: Clone>(
71    provider: Option<&MetricsProvider>,
72    names: &[N; 5],
73) -> Vec<(N, String)> {
74    let [status, l1_hits, l2_hits, misses, hit_rate] = names.clone();
75    let disabled = vec![(status.clone(), "disabled".to_string())];
76
77    let provider = match provider {
78        Some(p) => p,
79        None => return disabled,
80    };
81
82    let stats = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (provider)())) {
83        Ok(Some(s)) => s,
84        _ => return disabled,
85    };
86
87    if !stats.l1_enabled {
88        return disabled;
89    }
90
91    vec![
92        // The server accepts exactly `hit`, `miss`, or `disabled` and answers
93        // 400 to an SDK key sending anything else (spec/saas-api.md, "Optional
94        // Metrics Headers"). Like the Python and TypeScript SDKs we report the
95        // aggregate `miss` whenever L1 is on — per-request classification is
96        // not something an L2 request can know about itself.
97        (status, "miss".to_string()),
98        (l1_hits, stats.l1_hits.to_string()),
99        (l2_hits, stats.l2_hits.to_string()),
100        (misses, stats.misses.to_string()),
101        (hit_rate, format!("{:.3}", stats.l1_hit_rate())),
102    ]
103}
104
105// ── Key hashing ──────────────────────────────────────────────────────────────
106
107/// Blake2b-128 digest of a storage key as 32 lowercase hex characters.
108///
109/// Cache keys routinely embed user identifiers, so `tracing` events carry this
110/// digest instead of the key (CWE-532). It is a **correlator, not a
111/// redaction**: it is unkeyed and deterministic, so the same key hashes
112/// identically in every process and matches the File backend's on-disk
113/// filename (and cachekit-py's `hashlib.blake2b(key, digest_size=16)`) — and
114/// for that same reason a low-entropy key such as `user:42` can be recovered
115/// from its digest by enumeration. Treat `cachekit=debug` output with the
116/// care you give the keys themselves.
117pub fn key_hash(key: &str) -> String {
118    use blake2::{digest::consts::U16, Blake2b, Digest};
119
120    let mut hasher = Blake2b::<U16>::new();
121    hasher.update(key.as_bytes());
122    hex::encode(hasher.finalize())
123}
124
125// ── Live counters ────────────────────────────────────────────────────────────
126
127/// How a value read was served. Counted by [`CacheCounters`] and, with the
128/// `tracing` feature, emitted as the `outcome` field of the read event.
129///
130/// Public only so `#[cachekit]` can carry a call's outcome from its reads to
131/// [`CacheKit::__count`](crate::CacheKit::__count) — not public API.
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133#[doc(hidden)]
134#[non_exhaustive]
135pub enum ReadOutcome {
136    /// Served from the in-process L1 cache, within its freshness window.
137    L1Hit,
138    /// Served from L1 past the SWR freshness threshold: still an L1 hit for
139    /// the counters, but the caller is about to refresh it in the background.
140    L1Stale,
141    /// Served from the L2 backend (and backfilled into L1 when enabled, unless
142    /// the server marked the read stale or its freshness exhausted).
143    L2Hit,
144    /// Neither layer had the key.
145    Miss,
146}
147
148#[cfg(feature = "tracing")]
149impl ReadOutcome {
150    fn as_str(self) -> &'static str {
151        match self {
152            Self::L1Hit => "l1_hit",
153            Self::L1Stale => "l1_stale",
154            Self::L2Hit => "l2_hit",
155            Self::Miss => "miss",
156        }
157    }
158}
159
160/// Live counters behind [`L1Stats`], owned by a client and shared with its
161/// clones and its backend's [`MetricsProvider`].
162///
163/// Relaxed atomics: each counter is an independent monotonic tally and a
164/// snapshot may observe one counter a step ahead of another — fine for
165/// telemetry, and the cost of a stronger ordering on the read hot path is not.
166#[derive(Debug)]
167pub(crate) struct CacheCounters {
168    l1_hits: AtomicU64,
169    l2_hits: AtomicU64,
170    misses: AtomicU64,
171    /// Fixed at build time: whether the owning client has an L1.
172    l1_enabled: bool,
173}
174
175impl CacheCounters {
176    pub(crate) fn new(l1_enabled: bool) -> Self {
177        Self {
178            l1_hits: AtomicU64::new(0),
179            l2_hits: AtomicU64::new(0),
180            misses: AtomicU64::new(0),
181            l1_enabled,
182        }
183    }
184
185    /// Count one read outcome and emit its `tracing` event (feature `tracing`).
186    pub(crate) fn record(&self, outcome: ReadOutcome, full_key: &str) {
187        let counter = match outcome {
188            ReadOutcome::L1Hit | ReadOutcome::L1Stale => &self.l1_hits,
189            ReadOutcome::L2Hit => &self.l2_hits,
190            ReadOutcome::Miss => &self.misses,
191        };
192        counter.fetch_add(1, Ordering::Relaxed);
193        trace_read(full_key, outcome);
194    }
195
196    /// Current totals.
197    pub(crate) fn snapshot(&self) -> L1Stats {
198        L1Stats {
199            l1_hits: self.l1_hits.load(Ordering::Relaxed),
200            l2_hits: self.l2_hits.load(Ordering::Relaxed),
201            misses: self.misses.load(Ordering::Relaxed),
202            l1_enabled: self.l1_enabled,
203        }
204    }
205
206    /// A [`MetricsProvider`] over these counters, for
207    /// [`Backend::attach_metrics`](crate::backend::Backend::attach_metrics).
208    ///
209    /// Holds the counters weakly: a backend can outlive the client that was
210    /// built over it, and once every clone of that client is gone the provider
211    /// reports `None` — the headers fall back to `disabled` — rather than the
212    /// frozen numbers of a dead client.
213    pub(crate) fn provider(self: &Arc<Self>) -> MetricsProvider {
214        let counters = Arc::downgrade(self);
215        Arc::new(move || counters.upgrade().map(|c| c.snapshot()))
216    }
217}
218
219// ── tracing events ───────────────────────────────────────────────────────────
220//
221// One `debug` event per completed cache operation on the `cachekit` target
222// (`RUST_LOG=cachekit=debug`), one per failed fill-lock call, and one per
223// `#[cachekit]` result the macro could not store. Fields: `op`
224// (`get` | `set` | `delete` | `lock` | `unlock`), `key_hash` (see `key_hash`),
225// and per op `outcome` / `ttl_secs` / `existed` / `error_kind`.
226// Field expressions only run when a subscriber is enabled for the callsite,
227// so the hash is never computed for an uninterested process. Without the
228// feature these are empty functions the optimizer removes.
229
230/// Target for cache-operation events.
231#[cfg(feature = "tracing")]
232const TARGET: &str = "cachekit";
233
234fn trace_read(full_key: &str, outcome: ReadOutcome) {
235    #[cfg(feature = "tracing")]
236    tracing::debug!(
237        target: TARGET,
238        op = "get",
239        key_hash = %key_hash(full_key),
240        outcome = outcome.as_str(),
241    );
242    #[cfg(not(feature = "tracing"))]
243    let _ = (full_key, outcome);
244}
245
246/// Emit the event for a completed write (`set` and SWR refresh commits).
247pub(crate) fn trace_write(full_key: &str, ttl: Duration) {
248    #[cfg(feature = "tracing")]
249    tracing::debug!(
250        target: TARGET,
251        op = "set",
252        key_hash = %key_hash(full_key),
253        ttl_secs = crate::backend::ttl_wire_secs(ttl),
254    );
255    #[cfg(not(feature = "tracing"))]
256    let _ = (full_key, ttl);
257}
258
259/// Emit the event for a completed delete.
260pub(crate) fn trace_delete(full_key: &str, existed: bool) {
261    #[cfg(feature = "tracing")]
262    tracing::debug!(
263        target: TARGET,
264        op = "delete",
265        key_hash = %key_hash(full_key),
266        existed,
267    );
268    #[cfg(not(feature = "tracing"))]
269    let _ = (full_key, existed);
270}
271
272/// Emit the event for a failed fill-lock call (`op` is `lock` or `unlock`).
273/// The call bypasses the circuit breaker, so this is the only signal of a
274/// failing lock endpoint: refreshes stand down, cold misses fill without the
275/// lease, and an unreleased lease is left to expire. It carries the error's
276/// kind, never its message: a transport error names the request URL, and the
277/// URL holds the key (CWE-532).
278#[cfg(all(feature = "reliability", not(target_arch = "wasm32")))]
279pub(crate) fn trace_lock_error(full_key: &str, op: &'static str, err: &crate::BackendError) {
280    #[cfg(feature = "tracing")]
281    tracing::debug!(
282        target: TARGET,
283        op,
284        key_hash = %key_hash(full_key),
285        error_kind = %err.kind,
286    );
287    #[cfg(not(feature = "tracing"))]
288    let _ = (full_key, op, err);
289}
290
291/// Emit the event for a `#[cachekit]` result the macro computed but could not
292/// store: a cold-miss fill, or an SWR refresh whose commit failed. Macro
293/// plumbing. A cold-miss call still returns its result; a failed refresh
294/// commit is dropped and the stale value keeps being served. Either way this
295/// is the only signal of a failing store — otherwise it shows only as repeat
296/// misses or refreshes.
297/// The macro stores only on an un-namespaced client, so `key` is the storage
298/// key. Like the lock-error event, it carries the error's kind, never
299/// its message: a transport error names the request URL, and an invalid-key
300/// error the key (CWE-532).
301#[doc(hidden)]
302pub fn __trace_store_error(key: &str, err: &crate::CachekitError) {
303    #[cfg(feature = "tracing")]
304    {
305        use crate::CachekitError as E;
306        let error_kind: &dyn std::fmt::Display = match err {
307            E::Backend(be) => &be.kind,
308            E::Serialization(_) => &"serialization",
309            E::Encryption(_) => &"encryption",
310            E::Config(_) => &"config",
311            E::PayloadTooLarge { .. } => &"payload-too-large",
312            E::InvalidKey(_) => &"invalid-key",
313        };
314        tracing::debug!(
315            target: TARGET,
316            op = "set",
317            key_hash = %key_hash(key),
318            error_kind = %error_kind,
319        );
320    }
321    #[cfg(not(feature = "tracing"))]
322    let _ = (key, err);
323}
324
325#[cfg(test)]
326#[allow(clippy::panic)] // test-only: a missing header on a fixture should panic loudly
327mod tests {
328    use super::*;
329
330    fn header<'a>(headers: &'a [(&str, String)], name: &str) -> &'a str {
331        headers
332            .iter()
333            .find(|h| h.0 == name)
334            .map(|h| h.1.as_str())
335            .unwrap_or_else(|| panic!("header {name} missing from {headers:?}"))
336    }
337
338    fn provider(l1_hits: u64, l2_hits: u64, misses: u64, l1_enabled: bool) -> MetricsProvider {
339        Arc::new(move || {
340            Some(L1Stats {
341                l1_hits,
342                l2_hits,
343                misses,
344                l1_enabled,
345            })
346        })
347    }
348
349    #[test]
350    fn disabled_when_no_provider() {
351        let headers = metrics_headers(None);
352        assert_eq!(headers.len(), 1);
353        assert_eq!(headers[0], ("X-CacheKit-L1-Status", "disabled".to_string()));
354    }
355
356    #[test]
357    fn disabled_when_l1_not_enabled() {
358        let headers = metrics_headers(Some(&provider(0, 0, 0, false)));
359        assert_eq!(headers[0].1, "disabled");
360    }
361
362    /// The server rejects any status outside `hit|miss|disabled` with a 400
363    /// for SDK keys — this pins the value the SDK sends when L1 is on.
364    #[test]
365    fn status_is_a_server_accepted_value_when_l1_enabled() {
366        let headers = metrics_headers(Some(&provider(3, 2, 5, true)));
367        let status = header(&headers, "X-CacheKit-L1-Status");
368        assert_eq!(status, "miss");
369        assert!(["hit", "miss", "disabled"].contains(&status));
370    }
371
372    #[test]
373    fn correct_hit_rate_calculation() {
374        let headers = metrics_headers(Some(&provider(3, 2, 5, true)));
375        assert_eq!(header(&headers, "X-CacheKit-L1-Hit-Rate"), "0.300"); // 3 / (3+2+5)
376        assert_eq!(header(&headers, "X-CacheKit-L1-Hits"), "3");
377        assert_eq!(header(&headers, "X-CacheKit-L2-Hits"), "2");
378        assert_eq!(header(&headers, "X-CacheKit-Misses"), "5");
379    }
380
381    #[test]
382    fn zero_division_guard() {
383        let headers = metrics_headers(Some(&provider(0, 0, 0, true)));
384        assert_eq!(header(&headers, "X-CacheKit-L1-Hit-Rate"), "0.000");
385        assert_eq!(L1Stats::default().l1_hit_rate(), 0.0);
386    }
387
388    #[test]
389    fn disabled_when_provider_panics() {
390        #[allow(clippy::panic)]
391        let provider: MetricsProvider = Arc::new(|| panic!("boom"));
392        let headers = metrics_headers(Some(&provider));
393        assert_eq!(headers[0].1, "disabled");
394    }
395
396    #[test]
397    fn counters_record_and_snapshot() {
398        let counters = Arc::new(CacheCounters::new(true));
399        counters.record(ReadOutcome::L1Hit, "k");
400        counters.record(ReadOutcome::L1Stale, "k");
401        counters.record(ReadOutcome::L2Hit, "k");
402        counters.record(ReadOutcome::Miss, "k");
403        assert_eq!(
404            counters.snapshot(),
405            L1Stats {
406                l1_hits: 2,
407                l2_hits: 1,
408                misses: 1,
409                l1_enabled: true,
410            }
411        );
412        // The provider is a live view, not a copy...
413        let provider = counters.provider();
414        counters.record(ReadOutcome::Miss, "k");
415        assert_eq!(provider().map(|s| s.misses), Some(2));
416        // ...and a weak one: a dead client reports nothing, not stale numbers.
417        drop(counters);
418        assert_eq!(provider(), None);
419        assert_eq!(metrics_headers(Some(&provider))[0].1, "disabled");
420    }
421
422    /// Same digest as the File backend filename and cachekit-py's
423    /// `hashlib.blake2b(key, digest_size=16).hexdigest()`.
424    #[test]
425    fn key_hash_is_py_blake2b16_hex() {
426        assert_eq!(
427            key_hash("ns:app:func:m.f:args:abc:v1"),
428            "bcb35ae6f64fa65b2770ab3af631b1ce" // pragma: allowlist secret
429        );
430        assert_eq!(key_hash("").len(), 32);
431    }
432}