celers-backend-redis 0.2.0

Redis result backend for CeleRS
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
//! In-memory result cache for Redis backend
//!
//! This module provides an optional LRU cache layer that sits in front of Redis
//! to reduce latency and Redis load for frequently accessed task results.
//!
//! # Example
//!
//! ```
//! use celers_backend_redis::cache::{ResultCache, CacheConfig};
//! use std::time::Duration;
//!
//! // Create a cache with 1000 entry capacity and 5 minute TTL
//! let config = CacheConfig::new()
//!     .with_capacity(1000)
//!     .with_ttl(Duration::from_secs(300));
//!
//! let cache = ResultCache::new(config);
//! ```

use crate::TaskMeta;
use chrono::{DateTime, Utc};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use uuid::Uuid;

/// Cache entry with metadata
#[derive(Debug, Clone)]
struct CacheEntry {
    /// Cached task metadata
    data: TaskMeta,
    /// When this entry was cached
    cached_at: DateTime<Utc>,
    /// Number of times this entry has been accessed
    access_count: u64,
}

impl CacheEntry {
    fn new(data: TaskMeta) -> Self {
        Self {
            data,
            cached_at: Utc::now(),
            access_count: 0,
        }
    }

    fn is_expired(&self, ttl: Duration) -> bool {
        let age = Utc::now() - self.cached_at;
        age.num_milliseconds() > ttl.as_millis() as i64
    }

    fn access(&mut self) -> TaskMeta {
        self.access_count += 1;
        self.data.clone()
    }
}

/// Cache configuration
#[derive(Debug, Clone)]
pub struct CacheConfig {
    /// Maximum number of entries to cache
    pub capacity: usize,

    /// Time-to-live for cache entries
    pub ttl: Duration,

    /// Enable the cache
    pub enabled: bool,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            capacity: 1000,
            ttl: Duration::from_secs(300), // 5 minutes
            enabled: true,
        }
    }
}

impl CacheConfig {
    /// Create new cache configuration with defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Disable the cache
    pub fn disabled() -> Self {
        Self {
            capacity: 0,
            ttl: Duration::from_secs(0),
            enabled: false,
        }
    }

    /// Set cache capacity
    pub fn with_capacity(mut self, capacity: usize) -> Self {
        self.capacity = capacity;
        self
    }

    /// Set cache TTL
    pub fn with_ttl(mut self, ttl: Duration) -> Self {
        self.ttl = ttl;
        self
    }

    /// Enable or disable the cache
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
}

/// In-memory result cache
///
/// Thread-safe LRU cache with time-based expiration.
#[derive(Debug, Clone)]
pub struct ResultCache {
    config: CacheConfig,
    entries: Arc<RwLock<HashMap<Uuid, CacheEntry>>>,
}

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

