1use std::sync::Arc;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::time::Duration;
12
13use crate::clock::{AnyClock, Instant};
14use crate::context::CacheLifetime;
15
16const NOT_STARTED: u64 = u64::MAX;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum CacheState {
22 Cold,
25 Warm {
27 cold_in: Option<Duration>,
30 },
31}
32
33#[derive(Debug)]
34struct Inner {
35 lifetime: CacheLifetime,
36 clock: AnyClock,
37 entry_started_nanos: AtomicU64,
40}
41
42#[derive(Debug, Clone)]
48pub struct CacheWarmth {
49 inner: Arc<Inner>,
50}
51
52impl CacheWarmth {
53 pub(crate) fn new(lifetime: CacheLifetime, clock: AnyClock) -> Self {
55 Self {
56 inner: Arc::new(Inner {
57 lifetime,
58 clock,
59 entry_started_nanos: AtomicU64::new(NOT_STARTED),
60 }),
61 }
62 }
63
64 pub(crate) fn start_entry(&self, at: Instant) {
66 self.inner
67 .entry_started_nanos
68 .store(at.as_nanos(), Ordering::Relaxed);
69 }
70
71 pub(crate) fn start_entry_now(&self) {
73 self.start_entry(self.inner.clock.now());
74 }
75
76 fn idle(&self) -> Option<Duration> {
78 match self.inner.entry_started_nanos.load(Ordering::Relaxed) {
79 NOT_STARTED => None,
80 nanos => Some(self.inner.clock.since(Instant::from_nanos(nanos))),
81 }
82 }
83
84 pub(crate) fn has_expired(&self) -> bool {
87 match (self.inner.lifetime, self.idle()) {
88 (CacheLifetime::Limited(lifetime), Some(idle)) => idle >= lifetime,
89 _ => false,
90 }
91 }
92
93 #[must_use]
95 pub fn state(&self) -> CacheState {
96 let Some(idle) = self.idle() else {
97 return CacheState::Cold;
98 };
99 match self.inner.lifetime {
100 CacheLifetime::Permanent => CacheState::Warm { cold_in: None },
101 CacheLifetime::Limited(lifetime) => match lifetime.checked_sub(idle) {
102 Some(remaining) if !remaining.is_zero() => CacheState::Warm {
103 cold_in: Some(remaining),
104 },
105 _ => CacheState::Cold,
106 },
107 }
108 }
109
110 #[must_use]
112 pub fn is_warm(&self) -> bool {
113 matches!(self.state(), CacheState::Warm { .. })
114 }
115
116 #[must_use]
119 pub fn cold_in(&self) -> Option<Duration> {
120 match self.state() {
121 CacheState::Warm { cold_in } => cold_in,
122 CacheState::Cold => None,
123 }
124 }
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130 use crate::ManualClock;
131
132 const HOUR: Duration = Duration::from_secs(3600);
133
134 fn warmth(lifetime: CacheLifetime) -> (CacheWarmth, ManualClock) {
135 let clock = ManualClock::new();
136 (
137 CacheWarmth::new(lifetime, AnyClock::new(clock.clone())),
138 clock,
139 )
140 }
141
142 #[test]
143 fn it_is_cold_before_the_first_request() {
144 let (warmth, _clock) = warmth(CacheLifetime::Limited(HOUR));
145 assert_eq!(warmth.state(), CacheState::Cold);
146 assert!(!warmth.is_warm());
147 assert_eq!(warmth.cold_in(), None);
148 assert!(!warmth.has_expired());
149
150 let (permanent, _clock) = self::warmth(CacheLifetime::Permanent);
151 assert_eq!(permanent.state(), CacheState::Cold);
152 }
153
154 #[test]
155 fn a_warm_entry_goes_cold_once_its_lifetime_passes() {
156 let (warmth, clock) = warmth(CacheLifetime::Limited(HOUR));
157 clock.advance(Duration::from_secs(10));
158 warmth.start_entry_now();
159 assert_eq!(warmth.cold_in(), Some(HOUR));
160
161 clock.advance(Duration::from_secs(600));
162 assert!(warmth.is_warm());
163 assert_eq!(
164 warmth.state(),
165 CacheState::Warm {
166 cold_in: Some(Duration::from_secs(3000))
167 }
168 );
169
170 clock.advance(Duration::from_secs(3000) - Duration::from_nanos(1));
171 assert_eq!(warmth.cold_in(), Some(Duration::from_nanos(1)));
172 assert!(!warmth.has_expired());
173
174 clock.advance(Duration::from_nanos(1));
175 assert_eq!(warmth.state(), CacheState::Cold);
176 assert_eq!(warmth.cold_in(), None);
177 assert!(warmth.has_expired());
178 }
179
180 #[test]
181 fn a_permanent_entry_never_goes_cold() {
182 let (warmth, clock) = warmth(CacheLifetime::Permanent);
183 warmth.start_entry_now();
184 clock.advance(Duration::from_secs(100 * 86_400));
185 assert_eq!(warmth.state(), CacheState::Warm { cold_in: None });
186 assert!(warmth.is_warm());
187 assert_eq!(warmth.cold_in(), None);
188 assert!(!warmth.has_expired());
189 }
190
191 #[test]
192 fn a_clone_sees_later_requests() {
193 let (warmth, clock) = warmth(CacheLifetime::Limited(HOUR));
194 let early = warmth.clone();
195 warmth.start_entry_now();
196 clock.advance(Duration::from_secs(3000));
197 assert_eq!(early.cold_in(), Some(Duration::from_secs(600)));
198
199 warmth.start_entry_now();
200 assert_eq!(early.cold_in(), Some(HOUR));
201 }
202}