multi-tier-cache 0.6.5

Customizable multi-tier cache with L1 (Moka in-memory) + L2 (Redis distributed) defaults, expandable to L3/L4+, cross-instance invalidation via Pub/Sub, stampede protection, and flexible TTL scaling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Cache System Builder
//!
//! Provides a flexible builder pattern for constructing `CacheSystem` with custom backends.
//!
//! # Example: Using Default Backends
//!
//! ```rust,no_run
//! use multi_tier_cache::CacheSystemBuilder;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let cache = CacheSystemBuilder::new()
//!         .build()
//!         .await?;
//!     Ok(())
//! }
//! ```
//!
//! # Example: Custom L1 Backend
//!
//! ```rust,ignore
//! use multi_tier_cache::{CacheSystemBuilder, CacheBackend};
//! use std::sync::Arc;
//!
//! let custom_l1 = Arc::new(MyCustomL1Cache::new());
//!
//! let cache = CacheSystemBuilder::new()
//!     .with_l1(custom_l1)
//!     .build()
//!     .await?;
//! ```

#[cfg(feature = "moka")]
#[cfg_attr(docsrs, doc(cfg(feature = "moka")))]
use crate::backends::MokaCacheConfig;
use crate::traits::{CacheBackend, L2CacheBackend, StreamingBackend};
use crate::{CacheManager, CacheSystem, CacheTier, TierConfig};

#[cfg(feature = "moka")]
#[cfg_attr(docsrs, doc(cfg(feature = "moka")))]
use crate::L1Cache;
#[cfg(feature = "redis")]
#[cfg_attr(docsrs, doc(cfg(feature = "redis")))]
use crate::L2Cache;
use anyhow::Result;
use std::sync::Arc;
use tracing::info;

/// Builder for constructing `CacheSystem` with custom backends
///
/// This builder allows you to configure custom L1 (in-memory) and L2 (distributed)
/// cache backends, enabling you to swap Moka and Redis with alternative implementations.
///
/// # Multi-Tier Support (v0.5.0+)
///
/// The builder now supports dynamic multi-tier architectures (L1+L2+L3+L4+...).
/// Use `.with_tier()` to add custom tiers, or `.with_l3()` / `.with_l4()` for convenience.
///
/// # Default Behavior
///
/// If no custom backends are provided, the builder uses:
/// - **L1**: Moka in-memory cache
/// - **L2**: Redis distributed cache
///
/// # Type Safety
///
/// The builder accepts any type that implements the required traits:
/// - L1 backends must implement `CacheBackend`
/// - L2 backends must implement `L2CacheBackend` (extends `CacheBackend`)
/// - All tier backends must implement `L2CacheBackend` (for TTL support)
/// - Streaming backends must implement `StreamingBackend`
///
/// # Example - Default 2-Tier
///
/// ```rust,no_run
/// use multi_tier_cache::CacheSystemBuilder;
///
/// #[tokio::main]
/// async fn main() -> anyhow::Result<()> {
///     // Use default backends (Moka + Redis)
///     let cache = CacheSystemBuilder::new()
///         .build()
///         .await?;
///
///     Ok(())
/// }
/// ```
///
/// # Example - Custom 3-Tier (v0.5.0+)
///
/// ```rust,ignore
/// use multi_tier_cache::{CacheSystemBuilder, TierConfig};
/// use std::sync::Arc;
///
/// let l1 = Arc::new(L1Cache::new().await?);
/// let l2 = Arc::new(L2Cache::new().await?);
/// let l3 = Arc::new(RocksDBCache::new("/tmp/cache").await?);
///
/// let cache = CacheSystemBuilder::new()
///     .with_tier(l1, TierConfig::as_l1())
///     .with_tier(l2, TierConfig::as_l2())
///     .with_l3(l3)  // Convenience method
///     .build()
///     .await?;
/// ```
pub struct CacheSystemBuilder {
    // Legacy 2-tier configuration (v0.1.0 - v0.4.x)
    l1_backend: Option<Arc<dyn CacheBackend>>,
    l2_backend: Option<Arc<dyn L2CacheBackend>>,

