dmsc 0.1.9

Ri - A high-performance Rust middleware framework with modular architecture
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
//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
//!
//! This file is part of Ri.
//! The Ri project belongs to the Dunimd Team.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! You may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//!     http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.

//! # Cache Module
//! 
//! This module provides a comprehensive caching abstraction for Ri, offering a unified interface
//! with support for multiple backend implementations. It enables efficient data caching with
//! configurable policies and backend selection.
//! 
//! ## Key Components
//! 
//! - **RiCacheModule**: Main cache module implementing both sync and async service module traits
//! - **RiCacheManager**: Central cache management component
//! - **RiCache**: Unified cache interface implemented by all backends
//! - **RiCacheConfig**: Configuration for cache behavior
//! - **Backend Implementations**:
//!   - **RiMemoryCache**: In-memory cache implementation (internal)
//!   - **RiRedisCache**: Redis-based distributed cache (internal)
//!   - **RiHybridCache**: Combined memory and Redis cache for optimal performance (internal)
//! 
//! ## Design Principles
//! 
//! 1. **Unified Interface**: Consistent API across all backend implementations
//! 2. **Multiple Backends**: Support for different cache storage options
//! 3. **Async Support**: Full async/await compatibility
//! 4. **Configurable**: Highly configurable cache behavior
//! 5. **Non-critical**: Cache failures should not break the application
//! 6. **Stats Collection**: Built-in cache statistics for monitoring
//! 7. **Service Module Integration**: Implements both sync and async service module traits
//! 8. **Thread-safe**: Safe for concurrent use across multiple threads
//! 
//! ## Usage
//! 
//! ```rust,ignore
//! use ri::prelude::*;
//! 
//! async fn example() -> RiResult<()> {
//!     // Create cache configuration
//!     let cache_config = RiCacheConfig {
//!         enabled: true,
//!         default_ttl_secs: 3600,
//!         max_memory_mb: 512,
//!         cleanup_interval_secs: 300,
//!         backend_type: RiCacheBackendType::Memory,
//!         redis_url: "redis://127.0.0.1:6379".to_string(),
//!         redis_pool_size: 10,
//!     };
//!     
//!     // Create cache module
//!     let cache_module = RiCacheModule::new(cache_config);
//!     
//!     // Get cache manager
//!     let cache_manager = cache_module.cache_manager();
//!     
//!     // Use cache manager to get cache instance
//!     let cache = cache_manager.read().await.get_cache();
//!     
//!     // Set a value in cache
//!     cache.set("key", "value", Some(3600)).await?;
//!     
//!     // Get a value from cache
//!     let value = cache.get("key").await?;
//!     println!("Cached value: {:?}", value);
//!     
//!     Ok(())
//! }
//! ```

mod core;
mod manager;
mod backends;
mod config;

pub use config::{RiCacheConfig, RiCacheBackendType, RiCachePolicy};
pub use manager::{RiCacheManager, RiCacheEvent};
pub use core::{RiCachedValue, RiCacheStats, RiCache, RiCacheEvent as CoreCacheEvent};
// Re-export backend implementations
pub use backends::RiMemoryCache;
#[cfg(feature = "redis")]
pub use backends::{RiRedisCache, RiHybridCache};

use crate::core::{RiResult, RiServiceContext};
use std::sync::Arc;
use tokio::sync::RwLock;

#[cfg(feature = "pyo3")]
use pyo3::pymethods;

/// Main cache module for Ri.
/// 
/// This module provides a unified caching abstraction with support for multiple backend implementations.
/// It implements both the `AsyncServiceModule` and `ServiceModule` traits for seamless integration
/// into the Ri application lifecycle.
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiCacheModule {
    /// Cache configuration
    config: RiCacheConfig,
    /// Cache manager wrapped in an async RwLock for thread-safe access
    manager: std::sync::Arc<tokio::sync::RwLock<RiCacheManager>>,
}

impl RiCacheModule {
    /// Creates a new cache module with the given configuration.
    /// 
    /// This method initializes the cache manager with the appropriate backend based on the
    /// provided configuration. The backend is created immediately, not as a placeholder.
    /// 
    /// # Parameters
    /// 
    /// - `config`: The cache configuration to use
    /// 
    /// # Returns
    /// 
    /// A new `RiCacheModule` instance
    pub async fn new(config: RiCacheConfig) -> Self {
        #[cfg(feature = "redis")]
        let backend: std::sync::Arc<dyn crate::cache::RiCache> = match config.backend_type {
            crate::cache::config::RiCacheBackendType::Memory => {
                std::sync::Arc::new(RiMemoryCache::new())
            }
            crate::cache::config::RiCacheBackendType::Redis => {
                match RiRedisCache::new(&config.redis_url).await {
                    Ok(cache) => Arc::new(cache),
                    Err(e) => {
                        log::warn!("Failed to create Redis cache ({}): {}. Falling back to memory backend", config.redis_url, e);
                        Arc::new(RiMemoryCache::new()) as Arc<dyn crate::cache::RiCache>
                    }
                }
            }
            crate::cache::config::RiCacheBackendType::Hybrid => {
                match RiHybridCache::new(&config.redis_url).await {
                    Ok(backend) => Arc::new(backend),
                    Err(e) => {
                        log::warn!("Failed to create hybrid cache backend (Redis URL: {}): {}. Falling back to memory backend", config.redis_url, e);
                        Arc::new(RiMemoryCache::new()) as Arc<dyn crate::cache::RiCache>
                    }
                }
            }
        };

        #[cfg(not(feature = "redis"))]
        let backend: std::sync::Arc<dyn crate::cache::RiCache> = match config.backend_type {
            crate::cache::config::RiCacheBackendType::Memory => {
                std::sync::Arc::new(RiMemoryCache::new())
            }
            crate::cache::config::RiCacheBackendType::Redis | crate::cache::config::RiCacheBackendType::Hybrid => {
                std::sync::Arc::new(RiMemoryCache::new())
            }
        };

        let manager = RiCacheManager::new(backend);

        Self {
            config,
            manager: Arc::new(RwLock::new(manager)),
        }
    }

