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
//! 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.

#![allow(non_snake_case)]

//! # In-memory Cache Backend
//! 
//! This module provides an in-memory cache implementation using DashMap for high performance
//! and thread safety. It implements the RiCache trait, providing all standard cache operations
//! with automatic expiration handling and comprehensive statistics.
//! 
//! ## Key Features
//! 
//! - **High Performance**: Uses DashMap for concurrent access without blocking
//! - **Automatic Expiration**: Automatically removes expired entries on access
//! - **Comprehensive Statistics**: Tracks hit count, miss count, and eviction count
//! - **Thread Safe**: Safe for concurrent access from multiple threads
//! - **LRU-like Behavior**: Touches entries on access to support LRU eviction (if implemented)
//! - **Expired Entry Cleanup**: Provides a method to explicitly cleanup all expired entries
//! 
//! ## Design Principles
//! 
//! 1. **Non-blocking**: Uses DashMap for lock-free concurrent access
//! 2. **Automatic Expiration**: Expired entries are removed when accessed
//! 3. **Statistics-driven**: Comprehensive cache statistics for monitoring
//! 4. **Simple API**: Implements the standard RiCache trait
//! 5. **Memory Efficient**: Automatically cleans up expired entries
//! 6. **Thread-safe**: Safe for use in multi-threaded applications
//! 7. **Fast Access**: In-memory storage for minimal latency
//! 8. **Easy to Use**: Simple constructor with no configuration required
//! 
//! ## Usage
//! 
//! ```rust
//! use ri::prelude::*;
//! use std::time::Duration;
//! 
//! async fn example() -> RiResult<()> {
//!     // Create a new in-memory cache
//!     let cache = RiMemoryCache::new();
//!     
//!     // Create a cached value with 1-hour expiration
//!     let value = RiCachedValue::new(b"test_value".to_vec(), Duration::from_secs(3600));
//!     
//!     // Set the value in the cache
//!     cache.set("test_key", value).await?;
//!     
//!     // Get the value from the cache
//!     if let Some(retrieved_value) = cache.get("test_key").await {
//!         println!("Retrieved value: {:?}", retrieved_value.payload);
//!     }
//!     
//!     // Check if a key exists
//!     if cache.exists("test_key").await {
//!         println!("Key exists in cache");
//!     }
//!     
//!     // Get cache statistics
//!     let stats = cache.stats().await;
//!     println!("Cache hit rate: {:.2}%", stats.avg_hit_rate * 100.0);
//!     
//!     // Cleanup expired entries
//!     let cleaned = cache.cleanup_expired().await?;
//!     println!("Cleaned up {} expired entries", cleaned);
//!     
//!     Ok(())
//! }
//! ```

use dashmap::DashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use crate::cache::{RiCache, RiCachedValue, RiCacheStats};
use crate::core::RiResult;

/// Atomic cache statistics for lock-free performance tracking.
struct AtomicCacheStats {
    hits: AtomicU64,
    misses: AtomicU64,
    entries: AtomicUsize,
    memory_usage_bytes: AtomicUsize,
    eviction_count: AtomicU64,
}

impl AtomicCacheStats {
    fn new() -> Self {
        Self {
            hits: AtomicU64::new(0),
            misses: AtomicU64::new(0),
            entries: AtomicUsize::new(0),
            memory_usage_bytes: AtomicUsize::new(0),
            eviction_count: AtomicU64::new(0),
        }
    }

    fn increment_hits(&self) {
        self.hits.fetch_add(1, Ordering::Relaxed);
    }

    fn increment_misses(&self) {
        self.misses.fetch_add(1, Ordering::Relaxed);
    }

    #[allow(dead_code)]
    fn increment_evictions(&self) {
        self.eviction_count.fetch_add(1, Ordering::Relaxed);
    }