    streaming_backend: Option<Arc<dyn StreamingBackend>>,
    #[cfg(feature = "moka")]
    #[cfg_attr(docsrs, doc(cfg(feature = "moka")))]
    moka_config: Option<MokaCacheConfig>,

    // Multi-tier configuration (v0.5.0+)
    tiers: Vec<(Arc<dyn L2CacheBackend>, TierConfig)>,
}

impl CacheSystemBuilder {
    /// Create a new builder with no custom backends configured
    ///
    /// By default, calling `.build()` will use Moka (L1) and Redis (L2).
    /// Use `.with_tier()` to configure multi-tier architecture (v0.5.0+).
    #[must_use]
    pub fn new() -> Self {
        Self {
            l1_backend: None,
            l2_backend: None,

            streaming_backend: None,
            #[cfg(feature = "moka")]
            #[cfg_attr(docsrs, doc(cfg(feature = "moka")))]
            moka_config: None,
            tiers: Vec::new(),
        }
    }

    /// Configure a custom L1 (in-memory) cache backend
    ///
    /// # Arguments
    ///
    /// * `backend` - Any type implementing `CacheBackend` trait
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::sync::Arc;
    /// use multi_tier_cache::CacheSystemBuilder;
    ///
    /// let custom_l1 = Arc::new(MyCustomL1::new());
    ///
    /// let cache = CacheSystemBuilder::new()
    ///     .with_l1(custom_l1)
    ///     .build()
    ///     .await?;
    /// ```
    #[must_use]
    pub fn with_l1(mut self, backend: Arc<dyn CacheBackend>) -> Self {
        self.l1_backend = Some(backend);
        self
    }

    /// Configure custom configuration for default L1 (Moka) backend
    #[must_use]
    #[cfg(feature = "moka")]
    #[cfg_attr(docsrs, doc(cfg(feature = "moka")))]
    pub fn with_moka_config(mut self, config: MokaCacheConfig) -> Self {
        self.moka_config = Some(config);
        self
    }

    /// Configure a custom L2 (distributed) cache backend
    ///
    /// # Arguments
    ///
    /// * `backend` - Any type implementing `L2CacheBackend` trait
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::sync::Arc;
    /// use multi_tier_cache::CacheSystemBuilder;
    ///
    /// let custom_l2 = Arc::new(MyMemcachedBackend::new());
    ///
    /// let cache = CacheSystemBuilder::new()
    ///     .with_l2(custom_l2)
    ///     .build()
    ///     .await?;
    /// ```
    #[must_use]
    pub fn with_l2(mut self, backend: Arc<dyn L2CacheBackend>) -> Self {
        self.l2_backend = Some(backend);
        self
    }

    /// Configure a custom streaming backend
    ///
    /// This is optional. If not provided, streaming functionality will use
    /// the L2 backend if it implements `StreamingBackend`.
    ///
    /// # Arguments
    ///
    /// * `backend` - Any type implementing `StreamingBackend` trait
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::sync::Arc;
    /// use multi_tier_cache::CacheSystemBuilder;
    ///
    /// let kafka_backend = Arc::new(MyKafkaBackend::new());
    ///
    /// let cache = CacheSystemBuilder::new()
    ///     .with_streams(kafka_backend)
    ///     .build()
    ///     .await?;
    /// ```
    #[must_use]
    pub fn with_streams(mut self, backend: Arc<dyn StreamingBackend>) -> Self {
        self.streaming_backend = Some(backend);
        self
    }

    /// Configure a cache tier with custom settings (v0.5.0+)
    ///
    /// Add a cache tier to the multi-tier architecture. Tiers will be sorted
    /// by `tier_level` during build.
    ///
    /// # Arguments
    ///
    /// * `backend` - Any type implementing `L2CacheBackend` trait
    /// * `config` - Tier configuration (level, promotion, TTL scale)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use multi_tier_cache::{CacheSystemBuilder, TierConfig, L1Cache, L2Cache};
    /// use std::sync::Arc;
    ///
    /// let l1 = Arc::new(L1Cache::new().await?);
    /// let l2 = Arc::new(L2Cache::new().await?);
    /// let l3 = Arc::new(RocksDBCache::new("/tmp").await?);
    ///
    /// let cache = CacheSystemBuilder::new()
    ///     .with_tier(l1, TierConfig::as_l1())
    ///     .with_tier(l2, TierConfig::as_l2())
    ///     .with_tier(l3, TierConfig::as_l3())
    ///     .build()
    ///     .await?;
    /// ```
    #[must_use]
    pub fn with_tier(mut self, backend: Arc<dyn L2CacheBackend>, config: TierConfig) -> Self {
        self.tiers.push((backend, config));
        self
    }