    /// Creates a new cache module with the given configuration (synchronous version).
    /// 
    /// This is a synchronous wrapper around the async `new` method for use in the builder pattern.
    /// For Redis and Hybrid backends, it will block on the current thread to create the backend.
    /// 
    /// # Parameters
    /// 
    /// - `config`: The cache configuration to use
    /// 
    /// # Returns
    /// 
    /// A new `RiCacheModule` instance
    pub fn with_config(config: RiCacheConfig) -> Self {
        #[cfg(feature = "redis")]
        let backend: std::sync::Arc<dyn crate::cache::RiCache> = match config.backend_type {
            crate::cache::config::RiCacheBackendType::Memory => {
                std::sync::Arc::new(RiMemoryCache::new())
            }
            crate::cache::config::RiCacheBackendType::Redis => {
                match tokio::runtime::Handle::try_current() {
                    Ok(handle) => {
                        match handle.block_on(RiRedisCache::new(&config.redis_url)) {
                            Ok(cache) => Arc::new(cache),
                            Err(e) => {
                                log::warn!("Failed to create Redis cache ({}): {}. Falling back to memory backend", config.redis_url, e);
                                Arc::new(RiMemoryCache::new()) as Arc<dyn crate::cache::RiCache>
                            }
                        }
                    }
                    Err(_) => {
                        log::warn!("No Tokio runtime available for Redis cache creation. Falling back to memory backend");
                        Arc::new(RiMemoryCache::new()) as Arc<dyn crate::cache::RiCache>
                    }
                }
            }
            crate::cache::config::RiCacheBackendType::Hybrid => {
                match tokio::runtime::Handle::try_current() {
                    Ok(handle) => {
                        match handle.block_on(RiHybridCache::new(&config.redis_url)) {
                            Ok(backend) => Arc::new(backend),
                            Err(e) => {
                                log::warn!("Failed to create hybrid cache backend (Redis URL: {}): {}. Falling back to memory backend", config.redis_url, e);
                                Arc::new(RiMemoryCache::new()) as Arc<dyn crate::cache::RiCache>
                            }
                        }
                    }
                    Err(_) => {
                        log::warn!("No Tokio runtime available for hybrid cache creation. Falling back to memory backend");
                        Arc::new(RiMemoryCache::new()) as Arc<dyn crate::cache::RiCache>
                    }
                }
            }
        };

        #[cfg(not(feature = "redis"))]
        let backend: std::sync::Arc<dyn crate::cache::RiCache> = match config.backend_type {
            crate::cache::config::RiCacheBackendType::Memory => {
                std::sync::Arc::new(RiMemoryCache::new())
            }
            crate::cache::config::RiCacheBackendType::Redis | crate::cache::config::RiCacheBackendType::Hybrid => {
                log::warn!("Redis feature not enabled. Falling back to memory backend");
                std::sync::Arc::new(RiMemoryCache::new())
            }
        };

        let manager = RiCacheManager::new(backend);

        Self {
            config,
            manager: Arc::new(RwLock::new(manager)),
        }
    }
    
    /// Returns a reference to the cache manager.
    /// 
    /// The cache manager is wrapped in an Arc<RwLock<>> to allow thread-safe access
    /// from multiple async tasks.
    /// 
    /// # Returns
    /// 
    /// An Arc<RwLock<RiCacheManager>> providing thread-safe access to the cache manager
    pub fn cache_manager(&self) -> Arc<RwLock<RiCacheManager>> {
        self.manager.clone()
    }
}

#[cfg(feature = "pyo3")]
#[pymethods]
impl RiCacheModule {
    #[new]
    fn py_new(config: RiCacheConfig) -> Result<Self, pyo3::PyErr> {
        let rt = match tokio::runtime::Runtime::new() {
            Ok(r) => r,
            Err(e) => {
                return Err(pyo3::PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                    format!("Failed to create runtime: {}", e),
                ));
            }
        };
        rt.block_on(async {
            Ok(Self::new(config).await)
        })
    }
    
    /// Get cache manager status for Python (Python wrapper)
    fn get_cache_manager_status(&self) -> String {
        format!("Cache manager initialized with backend: {:?}", self.config.backend_type)
    }
}

