cache-kit 0.9.0

A type-safe, fully generic, production-ready caching framework for Rust
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Redis cache backend implementation.

use super::CacheBackend;
use crate::error::{Error, Result};
use deadpool_redis::{redis::AsyncCommands, Config as PoolConfig, Pool, Runtime};
use std::time::Duration;

/// Pool statistics information.
#[derive(Debug, Clone)]
pub struct PoolStats {
    pub connections: u32,
    pub idle_connections: u32,
}

/// Default Redis connection pool size.
/// Formula: (CPU cores × 2) + 1
/// For 8-core systems: 16 connections is optimal
/// Override with REDIS_POOL_SIZE environment variable
const DEFAULT_POOL_SIZE: u32 = 16;

/// Configuration for Redis backend.
#[derive(Clone, Debug)]
pub struct RedisConfig {
    pub host: String,
    pub port: u16,
    pub username: Option<String>,
    pub password: Option<String>,
    pub database: u32,
    pub pool_size: u32,
    pub connection_timeout: Duration,
}

impl Default for RedisConfig {
    fn default() -> Self {
        RedisConfig {
            host: "localhost".to_string(),
            port: 6379,
            username: None,
            password: None,
            database: 0,
            pool_size: DEFAULT_POOL_SIZE,
            connection_timeout: Duration::from_secs(5),
        }
    }
}

impl RedisConfig {
    /// Build Redis connection string.
    pub fn connection_string(&self) -> String {
        if let Some(password) = &self.password {
            if let Some(username) = &self.username {
                format!(
                    "redis://{}:{}@{}:{}/{}",
                    username, password, self.host, self.port, self.database
                )
            } else {
                format!(
                    "redis://default:{}@{}:{}/{}",
                    password, self.host, self.port, self.database
                )
            }
        } else {
            format!("redis://{}:{}/{}", self.host, self.port, self.database)
        }
    }
}

/// Redis backend with connection pooling and async operations.
///
/// Uses deadpool for efficient async resource management and pooling.
///
/// # Example
///
/// ```no_run
/// # use cache_kit::backend::{RedisBackend, RedisConfig, CacheBackend};
/// # use cache_kit::error::Result;
/// # async fn example() -> Result<()> {
/// let config = RedisConfig::default();
/// let mut backend = RedisBackend::new(config).await?;
///
/// backend.set("key", b"value".to_vec(), None).await?;
/// let value = backend.get("key").await?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct RedisBackend {
    pool: Pool,
}

impl RedisBackend {
    /// Create new Redis backend from configuration.
    ///
    /// # Errors
    /// Returns `Err` if pool creation fails or connection cannot be established.
    pub async fn new(config: RedisConfig) -> Result<Self> {
        let conn_str = config.connection_string();
        let mut cfg = PoolConfig::from_url(conn_str);
        cfg.pool = Some(deadpool_redis::PoolConfig::new(config.pool_size as usize));

        let pool = cfg
            .create_pool(Some(Runtime::Tokio1))
            .map_err(|e| Error::BackendError(format!("Failed to create Redis pool: {}", e)))?;

        info!(
            "✓ Redis backend initialized: {}:{}",
            config.host, config.port
        );

        Ok(RedisBackend { pool })
    }

    /// Create from connection string directly.
    ///
    /// Pool size is determined by:
    /// 1. `REDIS_POOL_SIZE` environment variable (if set)
    /// 2. `DEFAULT_POOL_SIZE` constant (16)
    ///
    /// # Errors
    /// Returns `Err` if pool creation fails or connection cannot be established.
    pub async fn from_connection_string(conn_str: &str) -> Result<Self> {
        let pool_size = std::env::var("REDIS_POOL_SIZE")
            .ok()
            .and_then(|s| s.parse::<u32>().ok())
            .unwrap_or(DEFAULT_POOL_SIZE);

        let mut cfg = PoolConfig::from_url(conn_str);
        cfg.pool = Some(deadpool_redis::PoolConfig::new(pool_size as usize));

        let pool = cfg
            .create_pool(Some(Runtime::Tokio1))
            .map_err(|e| Error::BackendError(format!("Failed to create Redis pool: {}", e)))?;

        info!(
            "✓ Redis backend initialized from connection string (pool size: {})",
            pool_size
        );

        Ok(RedisBackend { pool })
    }