    /// Convenience method to add L3 cache tier (v0.5.0+)
    ///
    /// Adds a cold storage tier with 2x TTL multiplier.
    ///
    /// # Arguments
    ///
    /// * `backend` - L3 backend (e.g., `RocksDB`, `LevelDB`)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::sync::Arc;
    ///
    /// let rocksdb = Arc::new(RocksDBCache::new("/tmp/l3cache").await?);
    ///
    /// let cache = CacheSystemBuilder::new()
    ///     .with_l3(rocksdb)
    ///     .build()
    ///     .await?;
    /// ```
    #[must_use]
    pub fn with_l3(mut self, backend: Arc<dyn L2CacheBackend>) -> Self {
        self.tiers.push((backend, TierConfig::as_l3()));
        self
    }

    /// Convenience method to add L4 cache tier (v0.5.0+)
    ///
    /// Adds an archive storage tier with 8x TTL multiplier.
    ///
    /// # Arguments
    ///
    /// * `backend` - L4 backend (e.g., S3, file system)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::sync::Arc;
    ///
    /// let s3_cache = Arc::new(S3Cache::new("my-bucket").await?);
    ///
    /// let cache = CacheSystemBuilder::new()
    ///     .with_l4(s3_cache)
    ///     .build()
    ///     .await?;
    /// ```
    #[must_use]
    pub fn with_l4(mut self, backend: Arc<dyn L2CacheBackend>) -> Self {
        self.tiers.push((backend, TierConfig::as_l4()));
        self
    }

    /// Build the `CacheSystem` with configured or default backends
    ///
    /// If no custom backends were provided via `.with_l1()` or `.with_l2()`,
    /// this method creates default backends (Moka for L1, Redis for L2).
    ///
    /// # Multi-Tier Mode (v0.5.0+)
    ///
    /// If tiers were configured via `.with_tier()`, `.with_l3()`, or `.with_l4()`,
    /// the builder creates a multi-tier `CacheManager` using `new_with_tiers()`.
    ///
    /// # Returns
    ///
    /// * `Ok(CacheSystem)` - Successfully constructed cache system
    /// * `Err(e)` - Failed to initialize backends (e.g., Redis connection error)
    ///
    /// # Example - Default 2-Tier
    ///
    /// ```rust,no_run
    /// use multi_tier_cache::CacheSystemBuilder;
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     let cache = CacheSystemBuilder::new()
    ///         .build()
    ///         .await?;
    ///
    ///     // Use cache_manager for operations
    ///     let manager = cache.cache_manager();
    ///
    ///     Ok(())
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns an error if the default backends cannot be initialized.
    pub async fn build(self) -> Result<CacheSystem> {
        info!("Building Multi-Tier Cache System");

        if !self.tiers.is_empty() {
            self.build_multi_tier()
        } else if self.l1_backend.is_none() && self.l2_backend.is_none() {
            self.build_default_2_tier().await
        } else {
            self.build_custom_2_tier().await
        }
    }

    /// Internal helper for multi-tier mode (v0.5.0+)
    fn build_multi_tier(self) -> Result<CacheSystem> {
        info!(
            tier_count = self.tiers.len(),
            "Initializing multi-tier architecture"
        );

        // Sort tiers by tier_level (ascending: L1 first, L4 last)
        let mut tiers = self.tiers;
        tiers.sort_by_key(|(_, config)| config.tier_level);

        // Convert to CacheTier instances
        let cache_tiers: Vec<CacheTier> = tiers
            .into_iter()
            .map(|(backend, config)| {
                CacheTier::new(
                    backend,
                    config.tier_level,
                    config.promotion_enabled,
                    config.promotion_frequency,
                    config.ttl_scale,
                )
            })
            .collect();

        // Create cache manager with multi-tier support
        let cache_manager = Arc::new(CacheManager::new_with_tiers(
            cache_tiers,
            self.streaming_backend,
        )?);

        info!("Multi-Tier Cache System built successfully");
        info!("Note: Using multi-tier mode - use cache_manager() for all operations");

        Ok(CacheSystem {
            cache_manager,
            #[cfg(feature = "moka")]
            #[cfg_attr(docsrs, doc(cfg(feature = "moka")))]
            l1_cache: None,
            #[cfg(feature = "redis")]
            #[cfg_attr(docsrs, doc(cfg(feature = "redis")))]
            l2_cache: None,
        })
    }

