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 ttl = inner.ttl;
237 Self::remove_entries_where_inner(inner, |_, entry| entry.is_expired(ttl));
238 }
239
240 fn remove_entries_where_inner<F>(inner: &mut UnifiedCacheInner<K, V>, mut predicate: F) -> usize
242 where
243 F: FnMut(&K, &CacheEntry<V>) -> bool,
244 {
245 let UnifiedCacheInner { entries, stats, .. } = inner;
246 let previous_size = entries.len();
247 entries.retain(|key, entry| {
248 if predicate(key, entry) {
249 stats.total_memory_bytes = stats.total_memory_bytes.saturating_sub(entry.size_bytes);
250 false
251 } else {
252 true
253 }
254 });
255 stats.current_size = entries.len();
256 previous_size - entries.len()
257 }
258
259 fn evict_batch_inner(inner: &mut UnifiedCacheInner<K, V>, count: usize) -> usize {
263 if count == 0 || inner.entries.is_empty() {
264 return 0;
265 }
266
267 let keys_to_remove: Vec<K> = {
268 let mut entries: Vec<_> = inner.entries.iter().collect();
269 match inner.eviction_policy {
270 EvictionPolicy::Lru => entries.sort_by_key(|(_, entry)| entry.last_accessed),
271 EvictionPolicy::Lfu => entries.sort_by_key(|(_, entry)| entry.access_count),
272 EvictionPolicy::Fifo | EvictionPolicy::TtlOnly => {
273 entries.sort_by_key(|(_, entry)| entry.created_at);
274 }
275 }
276 entries.into_iter().take(count).map(|(key, _)| key.clone()).collect()
277 };
278
279 for key in &keys_to_remove {
280 Self::remove_inner(inner, key);
281 }
282 inner.stats.evictions += keys_to_remove.len() as u64;
283 keys_to_remove.len()
284 }
285
286 fn remove_inner(inner: &mut UnifiedCacheInner<K, V>, key: &K) {
287 if let Some(entry) = inner.entries.remove(key) {
288 inner.stats.total_memory_bytes = inner.stats.total_memory_bytes.saturating_sub(entry.size_bytes);
289 inner.stats.current_size = inner.entries.len();
290 }
291 }
292
293 pub fn stats(&self) -> CacheStats {
295 self.inner.read().map(|inner| inner.stats.clone()).unwrap_or_default()
296 }
297
298 pub fn clear(&self) {
300 if let Ok(mut inner) = self.inner.write() {
301 inner.entries.clear();
302 inner.stats.current_size = 0;
303 inner.stats.total_memory_bytes = 0;
304 }
305 }
306
307 pub fn remove(&self, key: &K) {
309 let Ok(mut inner) = self.inner.write() else {
310 return;
311 };
312 Self::remove_inner(&mut inner, key);
313 }
314
315 pub fn len(&self) -> usize {
317 self.inner.read().map(|inner| inner.entries.len()).unwrap_or(0)
318 }
319
320 pub fn is_empty(&self) -> bool {
321 self.len() == 0
322 }
323
324 pub fn invalidate_prefix(&self, prefix: &str) {
333 self.remove_where(|key| key.to_cache_key().starts_with(prefix));
334 }
335
336 pub fn invalidate_path(&self, path: &str) {
345 self.invalidate_prefix(&format!("{path}:"));
346 }
347
348 pub fn invalidate_suffix(&self, suffix: &str) {
356 self.remove_where(|key| key.to_cache_key().ends_with(suffix));
357 }
358
359 pub fn invalidate_containing(&self, substring: &str) {
367 self.remove_where(|key| key.to_cache_key().contains(substring));
368 }
369
370 pub fn remove_where<F>(&self, mut predicate: F) -> usize
374 where
375 F: FnMut(&K) -> bool,
376 {
377 let Ok(mut inner) = self.inner.write() else {
378 return 0;
379 };
380
381 Self::remove_entries_where_inner(&mut inner, |key, _| predicate(key))
382 }
383
384 pub fn total_memory_bytes(&self) -> u64 {
386 self.inner.read().map(|inner| inner.stats.total_memory_bytes).unwrap_or(0)
387 }
388
389 pub fn estimate_entry_cost(entry: &CacheEntry<V>) -> u64 {
392 let base_overhead: u64 = 100; let value_size = entry.size_bytes;
395 base_overhead + value_size
396 }
397
398 pub fn reduce_ttl(&self, factor: f64) -> Duration {
401 let Ok(mut inner) = self.inner.write() else {
402 return Duration::ZERO;
403 };
404 let new_ttl = Duration::from_secs_f64(inner.ttl.as_secs_f64() * factor);
405 inner.ttl = new_ttl;
406 new_ttl
407 }
408
409 pub fn evict_under_pressure(&self, target_reduction_percent: u32) -> usize {
419 let Ok(mut inner) = self.inner.write() else {
420 return 0;
421 };
422
423 let target_percent = std::cmp::min(100, target_reduction_percent);
425
426 let expired_before = inner.entries.len();
428 Self::remove_expired_entries_inner(&mut inner);
429 let expired_removed = expired_before - inner.entries.len();
430
431 let current_size = inner.entries.len();
433 let target_size = (current_size * (100 - target_percent) as usize) / 100;
434
435 expired_removed + Self::evict_batch_inner(&mut inner, current_size - target_size)
436 }
437
438 pub fn clear_least_used(&self, percent_to_clear: u32) -> usize {
441 let Ok(mut inner) = self.inner.write() else {
442 return 0;
443 };
444
445 let percent = std::cmp::min(100, percent_to_clear);
446 let entries_to_remove = (inner.entries.len() * percent as usize) / 100;
447
448 Self::evict_batch_inner(&mut inner, entries_to_remove)
449 }
450
451 pub fn entries_by_usefulness(&self) -> Vec<(K, CacheEntry<V>)> {
454 let Ok(inner) = self.inner.read() else {
455 return Vec::new();
456 };
457
458 let now = SystemTime::now();
459 let mut entries: Vec<(K, CacheEntry<V>, u64)> = inner
460 .entries
461 .iter()
462 .map(|(k, entry)| {
463 let age_secs = now.duration_since(entry.last_accessed).unwrap_or_default().as_secs();
465
466 let recency_factor = std::cmp::max(1_u64, 3600 / (age_secs + 1));
468 let usefulness_score = entry.access_count * recency_factor;
469
470 (k.clone(), entry.clone(), usefulness_score)
471 })
472 .collect();
473
474 entries.sort_by_key(|(_, _, score)| std::cmp::Reverse(*score));
476 entries.into_iter().map(|(k, e, _)| (k, e)).collect()
477 }
478}
479
480pub fn estimate_json_size(value: &serde_json::Value) -> u64 {
482 match value {
483 serde_json::Value::Null => 4,
484 serde_json::Value::Bool(_) => 5,
485 serde_json::Value::Number(n) => n.to_string().len() as u64,
486 serde_json::Value::String(s) => s.len() as u64,
487 serde_json::Value::Array(arr) => arr
488 .iter()
489 .map(estimate_json_size)
490 .fold(0u64, |acc, size| acc.saturating_add(size)),
491 serde_json::Value::Object(obj) => obj
492 .iter()
493 .map(|(k, v)| (k.len() as u64).saturating_add(estimate_json_size(v)).saturating_add(3)) .fold(0u64, |acc, size| acc.saturating_add(size)),
495 }
496}
497
498pub fn create_cache_key<T: Serialize>(data: &T) -> Result<String> {
500 let json_bytes = serde_json::to_vec(data)?;
501
502 let mut hash = 0u64;
504 for (i, byte) in json_bytes.iter().enumerate() {
505 hash = hash.wrapping_mul(31).wrapping_add(*byte as u64);
506 hash = hash.rotate_left((i % 64) as u32);
507 }
508
509 Ok(format!("{hash:016x}"))
510}
511
512pub struct ContextAwareCache<K, V> {
514 inner: UnifiedCache<K, V>,
515}
516
517impl<K, V> ContextAwareCache<K, V>
518where
519 K: CacheKey,
520 V: CacheValue,
521{
522 pub fn new(max_size: usize, ttl: Duration, eviction_policy: EvictionPolicy) -> Self {
523 Self {
524 inner: UnifiedCache::new(max_size, ttl, eviction_policy),
525 }
526 }
527
528 pub fn get_context_limited<F>(&self, keys: &[K], mut process_fn: F) -> Vec<V>
530 where
531 F: FnMut(&K) -> Option<V>,
532 {
533 let mut results = Vec::with_capacity(MAX_CONTEXT_ITEMS.min(keys.len()));
534 let mut overflow_count = 0;
535
536 for key in keys {
537 if results.len() >= MAX_CONTEXT_ITEMS {
538 overflow_count += 1;
539 continue;
540 }
541
542 if let Some(value) = self.inner.get(key) {
543 results.push((*value).clone());
544 } else if let Some(value) = process_fn(key) {
545 let size = size_of_val(&value) as u64;
547 self.inner.insert(key.clone(), value.clone(), size);
548 results.push(value);
549 }
550 }
551
552 if overflow_count > 0 {
554 }
557
558 results
559 }
560
561 pub fn stats(&self) -> CacheStats {
562 self.inner.stats()
563 }
564}
565
566#[cfg(test)]
567mod eviction_tests;
568
569#[cfg(test)]
570mod tests {
571 use super::*;
572
573 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
574 struct TestKey(String);
575
576 impl CacheKey for TestKey {
577 fn to_cache_key(&self) -> String {
578 self.0.clone()
579 }
580 }
581
582 #[test]
583 fn test_cache_basic_operations() {
584 let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
585 let key = TestKey("test".into());
586 let value: String = "test_value".into();
587
588 cache.insert(key.clone(), value.clone(), 100);
590 assert_eq!(*cache.get(&key).unwrap(), value);
591
592 let stats = cache.stats();
594 assert_eq!(stats.hits, 1);
595 assert_eq!(stats.misses, 0);
596 assert_eq!(stats.current_size, 1);
597 }
598
599 #[test]
600 fn insert_arc_preserves_value_arc_and_statistics() {
601 let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
602 let key = TestKey("arc".into());
603 let value = Arc::new("shared value".to_string());
604
605 cache.insert_arc(key.clone(), Arc::clone(&value), value.len() as u64);
606
607 let cached = cache.get(&key).expect("inserted value should be cached");
608 assert!(Arc::ptr_eq(&cached, &value));
609 assert_eq!(cache.stats().total_memory_bytes, value.len() as u64);
610 }
611
612 #[test]
613 fn replacing_entry_updates_memory_statistics() {
614 let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
615 let key = TestKey("replacement".into());
616
617 cache.insert(key.clone(), "small".to_string(), 5);
618 cache.insert(key, "larger replacement".to_string(), 18);
619
620 let stats = cache.stats();
621 assert_eq!(stats.current_size, 1);
622 assert_eq!(stats.total_memory_bytes, 18);
623 }
624
625 #[test]
626 fn replacing_entry_at_capacity_does_not_evict() {
627 let cache = UnifiedCache::new(1, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
628 let key = TestKey("replacement".into());
629
630 cache.insert(key.clone(), "old".to_string(), 3);
631 cache.insert(key.clone(), "new value".to_string(), 9);
632
633 assert_eq!(cache.get_owned(&key).as_deref(), Some("new value"));
634 let stats = cache.stats();
635 assert_eq!(stats.current_size, 1);
636 assert_eq!(stats.evictions, 0);
637 assert_eq!(stats.total_memory_bytes, 9);
638 }
639
640 #[test]
641 fn zero_capacity_cache_rejects_entries() {
642 let cache = UnifiedCache::new(0, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
643
644 cache.insert(TestKey("rejected".into()), "value".to_string(), 5);
645
646 assert_eq!(cache.len(), 0);
647 assert_eq!(cache.total_memory_bytes(), 0);
648 assert_eq!(cache.stats().evictions, 0);
649 }
650
651 #[test]
652 fn test_cache_expiration() {
653 let cache = UnifiedCache::new(10, Duration::from_millis(100), EvictionPolicy::Lru);
654 let key = TestKey("test".into());
655 let value: String = "test_value".into();
656
657 cache.insert(key.clone(), value, 100);
658 assert!(cache.get(&key).is_some());
659
660 std::thread::sleep(Duration::from_millis(150));
662 assert!(cache.get(&key).is_none());
663 }
664
665 #[test]
666 fn test_context_limited_cache() {
667 let cache = ContextAwareCache::new(100, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
668 let keys: Vec<TestKey> = (0..10).map(|i| TestKey(i.to_string())).collect();
669
670 let results = cache.get_context_limited(&keys, |key| Some(format!("value_{}", key.0)));
671
672 assert_eq!(results.len(), MAX_CONTEXT_ITEMS);
674 assert_eq!(results[0], "value_0");
675 assert_eq!(results[4], "value_4");
676 }
677
678 #[test]
679 fn test_pressure_aware_total_memory() {
680 let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
681
682 cache.insert(TestKey("k1".into()), "v1".to_string(), 100);
684 cache.insert(TestKey("k2".into()), "v2".to_string(), 200);
685 cache.insert(TestKey("k3".into()), "v3".to_string(), 300);
686
687 assert_eq!(cache.total_memory_bytes(), 600);
689 }
690
691 #[test]
692 fn test_pressure_aware_reduce_ttl() {
693 let cache: UnifiedCache<TestKey, String> = UnifiedCache::new(10, Duration::from_secs(300), EvictionPolicy::Lru);
694
695 let new_ttl = cache.reduce_ttl(0.4);
697 assert_eq!(new_ttl.as_secs(), 120); let new_ttl = cache.reduce_ttl(0.1);
701 assert_eq!(new_ttl.as_secs(), 12); }
703
704 #[test]
705 fn test_pressure_aware_evict_under_pressure() {
706 let cache: UnifiedCache<TestKey, String> =
707 UnifiedCache::new(20, Duration::from_secs(3600), EvictionPolicy::Lru);
708
709 for i in 0..10 {
711 cache.insert(TestKey(format!("key_{i}")), format!("value_{i}"), 100);
712 }
713
714 assert_eq!(cache.len(), 10);
715
716 let removed = cache.evict_under_pressure(50);
718 assert_eq!(removed, 5);
719 assert_eq!(cache.len(), 5);
720 }
721
722 #[test]
723 fn test_pressure_aware_clear_least_used() {
724 let cache: UnifiedCache<TestKey, String> =
725 UnifiedCache::new(20, Duration::from_secs(3600), EvictionPolicy::Lru);
726
727 for i in 0..10 {
729 cache.insert(TestKey(format!("key_{i}")), format!("value_{i}"), 100);
730 }
731
732 let _ = cache.get(&TestKey("key_0".into()));
734 let _ = cache.get(&TestKey("key_1".into()));
735
736 assert_eq!(cache.len(), 10);
737
738 let removed = cache.clear_least_used(30);
740 assert!(removed <= 4, "Should remove ~3 entries (30% of 10)");
741 assert!(cache.len() >= 6, "Should have ~7 entries left");
742 }
743
744 #[test]
745 fn test_pressure_aware_entries_by_usefulness() {
746 let cache: UnifiedCache<TestKey, String> =
747 UnifiedCache::new(20, Duration::from_secs(3600), EvictionPolicy::Lru);
748
749 cache.insert(TestKey("hot".into()), "value".to_string(), 100);
751 cache.insert(TestKey("cold".into()), "value".to_string(), 100);
752 cache.insert(TestKey("warm".into()), "value".to_string(), 100);
753
754 for _ in 0..5 {
756 let _ = cache.get(&TestKey("hot".into()));
757 }
758
759 let _ = cache.get(&TestKey("warm".into()));
761
762 let usefulness = cache.entries_by_usefulness();
765 assert_eq!(usefulness.len(), 3);
766
767 assert_eq!(usefulness[0].0.0, "hot");
769 }
770
771 #[test]
772 fn test_pressure_aware_estimate_entry_cost() {
773 let entry = CacheEntry::new("test_value".to_string(), 1000);
774 let cost = UnifiedCache::<TestKey, String>::estimate_entry_cost(&entry);
775
776 assert!(cost >= 1000);
778 assert!(cost <= 1200); }
780}