    /// Get current pool statistics.
    pub fn pool_stats(&self) -> PoolStats {
        let status = self.pool.status();
        PoolStats {
            connections: status.size as u32,
            idle_connections: status.available as u32,
        }
    }
}

impl CacheBackend for RedisBackend {
    async fn get(&self, key: &str) -> Result<Option<Vec<u8>>> {
        let mut conn =
            self.pool.get().await.map_err(|e| {
                Error::BackendError(format!("Failed to get Redis connection: {}", e))
            })?;

        let value: Option<Vec<u8>> = conn
            .get(key)
            .await
            .map_err(|e| Error::BackendError(format!("Redis GET failed for key {}: {}", key, e)))?;

        if value.is_some() {
            debug!("✓ Redis GET {} -> HIT", key);
        } else {
            debug!("✓ Redis GET {} -> MISS", key);
        }

        Ok(value)
    }

    async fn set(&self, key: &str, value: Vec<u8>, ttl: Option<Duration>) -> Result<()> {
        let mut conn =
            self.pool.get().await.map_err(|e| {
                Error::BackendError(format!("Failed to get Redis connection: {}", e))
            })?;

        match ttl {
            Some(duration) => {
                let seconds = duration.as_secs();
                conn.set_ex::<_, _, ()>(key, value, seconds)
                    .await
                    .map_err(|e| {
                        Error::BackendError(format!("Redis SET_EX failed for key {}: {}", key, e))
                    })?;
                debug!("✓ Redis SET {} (TTL: {}s)", key, seconds);
            }
            None => {
                conn.set::<_, _, ()>(key, value).await.map_err(|e| {
                    Error::BackendError(format!("Redis SET failed for key {}: {}", key, e))
                })?;
                debug!("✓ Redis SET {}", key);
            }
        }

        Ok(())
    }

    async fn delete(&self, key: &str) -> Result<()> {
        let mut conn =
            self.pool.get().await.map_err(|e| {
                Error::BackendError(format!("Failed to get Redis connection: {}", e))
            })?;

        conn.del::<_, ()>(key)
            .await
            .map_err(|e| Error::BackendError(format!("Redis DEL failed for key {}: {}", key, e)))?;

        debug!("✓ Redis DELETE {}", key);
        Ok(())
    }

    async fn exists(&self, key: &str) -> Result<bool> {
        let mut conn =
            self.pool.get().await.map_err(|e| {
                Error::BackendError(format!("Failed to get Redis connection: {}", e))
            })?;

        let exists: bool = conn.exists(key).await.map_err(|e| {
            Error::BackendError(format!("Redis EXISTS failed for key {}: {}", key, e))
        })?;

        Ok(exists)
    }

    async fn mget(&self, keys: &[&str]) -> Result<Vec<Option<Vec<u8>>>> {
        let mut conn =
            self.pool.get().await.map_err(|e| {
                Error::BackendError(format!("Failed to get Redis connection: {}", e))
            })?;

        let values: Vec<Option<Vec<u8>>> = conn
            .get(keys)
            .await
            .map_err(|e| Error::BackendError(format!("Redis MGET failed: {}", e)))?;

        debug!("✓ Redis MGET {} keys", keys.len());
        Ok(values)
    }

    async fn mdelete(&self, keys: &[&str]) -> Result<()> {
        let mut conn =
            self.pool.get().await.map_err(|e| {
                Error::BackendError(format!("Failed to get Redis connection: {}", e))
            })?;

        conn.del::<_, ()>(keys)
            .await
            .map_err(|e| Error::BackendError(format!("Redis DEL (bulk) failed: {}", e)))?;

        debug!("✓ Redis MDELETE {} keys", keys.len());
        Ok(())
    }

