multi_tier_cache/lib.rs
1//! Multi-Tier Cache
2//!
3//! A high-performance, production-ready multi-tier caching library for Rust featuring:
4//! - **L1 Cache**: In-memory caching with Moka (sub-millisecond latency)
5//! - **L2 Cache**: Distributed caching with Redis (persistent storage)
6//! - **Cache Stampede Protection**: DashMap + Mutex request coalescing
7//! - **Redis Streams**: Built-in support for event streaming
8//! - **Automatic L2-to-L1 Promotion**: Intelligent cache tier promotion
9//! - **Comprehensive Statistics**: Hit rates, promotions, in-flight tracking
10//!
11//! # Quick Start
12//!
13//! ```rust,no_run
14//! use multi_tier_cache::{CacheSystem, CacheStrategy};
15//!
16//! #[tokio::main]
17//! async fn main() -> anyhow::Result<()> {
18//! // Initialize cache system
19//! let cache = CacheSystem::new().await?;
20//!
21//! // Store data with cache strategy
22//! let data = serde_json::json!({"user": "alice", "score": 100});
23//! cache.cache_manager()
24//! .set_with_strategy("user:1", data, CacheStrategy::ShortTerm)
25//! .await?;
26//!
27//! // Retrieve data (L1 first, then L2 fallback)
28//! if let Some(cached) = cache.cache_manager().get("user:1").await? {
29//! println!("Cached data: {}", cached);
30//! }
31//!
32//! // Get statistics
33//! let stats = cache.cache_manager().get_stats();
34//! println!("Hit rate: {:.2}%", stats.hit_rate);
35//!
36//! Ok(())
37//! }
38//! ```
39//!
40//! # Features
41//!
42//! - **Multi-Tier Architecture**: Combines fast in-memory (L1) with persistent distributed (L2) caching
43//! - **Cache Stampede Protection**: Prevents duplicate computations during cache misses
44//! - **Redis Streams**: Publish/subscribe with automatic trimming
45//! - **Zero-Config**: Sensible defaults, works out of the box
46//! - **Production-Proven**: Battle-tested at 16,829+ RPS with 5.2ms latency
47//!
48//! # Architecture
49//!
50//! ```text
51//! Request → L1 Cache (Moka) → L2 Cache (Redis) → Compute/Fetch
52//! ↓ Hit (90%) ↓ Hit (75%) ↓ Miss (5%)
53//! Return Promote to L1 Store in L1+L2
54//! ```
55
56use std::sync::Arc;
57use anyhow::Result;
58
59pub mod l1_cache;
60pub mod l2_cache;
61pub mod cache_manager;
62pub mod traits;
63pub mod builder;
64pub mod invalidation;
65
66pub use l1_cache::L1Cache;
67pub use l2_cache::L2Cache;
68pub use cache_manager::{CacheManager, CacheStrategy, CacheManagerStats};
69pub use traits::{CacheBackend, L2CacheBackend, StreamingBackend};
70pub use builder::CacheSystemBuilder;
71pub use invalidation::{
72 InvalidationConfig, InvalidationMessage, InvalidationStats,
73 InvalidationPublisher, InvalidationSubscriber,
74};
75
76// Re-export async_trait for user convenience
77pub use async_trait::async_trait;
78
79/// Main entry point for the Multi-Tier Cache system
80///
81/// Provides unified access to L1 (Moka) and L2 (Redis) caches with
82/// automatic failover, promotion, and stampede protection.
83///
84/// # Example
85///
86/// ```rust,no_run
87/// use multi_tier_cache::CacheSystem;
88///
89/// #[tokio::main]
90/// async fn main() -> anyhow::Result<()> {
91/// let cache = CacheSystem::new().await?;
92///
93/// // Use cache_manager for all operations
94/// let manager = cache.cache_manager();
95///
96/// Ok(())
97/// }
98/// ```
99#[derive(Clone)]
100pub struct CacheSystem {
101 /// Unified cache manager (primary interface)
102 pub cache_manager: Arc<CacheManager>,
103 /// L1 Cache (in-memory, Moka)
104 pub l1_cache: Arc<L1Cache>,
105 /// L2 Cache (distributed, Redis)
106 pub l2_cache: Arc<L2Cache>,
107}
108
109impl CacheSystem {
110 /// Create new cache system with default configuration
111 ///
112 /// # Configuration
113 ///
114 /// Redis connection is configured via `REDIS_URL` environment variable.
115 /// Default: `redis://127.0.0.1:6379`
116 ///
117 /// # Example
118 ///
119 /// ```rust,no_run
120 /// use multi_tier_cache::CacheSystem;
121 ///
122 /// #[tokio::main]
123 /// async fn main() -> anyhow::Result<()> {
124 /// // Set environment variable (optional)
125 /// std::env::set_var("REDIS_URL", "redis://localhost:6379");
126 ///
127 /// let cache = CacheSystem::new().await?;
128 /// Ok(())
129 /// }
130 /// ```
131 pub async fn new() -> Result<Self> {
132 println!("🏗️ Initializing Multi-Tier Cache System...");
133
134 // Initialize L1 cache (Moka)
135 let l1_cache = Arc::new(L1Cache::new().await?);
136
137 // Initialize L2 cache (Redis)
138 let l2_cache = Arc::new(L2Cache::new().await?);
139
140 // Initialize cache manager
141 let cache_manager = Arc::new(CacheManager::new(l1_cache.clone(), l2_cache.clone()).await?);
142
143 println!("✅ Multi-Tier Cache System initialized successfully");
144
145 Ok(Self {
146 cache_manager,
147 l1_cache,
148 l2_cache,
149 })
150 }
151
152 /// Create cache system with custom Redis URL
153 ///
154 /// # Arguments
155 ///
156 /// * `redis_url` - Redis connection string (e.g., "redis://localhost:6379")
157 ///
158 /// # Example
159 ///
160 /// ```rust,no_run
161 /// use multi_tier_cache::CacheSystem;
162 ///
163 /// #[tokio::main]
164 /// async fn main() -> anyhow::Result<()> {
165 /// let cache = CacheSystem::with_redis_url("redis://custom:6379").await?;
166 /// Ok(())
167 /// }
168 /// ```
169 pub async fn with_redis_url(redis_url: &str) -> Result<Self> {
170 // Temporarily set environment variable for L2Cache initialization
171 std::env::set_var("REDIS_URL", redis_url);
172 Self::new().await
173 }
174
175 /// Perform health check on all cache tiers
176 ///
177 /// Returns `true` if at least L1 is operational.
178 /// L2 failure is tolerated (graceful degradation).
179 ///
180 /// # Example
181 ///
182 /// ```rust,no_run
183 /// use multi_tier_cache::CacheSystem;
184 ///
185 /// #[tokio::main]
186 /// async fn main() -> anyhow::Result<()> {
187 /// let cache = CacheSystem::new().await?;
188 ///
189 /// if cache.health_check().await {
190 /// println!("Cache system healthy");
191 /// }
192 ///
193 /// Ok(())
194 /// }
195 /// ```
196 pub async fn health_check(&self) -> bool {
197 let l1_ok = self.l1_cache.health_check().await;
198 let l2_ok = self.l2_cache.health_check().await;
199
200 if l1_ok && l2_ok {
201 println!(" ✅ Multi-Tier Cache health check passed");
202 true
203 } else {
204 println!(" ⚠️ Multi-Tier Cache health check - L1: {}, L2: {}", l1_ok, l2_ok);
205 l1_ok // At minimum, L1 should work
206 }
207 }
208
209 /// Get reference to cache manager (primary interface)
210 ///
211 /// Use this for all cache operations: get, set, streams, etc.
212 pub fn cache_manager(&self) -> &Arc<CacheManager> {
213 &self.cache_manager
214 }
215}