#[async_trait::async_trait]
impl crate::core::RiModule for RiCacheModule {
    /// Returns the name of the cache module.
    /// 
    /// # Returns
    /// 
    /// The module name as a string
    fn name(&self) -> &str {
        "Ri.Cache"
    }
    
    /// Indicates whether the cache module is critical.
    /// 
    /// The cache module is non-critical, meaning that if it fails to initialize or operate,
    /// it should not break the entire application. This allows the core functionality to continue
    /// even if caching features are unavailable.
    /// 
    /// # Returns
    /// 
    /// `false` since cache is non-critical
    fn is_critical(&self) -> bool {
        false // Cache failures should not break the application
    }
    
    /// Initializes the cache module asynchronously.
    /// 
    /// This method performs the following steps:
    /// 1. Loads configuration from the service context
    /// 2. Updates the module configuration if provided
    /// 3. Initializes the appropriate cache backend based on configuration
    /// 4. Creates and sets the cache manager with the initialized backend
    /// 
    /// # Parameters
    /// 
    /// - `ctx`: The service context containing configuration and other services
    /// 
    /// # Returns
    /// 
    /// A `RiResult<()>` indicating success or failure
    async fn init(&mut self, ctx: &mut RiServiceContext) -> RiResult<()> {
        log::info!("Initializing Ri Cache Module");
        
        // Load configuration
        let binding = ctx.config();
        let cfg = binding.config();
        
        // Update configuration if provided
        if let Some(cache_config) = cfg.get("cache") {
            self.config = serde_yaml::from_str(cache_config)
                .unwrap_or_else(|_| RiCacheConfig::default());
        } else {
            self.config = RiCacheConfig::default();
        }
        
        // Initialize the cache manager based on configuration
        match self.config.backend_type {
            crate::cache::config::RiCacheBackendType::Memory => {
                let backend = Arc::new(RiMemoryCache::new());
                let manager = RiCacheManager::new(backend);
                *self.manager.write().await = manager;
            }
            #[cfg(feature = "redis")]
            crate::cache::config::RiCacheBackendType::Redis => {
                let backend = Arc::new(RiRedisCache::new(&self.config.redis_url).await?);
                let manager = RiCacheManager::new(backend);
                *self.manager.write().await = manager;
            }
            #[cfg(feature = "redis")]
            crate::cache::config::RiCacheBackendType::Hybrid => {
                let backend = Arc::new(RiHybridCache::new(&self.config.redis_url).await?);
                let manager = RiCacheManager::new(backend);
                *self.manager.write().await = manager;
            }
            #[cfg(not(feature = "redis"))]
            crate::cache::config::RiCacheBackendType::Redis | crate::cache::config::RiCacheBackendType::Hybrid => {
                // Fallback to memory cache if Redis is not enabled
                let backend = Arc::new(RiMemoryCache::new());
                let manager = RiCacheManager::new(backend);
                *self.manager.write().await = manager;
            }
        }
        
                // Log successful initialization
        if let Ok(fs) = crate::fs::RiFileSystem::new_auto_root() {
            let logger = crate::log::RiLogger::new(&crate::log::RiLogConfig::default(), fs);
            let _ = logger.info("cache", "Ri Cache Module initialized successfully");
        }
        Ok(())
    }
    
    /// Performs asynchronous cleanup after the application has shut down.
    /// 
    /// This method performs the following steps:
    /// 1. Prints cache statistics
    /// 2. Cleans up expired cache entries
    /// 3. Prints cleanup results
    /// 
    /// # Parameters
    /// 
    /// - `_ctx`: The service context (not used in this implementation)
    /// 
    /// # Returns
    /// 
    /// A `RiResult<()>` indicating success or failure
    async fn after_shutdown(&mut self, _ctx: &mut RiServiceContext) -> RiResult<()> {
        log::info!("Cleaning up Ri Cache Module");
        
        let manager = self.manager.read().await;
        let stats = manager.stats().await;
        log::info!("Cache stats: {stats:?}");
        
        // Cleanup expired entries
        let cleaned = manager.cleanup_expired().await?;
        log::info!("Cleaned up {cleaned} expired cache entries");
        log::info!("Ri Cache Module cleanup completed");
        Ok(())
    }
}

impl crate::core::ServiceModule for RiCacheModule {
    fn name(&self) -> &str {
        "Ri.Cache"
    }

    fn is_critical(&self) -> bool {
        false
    }

    fn priority(&self) -> i32 {
        10
    }

    fn dependencies(&self) -> Vec<&str> {
        vec![]
    }

    fn init(&mut self, _ctx: &mut crate::core::RiServiceContext) -> crate::core::RiResult<()> {
        Ok(())
    }

    fn start(&mut self, _ctx: &mut crate::core::RiServiceContext) -> crate::core::RiResult<()> {
        Ok(())
    }

    fn shutdown(&mut self, _ctx: &mut crate::core::RiServiceContext) -> crate::core::RiResult<()> {
        Ok(())
    }
}