1use anyhow::Result;
10use rustc_hash::FxHashMap;
11use serde::{Deserialize, Serialize};
12use std::sync::{Arc, RwLock};
13use std::time::{Duration, SystemTime};
14
15pub const DEFAULT_CACHE_TTL: Duration = Duration::from_secs(120);
17
18pub const DEFAULT_MAX_CACHE_CAPACITY: usize = 1_000;
20
21pub const MAX_CONTEXT_ITEMS: usize = 5;
23
24pub trait CacheKey: Send + Sync + std::hash::Hash + Eq + Clone + 'static {
26 fn to_cache_key(&self) -> String;
27}
28
29pub trait CacheValue: Send + Sync + Clone + 'static {}
31
32impl<T> CacheValue for T where T: Send + Sync + Clone + 'static {}
33
34#[derive(Debug, Clone, Serialize, Deserialize, Default)]
36pub struct CacheStats {
37 pub hits: u64,
38 pub misses: u64,
39 pub evictions: u64,
40 pub current_size: usize,
41 pub max_size: usize,
42 pub total_memory_bytes: u64,
43}
44
45#[derive(Debug, Clone)]
47pub struct CacheEntry<V> {
48 pub value: Arc<V>,
49 pub created_at: SystemTime,
50 pub last_accessed: SystemTime,
51 pub access_count: u64,
52 pub size_bytes: u64,
53}
54
55impl<V> CacheEntry<V> {
56 pub fn new(value: V, size_bytes: u64) -> Self {
57 Self::from_arc(Arc::new(value), size_bytes)
58 }
59
60 pub fn from_arc(value: Arc<V>, size_bytes: u64) -> Self {
61 let now = SystemTime::now();
62 Self {
63 value,
64 created_at: now,
65 last_accessed: now,
66 access_count: 1,
67 size_bytes,
68 }
69 }
70
71 pub fn mark_accessed(&mut self) {
72 self.last_accessed = SystemTime::now();
73 self.access_count += 1;
74 }
75
76 pub fn is_expired(&self, ttl: Duration) -> bool {
77 SystemTime::now()
78 .duration_since(self.created_at)
79 .map(|age| age > ttl)
80 .unwrap_or(true)
81 }
82}
83
84pub struct UnifiedCache<K, V> {
89 inner: RwLock<UnifiedCacheInner<K, V>>,
90}
91
92struct UnifiedCacheInner<K, V> {
94 entries: FxHashMap<K, CacheEntry<V>>,
95 max_size: usize,
96 ttl: Duration,
97 stats: CacheStats,
98 eviction_policy: EvictionPolicy,
99}
100
101#[derive(Debug, Clone, Copy)]
102pub enum EvictionPolicy {
103 Lru,
105 Lfu,
107 Fifo,
109 TtlOnly,
111}
112
113impl<K, V> UnifiedCache<K, V>
114where
115 K: CacheKey,
116 V: CacheValue,
117{
118 pub fn new(max_size: usize, ttl: Duration, eviction_policy: EvictionPolicy) -> Self {
119 Self {
120 inner: RwLock::new(UnifiedCacheInner {
121 entries: FxHashMap::with_capacity_and_hasher(max_size, Default::default()),
122 max_size,
123 ttl,
124 stats: CacheStats { max_size, ..Default::default() },
125 eviction_policy,
126 }),
127 }
128 }
129
130 pub fn get(&self, key: &K) -> Option<Arc<V>> {
135 enum LookupState<T> {
136 Hit(Arc<T>),
137 Expired,
138 Miss,
139 }
140
141 let state = {
142 let inner = self.inner.read().unwrap_or_else(|e| e.into_inner());
143 let ttl = inner.ttl;
144
145 match inner.entries.get(key) {
146 Some(entry) if !entry.is_expired(ttl) => LookupState::Hit(Arc::clone(&entry.value)),
147 Some(_) => LookupState::Expired,
148 None => LookupState::Miss,
149 }
150 };
151
152 match state {
153 LookupState::Hit(value) => {
154 if let Ok(mut inner) = self.inner.try_write() {
155 if let Some(entry) = inner.entries.get_mut(key) {
156 entry.mark_accessed();
157 }
158 inner.stats.hits += 1;
159 }
160 Some(value)
161 }
162 LookupState::Expired => {
163 if let Ok(mut inner) = self.inner.try_write() {
164 let ttl = inner.ttl;
165 let should_remove = inner.entries.get(key).map(|entry| entry.is_expired(ttl)).unwrap_or(false);
166 if should_remove {
167 Self::remove_inner(&mut inner, key);
168 }
169 inner.stats.misses += 1;
170 }
171 None
172 }
173 LookupState::Miss => {
174 if let Ok(mut inner) = self.inner.try_write() {
175 inner.stats.misses += 1;
176 }
177 None
178 }
179 }
180 }
181
182 pub fn get_owned(&self, key: &K) -> Option<V> {
184 self.get(key).map(|arc| (*arc).clone())
185 }
186
187 pub fn insert(&self, key: K, value: V, size_bytes: u64) {
189 self.insert_entry(key, CacheEntry::new(value, size_bytes));
190 }
191
192 pub fn insert_arc(&self, key: K, value: Arc<V>, size_bytes: u64) {
194 self.insert_entry(key, CacheEntry::from_arc(value, size_bytes));
195 }
196
197 fn insert_entry(&self, key: K, entry: CacheEntry<V>) {
198 let Ok(mut inner) = self.inner.write() else {
199 return;
200 };
201
202 Self::remove_expired_entries_inner(&mut inner);
204
205 if inner.max_size == 0 {
207 return;
208 }
209
210 let size_bytes = entry.size_bytes;
211
212 if let Some(current) = inner.entries.get_mut(&key) {
215 let previous = std::mem::replace(current, entry);
216 inner.stats.total_memory_bytes = inner.stats.total_memory_bytes.saturating_sub(previous.size_bytes);
217 inner.stats.current_size = inner.entries.len();
218 inner.stats.total_memory_bytes = inner.stats.total_memory_bytes.saturating_add(size_bytes);
219 return;
220 }
221
222 if inner.entries.len() >= inner.max_size {
225 let to_remove = (inner.max_size / 10).max(1);
226 Self::evict_batch_inner(&mut inner, to_remove);
227 }
228
229 inner.entries.insert(key, entry);
230 inner.stats.current_size = inner.entries.len();
231 inner.stats.total_memory_bytes = inner.stats.total_memory_bytes.saturating_add(size_bytes);
232 }
233
234 fn remove_expired_entries_inner(inner: &mut UnifiedCacheInner<K, V>) {
236 let UnifiedCacheInner { entries, ttl, stats, .. } = inner;
237 entries.retain(|_, entry| {
238 if entry.is_expired(*ttl) {
239 stats.total_memory_bytes = stats.total_memory_bytes.saturating_sub(entry.size_bytes);
240 false
241 } else {
242 true
243 }
244 });
245 stats.current_size = entries.len();
246 }
247
248 fn evict_batch_inner(inner: &mut UnifiedCacheInner<K, V>, count: usize) -> usize {
252 if count == 0 || inner.entries.is_empty() {
253 return 0;
254 }
255
256 let keys_to_remove: Vec<K> = {
257 let mut entries: Vec<_> = inner.entries.iter().collect();
258 match inner.eviction_policy {
259 EvictionPolicy::Lru => entries.sort_by_key(|(_, entry)| entry.last_accessed),
260 EvictionPolicy::Lfu => entries.sort_by_key(|(_, entry)| entry.access_count),
261 EvictionPolicy::Fifo | EvictionPolicy::TtlOnly => {
262 entries.sort_by_key(|(_, entry)| entry.created_at);
263 }
264 }
265 entries.into_iter().take(count).map(|(key, _)| key.clone()).collect()
266 };
267
268 for key in &keys_to_remove {
269 Self::remove_inner(inner, key);
270 }
271 inner.stats.evictions += keys_to_remove.len() as u64;
272 keys_to_remove.len()
273 }
274
275 fn remove_inner(inner: &mut UnifiedCacheInner<K, V>, key: &K) {
276 if let Some(entry) = inner.entries.remove(key) {
277 inner.stats.total_memory_bytes = inner.stats.total_memory_bytes.saturating_sub(entry.size_bytes);
278 inner.stats.current_size = inner.entries.len();
279 }
280 }
281
282 pub fn stats(&self) -> CacheStats {
284 self.inner.read().map(|inner| inner.stats.clone()).unwrap_or_default()
285 }
286
287 pub fn clear(&self) {
289 if let Ok(mut inner) = self.inner.write() {
290 inner.entries.clear();
291 inner.stats.current_size = 0;
292 inner.stats.total_memory_bytes = 0;
293 }
294 }
295
296 pub fn remove(&self, key: &K) {
298 let Ok(mut inner) = self.inner.write() else {
299 return;
300 };
301 Self::remove_inner(&mut inner, key);
302 }
303
304 pub fn len(&self) -> usize {
306 self.inner.read().map(|inner| inner.entries.len()).unwrap_or(0)
307 }
308
309 pub fn is_empty(&self) -> bool {
310 self.len() == 0
311 }
312
313 pub fn invalidate_prefix(&self, prefix: &str) {
322 self.remove_where(|key| key.to_cache_key().starts_with(prefix));
323 }
324
325 pub fn invalidate_path(&self, path: &str) {
334 self.invalidate_prefix(&format!("{path}:"));
335 }
336
337 pub fn invalidate_suffix(&self, suffix: &str) {
345 self.remove_where(|key| key.to_cache_key().ends_with(suffix));
346 }
347
348 pub fn invalidate_containing(&self, substring: &str) {
356 self.remove_where(|key| key.to_cache_key().contains(substring));
357 }
358
359 pub fn remove_where<F>(&self, mut predicate: F) -> usize
363 where
364 F: FnMut(&K) -> bool,
365 {
366 let Ok(mut inner) = self.inner.write() else {
367 return 0;
368 };
369
370 let keys_to_remove: Vec<K> = inner.entries.keys().filter(|key| predicate(key)).cloned().collect();
371
372 let removed_count = keys_to_remove.len();
373 for key in keys_to_remove {
374 Self::remove_inner(&mut inner, &key);
375 }
376 removed_count
377 }
378
379 pub fn total_memory_bytes(&self) -> u64 {
381 self.inner.read().map(|inner| inner.stats.total_memory_bytes).unwrap_or(0)
382 }
383
384 pub fn estimate_entry_cost(entry: &CacheEntry<V>) -> u64 {
387 let base_overhead: u64 = 100; let value_size = entry.size_bytes;
390 base_overhead + value_size
391 }
392
393 pub fn reduce_ttl(&self, factor: f64) -> Duration {
396 let Ok(mut inner) = self.inner.write() else {
397 return Duration::ZERO;
398 };
399 let new_ttl = Duration::from_secs_f64(inner.ttl.as_secs_f64() * factor);
400 inner.ttl = new_ttl;
401 new_ttl
402 }
403
404 pub fn evict_under_pressure(&self, target_reduction_percent: u32) -> usize {
414 let Ok(mut inner) = self.inner.write() else {
415 return 0;
416 };
417
418 let target_percent = std::cmp::min(100, target_reduction_percent);
420
421 let expired_before = inner.entries.len();
423 Self::remove_expired_entries_inner(&mut inner);
424 let expired_removed = expired_before - inner.entries.len();
425
426 let current_size = inner.entries.len();
428 let target_size = (current_size * (100 - target_percent) as usize) / 100;
429
430 expired_removed + Self::evict_batch_inner(&mut inner, current_size - target_size)
431 }
432
433 pub fn clear_least_used(&self, percent_to_clear: u32) -> usize {
436 let Ok(mut inner) = self.inner.write() else {
437 return 0;
438 };
439
440 let percent = std::cmp::min(100, percent_to_clear);
441 let entries_to_remove = (inner.entries.len() * percent as usize) / 100;
442
443 Self::evict_batch_inner(&mut inner, entries_to_remove)
444 }
445
446 pub fn entries_by_usefulness(&self) -> Vec<(K, CacheEntry<V>)> {
449 let Ok(inner) = self.inner.read() else {
450 return Vec::new();
451 };
452
453 let now = SystemTime::now();
454 let mut entries: Vec<(K, CacheEntry<V>, u64)> = inner
455 .entries
456 .iter()
457 .map(|(k, entry)| {
458 let age_secs = now.duration_since(entry.last_accessed).unwrap_or_default().as_secs();
460
461 let recency_factor = std::cmp::max(1_u64, 3600 / (age_secs + 1));
463 let usefulness_score = entry.access_count * recency_factor;
464
465 (k.clone(), entry.clone(), usefulness_score)
466 })
467 .collect();
468
469 entries.sort_by_key(|(_, _, score)| std::cmp::Reverse(*score));
471 entries.into_iter().map(|(k, e, _)| (k, e)).collect()
472 }
473}
474
475pub fn estimate_json_size(value: &serde_json::Value) -> u64 {
477 match value {
478 serde_json::Value::Null => 4,
479 serde_json::Value::Bool(_) => 5,
480 serde_json::Value::Number(n) => n.to_string().len() as u64,
481 serde_json::Value::String(s) => s.len() as u64,
482 serde_json::Value::Array(arr) => arr
483 .iter()
484 .map(estimate_json_size)
485 .fold(0u64, |acc, size| acc.saturating_add(size)),
486 serde_json::Value::Object(obj) => obj
487 .iter()
488 .map(|(k, v)| (k.len() as u64).saturating_add(estimate_json_size(v)).saturating_add(3)) .fold(0u64, |acc, size| acc.saturating_add(size)),
490 }
491}
492
493pub fn create_cache_key<T: Serialize>(data: &T) -> Result<String> {
495 let json_bytes = serde_json::to_vec(data)?;
496
497 let mut hash = 0u64;
499 for (i, byte) in json_bytes.iter().enumerate() {
500 hash = hash.wrapping_mul(31).wrapping_add(*byte as u64);
501 hash = hash.rotate_left((i % 64) as u32);
502 }
503
504 Ok(format!("{hash:016x}"))
505}
506
507pub struct ContextAwareCache<K, V> {
509 inner: UnifiedCache<K, V>,
510}
511
512impl<K, V> ContextAwareCache<K, V>
513where
514 K: CacheKey,
515 V: CacheValue,
516{
517 pub fn new(max_size: usize, ttl: Duration, eviction_policy: EvictionPolicy) -> Self {
518 Self {
519 inner: UnifiedCache::new(max_size, ttl, eviction_policy),
520 }
521 }
522
523 pub fn get_context_limited<F>(&self, keys: &[K], mut process_fn: F) -> Vec<V>
525 where
526 F: FnMut(&K) -> Option<V>,
527 {
528 let mut results = Vec::with_capacity(MAX_CONTEXT_ITEMS.min(keys.len()));
529 let mut overflow_count = 0;
530
531 for key in keys {
532 if results.len() >= MAX_CONTEXT_ITEMS {
533 overflow_count += 1;
534 continue;
535 }
536
537 if let Some(value) = self.inner.get(key) {
538 results.push((*value).clone());
539 } else if let Some(value) = process_fn(key) {
540 let size = size_of_val(&value) as u64;
542 self.inner.insert(key.clone(), value.clone(), size);
543 results.push(value);
544 }
545 }
546
547 if overflow_count > 0 {
549 }
552
553 results
554 }
555
556 pub fn stats(&self) -> CacheStats {
557 self.inner.stats()
558 }
559}
560
561#[cfg(test)]
562mod eviction_tests;
563
564#[cfg(test)]
565mod tests {
566 use super::*;
567
568 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
569 struct TestKey(String);
570
571 impl CacheKey for TestKey {
572 fn to_cache_key(&self) -> String {
573 self.0.clone()
574 }
575 }
576
577 #[test]
578 fn test_cache_basic_operations() {
579 let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
580 let key = TestKey("test".into());
581 let value: String = "test_value".into();
582
583 cache.insert(key.clone(), value.clone(), 100);
585 assert_eq!(*cache.get(&key).unwrap(), value);
586
587 let stats = cache.stats();
589 assert_eq!(stats.hits, 1);
590 assert_eq!(stats.misses, 0);
591 assert_eq!(stats.current_size, 1);
592 }
593
594 #[test]
595 fn insert_arc_preserves_value_arc_and_statistics() {
596 let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
597 let key = TestKey("arc".into());
598 let value = Arc::new("shared value".to_string());
599
600 cache.insert_arc(key.clone(), Arc::clone(&value), value.len() as u64);
601
602 let cached = cache.get(&key).expect("inserted value should be cached");
603 assert!(Arc::ptr_eq(&cached, &value));
604 assert_eq!(cache.stats().total_memory_bytes, value.len() as u64);
605 }
606
607 #[test]
608 fn replacing_entry_updates_memory_statistics() {
609 let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
610 let key = TestKey("replacement".into());
611
612 cache.insert(key.clone(), "small".to_string(), 5);
613 cache.insert(key, "larger replacement".to_string(), 18);
614
615 let stats = cache.stats();
616 assert_eq!(stats.current_size, 1);
617 assert_eq!(stats.total_memory_bytes, 18);
618 }
619
620 #[test]
621 fn replacing_entry_at_capacity_does_not_evict() {
622 let cache = UnifiedCache::new(1, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
623 let key = TestKey("replacement".into());
624
625 cache.insert(key.clone(), "old".to_string(), 3);
626 cache.insert(key.clone(), "new value".to_string(), 9);
627
628 assert_eq!(cache.get_owned(&key).as_deref(), Some("new value"));
629 let stats = cache.stats();
630 assert_eq!(stats.current_size, 1);
631 assert_eq!(stats.evictions, 0);
632 assert_eq!(stats.total_memory_bytes, 9);
633 }
634
635 #[test]
636 fn zero_capacity_cache_rejects_entries() {
637 let cache = UnifiedCache::new(0, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
638
639 cache.insert(TestKey("rejected".into()), "value".to_string(), 5);
640
641 assert_eq!(cache.len(), 0);
642 assert_eq!(cache.total_memory_bytes(), 0);
643 assert_eq!(cache.stats().evictions, 0);
644 }
645
646 #[test]
647 fn test_cache_expiration() {
648 let cache = UnifiedCache::new(10, Duration::from_millis(100), EvictionPolicy::Lru);
649 let key = TestKey("test".into());
650 let value: String = "test_value".into();
651
652 cache.insert(key.clone(), value, 100);
653 assert!(cache.get(&key).is_some());
654
655 std::thread::sleep(Duration::from_millis(150));
657 assert!(cache.get(&key).is_none());
658 }
659
660 #[test]
661 fn test_context_limited_cache() {
662 let cache = ContextAwareCache::new(100, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
663 let keys: Vec<TestKey> = (0..10).map(|i| TestKey(i.to_string())).collect();
664
665 let results = cache.get_context_limited(&keys, |key| Some(format!("value_{}", key.0)));
666
667 assert_eq!(results.len(), MAX_CONTEXT_ITEMS);
669 assert_eq!(results[0], "value_0");
670 assert_eq!(results[4], "value_4");
671 }
672
673 #[test]
674 fn test_pressure_aware_total_memory() {
675 let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
676
677 cache.insert(TestKey("k1".into()), "v1".to_string(), 100);
679 cache.insert(TestKey("k2".into()), "v2".to_string(), 200);
680 cache.insert(TestKey("k3".into()), "v3".to_string(), 300);
681
682 assert_eq!(cache.total_memory_bytes(), 600);
684 }
685
686 #[test]
687 fn test_pressure_aware_reduce_ttl() {
688 let cache: UnifiedCache<TestKey, String> = UnifiedCache::new(10, Duration::from_secs(300), EvictionPolicy::Lru);
689
690 let new_ttl = cache.reduce_ttl(0.4);
692 assert_eq!(new_ttl.as_secs(), 120); let new_ttl = cache.reduce_ttl(0.1);
696 assert_eq!(new_ttl.as_secs(), 12); }
698
699 #[test]
700 fn test_pressure_aware_evict_under_pressure() {
701 let cache: UnifiedCache<TestKey, String> =
702 UnifiedCache::new(20, Duration::from_secs(3600), EvictionPolicy::Lru);
703
704 for i in 0..10 {
706 cache.insert(TestKey(format!("key_{i}")), format!("value_{i}"), 100);
707 }
708
709 assert_eq!(cache.len(), 10);
710
711 let removed = cache.evict_under_pressure(50);
713 assert_eq!(removed, 5);
714 assert_eq!(cache.len(), 5);
715 }
716
717 #[test]
718 fn test_pressure_aware_clear_least_used() {
719 let cache: UnifiedCache<TestKey, String> =
720 UnifiedCache::new(20, Duration::from_secs(3600), EvictionPolicy::Lru);
721
722 for i in 0..10 {
724 cache.insert(TestKey(format!("key_{i}")), format!("value_{i}"), 100);
725 }
726
727 let _ = cache.get(&TestKey("key_0".into()));
729 let _ = cache.get(&TestKey("key_1".into()));
730
731 assert_eq!(cache.len(), 10);
732
733 let removed = cache.clear_least_used(30);
735 assert!(removed <= 4, "Should remove ~3 entries (30% of 10)");
736 assert!(cache.len() >= 6, "Should have ~7 entries left");
737 }
738
739 #[test]
740 fn test_pressure_aware_entries_by_usefulness() {
741 let cache: UnifiedCache<TestKey, String> =
742 UnifiedCache::new(20, Duration::from_secs(3600), EvictionPolicy::Lru);
743
744 cache.insert(TestKey("hot".into()), "value".to_string(), 100);
746 cache.insert(TestKey("cold".into()), "value".to_string(), 100);
747 cache.insert(TestKey("warm".into()), "value".to_string(), 100);
748
749 for _ in 0..5 {
751 let _ = cache.get(&TestKey("hot".into()));
752 }
753
754 let _ = cache.get(&TestKey("warm".into()));
756
757 let usefulness = cache.entries_by_usefulness();
760 assert_eq!(usefulness.len(), 3);
761
762 assert_eq!(usefulness[0].0.0, "hot");
764 }
765
766 #[test]
767 fn test_pressure_aware_estimate_entry_cost() {
768 let entry = CacheEntry::new("test_value".to_string(), 1000);
769 let cost = UnifiedCache::<TestKey, String>::estimate_entry_cost(&entry);
770
771 assert!(cost >= 1000);
773 assert!(cost <= 1200); }
775}