Skip to main content

oxigeo_cache_advanced/
lib.rs

1//! Advanced Multi-Tier Caching for OxiGeo
2//!
3//! This crate provides intelligent caching with:
4//! - Multi-tier cache (L1: memory, L2: SSD, L3: network)
5//! - Predictive prefetching with ML
6//! - Adaptive compression
7//! - Distributed cache protocol
8//! - Cache analytics and warming
9//! - Advanced eviction policies
10
11#![warn(missing_docs)]
12#![deny(unsafe_code)]
13
14pub mod analytics;
15pub mod coherency;
16pub mod compression;
17pub mod distributed;
18pub mod error;
19pub mod eviction;
20pub mod multi_tier;
21pub mod observability;
22pub mod partitioning;
23pub mod predictive;
24pub mod tiering;
25pub mod warming;
26pub mod write_policy;
27
28pub use error::{CacheError, Result};
29pub use eviction::{
30    CountMinSketch, EvictionPolicy, EvictionPolicyType, EvictionStats, WTinyLfuEviction,
31};
32pub use multi_tier::{CacheKey, CacheTier, CacheValue, MultiTierCache};
33
34/// Cache statistics
35#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
36pub struct CacheStats {
37    /// Total number of cache hits
38    pub hits: u64,
39    /// Total number of cache misses
40    pub misses: u64,
41    /// Number of evictions
42    pub evictions: u64,
43    /// Total bytes stored
44    pub bytes_stored: u64,
45    /// Number of items in cache
46    pub item_count: usize,
47}
48
49impl CacheStats {
50    /// Create new cache statistics
51    pub fn new() -> Self {
52        Self {
53            hits: 0,
54            misses: 0,
55            evictions: 0,
56            bytes_stored: 0,
57            item_count: 0,
58        }
59    }
60
61    /// Calculate hit rate as a percentage
62    pub fn hit_rate(&self) -> f64 {
63        if self.hits + self.misses == 0 {
64            0.0
65        } else {
66            (self.hits as f64) / ((self.hits + self.misses) as f64) * 100.0
67        }
68    }
69
70    /// Calculate average item size in bytes
71    pub fn avg_item_size(&self) -> f64 {
72        if self.item_count == 0 {
73            0.0
74        } else {
75            (self.bytes_stored as f64) / (self.item_count as f64)
76        }
77    }
78}
79
80impl Default for CacheStats {
81    fn default() -> Self {
82        Self::new()
83    }
84}
85
86/// Cache configuration
87#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
88pub struct CacheConfig {
89    /// L1 cache size in bytes
90    pub l1_size: usize,
91    /// L2 cache size in bytes
92    pub l2_size: usize,
93    /// L3 cache size in bytes
94    pub l3_size: usize,
95    /// Enable compression
96    pub enable_compression: bool,
97    /// Enable predictive prefetching
98    pub enable_prefetch: bool,
99    /// Enable distributed cache
100    pub enable_distributed: bool,
101    /// Cache directory for disk-based tiers
102    pub cache_dir: Option<std::path::PathBuf>,
103    /// Eviction policy used by the in-memory (L1) and disk (L2) tiers.
104    ///
105    /// Defaults to [`EvictionPolicyType::Lru`]. Set this to
106    /// [`EvictionPolicyType::WTinyLfu`] to drive the multi-tier cache with the
107    /// crate's Window-TinyLFU admission policy instead of plain LRU.
108    #[serde(default)]
109    pub eviction_policy: EvictionPolicyType,
110}
111
112impl Default for CacheConfig {
113    fn default() -> Self {
114        Self {
115            l1_size: 128 * 1024 * 1024,       // 128 MB
116            l2_size: 1024 * 1024 * 1024,      // 1 GB
117            l3_size: 10 * 1024 * 1024 * 1024, // 10 GB
118            enable_compression: true,
119            enable_prefetch: true,
120            enable_distributed: false,
121            cache_dir: None,
122            eviction_policy: EvictionPolicyType::Lru,
123        }
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    #[test]
132    fn test_cache_stats_hit_rate() {
133        let mut stats = CacheStats::new();
134        stats.hits = 80;
135        stats.misses = 20;
136
137        approx::assert_relative_eq!(stats.hit_rate(), 80.0, epsilon = 0.01);
138    }
139
140    #[test]
141    fn test_cache_stats_avg_size() {
142        let mut stats = CacheStats::new();
143        stats.bytes_stored = 1000;
144        stats.item_count = 10;
145
146        approx::assert_relative_eq!(stats.avg_item_size(), 100.0, epsilon = 0.01);
147    }
148
149    #[test]
150    fn test_default_config() {
151        let config = CacheConfig::default();
152        assert!(config.enable_compression);
153        assert!(config.enable_prefetch);
154        assert!(!config.enable_distributed);
155    }
156}