Skip to main content

mytheclipse_cache/
metrics.rs

1//! Cache instrumentation metrics (hit/miss/eviction counters).
2
3use std::sync::atomic::{AtomicU64, Ordering};
4
5/// Tracks cache hit, miss, eviction, and error counts.
6#[derive(Default)]
7pub struct CacheMetrics {
8    hits: AtomicU64,
9    misses: AtomicU64,
10    evictions: AtomicU64,
11    errors: AtomicU64,
12}
13
14impl CacheMetrics {
15    pub fn new() -> Self {
16        Self::default()
17    }
18
19    pub fn hit(&self) {
20        self.hits.fetch_add(1, Ordering::Relaxed);
21    }
22
23    pub fn miss(&self) {
24        self.misses.fetch_add(1, Ordering::Relaxed);
25    }
26
27    pub fn eviction(&self) {
28        self.evictions.fetch_add(1, Ordering::Relaxed);
29    }
30
31    pub fn error(&self) {
32        self.errors.fetch_add(1, Ordering::Relaxed);
33    }
34
35    pub fn snapshot(&self) -> CacheSnapshot {
36        CacheSnapshot {
37            hits: self.hits.load(Ordering::Relaxed),
38            misses: self.misses.load(Ordering::Relaxed),
39            evictions: self.evictions.load(Ordering::Relaxed),
40            errors: self.errors.load(Ordering::Relaxed),
41        }
42    }
43}
44
45/// A point-in-time read of cache metrics.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct CacheSnapshot {
48    pub hits: u64,
49    pub misses: u64,
50    pub evictions: u64,
51    pub errors: u64,
52}
53
54impl CacheSnapshot {
55    pub fn hit_rate(&self) -> f64 {
56        let total = self.hits + self.misses;
57        if total == 0 {
58            0.0
59        } else {
60            self.hits as f64 / total as f64
61        }
62    }
63}