    fn to_cache_stats(&self) -> RiCacheStats {
        let hits = self.hits.load(Ordering::Relaxed);
        let misses = self.misses.load(Ordering::Relaxed);
        let total = hits + misses;
        let avg_hit_rate = if total > 0 {
            hits as f64 / total as f64
        } else {
            0.0
        };

        RiCacheStats {
            hits,
            misses,
            entries: self.entries.load(Ordering::Relaxed),
            memory_usage_bytes: self.memory_usage_bytes.load(Ordering::Relaxed),
            avg_hit_rate,
            hit_count: hits,
            miss_count: misses,
            eviction_count: self.eviction_count.load(Ordering::Relaxed),
        }
    }
}

/// In-memory cache implementation using DashMap for high performance and thread safety.
///
/// This struct provides an in-memory cache with automatic expiration handling, comprehensive
/// statistics, and thread-safe concurrent access.
pub struct RiMemoryCache {
    /// Underlying storage using DashMap for concurrent access
    store: Arc<DashMap<String, RiCachedValue>>,
    /// Cache statistics using atomic operations for lock-free performance
    stats: Arc<AtomicCacheStats>,
}

/// Maximum key length in bytes (1 KB)
const MAX_KEY_LENGTH: usize = 1024;
/// Maximum value length in bytes (10 MB)
const MAX_VALUE_LENGTH: usize = 10 * 1024 * 1024;
/// Maximum number of entries in cache (100,000)
const MAX_ENTRIES: usize = 100_000;

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

impl RiMemoryCache {
    /// Creates a new in-memory cache instance.
    ///
    /// # Returns
    ///
    /// A new RiMemoryCache instance
    pub fn new() -> Self {
        RiMemoryCache {
            store: Arc::new(DashMap::new()),
            stats: Arc::new(AtomicCacheStats::new()),
        }
    }

    /// Validates a cache key to prevent injection and memory exhaustion attacks.
    ///
    /// # Security
    ///
    /// Keys must:
    /// - Not be empty
    /// - Not exceed MAX_KEY_LENGTH (1 KB)
    /// - Not contain control characters
    /// - Not contain null bytes
    fn validate_key(key: &str) -> crate::core::RiResult<()> {
        if key.is_empty() {
            return Err(crate::core::RiError::Other(
                "Cache key cannot be empty".to_string()
            ));
        }

        if key.len() > MAX_KEY_LENGTH {
            return Err(crate::core::RiError::Other(format!(
                "Cache key too long: {} bytes (max {} bytes)",
                key.len(), MAX_KEY_LENGTH
            )));
        }

        // Check for control characters and null bytes
        for c in key.chars() {
            if c.is_control() || c == '\0' {
                return Err(crate::core::RiError::Other(
                    "Cache key contains invalid characters (control characters or null bytes)".to_string()
                ));
            }
        }

        Ok(())
    }

    /// Validates a cache value to prevent memory exhaustion attacks.
    ///
    /// # Security
    ///
    /// Values must not exceed MAX_VALUE_LENGTH (10 MB)
    fn validate_value(value: &str) -> crate::core::RiResult<()> {
        if value.len() > MAX_VALUE_LENGTH {
            return Err(crate::core::RiError::Other(format!(
                "Cache value too large: {} bytes (max {} bytes)",
                value.len(), MAX_VALUE_LENGTH
            )));
        }

        Ok(())
    }

    /// Checks if adding a new entry would exceed the maximum entry count.
    fn check_entry_limit(&self) -> crate::core::RiResult<()> {
        let current_entries = self.store.len();
        if current_entries >= MAX_ENTRIES {
            return Err(crate::core::RiError::Other(format!(
                "Cache entry limit reached: {} entries (max {} entries)",
                current_entries, MAX_ENTRIES
            )));
        }

        Ok(())
    }
}