    async fn health_check(&self) -> Result<bool> {
        let mut conn =
            self.pool.get().await.map_err(|e| {
                Error::BackendError(format!("Failed to get Redis connection: {}", e))
            })?;

        // Use deadpool_redis::redis::cmd for PING command
        let pong: String = deadpool_redis::redis::cmd("PING")
            .query_async(&mut *conn)
            .await
            .map_err(|e| Error::BackendError(format!("Redis PING failed: {}", e)))?;

        Ok(pong == "PONG" || pong.contains("PONG"))
    }

    async fn clear_all(&self) -> Result<()> {
        let mut conn =
            self.pool.get().await.map_err(|e| {
                Error::BackendError(format!("Failed to get Redis connection: {}", e))
            })?;

        deadpool_redis::redis::cmd("FLUSHDB")
            .query_async::<()>(&mut *conn)
            .await
            .map_err(|e| Error::BackendError(format!("Redis FLUSHDB failed: {}", e)))?;

        warn!("⚠ Redis FLUSHDB executed - all cache cleared!");
        Ok(())
    }
}

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

    #[test]
    fn test_redis_config_connection_string() {
        let config = RedisConfig {
            host: "localhost".to_string(),
            port: 6379,
            password: Some("password".to_string()),
            username: Some("user".to_string()),
            database: 0,
            pool_size: 10,
            connection_timeout: Duration::from_secs(5),
        };

        assert_eq!(
            config.connection_string(),
            "redis://user:password@localhost:6379/0"
        );
    }

    #[test]
    fn test_redis_config_default() {
        let config = RedisConfig::default();
        assert_eq!(config.host, "localhost");
        assert_eq!(config.port, 6379);
        assert_eq!(config.database, 0);
        assert_eq!(config.pool_size, DEFAULT_POOL_SIZE);
    }

    #[test]
    fn test_redis_config_no_auth() {
        let config = RedisConfig::default();
        assert_eq!(config.connection_string(), "redis://localhost:6379/0");
    }

    #[test]
    fn test_redis_config_custom_timeout() {
        let timeout = Duration::from_secs(10);
        let config = RedisConfig {
            host: "localhost".to_string(),
            port: 6379,
            username: None,
            password: None,
            database: 0,
            pool_size: 16,
            connection_timeout: timeout,
        };

        assert_eq!(config.connection_timeout, timeout);
    }

    // Integration tests - require running Redis server
    // Uncomment and run with: cargo test -- --ignored
    #[tokio::test]
    #[ignore]
    async fn test_redis_backend_new() {
        let config = RedisConfig {
            host: "localhost".to_string(),
            port: 6379,
            username: None,
            password: None,
            database: 0,
            pool_size: 16,
            connection_timeout: Duration::from_secs(5),
        };

        let result = RedisBackend::new(config).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    #[ignore]
    async fn test_redis_backend_from_connection_string() {
        let result = RedisBackend::from_connection_string("redis://localhost:6379/0").await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    #[ignore]
    async fn test_redis_backend_set_get() {
        let backend = RedisBackend::from_connection_string("redis://localhost:6379/0")
            .await
            .expect("Failed to create backend");

        backend
            .set("test_key", b"test_value".to_vec(), None)
            .await
            .expect("Failed to set");

        let result = backend.get("test_key").await.expect("Failed to get");
        assert_eq!(result, Some(b"test_value".to_vec()));
    }

    #[tokio::test]
    #[ignore]
    async fn test_redis_backend_get_miss() {
        let backend = RedisBackend::from_connection_string("redis://localhost:6379/0")
            .await
            .expect("Failed to create backend");

        let result = backend.get("nonexistent_key").await.expect("Failed to get");
        assert_eq!(result, None);
    }

    #[tokio::test]
    #[ignore]
    async fn test_redis_backend_delete() {
        let backend = RedisBackend::from_connection_string("redis://localhost:6379/0")
            .await
            .expect("Failed to create backend");

        backend
            .set("delete_key", b"value".to_vec(), None)
            .await
            .expect("Failed to set");

        backend
            .delete("delete_key")
            .await
            .expect("Failed to delete");

        let result = backend.get("delete_key").await.expect("Failed to get");
        assert_eq!(result, None);
    }

    #[tokio::test]
    #[ignore]
    async fn test_redis_backend_exists() {
        let backend = RedisBackend::from_connection_string("redis://localhost:6379/0")
            .await
            .expect("Failed to create backend");

        backend
            .set("exists_key", b"value".to_vec(), None)
            .await
            .expect("Failed to set");

        let exists = backend
            .exists("exists_key")
            .await
            .expect("Failed to check exists");
        assert!(exists);

        let not_exists = backend
            .exists("nonexistent")
            .await
            .expect("Failed to check exists");
        assert!(!not_exists);
    }

    #[tokio::test]
    #[ignore]
    async fn test_redis_backend_mget() {
        let backend = RedisBackend::from_connection_string("redis://localhost:6379/0")
            .await
            .expect("Failed to create backend");

        backend
            .set("mget_key1", b"value1".to_vec(), None)
            .await
            .expect("Failed to set");
        backend
            .set("mget_key2", b"value2".to_vec(), None)
            .await
            .expect("Failed to set");

        let results = backend
            .mget(&["mget_key1", "mget_key2", "nonexistent"])
            .await
            .expect("Failed to mget");

        assert_eq!(results.len(), 3);
        assert_eq!(results[0], Some(b"value1".to_vec()));
        assert_eq!(results[1], Some(b"value2".to_vec()));
        assert_eq!(results[2], None);
    }

    #[tokio::test]
    #[ignore]
    async fn test_redis_backend_mdelete() {
        let backend = RedisBackend::from_connection_string("redis://localhost:6379/0")
            .await
            .expect("Failed to create backend");

        backend
            .set("mdelete_key1", b"value1".to_vec(), None)
            .await
            .expect("Failed to set");
        backend
            .set("mdelete_key2", b"value2".to_vec(), None)
            .await
            .expect("Failed to set");

        backend
            .mdelete(&["mdelete_key1", "mdelete_key2"])
            .await
            .expect("Failed to mdelete");

        let result1 = backend.get("mdelete_key1").await.expect("Failed to get");
        let result2 = backend.get("mdelete_key2").await.expect("Failed to get");
        assert_eq!(result1, None);
        assert_eq!(result2, None);
    }

    #[tokio::test]
    #[ignore]
    async fn test_redis_backend_ttl() {
        let backend = RedisBackend::from_connection_string("redis://localhost:6379/0")
            .await
            .expect("Failed to create backend");

        backend
            .set(
                "ttl_key",
                b"expires_soon".to_vec(),
                Some(Duration::from_secs(2)),
            )
            .await
            .expect("Failed to set");

        let result = backend.get("ttl_key").await.expect("Failed to get");
        assert_eq!(result, Some(b"expires_soon".to_vec()));

        // Wait for expiration
        tokio::time::sleep(Duration::from_secs(3)).await;

        let expired = backend.get("ttl_key").await.expect("Failed to get");
        assert_eq!(expired, None);
    }

    #[tokio::test]
    #[ignore]
    async fn test_redis_backend_health_check() {
        let backend = RedisBackend::from_connection_string("redis://localhost:6379/0")
            .await
            .expect("Failed to create backend");

        let healthy = backend
            .health_check()
            .await
            .expect("Failed to check health");
        assert!(healthy);
    }

    #[tokio::test]
    #[ignore]
    async fn test_redis_backend_clear_all() {
        let backend = RedisBackend::from_connection_string("redis://localhost:6379/0")
            .await
            .expect("Failed to create backend");

        backend
            .set("clear_key1", b"value1".to_vec(), None)
            .await
            .expect("Failed to set");
        backend
            .set("clear_key2", b"value2".to_vec(), None)
            .await
            .expect("Failed to set");

        backend.clear_all().await.expect("Failed to clear");

        let result1 = backend.get("clear_key1").await.expect("Failed to get");
        let result2 = backend.get("clear_key2").await.expect("Failed to get");
        assert_eq!(result1, None);
        assert_eq!(result2, None);
    }
}