impl ResultCache {
    /// Create a new result cache with the given configuration
    pub fn new(config: CacheConfig) -> Self {
        Self {
            config,
            entries: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Create a disabled cache (no-op)
    pub fn disabled() -> Self {
        Self::new(CacheConfig::disabled())
    }

    /// Check if the cache is enabled
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Get the cache configuration
    pub fn config(&self) -> &CacheConfig {
        &self.config
    }

    /// Get a result from the cache
    ///
    /// Returns `None` if the entry is not in the cache or has expired.
    pub fn get(&self, task_id: Uuid) -> Option<TaskMeta> {
        if !self.config.enabled {
            return None;
        }

        let mut entries = self.entries.write().ok()?;

        if let Some(entry) = entries.get_mut(&task_id) {
            if entry.is_expired(self.config.ttl) {
                // Entry expired, remove it
                entries.remove(&task_id);
                return None;
            }
            // Entry is valid, return it
            Some(entry.access())
        } else {
            None
        }
    }

    /// Put a result into the cache
    ///
    /// If the cache is full, removes the oldest entry.
    pub fn put(&self, task_id: Uuid, meta: TaskMeta) {
        if !self.config.enabled {
            return;
        }

        let mut entries = self.entries.write().expect("lock should not be poisoned");

        // If at capacity, remove oldest entry
        if entries.len() >= self.config.capacity && !entries.contains_key(&task_id) {
            self.evict_oldest(&mut entries);
        }

        entries.insert(task_id, CacheEntry::new(meta));
    }

    /// Invalidate (remove) a cache entry
    pub fn invalidate(&self, task_id: Uuid) {
        if !self.config.enabled {
            return;
        }

        if let Ok(mut entries) = self.entries.write() {
            entries.remove(&task_id);
        }
    }

    /// Clear all cache entries
    pub fn clear(&self) {
        if let Ok(mut entries) = self.entries.write() {
            entries.clear();
        }
    }

    /// Get the number of cached entries
    pub fn len(&self) -> usize {
        self.entries.read().map(|e| e.len()).unwrap_or(0)
    }

    /// Check if the cache is empty
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Remove expired entries from the cache
    ///
    /// This should be called periodically to prevent memory leaks.
    pub fn cleanup_expired(&self) -> usize {
        if !self.config.enabled {
            return 0;
        }

        let mut entries = match self.entries.write() {
            Ok(e) => e,
            Err(_) => return 0,
        };

        let before_count = entries.len();

        // Collect expired keys
        let expired_keys: Vec<Uuid> = entries
            .iter()
            .filter(|(_, entry)| entry.is_expired(self.config.ttl))
            .map(|(key, _)| *key)
            .collect();

        // Remove expired entries
        for key in expired_keys {
            entries.remove(&key);
        }

        before_count - entries.len()
    }

    /// Evict the oldest entry based on cached_at timestamp
    fn evict_oldest(&self, entries: &mut HashMap<Uuid, CacheEntry>) {
        if let Some((&oldest_key, _)) = entries.iter().min_by_key(|(_, entry)| entry.cached_at) {
            entries.remove(&oldest_key);
        }
    }

    /// Get cache statistics
    pub fn stats(&self) -> CacheStats {
        let entries = match self.entries.read() {
            Ok(e) => e,
            Err(_) => {
                return CacheStats {
                    size: 0,
                    capacity: self.config.capacity,
                    expired_count: 0,
                }
            }
        };

        let expired_count = entries
            .values()
            .filter(|entry| entry.is_expired(self.config.ttl))
            .count();

        CacheStats {
            size: entries.len(),
            capacity: self.config.capacity,
            expired_count,
        }
    }
}

/// Cache statistics
#[derive(Debug, Clone)]
pub struct CacheStats {
    /// Current number of entries in cache
    pub size: usize,
    /// Maximum cache capacity
    pub capacity: usize,
    /// Number of expired entries
    pub expired_count: usize,
}

impl std::fmt::Display for CacheStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Cache: {}/{} entries ({} expired)",
            self.size, self.capacity, self.expired_count
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cache_config_defaults() {
        let config = CacheConfig::default();
        assert_eq!(config.capacity, 1000);
        assert_eq!(config.ttl.as_secs(), 300);
        assert!(config.enabled);
    }

    #[test]
    fn test_cache_config_builder() {
        let config = CacheConfig::new()
            .with_capacity(500)
            .with_ttl(Duration::from_secs(60))
            .with_enabled(true);

        assert_eq!(config.capacity, 500);
        assert_eq!(config.ttl.as_secs(), 60);
        assert!(config.enabled);
    }

    #[test]
    fn test_cache_disabled() {
        let cache = ResultCache::disabled();
        assert!(!cache.is_enabled());

        let task_id = Uuid::new_v4();
        let meta = TaskMeta::new(task_id, "test".to_string());

        cache.put(task_id, meta.clone());
        assert!(cache.get(task_id).is_none());
    }

    #[test]
    fn test_cache_put_and_get() {
        let cache = ResultCache::new(CacheConfig::new());
        let task_id = Uuid::new_v4();
        let meta = TaskMeta::new(task_id, "test".to_string());

        cache.put(task_id, meta.clone());
        let result = cache.get(task_id);

        assert!(result.is_some());
        assert_eq!(result.unwrap().task_id, task_id);
    }

    #[test]
    fn test_cache_miss() {
        let cache = ResultCache::new(CacheConfig::new());
        let task_id = Uuid::new_v4();

        assert!(cache.get(task_id).is_none());
    }

    #[test]
    fn test_cache_invalidate() {
        let cache = ResultCache::new(CacheConfig::new());
        let task_id = Uuid::new_v4();
        let meta = TaskMeta::new(task_id, "test".to_string());

        cache.put(task_id, meta.clone());
        assert!(cache.get(task_id).is_some());

        cache.invalidate(task_id);
        assert!(cache.get(task_id).is_none());
    }

    #[test]
    fn test_cache_clear() {
        let cache = ResultCache::new(CacheConfig::new());

        for i in 0..10 {
            let task_id = Uuid::new_v4();
            let meta = TaskMeta::new(task_id, format!("test-{}", i));
            cache.put(task_id, meta);
        }

        assert_eq!(cache.len(), 10);
        cache.clear();
        assert_eq!(cache.len(), 0);
    }

    #[test]
    fn test_cache_capacity() {
        let config = CacheConfig::new().with_capacity(5);
        let cache = ResultCache::new(config);

        // Add 10 entries (should only keep 5)
        let mut task_ids = Vec::new();
        for i in 0..10 {
            let task_id = Uuid::new_v4();
            let meta = TaskMeta::new(task_id, format!("test-{}", i));
            cache.put(task_id, meta);
            task_ids.push(task_id);
        }

        assert_eq!(cache.len(), 5);

        // The last 5 entries should be in the cache
        for task_id in task_ids.iter().skip(5) {
            assert!(cache.get(*task_id).is_some());
        }
    }

    #[test]
    fn test_cache_expiration() {
        let config = CacheConfig::new().with_ttl(Duration::from_millis(50));
        let cache = ResultCache::new(config);

        let task_id = Uuid::new_v4();
        let meta = TaskMeta::new(task_id, "test".to_string());
        cache.put(task_id, meta);

        // Should be in cache immediately
        assert!(cache.get(task_id).is_some());

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(100));

        // Should be expired now
        assert!(cache.get(task_id).is_none());
    }

    #[test]
    fn test_cache_cleanup_expired() {
        let config = CacheConfig::new().with_ttl(Duration::from_millis(50));
        let cache = ResultCache::new(config);

        // Add entries
        for i in 0..5 {
            let task_id = Uuid::new_v4();
            let meta = TaskMeta::new(task_id, format!("test-{}", i));
            cache.put(task_id, meta);
        }

        assert_eq!(cache.len(), 5);

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(100));

        // Cleanup expired entries
        let removed = cache.cleanup_expired();
        assert_eq!(removed, 5);
        assert_eq!(cache.len(), 0);
    }

    #[test]
    fn test_cache_stats() {
        let cache = ResultCache::new(CacheConfig::new().with_capacity(10));

        for i in 0..5 {
            let task_id = Uuid::new_v4();
            let meta = TaskMeta::new(task_id, format!("test-{}", i));
            cache.put(task_id, meta);
        }

        let stats = cache.stats();
        assert_eq!(stats.size, 5);
        assert_eq!(stats.capacity, 10);
    }
}