staticweaver/cache.rs
1// Copyright © 2024 StaticWeaver. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! # Cache Module
5//!
6//! Generic time-bounded cache used by the engine for `render_page`
7//! results. Two policies stack:
8//!
9//! - **TTL expiration** — every entry carries a per-insert deadline.
10//! `Cache::get` returns `None` once the deadline has passed; call
11//! `Cache::remove_expired` periodically to reclaim memory.
12//! - **LRU eviction** — when constructed with `Cache::with_capacity`,
13//! the cache enforces a hard upper bound. Inserts that would exceed
14//! the cap evict the least-recently-used entry. `Cache::get` bumps
15//! access recency, so frequently-read entries stay hot.
16//!
17//! The type is generic over both key and value (`Cache<K, V>`); the
18//! engine instantiates it as `Cache<String, String>` to cache
19//! rendered page bodies.
20//!
21//! # Examples
22//!
23//! ```
24//! use staticweaver::cache::Cache;
25//! use std::time::Duration;
26//!
27//! let mut cache: Cache<String, u32> =
28//! Cache::with_capacity(Duration::from_secs(60), 2);
29//! let _ = cache.insert("a".to_string(), 1);
30//! let _ = cache.insert("b".to_string(), 2);
31//! // Touching `a` promotes it; the next insert evicts `b`, not `a`.
32//! let _ = cache.get(&"a".to_string());
33//! let _ = cache.insert("c".to_string(), 3);
34//! assert!(cache.contains_key(&"a".to_string()));
35//! assert!(!cache.contains_key(&"b".to_string()));
36//! ```
37
38use std::collections::HashMap;
39use std::hash::Hash;
40use std::time::{Duration, Instant};
41
42/// Snapshot of cache counters at a point in time. Returned by
43/// [`Cache::stats`].
44///
45/// All fields are monotonically increasing `u64`s — they grow as the cache
46/// is used and never decrement. Take two snapshots and subtract to get a
47/// rate / per-window count. Designed for cheap export to `prometheus`,
48/// `metrics`, or `opentelemetry` without forcing a dep choice on the
49/// caller. Issue #40.
50///
51/// # Examples
52///
53/// ```
54/// use staticweaver::cache::Cache;
55/// use std::time::Duration;
56///
57/// let mut cache: Cache<String, u32> = Cache::new(Duration::from_secs(60));
58/// let _ = cache.insert("a".to_string(), 1);
59/// let _ = cache.get(&"a".to_string()); // hit
60/// let _ = cache.get(&"b".to_string()); // miss
61///
62/// let stats = cache.stats();
63/// assert_eq!(stats.inserts, 1);
64/// assert_eq!(stats.hits, 1);
65/// assert_eq!(stats.misses, 1);
66/// ```
67#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
68pub struct CacheStats {
69 /// Number of `insert` calls (new entries + updates).
70 pub inserts: u64,
71 /// Number of `get` calls that returned `Some` for a live entry.
72 pub hits: u64,
73 /// Number of `get` calls that returned `None` (absent key, no hit).
74 pub misses: u64,
75 /// Number of entries removed because they hit the capacity ceiling
76 /// (LRU evictions). Does **not** count TTL expirations — see
77 /// `ttl_expired` for those.
78 pub evictions: u64,
79 /// Number of entries reaped by `get` finding them expired or by
80 /// `remove_expired` sweeping them.
81 pub ttl_expired: u64,
82}
83
84/// Represents a cached item with its value, expiration time, and the
85/// monotonic counter value at the entry's most recent access (used for
86/// LRU eviction when a capacity bound is hit).
87#[derive(Debug, Clone)]
88struct CachedItem<T> {
89 value: T,
90 expiration: Instant,
91 last_access: u64,
92}
93
94/// A simple cache implementation with expiration and optional capacity limit.
95///
96/// This cache provides time-based expiration for items and an optional maximum capacity.
97/// It's designed to be generic over both key and value types for maximum flexibility.
98///
99/// # Examples
100///
101/// ```
102/// use staticweaver::cache::Cache;
103/// use std::time::Duration;
104///
105/// let mut cache: Cache<String, u32> = Cache::new(Duration::from_secs(60));
106/// let _ = cache.insert("visits".to_string(), 1);
107/// assert_eq!(cache.get(&"visits".to_string()), Some(&1));
108/// ```
109#[derive(Debug, Clone)]
110pub struct Cache<K, V> {
111 items: HashMap<K, CachedItem<V>>,
112 ttl: Duration,
113 capacity: Option<usize>,
114 /// Monotonic counter bumped on every `get` / `insert` / `update` /
115 /// `refresh` hit. The `CachedItem::last_access` field copies the
116 /// counter's value at that moment, producing a total ordering on
117 /// usage recency without allocating a secondary index.
118 access_counter: u64,
119 /// Cumulative hit / miss / eviction / ttl-expiry counters. Exposed
120 /// via [`Cache::stats`]. Issue #40.
121 stats: CacheStats,
122}
123
124impl<K: Hash + Eq + Clone, V: Clone> Cache<K, V> {
125 /// Creates a new Cache with the specified time-to-live (TTL) for items.
126 ///
127 /// # Arguments
128 ///
129 /// * `ttl` - The time-to-live for cached items.
130 ///
131 /// # Panics
132 ///
133 /// Panics if `ttl` is zero.
134 ///
135 /// # Example
136 ///
137 /// ```
138 /// use staticweaver::cache::Cache;
139 /// use std::time::Duration;
140 ///
141 /// let cache: Cache<String, String> = Cache::new(Duration::from_secs(60));
142 /// ```
143 #[must_use]
144 pub fn new(ttl: Duration) -> Self {
145 assert!(!ttl.is_zero(), "TTL must be greater than zero");
146 Self {
147 items: HashMap::new(),
148 ttl,
149 capacity: None,
150 access_counter: 0,
151 stats: CacheStats::default(),
152 }
153 }
154
155 /// Returns an iterator over the key-value pairs in the cache.
156 ///
157 /// Only entries that have not yet expired are yielded.
158 ///
159 /// # Returns
160 ///
161 /// An iterator over the key-value pairs in the cache.
162 ///
163 /// # Examples
164 ///
165 /// ```
166 /// use staticweaver::cache::Cache;
167 /// use std::time::Duration;
168 ///
169 /// let mut cache: Cache<String, String> =
170 /// Cache::new(Duration::from_secs(60));
171 /// let _ = cache.insert("a".to_string(), "1".to_string());
172 /// let _ = cache.insert("b".to_string(), "2".to_string());
173 /// assert_eq!(cache.iter().count(), 2);
174 /// ```
175 pub fn iter(&self) -> impl Iterator<Item = (&K, &V)> {
176 let now = Instant::now();
177 self.items.iter().filter_map(move |(k, item)| {
178 if item.expiration > now {
179 Some((k, &item.value))
180 } else {
181 None
182 }
183 })
184 }
185
186 /// Creates a new Cache with the specified TTL and initial capacity.
187 ///
188 /// # Arguments
189 ///
190 /// * `ttl` - The time-to-live for cached items.
191 /// * `capacity` - The initial capacity of the cache.
192 ///
193 /// # Panics
194 ///
195 /// Panics if `ttl` is zero.
196 ///
197 /// # Example
198 ///
199 /// ```
200 /// use staticweaver::cache::Cache;
201 /// use std::time::Duration;
202 ///
203 /// let cache: Cache<String, String> = Cache::with_capacity(Duration::from_secs(60), 100);
204 /// ```
205 #[must_use]
206 pub fn with_capacity(ttl: Duration, capacity: usize) -> Self {
207 assert!(!ttl.is_zero(), "TTL must be greater than zero");
208 Self {
209 items: HashMap::with_capacity(capacity),
210 ttl,
211 capacity: Some(capacity),
212 access_counter: 0,
213 stats: CacheStats::default(),
214 }
215 }
216
217 /// Returns a snapshot of cumulative cache counters (hits, misses,
218 /// evictions, ttl-expirations, inserts). Issue #40.
219 ///
220 /// All counters are monotonically increasing `u64`s. Take two
221 /// snapshots and subtract to get a per-window rate. Designed for
222 /// cheap export to `prometheus`, `metrics`, or `opentelemetry`
223 /// without forcing a dependency choice.
224 ///
225 /// # Examples
226 ///
227 /// ```
228 /// use staticweaver::cache::Cache;
229 /// use std::time::Duration;
230 ///
231 /// let mut cache: Cache<String, u32> = Cache::new(Duration::from_secs(60));
232 /// assert_eq!(cache.stats().inserts, 0);
233 /// let _ = cache.insert("k".to_string(), 1);
234 /// assert_eq!(cache.stats().inserts, 1);
235 /// ```
236 #[must_use]
237 pub fn stats(&self) -> CacheStats {
238 self.stats
239 }
240
241 /// Inserts a key-value pair into the cache.
242 ///
243 /// If the cache is at capacity and the key doesn't already exist, the
244 /// least-recently-used entry is evicted to make room.
245 ///
246 /// # Arguments
247 ///
248 /// * `key` - The key to insert.
249 /// * `value` - The value to insert.
250 ///
251 /// # Returns
252 ///
253 /// The old value if the key was already present.
254 ///
255 /// # Example
256 ///
257 /// ```
258 /// use staticweaver::cache::Cache;
259 /// use std::time::Duration;
260 ///
261 /// let mut cache = Cache::new(Duration::from_secs(60));
262 /// cache.insert("key".to_string(), "value".to_string());
263 /// ```
264 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
265 // If adding a *new* key would exceed capacity, evict the
266 // least-recently-used entry first. Updating an existing key is
267 // always allowed and doesn't trigger eviction. The loop handles
268 // the case where the cap was lowered below the current size —
269 // repeatedly drop the oldest entry until there's room for the
270 // new key.
271 if let Some(cap) = self.capacity {
272 while self.items.len() >= cap
273 && !self.items.contains_key(&key)
274 {
275 let victim = self
276 .items
277 .iter()
278 .min_by_key(|(_, item)| item.last_access)
279 .map(|(k, _)| k.clone());
280 match victim {
281 Some(k) => {
282 let _ = self.items.remove(&k);
283 self.stats.evictions =
284 self.stats.evictions.wrapping_add(1);
285 }
286 None => break,
287 }
288 }
289 }
290 self.access_counter = self.access_counter.wrapping_add(1);
291 let expiration = Instant::now() + self.ttl;
292 self.stats.inserts = self.stats.inserts.wrapping_add(1);
293 self.items
294 .insert(
295 key,
296 CachedItem {
297 value,
298 expiration,
299 last_access: self.access_counter,
300 },
301 )
302 .map(|old_item| old_item.value)
303 }
304
305 /// Retrieves a value from the cache if it exists and hasn't expired.
306 ///
307 /// # Arguments
308 ///
309 /// * `key` - The key to look up.
310 ///
311 /// # Returns
312 ///
313 /// An `Option` containing a reference to the value if it exists and hasn't expired, or `None` otherwise.
314 ///
315 /// # Example
316 ///
317 /// ```
318 /// use staticweaver::cache::Cache;
319 /// use std::time::Duration;
320 ///
321 /// let mut cache = Cache::new(Duration::from_secs(60));
322 /// cache.insert("key".to_string(), "value".to_string());
323 ///
324 /// assert_eq!(cache.get(&"key".to_string()), Some(&"value".to_string()));
325 /// ```
326 pub fn get(&mut self, key: &K) -> Option<&V> {
327 // Promote the entry to most-recently-used on a live hit so the
328 // LRU eviction policy actually tracks usage, not just insertion
329 // order. Expired entries are not promoted; callers get `None`
330 // and `remove_expired` will collect them on the next pass.
331 let now = Instant::now();
332 let next = self.access_counter.wrapping_add(1);
333 let item = match self.items.get_mut(key) {
334 Some(item) => item,
335 None => {
336 self.stats.misses = self.stats.misses.wrapping_add(1);
337 return None;
338 }
339 };
340 if item.expiration > now {
341 item.last_access = next;
342 self.access_counter = next;
343 self.stats.hits = self.stats.hits.wrapping_add(1);
344 Some(&item.value)
345 } else {
346 self.stats.ttl_expired =
347 self.stats.ttl_expired.wrapping_add(1);
348 self.stats.misses = self.stats.misses.wrapping_add(1);
349 None
350 }
351 }
352
353 /// Removes expired items from the cache.
354 ///
355 /// This method should be called periodically to clean up the cache.
356 ///
357 /// Time complexity: O(n) where n is the number of items in the cache.
358 ///
359 /// # Examples
360 ///
361 /// ```
362 /// use staticweaver::cache::Cache;
363 /// use std::time::Duration;
364 ///
365 /// let mut cache: Cache<String, String> =
366 /// Cache::new(Duration::from_secs(60));
367 /// let _ = cache.insert("k".to_string(), "v".to_string());
368 /// cache.remove_expired();
369 /// assert_eq!(cache.len(), 1);
370 /// ```
371 pub fn remove_expired(&mut self) {
372 let now = Instant::now();
373 let before = self.items.len() as u64;
374 self.items.retain(|_, item| item.expiration > now);
375 let reaped = before.saturating_sub(self.items.len() as u64);
376 self.stats.ttl_expired =
377 self.stats.ttl_expired.wrapping_add(reaped);
378 }
379
380 /// Checks if a key exists in the cache and hasn't expired.
381 ///
382 /// # Arguments
383 ///
384 /// * `key` - The key to check.
385 ///
386 /// # Returns
387 ///
388 /// `true` if the key exists and hasn't expired, `false` otherwise.
389 ///
390 /// # Examples
391 ///
392 /// ```
393 /// use staticweaver::cache::Cache;
394 /// use std::time::Duration;
395 ///
396 /// let mut cache: Cache<String, i32> =
397 /// Cache::new(Duration::from_secs(60));
398 /// let _ = cache.insert("n".to_string(), 1);
399 /// assert!(cache.contains_key(&"n".to_string()));
400 /// assert!(!cache.contains_key(&"missing".to_string()));
401 /// ```
402 pub fn contains_key(&self, key: &K) -> bool {
403 self.items
404 .get(key)
405 .is_some_and(|item| item.expiration > Instant::now())
406 }
407
408 /// Gets the remaining time-to-live for an item.
409 ///
410 /// # Arguments
411 ///
412 /// * `key` - The key to check.
413 ///
414 /// # Returns
415 ///
416 /// An `Option` containing the remaining TTL if the item exists and hasn't expired, or `None` otherwise.
417 ///
418 /// # Examples
419 ///
420 /// ```
421 /// use staticweaver::cache::Cache;
422 /// use std::time::Duration;
423 ///
424 /// let mut cache: Cache<String, i32> =
425 /// Cache::new(Duration::from_secs(60));
426 /// let _ = cache.insert("n".to_string(), 1);
427 /// assert!(cache.ttl(&"n".to_string()).is_some());
428 /// assert!(cache.ttl(&"missing".to_string()).is_none());
429 /// ```
430 pub fn ttl(&self, key: &K) -> Option<Duration> {
431 self.items.get(key).and_then(|item| {
432 let now = Instant::now();
433 if item.expiration > now {
434 Some(item.expiration - now)
435 } else {
436 None
437 }
438 })
439 }
440
441 /// Refreshes the expiration time for an item.
442 ///
443 /// # Arguments
444 ///
445 /// * `key` - The key of the item to refresh.
446 ///
447 /// # Returns
448 ///
449 /// `true` if the item was found and refreshed, `false` otherwise.
450 ///
451 /// # Examples
452 ///
453 /// ```
454 /// use staticweaver::cache::Cache;
455 /// use std::time::Duration;
456 ///
457 /// let mut cache: Cache<String, i32> =
458 /// Cache::new(Duration::from_secs(60));
459 /// let _ = cache.insert("n".to_string(), 1);
460 /// assert!(cache.refresh(&"n".to_string()));
461 /// assert!(!cache.refresh(&"missing".to_string()));
462 /// ```
463 pub fn refresh(&mut self, key: &K) -> bool {
464 let next = self.access_counter.wrapping_add(1);
465 if let Some(item) = self.items.get_mut(key) {
466 item.expiration = Instant::now() + self.ttl;
467 item.last_access = next;
468 self.access_counter = next;
469 true
470 } else {
471 false
472 }
473 }
474
475 /// Removes a key-value pair from the cache.
476 ///
477 /// # Arguments
478 ///
479 /// * `key` - The key to remove.
480 ///
481 /// # Returns
482 ///
483 /// The removed value if the key was present, or `None` otherwise.
484 ///
485 /// # Examples
486 ///
487 /// ```
488 /// use staticweaver::cache::Cache;
489 /// use std::time::Duration;
490 ///
491 /// let mut cache: Cache<String, String> =
492 /// Cache::new(Duration::from_secs(60));
493 /// let _ = cache.insert("k".to_string(), "v".to_string());
494 /// assert_eq!(cache.remove(&"k".to_string()), Some("v".to_string()));
495 /// assert_eq!(cache.remove(&"k".to_string()), None);
496 /// ```
497 pub fn remove(&mut self, key: &K) -> Option<V> {
498 self.items.remove(key).map(|item| item.value)
499 }
500
501 /// Updates the value for an existing key in the cache.
502 ///
503 /// # Arguments
504 ///
505 /// * `key` - The key to update.
506 /// * `value` - The new value to set.
507 ///
508 /// # Returns
509 ///
510 /// `true` if the key was found and updated, `false` otherwise.
511 ///
512 /// # Examples
513 ///
514 /// ```
515 /// use staticweaver::cache::Cache;
516 /// use std::time::Duration;
517 ///
518 /// let mut cache: Cache<String, String> =
519 /// Cache::new(Duration::from_secs(60));
520 /// let _ = cache.insert("k".to_string(), "old".to_string());
521 /// assert!(cache.update(&"k".to_string(), "new".to_string()));
522 /// assert_eq!(cache.get(&"k".to_string()), Some(&"new".to_string()));
523 /// ```
524 pub fn update(&mut self, key: &K, value: V) -> bool {
525 let next = self.access_counter.wrapping_add(1);
526 if let Some(item) = self.items.get_mut(key) {
527 item.value = value;
528 item.expiration = Instant::now() + self.ttl;
529 item.last_access = next;
530 self.access_counter = next;
531 true
532 } else {
533 false
534 }
535 }
536
537 /// Sets a maximum capacity for the cache.
538 ///
539 /// If the cache is already larger than this capacity, it will not
540 /// remove items immediately, but it will prevent new items from being
541 /// added until it's below capacity (via LRU eviction on `insert`).
542 ///
543 /// # Arguments
544 ///
545 /// * `capacity` - The maximum number of items the cache can hold.
546 ///
547 /// # Examples
548 ///
549 /// ```
550 /// use staticweaver::cache::Cache;
551 /// use std::time::Duration;
552 ///
553 /// let mut cache: Cache<String, String> =
554 /// Cache::new(Duration::from_secs(60));
555 /// cache.set_capacity(128);
556 /// ```
557 pub fn set_capacity(&mut self, capacity: usize) {
558 self.capacity = Some(capacity);
559 }
560
561 /// Clears all items from the cache.
562 ///
563 /// # Examples
564 ///
565 /// ```
566 /// use staticweaver::cache::Cache;
567 /// use std::time::Duration;
568 ///
569 /// let mut cache: Cache<String, i32> =
570 /// Cache::new(Duration::from_secs(60));
571 /// let _ = cache.insert("n".to_string(), 1);
572 /// cache.clear();
573 /// assert!(cache.is_empty());
574 /// ```
575 pub fn clear(&mut self) {
576 self.items.clear();
577 }
578
579 /// Returns the number of items in the cache.
580 ///
581 /// # Returns
582 ///
583 /// The number of key-value pairs currently in the cache.
584 ///
585 /// # Examples
586 ///
587 /// ```
588 /// use staticweaver::cache::Cache;
589 /// use std::time::Duration;
590 ///
591 /// let mut cache: Cache<String, i32> =
592 /// Cache::new(Duration::from_secs(60));
593 /// assert_eq!(cache.len(), 0);
594 /// let _ = cache.insert("a".to_string(), 1);
595 /// assert_eq!(cache.len(), 1);
596 /// ```
597 #[must_use]
598 pub fn len(&self) -> usize {
599 self.items.len()
600 }
601
602 /// Checks if the cache is empty.
603 ///
604 /// # Returns
605 ///
606 /// `true` if the cache is empty, `false` otherwise.
607 ///
608 /// # Examples
609 ///
610 /// ```
611 /// use staticweaver::cache::Cache;
612 /// use std::time::Duration;
613 ///
614 /// let cache: Cache<String, String> =
615 /// Cache::new(Duration::from_secs(60));
616 /// assert!(cache.is_empty());
617 /// ```
618 #[must_use]
619 pub fn is_empty(&self) -> bool {
620 self.items.is_empty()
621 }
622}
623
624impl<K: Hash + Eq + Clone, V: Clone> IntoIterator for Cache<K, V> {
625 type Item = (K, V);
626 type IntoIter = std::collections::hash_map::IntoIter<K, V>;
627
628 fn into_iter(self) -> Self::IntoIter {
629 let now = Instant::now();
630 self.items
631 .into_iter()
632 .filter(|(_, item)| item.expiration > now)
633 .map(|(k, item)| (k, item.value))
634 .collect::<HashMap<K, V>>()
635 .into_iter()
636 }
637}
638
639impl<K: Hash + Eq + Clone, V: Clone> Default for Cache<K, V> {
640 fn default() -> Self {
641 Self::new(Duration::from_secs(60))
642 }
643}
644
645impl<K: Hash + Eq + Clone, V: Clone> FromIterator<(K, V)>
646 for Cache<K, V>
647{
648 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
649 let mut cache = Self::default();
650 for (k, v) in iter {
651 let _ = cache.insert(k, v);
652 }
653 cache
654 }
655}
656
657#[cfg(test)]
658mod tests {
659 use super::*;
660 use std::thread::sleep;
661
662 #[test]
663 fn test_new_cache() {
664 let cache: Cache<String, i32> =
665 Cache::new(Duration::from_secs(60));
666 assert!(cache.items.is_empty());
667 assert_eq!(cache.ttl, Duration::from_secs(60));
668 }
669
670 #[test]
671 fn test_insert_and_get() {
672 let mut cache: Cache<String, i32> =
673 Cache::new(Duration::from_secs(60));
674 assert_eq!(cache.insert("key1".to_string(), 42), None);
675 assert_eq!(cache.get(&"key1".to_string()), Some(&42));
676 }
677
678 #[test]
679 fn test_insert_overwrite() {
680 let mut cache: Cache<String, i32> =
681 Cache::new(Duration::from_secs(60));
682 let _ = cache.insert("key1".to_string(), 42);
683 assert_eq!(cache.insert("key1".to_string(), 43), Some(42));
684 assert_eq!(cache.get(&"key1".to_string()), Some(&43));
685 }
686
687 #[test]
688 fn test_get_expired() {
689 let mut cache = Cache::new(Duration::from_millis(100));
690 let _ = cache.insert("key1".to_string(), 42);
691 sleep(Duration::from_millis(150));
692 assert_eq!(cache.get(&"key1".to_string()), None);
693 }
694
695 #[test]
696 fn test_remove_expired() {
697 let mut cache = Cache::new(Duration::from_millis(100));
698 let _ = cache.insert("key1".to_string(), 42);
699 let _ = cache.insert("key2".to_string(), 43);
700 sleep(Duration::from_millis(150));
701 cache.remove_expired();
702 assert!(cache.items.is_empty());
703 }
704
705 #[test]
706 fn test_contains_key() {
707 let mut cache = Cache::new(Duration::from_millis(100));
708 let _ = cache.insert("key1".to_string(), 42);
709 assert!(cache.contains_key(&"key1".to_string()));
710 assert!(!cache.contains_key(&"key2".to_string()));
711 sleep(Duration::from_millis(150));
712 assert!(!cache.contains_key(&"key1".to_string()));
713 }
714
715 #[test]
716 fn test_ttl() {
717 let mut cache = Cache::new(Duration::from_millis(100));
718 let _ = cache.insert("key1".to_string(), 42);
719 assert!(cache.ttl(&"key1".to_string()).is_some());
720 assert!(
721 cache.ttl(&"key1".to_string()).unwrap()
722 <= Duration::from_millis(100)
723 );
724 assert_eq!(cache.ttl(&"key2".to_string()), None);
725 sleep(Duration::from_millis(150));
726 assert_eq!(cache.ttl(&"key1".to_string()), None);
727 }
728
729 #[test]
730 fn test_refresh() {
731 // Wide timing margin — shared CI runners (especially the macOS
732 // matrix) can stall between sleeps for tens of ms. Use a 500 ms
733 // TTL with 200 + 200 ms sleeps so the post-refresh checkpoint
734 // sits at t=400 ms with the new expiry at t=200+500=700 ms.
735 let mut cache = Cache::new(Duration::from_millis(500));
736 let _ = cache.insert("key1".to_string(), 42);
737 sleep(Duration::from_millis(200));
738 assert!(cache.refresh(&"key1".to_string()));
739 sleep(Duration::from_millis(200));
740 assert_eq!(cache.get(&"key1".to_string()), Some(&42));
741 assert!(!cache.refresh(&"key2".to_string()));
742 }
743
744 #[test]
745 fn test_default() {
746 let cache: Cache<String, i32> = Cache::default();
747 assert!(cache.items.is_empty());
748 assert_eq!(cache.ttl, Duration::from_secs(60));
749 }
750
751 #[test]
752 fn test_multiple_types() {
753 let mut cache: Cache<i32, String> =
754 Cache::new(Duration::from_secs(60));
755 let _ = cache.insert(1, "one".to_string());
756 assert_eq!(cache.get(&1), Some(&"one".to_string()));
757 }
758
759 #[test]
760 fn test_large_cache() {
761 let mut cache: Cache<String, i32> =
762 Cache::new(Duration::from_secs(60));
763 for i in 0..1000 {
764 let _ = cache.insert(i.to_string(), i);
765 }
766 assert_eq!(cache.items.len(), 1000);
767 for i in 0..1000 {
768 assert_eq!(cache.get(&i.to_string()), Some(&i));
769 }
770 }
771
772 #[test]
773 fn test_set_capacity_evicts_lru_on_overflow() {
774 let mut cache: Cache<String, String> =
775 Cache::new(Duration::from_secs(60));
776 cache.set_capacity(2);
777
778 let _ = cache.insert("key1".to_string(), "1".to_string());
779 let _ = cache.insert("key2".to_string(), "2".to_string());
780 // Third insert at capacity evicts the oldest entry (`key1`).
781 let _ = cache.insert("key3".to_string(), "3".to_string());
782
783 assert_eq!(
784 cache.get(&"key1".to_string()),
785 None,
786 "oldest entry must be evicted under LRU"
787 );
788 assert_eq!(
789 cache.get(&"key2".to_string()),
790 Some(&"2".to_string())
791 );
792 assert_eq!(
793 cache.get(&"key3".to_string()),
794 Some(&"3".to_string())
795 );
796 }
797
798 #[test]
799 fn lru_promotes_on_get() {
800 let mut cache: Cache<String, String> =
801 Cache::new(Duration::from_secs(60));
802 cache.set_capacity(2);
803
804 let _ = cache.insert("k1".to_string(), "1".to_string());
805 let _ = cache.insert("k2".to_string(), "2".to_string());
806
807 // Touch k1 — now k2 is the oldest.
808 assert_eq!(
809 cache.get(&"k1".to_string()),
810 Some(&"1".to_string())
811 );
812
813 // Inserting k3 should evict k2, not k1.
814 let _ = cache.insert("k3".to_string(), "3".to_string());
815 assert_eq!(
816 cache.get(&"k1".to_string()),
817 Some(&"1".to_string())
818 );
819 assert_eq!(cache.get(&"k2".to_string()), None);
820 assert_eq!(
821 cache.get(&"k3".to_string()),
822 Some(&"3".to_string())
823 );
824 }
825
826 #[test]
827 fn test_clear() {
828 let mut cache: Cache<String, i32> =
829 Cache::new(Duration::from_secs(60));
830 let _ = cache.insert("key1".to_string(), 1);
831 let _ = cache.insert("key2".to_string(), 2);
832
833 assert_eq!(cache.get(&"key1".to_string()), Some(&1));
834 assert_eq!(cache.get(&"key2".to_string()), Some(&2));
835
836 cache.clear();
837
838 assert_eq!(cache.get(&"key1".to_string()), None);
839 assert_eq!(cache.get(&"key2".to_string()), None);
840 }
841
842 #[test]
843 fn test_remove() {
844 let mut cache: Cache<String, String> =
845 Cache::new(Duration::from_secs(60));
846 let _ = cache.insert("key1".to_string(), "value1".to_string());
847
848 assert_eq!(
849 cache.remove(&"key1".to_string()),
850 Some("value1".to_string())
851 );
852 assert_eq!(cache.remove(&"key1".to_string()), None);
853 }
854
855 #[test]
856 fn test_update() {
857 let mut cache: Cache<String, String> =
858 Cache::new(Duration::from_secs(60));
859 let _ = cache.insert("key1".to_string(), "value1".to_string());
860
861 assert!(cache.update(&"key1".to_string(), "value2".to_string()));
862 assert_eq!(
863 cache.get(&"key1".to_string()),
864 Some(&"value2".to_string())
865 );
866
867 assert!(
868 !cache.update(&"key2".to_string(), "value3".to_string())
869 );
870 }
871
872 #[test]
873 fn test_capacity() {
874 let mut cache: Cache<String, String> =
875 Cache::new(Duration::from_secs(60));
876 assert_eq!(cache.capacity, None);
877
878 cache.set_capacity(100);
879 assert_eq!(cache.capacity, Some(100));
880 }
881
882 #[test]
883 fn test_iter() {
884 let mut cache = Cache::new(Duration::from_millis(100));
885 let _ = cache.insert("key1".to_string(), "value1".to_string());
886 let _ = cache.insert("key2".to_string(), "value2".to_string());
887
888 let items: Vec<(&String, &String)> = cache.iter().collect();
889 assert_eq!(items.len(), 2);
890
891 sleep(Duration::from_millis(150));
892
893 let items: Vec<(&String, &String)> = cache.iter().collect();
894 assert_eq!(items.len(), 0);
895 }
896
897 #[test]
898 fn test_from_iterator() {
899 let items = vec![
900 ("key1".to_string(), "value1".to_string()),
901 ("key2".to_string(), "value2".to_string()),
902 ];
903 let mut cache: Cache<String, String> =
904 items.into_iter().collect();
905 assert_eq!(
906 cache.get(&"key1".to_string()),
907 Some(&"value1".to_string())
908 );
909 assert_eq!(
910 cache.get(&"key2".to_string()),
911 Some(&"value2".to_string())
912 );
913 }
914
915 #[test]
916 fn test_with_capacity() {
917 let cache: Cache<String, String> =
918 Cache::with_capacity(Duration::from_secs(60), 100);
919 assert!(cache.items.capacity() >= 100);
920 }
921
922 #[test]
923 fn into_iter_yields_live_entries_and_skips_expired() {
924 let mut cache: Cache<String, String> =
925 Cache::new(Duration::from_secs(60));
926 let _ = cache.insert("a".to_string(), "1".to_string());
927 let _ = cache.insert("b".to_string(), "2".to_string());
928
929 let mut items: Vec<_> = cache.into_iter().collect();
930 items.sort_by(|a, b| a.0.cmp(&b.0));
931 assert_eq!(
932 items,
933 vec![
934 ("a".to_string(), "1".to_string()),
935 ("b".to_string(), "2".to_string()),
936 ]
937 );
938 }
939
940 #[test]
941 fn into_iter_drops_expired_entries() {
942 let mut cache: Cache<String, i32> =
943 Cache::new(Duration::from_millis(30));
944 let _ = cache.insert("k".to_string(), 1);
945 sleep(Duration::from_millis(60));
946 let items: Vec<_> = cache.into_iter().collect();
947 assert!(
948 items.is_empty(),
949 "expired entries must not be yielded via IntoIterator"
950 );
951 }
952
953 // ── #40: CacheStats observability ───────────────────────────────
954
955 #[test]
956 fn stats_default_is_all_zeros() {
957 let cache: Cache<String, u32> =
958 Cache::new(Duration::from_secs(60));
959 let s = cache.stats();
960 assert_eq!(s.inserts, 0);
961 assert_eq!(s.hits, 0);
962 assert_eq!(s.misses, 0);
963 assert_eq!(s.evictions, 0);
964 assert_eq!(s.ttl_expired, 0);
965 }
966
967 #[test]
968 fn stats_inserts_count_includes_updates() {
969 let mut cache: Cache<String, u32> =
970 Cache::new(Duration::from_secs(60));
971 let _ = cache.insert("k".to_string(), 1);
972 let _ = cache.insert("k".to_string(), 2); // overwrite, still counts
973 assert_eq!(cache.stats().inserts, 2);
974 }
975
976 #[test]
977 fn stats_hit_and_miss_paths() {
978 let mut cache: Cache<String, u32> =
979 Cache::new(Duration::from_secs(60));
980 let _ = cache.insert("a".to_string(), 1);
981 let _ = cache.get(&"a".to_string()); // hit
982 let _ = cache.get(&"a".to_string()); // hit
983 let _ = cache.get(&"missing".to_string()); // miss
984 let s = cache.stats();
985 assert_eq!(s.hits, 2);
986 assert_eq!(s.misses, 1);
987 }
988
989 #[test]
990 fn stats_ttl_expired_path_through_get() {
991 let mut cache: Cache<String, u32> =
992 Cache::new(Duration::from_millis(20));
993 let _ = cache.insert("k".to_string(), 1);
994 sleep(Duration::from_millis(40));
995 // get on an expired entry counts as both miss and ttl_expired.
996 let _ = cache.get(&"k".to_string());
997 let s = cache.stats();
998 assert_eq!(s.ttl_expired, 1);
999 assert_eq!(s.misses, 1);
1000 assert_eq!(s.hits, 0);
1001 }
1002
1003 #[test]
1004 fn stats_remove_expired_increments_ttl_counter() {
1005 let mut cache: Cache<String, u32> =
1006 Cache::new(Duration::from_millis(20));
1007 let _ = cache.insert("a".to_string(), 1);
1008 let _ = cache.insert("b".to_string(), 2);
1009 sleep(Duration::from_millis(40));
1010 cache.remove_expired();
1011 // Both entries reaped.
1012 assert_eq!(cache.stats().ttl_expired, 2);
1013 }
1014
1015 #[test]
1016 fn stats_lru_eviction_counter_increments() {
1017 let mut cache: Cache<String, u32> =
1018 Cache::with_capacity(Duration::from_secs(60), 2);
1019 let _ = cache.insert("a".to_string(), 1);
1020 let _ = cache.insert("b".to_string(), 2);
1021 let _ = cache.insert("c".to_string(), 3); // evicts oldest (a)
1022 let _ = cache.insert("d".to_string(), 4); // evicts oldest (b)
1023 let s = cache.stats();
1024 assert_eq!(s.inserts, 4);
1025 assert_eq!(s.evictions, 2);
1026 }
1027
1028 #[test]
1029 fn stats_struct_is_copy_and_default_and_eq() {
1030 // Compile-time checks via trait bounds.
1031 fn assert_copy_default_eq<T: Copy + Default + PartialEq>() {}
1032 assert_copy_default_eq::<CacheStats>();
1033 // Functional check: snapshots are independent of the cache.
1034 let mut cache: Cache<&str, u32> =
1035 Cache::new(Duration::from_secs(60));
1036 let s1 = cache.stats();
1037 let _ = cache.insert("k", 1);
1038 let s2 = cache.stats();
1039 assert_ne!(s1, s2); // mutating the cache doesn't mutate the snapshot
1040 assert_eq!(s1.inserts, 0);
1041 assert_eq!(s2.inserts, 1);
1042 }
1043}