tower_resilience_cache/
events.rs

1//! Event types for cache.
2
3use std::time::Instant;
4use tower_resilience_core::ResilienceEvent;
5
6/// Events emitted by the cache.
7#[derive(Debug, Clone)]
8pub enum CacheEvent {
9    /// A cache hit occurred.
10    Hit {
11        /// The name of the cache instance.
12        pattern_name: String,
13        /// When the event occurred.
14        timestamp: Instant,
15    },
16    /// A cache miss occurred.
17    Miss {
18        /// The name of the cache instance.
19        pattern_name: String,
20        /// When the event occurred.
21        timestamp: Instant,
22    },
23    /// An entry was evicted from the cache.
24    Eviction {
25        /// The name of the cache instance.
26        pattern_name: String,
27        /// When the event occurred.
28        timestamp: Instant,
29    },
30}
31
32impl ResilienceEvent for CacheEvent {
33    fn event_type(&self) -> &'static str {
34        match self {
35            CacheEvent::Hit { .. } => "cache_hit",
36            CacheEvent::Miss { .. } => "cache_miss",
37            CacheEvent::Eviction { .. } => "cache_eviction",
38        }
39    }
40
41    fn timestamp(&self) -> Instant {
42        match self {
43            CacheEvent::Hit { timestamp, .. }
44            | CacheEvent::Miss { timestamp, .. }
45            | CacheEvent::Eviction { timestamp, .. } => *timestamp,
46        }
47    }
48
49    fn pattern_name(&self) -> &str {
50        match self {
51            CacheEvent::Hit { pattern_name, .. }
52            | CacheEvent::Miss { pattern_name, .. }
53            | CacheEvent::Eviction { pattern_name, .. } => pattern_name,
54        }
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn test_event_types() {
64        let now = Instant::now();
65
66        let hit = CacheEvent::Hit {
67            pattern_name: "test".to_string(),
68            timestamp: now,
69        };
70        assert_eq!(hit.event_type(), "cache_hit");
71        assert_eq!(hit.pattern_name(), "test");
72
73        let miss = CacheEvent::Miss {
74            pattern_name: "test".to_string(),
75            timestamp: now,
76        };
77        assert_eq!(miss.event_type(), "cache_miss");
78
79        let eviction = CacheEvent::Eviction {
80            pattern_name: "test".to_string(),
81            timestamp: now,
82        };
83        assert_eq!(eviction.event_type(), "cache_eviction");
84    }
85}