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::{
69    CacheManager, CacheStrategy, CacheManagerStats,
70    // Multi-tier support (v0.5.0+)
71    TierConfig, CacheTier, TierStats,
72};
73pub use traits::{CacheBackend, L2CacheBackend, StreamingBackend};
74pub use builder::CacheSystemBuilder;
75pub use invalidation::{
76    InvalidationConfig, InvalidationMessage, InvalidationStats,
77    InvalidationPublisher, InvalidationSubscriber,
78};
79
80// Re-export async_trait for user convenience
81pub use async_trait::async_trait;
82
83/// Main entry point for the Multi-Tier Cache system
84///
85/// Provides unified access to L1 (Moka) and L2 (Redis) caches with
86/// automatic failover, promotion, and stampede protection.
87///
88/// # Example
89///
90/// ```rust,no_run
91/// use multi_tier_cache::CacheSystem;
92///
93/// #[tokio::main]
94/// async fn main() -> anyhow::Result<()> {
95///     let cache = CacheSystem::new().await?;
96///
97///     // Use cache_manager for all operations
98///     let manager = cache.cache_manager();
99///
100///     Ok(())
101/// }
102/// ```
103#[derive(Clone)]
104pub struct CacheSystem {
105    /// Unified cache manager (primary interface)
106    pub cache_manager: Arc<CacheManager>,
107    /// L1 Cache (in-memory, Moka)
108    pub l1_cache: Arc<L1Cache>,
109    /// L2 Cache (distributed, Redis)
110    pub l2_cache: Arc<L2Cache>,
111}
112
113impl CacheSystem {
114    /// Create new cache system with default configuration
115    ///
116    /// # Configuration
117    ///
118    /// Redis connection is configured via `REDIS_URL` environment variable.
119    /// Default: `redis://127.0.0.1:6379`
120    ///
121    /// # Example
122    ///
123    /// ```rust,no_run
124    /// use multi_tier_cache::CacheSystem;
125    ///
126    /// #[tokio::main]
127    /// async fn main() -> anyhow::Result<()> {
128    ///     // Set environment variable (optional)
129    ///     std::env::set_var("REDIS_URL", "redis://localhost:6379");
130    ///
131    ///     let cache = CacheSystem::new().await?;
132    ///     Ok(())
133    /// }
134    /// ```
135    pub async fn new() -> Result<Self> {
136        println!("🏗️ Initializing Multi-Tier Cache System...");
137
138        // Initialize L1 cache (Moka)
139        let l1_cache = Arc::new(L1Cache::new().await?);
140
141        // Initialize L2 cache (Redis)
142        let l2_cache = Arc::new(L2Cache::new().await?);
143
144        // Initialize cache manager
145        let cache_manager = Arc::new(CacheManager::new(l1_cache.clone(), l2_cache.clone()).await?);
146
147        println!("✅ Multi-Tier Cache System initialized successfully");
148
149        Ok(Self {
150            cache_manager,
151            l1_cache,
152            l2_cache,
153        })
154    }
155
156    /// Create cache system with custom Redis URL
157    ///
158    /// # Arguments
159    ///
160    /// * `redis_url` - Redis connection string (e.g., "redis://localhost:6379")
161    ///
162    /// # Example
163    ///
164    /// ```rust,no_run
165    /// use multi_tier_cache::CacheSystem;
166    ///
167    /// #[tokio::main]
168    /// async fn main() -> anyhow::Result<()> {
169    ///     let cache = CacheSystem::with_redis_url("redis://custom:6379").await?;
170    ///     Ok(())
171    /// }
172    /// ```
173    pub async fn with_redis_url(redis_url: &str) -> Result<Self> {
174        // Temporarily set environment variable for L2Cache initialization
175        std::env::set_var("REDIS_URL", redis_url);
176        Self::new().await
177    }
178
179    /// Perform health check on all cache tiers
180    ///
181    /// Returns `true` if at least L1 is operational.
182    /// L2 failure is tolerated (graceful degradation).
183    ///
184    /// # Example
185    ///
186    /// ```rust,no_run
187    /// use multi_tier_cache::CacheSystem;
188    ///
189    /// #[tokio::main]
190    /// async fn main() -> anyhow::Result<()> {
191    ///     let cache = CacheSystem::new().await?;
192    ///
193    ///     if cache.health_check().await {
194    ///         println!("Cache system healthy");
195    ///     }
196    ///
197    ///     Ok(())
198    /// }
199    /// ```
200    pub async fn health_check(&self) -> bool {
201        let l1_ok = self.l1_cache.health_check().await;
202        let l2_ok = self.l2_cache.health_check().await;
203
204        if l1_ok && l2_ok {
205            println!("  ✅ Multi-Tier Cache health check passed");
206            true
207        } else {
208            println!("  ⚠️ Multi-Tier Cache health check - L1: {}, L2: {}", l1_ok, l2_ok);
209            l1_ok // At minimum, L1 should work
210        }
211    }
212
213    /// Get reference to cache manager (primary interface)
214    ///
215    /// Use this for all cache operations: get, set, streams, etc.
216    pub fn cache_manager(&self) -> &Arc<CacheManager> {
217        &self.cache_manager
218    }
219}