    /// Internal helper for legacy default 2-tier mode
    async fn build_default_2_tier(self) -> Result<CacheSystem> {
        info!("Initializing default backends (Moka + Redis)");

        #[cfg(all(feature = "moka", feature = "redis"))]
        #[cfg_attr(docsrs, doc(cfg(all(feature = "moka", feature = "redis"))))]
        {
            let l1_cache = Arc::new(crate::L1Cache::new(self.moka_config.unwrap_or_default())?);
            let l2_cache: Arc<crate::L2Cache> = Arc::new(crate::L2Cache::new().await?);

            // Use legacy constructor that handles conversion to trait objects
            let cache_manager = Arc::new(CacheManager::new(l1_cache.clone(), l2_cache.clone()).await?);

            info!("Multi-Tier Cache System built successfully");

            Ok(CacheSystem {
                cache_manager,
                #[cfg(feature = "moka")]
                #[cfg_attr(docsrs, doc(cfg(feature = "moka")))]
                l1_cache: Some(l1_cache),
                #[cfg(feature = "redis")]
                #[cfg_attr(docsrs, doc(cfg(feature = "redis")))]
                l2_cache: Some(l2_cache),
            })
        }
        #[cfg(not(all(feature = "moka", feature = "redis")))]
        {
            Err(anyhow::anyhow!(
                "Default backends (Moka/Redis) are not enabled. Provide custom backends or enable 'moka' and 'redis' features."
            ))
        }
    }

    /// Internal helper for legacy custom 2-tier mode
    async fn build_custom_2_tier(self) -> Result<CacheSystem> {
        info!("Building with custom backends");

        let l1_backend: Arc<dyn CacheBackend> = if let Some(backend) = self.l1_backend {
            backend
        } else {
            #[cfg(feature = "moka")]
            #[cfg_attr(docsrs, doc(cfg(feature = "moka")))]
            {
                Arc::new(L1Cache::new(self.moka_config.unwrap_or_default())?)
            }
            #[cfg(not(feature = "moka"))]
            {
                return Err(anyhow::anyhow!(
                    "Moka feature not enabled. Provide a custom L1 backend."
                ));
            }
        };

        let l2_backend: Arc<dyn L2CacheBackend> = if let Some(backend) = self.l2_backend {
            backend
        } else {
            #[cfg(feature = "redis")]
            #[cfg_attr(docsrs, doc(cfg(feature = "redis")))]
            {
                Arc::new(L2Cache::new().await?)
            }
            #[cfg(not(feature = "redis"))]
            {
                return Err(anyhow::anyhow!(
                    "Redis feature not enabled. Provide a custom L2 backend."
                ));
            }
        };

        let streaming_backend = self.streaming_backend;

        // Create cache manager with trait objects
        let cache_manager = Arc::new(CacheManager::new_with_backends(
            l1_backend,
            l2_backend,
            streaming_backend,
        )?);

        info!("Multi-Tier Cache System built with custom backends");
        info!("Note: Using custom backends - use cache_manager() for all operations");

        Ok(CacheSystem {
            cache_manager,
            #[cfg(feature = "moka")]
            #[cfg_attr(docsrs, doc(cfg(feature = "moka")))]
            l1_cache: None,
            #[cfg(feature = "redis")]
            #[cfg_attr(docsrs, doc(cfg(feature = "redis")))]
            l2_cache: None,
        })
    }
}

impl Default for CacheSystemBuilder {
    fn default() -> Self {
        Self::new()
    }
}