#[async_trait::async_trait]
impl RiCache for RiMemoryCache {
    /// Gets a value from the cache by key.
    ///
    /// This method checks if the value exists and is not expired. If the value is expired,
    /// it is removed from the cache and None is returned. Otherwise, the value is returned
    /// and its last access time is updated.
    ///
    /// # Parameters
    ///
    /// - `key`: The key to retrieve
    ///
    /// # Returns
    ///
    /// An `Option<RiCachedValue>` containing the value if it exists and is not expired, or None otherwise
    async fn get(&self, key: &str) -> RiResult<Option<String>> {
        match self.store.get(key) {
            Some(entry) => {
                let value = entry.clone();
                if value.is_expired() {
                    drop(entry);
                    self.store.remove(key);
                    self.stats.increment_misses();
                    Ok(None)
                } else {
                    self.stats.increment_hits();
                    Ok(Some(value.value))
                }
            }
            None => {
                self.stats.increment_misses();
                Ok(None)
            }
        }
    }
    
    /// Sets a value in the cache with the given key.
    ///
    /// # Security
    ///
    /// This method validates:
    /// - Key length (max 1 KB)
    /// - Value length (max 10 MB)
    /// - Entry count (max 100,000 entries)
    /// - Key format (no control characters or null bytes)
    ///
    /// # Parameters
    ///
    /// - `key`: The key to set
    /// - `value`: The cached value to store
    ///
    /// # Returns
    ///
    /// A `RiResult<()>` indicating success or failure
    async fn set(&self, key: &str, value: &str, ttl_seconds: Option<u64>) -> crate::core::RiResult<()> {
        // Security: Validate key and value
        Self::validate_key(key)?;
        Self::validate_value(value)?;
        self.check_entry_limit()?;
        
        let cached_value = RiCachedValue::new(value.to_string(), ttl_seconds);
        self.store.insert(key.to_string(), cached_value);
        Ok(())
    }
    
    /// Deletes a value from the cache by key.
    ///
    /// # Parameters
    ///
    /// - `key`: The key to delete
    ///
    /// # Returns
    ///
    /// A `RiResult<bool>` indicating whether the key was found and deleted
    async fn delete(&self, key: &str) -> crate::core::RiResult<bool> {
        Ok(self.store.remove(key).is_some())
    }
    
    /// Checks if a key exists in the cache and is not expired.
    ///
    /// If the key exists but the value is expired, it is removed from the cache and false is returned.
    ///
    /// # Parameters
    ///
    /// - `key`: The key to check
    ///
    /// # Returns
    ///
    /// `true` if the key exists and is not expired, `false` otherwise
    async fn exists(&self, key: &str) -> bool {
        if let Some(entry) = self.store.get(key) {
            if entry.is_expired() {
                drop(entry);
                self.store.remove(key);
                false
            } else {
                true
            }
        } else {
            false
        }
    }
    
    /// Clears all entries from the cache.
    ///
    /// # Returns
    ///
    /// A `RiResult<()>` indicating success or failure
    async fn clear(&self) -> crate::core::RiResult<()> {
        self.store.clear();
        Ok(())
    }
    
    /// Gets cache statistics.
    ///
    /// # Returns
    ///
    /// A `RiCacheStats` struct containing cache statistics
    async fn stats(&self) -> RiCacheStats {
        let mut stats = self.stats.to_cache_stats();
        stats.entries = self.store.len();
        stats
    }
    
    /// Cleans up all expired entries from the cache.
    ///
    /// # Returns
    ///
    /// A `RiResult<usize>` containing the number of expired entries cleaned up
    async fn cleanup_expired(&self) -> crate::core::RiResult<usize> {
        let mut cleaned = 0;
        let keys: Vec<String> = self.store.iter().map(|entry| entry.key().clone()).collect();
        
        for key in keys {
            if let Some(entry) = self.store.get(&key) {
                if entry.is_expired() {
                    drop(entry);
                    self.store.remove(&key);
                    cleaned += 1;
                }
            }
        }
        
        Ok(cleaned)
    }

    /// Gets all keys from the cache.
    ///
    /// # Returns
    ///
    /// A `RiResult<Vec<String>>` containing all cache keys
    async fn keys(&self) -> crate::core::RiResult<Vec<String>> {
        let keys: Vec<String> = self.store.iter().map(|entry| entry.key().clone()).collect();
        Ok(keys)
    }
}