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 base_ttl: Duration,
99 ttl: Duration,
100 stats: CacheStats,
101 eviction_policy: EvictionPolicy,
102}
103
104#[derive(Debug, Clone, Copy)]
105pub enum EvictionPolicy {
106 Lru,
108 Lfu,
110 Fifo,
112 TtlOnly,
114}
115
116impl<K, V> UnifiedCache<K, V>
117where
118 K: CacheKey,
119 V: CacheValue,
120{
121 pub fn new(max_size: usize, ttl: Duration, eviction_policy: EvictionPolicy) -> Self {
122 Self {
123 inner: RwLock::new(UnifiedCacheInner {
124 entries: FxHashMap::with_capacity_and_hasher(max_size, Default::default()),
125 max_size,
126 base_ttl: ttl,
127 ttl,
128 stats: CacheStats { max_size, ..Default::default() },
129 eviction_policy,
130 }),
131 }
132 }
133
134 pub fn get(&self, key: &K) -> Option<Arc<V>> {
139 enum LookupState<T> {
140 Hit(Arc<T>),
141 Expired,
142 Miss,
143 }
144
145 let state = {
146 let inner = self.inner.read().unwrap_or_else(|e| e.into_inner());
147 let ttl = inner.ttl;
148
149 match inner.entries.get(key) {
150 Some(entry) if !entry.is_expired(ttl) => LookupState::Hit(Arc::clone(&entry.value)),
151 Some(_) => LookupState::Expired,
152 None => LookupState::Miss,
153 }
154 };
155
156 match state {
157 LookupState::Hit(value) => {
158 if let Ok(mut inner) = self.inner.try_write() {
159 if let Some(entry) = inner.entries.get_mut(key) {
160 entry.mark_accessed();
161 }
162 inner.stats.hits += 1;
163 }
164 Some(value)
165 }
166 LookupState::Expired => {
167 if let Ok(mut inner) = self.inner.try_write() {
168 let ttl = inner.ttl;
169 let should_remove = inner.entries.get(key).map(|entry| entry.is_expired(ttl)).unwrap_or(false);
170 if should_remove {
171 Self::remove_inner(&mut inner, key);
172 }
173 inner.stats.misses += 1;
174 }
175 None
176 }
177 LookupState::Miss => {
178 if let Ok(mut inner) = self.inner.try_write() {
179 inner.stats.misses += 1;
180 }
181 None
182 }
183 }
184 }
185
186 pub fn get_owned(&self, key: &K) -> Option<V> {
188 self.get(key).map(|arc| (*arc).clone())
189 }
190
191 pub fn insert(&self, key: K, value: V, size_bytes: u64) {
193 self.insert_entry(key, CacheEntry::new(value, size_bytes));
194 }
195
196 pub fn insert_arc(&self, key: K, value: Arc<V>, size_bytes: u64) {
198 self.insert_entry(key, CacheEntry::from_arc(value, size_bytes));
199 }
200
201 fn insert_entry(&self, key: K, entry: CacheEntry<V>) {
202 let Ok(mut inner) = self.inner.write() else {
203 return;
204 };
205
206 Self::remove_expired_entries_inner(&mut inner);
208
209 if inner.max_size == 0 {
211 return;
212 }
213
214 let size_bytes = entry.size_bytes;
215
216 if let Some(current) = inner.entries.get_mut(&key) {
219 let previous = std::mem::replace(current, entry);
220 inner.stats.total_memory_bytes = inner.stats.total_memory_bytes.saturating_sub(previous.size_bytes);
221 inner.stats.current_size = inner.entries.len();
222 inner.stats.total_memory_bytes = inner.stats.total_memory_bytes.saturating_add(size_bytes);
223 return;
224 }
225
226 if inner.entries.len() >= inner.max_size {
229 let to_remove = (inner.max_size / 10).max(1);
230 Self::evict_batch_inner(&mut inner, to_remove);
231 }
232
233 inner.entries.insert(key, entry);
234 inner.stats.current_size = inner.entries.len();
235 inner.stats.total_memory_bytes = inner.stats.total_memory_bytes.saturating_add(size_bytes);
236 }
237
238 fn remove_expired_entries_inner(inner: &mut UnifiedCacheInner<K, V>) {
240 let ttl = inner.ttl;
241 Self::remove_entries_where_inner(inner, |_, entry| entry.is_expired(ttl));
242 }
243
244 fn remove_entries_where_inner<F>(inner: &mut UnifiedCacheInner<K, V>, mut predicate: F) -> usize
246 where
247 F: FnMut(&K, &CacheEntry<V>) -> bool,
248 {
249 let UnifiedCacheInner { entries, stats, .. } = inner;
250 let previous_size = entries.len();
251 entries.retain(|key, entry| {
252 if predicate(key, entry) {
253 stats.total_memory_bytes = stats.total_memory_bytes.saturating_sub(entry.size_bytes);
254 false
255 } else {
256 true
257 }
258 });
259 stats.current_size = entries.len();
260 previous_size - entries.len()
261 }
262
263 fn evict_batch_inner(inner: &mut UnifiedCacheInner<K, V>, count: usize) -> usize {
267 if count == 0 || inner.entries.is_empty() {
268 return 0;
269 }
270
271 let keys_to_remove: Vec<K> = {
272 let mut entries: Vec<_> = inner.entries.iter().collect();
273 match inner.eviction_policy {
274 EvictionPolicy::Lru => entries.sort_by_key(|(_, entry)| entry.last_accessed),
275 EvictionPolicy::Lfu => entries.sort_by_key(|(_, entry)| entry.access_count),
276 EvictionPolicy::Fifo | EvictionPolicy::TtlOnly => {
277 entries.sort_by_key(|(_, entry)| entry.created_at);
278 }
279 }
280 entries.into_iter().take(count).map(|(key, _)| key.clone()).collect()
281 };
282
283 for key in &keys_to_remove {
284 Self::remove_inner(inner, key);
285 }
286 inner.stats.evictions += keys_to_remove.len() as u64;
287 keys_to_remove.len()
288 }
289
290 fn remove_inner(inner: &mut UnifiedCacheInner<K, V>, key: &K) {
291 if let Some(entry) = inner.entries.remove(key) {
292 inner.stats.total_memory_bytes = inner.stats.total_memory_bytes.saturating_sub(entry.size_bytes);
293 inner.stats.current_size = inner.entries.len();
294 }
295 }
296
297 pub fn stats(&self) -> CacheStats {
299 self.inner.read().map(|inner| inner.stats.clone()).unwrap_or_default()
300 }
301
302 pub fn clear(&self) {
304 if let Ok(mut inner) = self.inner.write() {
305 inner.entries.clear();
306 inner.stats.current_size = 0;
307 inner.stats.total_memory_bytes = 0;
308 }
309 }
310
311 pub fn remove(&self, key: &K) {
313 let Ok(mut inner) = self.inner.write() else {
314 return;
315 };
316 Self::remove_inner(&mut inner, key);
317 }
318
319 pub fn len(&self) -> usize {
321 self.inner.read().map(|inner| inner.entries.len()).unwrap_or(0)
322 }
323
324 pub fn is_empty(&self) -> bool {
325 self.len() == 0
326 }
327
328 pub fn invalidate_prefix(&self, prefix: &str) {
337 self.remove_where(|key| key.to_cache_key().starts_with(prefix));
338 }
339
340 pub fn invalidate_path(&self, path: &str) {
349 self.invalidate_prefix(&format!("{path}:"));
350 }
351
352 pub fn invalidate_suffix(&self, suffix: &str) {
360 self.remove_where(|key| key.to_cache_key().ends_with(suffix));
361 }
362
363 pub fn invalidate_containing(&self, substring: &str) {
371 self.remove_where(|key| key.to_cache_key().contains(substring));
372 }
373
374 pub fn remove_where<F>(&self, mut predicate: F) -> usize
378 where
379 F: FnMut(&K) -> bool,
380 {
381 let Ok(mut inner) = self.inner.write() else {
382 return 0;
383 };
384
385 Self::remove_entries_where_inner(&mut inner, |key, _| predicate(key))
386 }
387
388 pub fn total_memory_bytes(&self) -> u64 {
390 self.inner.read().map(|inner| inner.stats.total_memory_bytes).unwrap_or(0)
391 }
392
393 pub fn estimate_entry_cost(entry: &CacheEntry<V>) -> u64 {
396 let base_overhead: u64 = 100; let value_size = entry.size_bytes;
399 base_overhead + value_size
400 }
401
402 pub fn reduce_ttl(&self, factor: f64) -> Duration {
410 let Ok(mut inner) = self.inner.write() else {
411 return Duration::ZERO;
412 };
413 if !factor.is_finite() {
414 return inner.ttl;
415 }
416 let factor = factor.clamp(0.0, 1.0);
417 inner.ttl = if factor >= 1.0 {
421 inner.base_ttl
422 } else {
423 inner.base_ttl.mul_f64(factor)
424 };
425 inner.ttl
426 }
427
428 pub fn base_ttl(&self) -> Duration {
430 self.inner.read().map(|inner| inner.base_ttl).unwrap_or(Duration::ZERO)
431 }
432
433 pub fn evict_under_pressure(&self, target_reduction_percent: u32) -> usize {
443 let Ok(mut inner) = self.inner.write() else {
444 return 0;
445 };
446
447 let target_percent = std::cmp::min(100, target_reduction_percent);
449
450 let expired_before = inner.entries.len();
452 Self::remove_expired_entries_inner(&mut inner);
453 let expired_removed = expired_before - inner.entries.len();
454
455 let current_size = inner.entries.len();
457 let target_size = (current_size * (100 - target_percent) as usize) / 100;
458
459 expired_removed + Self::evict_batch_inner(&mut inner, current_size - target_size)
460 }
461
462 pub fn clear_least_used(&self, percent_to_clear: u32) -> usize {
465 let Ok(mut inner) = self.inner.write() else {
466 return 0;
467 };
468
469 let percent = std::cmp::min(100, percent_to_clear);
470 let entries_to_remove = (inner.entries.len() * percent as usize) / 100;
471
472 Self::evict_batch_inner(&mut inner, entries_to_remove)
473 }
474
475 pub fn entries_by_usefulness(&self) -> Vec<(K, CacheEntry<V>)> {
478 let Ok(inner) = self.inner.read() else {
479 return Vec::new();
480 };
481
482 let now = SystemTime::now();
483 let mut entries: Vec<(K, CacheEntry<V>, u64)> = inner
484 .entries
485 .iter()
486 .map(|(k, entry)| {
487 let age_secs = now.duration_since(entry.last_accessed).unwrap_or_default().as_secs();
489
490 let recency_factor = std::cmp::max(1_u64, 3600 / (age_secs + 1));
492 let usefulness_score = entry.access_count * recency_factor;
493
494 (k.clone(), entry.clone(), usefulness_score)
495 })
496 .collect();
497
498 entries.sort_by_key(|(_, _, score)| std::cmp::Reverse(*score));
500 entries.into_iter().map(|(k, e, _)| (k, e)).collect()
501 }
502}
503
504pub fn estimate_json_size(value: &serde_json::Value) -> u64 {
506 match value {
507 serde_json::Value::Null => 4,
508 serde_json::Value::Bool(_) => 5,
509 serde_json::Value::Number(n) => n.to_string().len() as u64,
510 serde_json::Value::String(s) => s.len() as u64,
511 serde_json::Value::Array(arr) => arr
512 .iter()
513 .map(estimate_json_size)
514 .fold(0u64, |acc, size| acc.saturating_add(size)),
515 serde_json::Value::Object(obj) => obj
516 .iter()
517 .map(|(k, v)| (k.len() as u64).saturating_add(estimate_json_size(v)).saturating_add(3)) .fold(0u64, |acc, size| acc.saturating_add(size)),
519 }
520}
521
522pub fn create_cache_key<T: Serialize>(data: &T) -> Result<String> {
524 let json_bytes = serde_json::to_vec(data)?;
525
526 let mut hash = 0u64;
528 for (i, byte) in json_bytes.iter().enumerate() {
529 hash = hash.wrapping_mul(31).wrapping_add(*byte as u64);
530 hash = hash.rotate_left((i % 64) as u32);
531 }
532
533 Ok(format!("{hash:016x}"))
534}
535
536pub struct ContextAwareCache<K, V> {
538 inner: UnifiedCache<K, V>,
539}
540
541impl<K, V> ContextAwareCache<K, V>
542where
543 K: CacheKey,
544 V: CacheValue,
545{
546 pub fn new(max_size: usize, ttl: Duration, eviction_policy: EvictionPolicy) -> Self {
547 Self {
548 inner: UnifiedCache::new(max_size, ttl, eviction_policy),
549 }
550 }
551
552 pub fn get_context_limited<F>(&self, keys: &[K], mut process_fn: F) -> Vec<V>
554 where
555 F: FnMut(&K) -> Option<V>,
556 {
557 let mut results = Vec::with_capacity(MAX_CONTEXT_ITEMS.min(keys.len()));
558 let mut overflow_count = 0;
559
560 for key in keys {
561 if results.len() >= MAX_CONTEXT_ITEMS {
562 overflow_count += 1;
563 continue;
564 }
565
566 if let Some(value) = self.inner.get(key) {
567 results.push((*value).clone());
568 } else if let Some(value) = process_fn(key) {
569 let size = size_of_val(&value) as u64;
571 self.inner.insert(key.clone(), value.clone(), size);
572 results.push(value);
573 }
574 }
575
576 if overflow_count > 0 {
578 }
581
582 results
583 }
584
585 pub fn stats(&self) -> CacheStats {
586 self.inner.stats()
587 }
588}
589
590#[cfg(test)]
591mod eviction_tests;
592
593#[cfg(test)]
594mod tests {
595 use super::*;
596
597 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
598 struct TestKey(String);
599
600 impl CacheKey for TestKey {
601 fn to_cache_key(&self) -> String {
602 self.0.clone()
603 }
604 }
605
606 #[test]
607 fn test_cache_basic_operations() {
608 let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
609 let key = TestKey("test".into());
610 let value: String = "test_value".into();
611
612 cache.insert(key.clone(), value.clone(), 100);
614 assert_eq!(*cache.get(&key).unwrap(), value);
615
616 let stats = cache.stats();
618 assert_eq!(stats.hits, 1);
619 assert_eq!(stats.misses, 0);
620 assert_eq!(stats.current_size, 1);
621 }
622
623 #[test]
624 fn insert_arc_preserves_value_arc_and_statistics() {
625 let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
626 let key = TestKey("arc".into());
627 let value = Arc::new("shared value".to_string());
628
629 cache.insert_arc(key.clone(), Arc::clone(&value), value.len() as u64);
630
631 let cached = cache.get(&key).expect("inserted value should be cached");
632 assert!(Arc::ptr_eq(&cached, &value));
633 assert_eq!(cache.stats().total_memory_bytes, value.len() as u64);
634 }
635
636 #[test]
637 fn replacing_entry_updates_memory_statistics() {
638 let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
639 let key = TestKey("replacement".into());
640
641 cache.insert(key.clone(), "small".to_string(), 5);
642 cache.insert(key, "larger replacement".to_string(), 18);
643
644 let stats = cache.stats();
645 assert_eq!(stats.current_size, 1);
646 assert_eq!(stats.total_memory_bytes, 18);
647 }
648
649 #[test]
650 fn replacing_entry_at_capacity_does_not_evict() {
651 let cache = UnifiedCache::new(1, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
652 let key = TestKey("replacement".into());
653
654 cache.insert(key.clone(), "old".to_string(), 3);
655 cache.insert(key.clone(), "new value".to_string(), 9);
656
657 assert_eq!(cache.get_owned(&key).as_deref(), Some("new value"));
658 let stats = cache.stats();
659 assert_eq!(stats.current_size, 1);
660 assert_eq!(stats.evictions, 0);
661 assert_eq!(stats.total_memory_bytes, 9);
662 }
663
664 #[test]
665 fn zero_capacity_cache_rejects_entries() {
666 let cache = UnifiedCache::new(0, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
667
668 cache.insert(TestKey("rejected".into()), "value".to_string(), 5);
669
670 assert_eq!(cache.len(), 0);
671 assert_eq!(cache.total_memory_bytes(), 0);
672 assert_eq!(cache.stats().evictions, 0);
673 }
674
675 #[test]
676 fn test_cache_expiration() {
677 let cache = UnifiedCache::new(10, Duration::from_millis(100), EvictionPolicy::Lru);
678 let key = TestKey("test".into());
679 let value: String = "test_value".into();
680
681 cache.insert(key.clone(), value, 100);
682 assert!(cache.get(&key).is_some());
683
684 std::thread::sleep(Duration::from_millis(150));
686 assert!(cache.get(&key).is_none());
687 }
688
689 #[test]
690 fn test_context_limited_cache() {
691 let cache = ContextAwareCache::new(100, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
692 let keys: Vec<TestKey> = (0..10).map(|i| TestKey(i.to_string())).collect();
693
694 let results = cache.get_context_limited(&keys, |key| Some(format!("value_{}", key.0)));
695
696 assert_eq!(results.len(), MAX_CONTEXT_ITEMS);
698 assert_eq!(results[0], "value_0");
699 assert_eq!(results[4], "value_4");
700 }
701
702 #[test]
703 fn test_pressure_aware_total_memory() {
704 let cache = UnifiedCache::new(10, DEFAULT_CACHE_TTL, EvictionPolicy::Lru);
705
706 cache.insert(TestKey("k1".into()), "v1".to_string(), 100);
708 cache.insert(TestKey("k2".into()), "v2".to_string(), 200);
709 cache.insert(TestKey("k3".into()), "v3".to_string(), 300);
710
711 assert_eq!(cache.total_memory_bytes(), 600);
713 }
714
715 #[test]
716 fn pressure_ttl_is_idempotent_and_recoverable() {
717 let cache: UnifiedCache<TestKey, String> = UnifiedCache::new(10, Duration::from_secs(300), EvictionPolicy::Lru);
718
719 assert_eq!(cache.base_ttl(), Duration::from_secs(300));
720 assert_eq!(cache.reduce_ttl(0.4), Duration::from_secs(120));
721 assert_eq!(cache.reduce_ttl(0.4), Duration::from_secs(120));
723 assert_eq!(cache.reduce_ttl(0.1), Duration::from_secs(30));
724 assert_eq!(cache.reduce_ttl(1.0), Duration::from_secs(300));
726 }
727
728 #[test]
729 fn pressure_ttl_clamps_out_of_range_factors_and_ignores_non_finite() {
730 let cache: UnifiedCache<TestKey, String> = UnifiedCache::new(10, Duration::from_secs(300), EvictionPolicy::Lru);
731 assert_eq!(cache.reduce_ttl(0.5), Duration::from_secs(150));
732
733 assert_eq!(cache.reduce_ttl(f64::NAN), Duration::from_secs(150));
735 assert_eq!(cache.reduce_ttl(f64::INFINITY), Duration::from_secs(150));
736 assert_eq!(cache.reduce_ttl(-1.0), Duration::ZERO);
738 assert_eq!(cache.reduce_ttl(2.0), Duration::from_secs(300));
739 }
740
741 #[test]
742 fn pressure_ttl_restore_never_panics_for_max_duration() {
743 let cache: UnifiedCache<TestKey, String> = UnifiedCache::new(1, Duration::MAX, EvictionPolicy::Lru);
744 assert_eq!(cache.reduce_ttl(0.5), Duration::from_secs(1 << 63));
745 assert_eq!(cache.reduce_ttl(1.0), Duration::MAX);
746 }
747
748 #[test]
749 fn test_pressure_aware_evict_under_pressure() {
750 let cache: UnifiedCache<TestKey, String> =
751 UnifiedCache::new(20, Duration::from_secs(3600), EvictionPolicy::Lru);
752
753 for i in 0..10 {
755 cache.insert(TestKey(format!("key_{i}")), format!("value_{i}"), 100);
756 }
757
758 assert_eq!(cache.len(), 10);
759
760 let removed = cache.evict_under_pressure(50);
762 assert_eq!(removed, 5);
763 assert_eq!(cache.len(), 5);
764 }
765
766 #[test]
767 fn test_pressure_aware_clear_least_used() {
768 let cache: UnifiedCache<TestKey, String> =
769 UnifiedCache::new(20, Duration::from_secs(3600), EvictionPolicy::Lru);
770
771 for i in 0..10 {
773 cache.insert(TestKey(format!("key_{i}")), format!("value_{i}"), 100);
774 }
775
776 let _ = cache.get(&TestKey("key_0".into()));
778 let _ = cache.get(&TestKey("key_1".into()));
779
780 assert_eq!(cache.len(), 10);
781
782 let removed = cache.clear_least_used(30);
784 assert!(removed <= 4, "Should remove ~3 entries (30% of 10)");
785 assert!(cache.len() >= 6, "Should have ~7 entries left");
786 }
787
788 #[test]
789 fn test_pressure_aware_entries_by_usefulness() {
790 let cache: UnifiedCache<TestKey, String> =
791 UnifiedCache::new(20, Duration::from_secs(3600), EvictionPolicy::Lru);
792
793 cache.insert(TestKey("hot".into()), "value".to_string(), 100);
795 cache.insert(TestKey("cold".into()), "value".to_string(), 100);
796 cache.insert(TestKey("warm".into()), "value".to_string(), 100);
797
798 for _ in 0..5 {
800 let _ = cache.get(&TestKey("hot".into()));
801 }
802
803 let _ = cache.get(&TestKey("warm".into()));
805
806 let usefulness = cache.entries_by_usefulness();
809 assert_eq!(usefulness.len(), 3);
810
811 assert_eq!(usefulness[0].0.0, "hot");
813 }
814
815 #[test]
816 fn test_pressure_aware_estimate_entry_cost() {
817 let entry = CacheEntry::new("test_value".to_string(), 1000);
818 let cost = UnifiedCache::<TestKey, String>::estimate_entry_cost(&entry);
819
820 assert!(cost >= 1000);
822 assert!(cost <= 1200); }
824}