Skip to main content

backbone_cache/
lib.rs

1//! Backbone Framework Cache Module
2//!
3//! Provides caching functionality with Redis and in-memory support.
4//!
5//! ## Features
6//!
7//! - **Redis Backend**: Distributed caching with Redis
8//! - **Memory Backend**: In-process caching for development/testing
9//! - **TTL Support**: Time-to-live for cache entries
10//! - **Async/Await**: Full async support with tokio
11//! - **Generic Types**: Cache any serializable data
12//!
13//! ## Quick Start
14//!
15//! ```no_run
16//! use backbone_cache::{Cache, RedisCache};
17//! use serde::{Serialize, Deserialize};
18//!
19//! #[derive(Serialize, Deserialize)]
20//! struct User {
21//!     id: String,
22//!     name: String,
23//! }
24//!
25//! # async fn doc() -> Result<(), Box<dyn std::error::Error>> {
26//! // Redis cache
27//! let cache = RedisCache::new("redis://localhost:6379").await?;
28//!
29//! // Store user in cache
30//! let user = User { id: "123".to_string(), name: "John".to_string() };
31//! cache.set("user:123", &user, Some(3600)).await?;
32//!
33//! // Retrieve user from cache
34//! let cached_user: Option<User> = cache.get("user:123").await?;
35//! # Ok(()) }
36//! ```
37
38pub mod memory;
39pub mod redis;
40pub mod traits;
41
42pub use traits::*;
43pub use memory::*;
44pub use redis::*;
45
46/// Cache module version
47pub const VERSION: &str = env!("CARGO_PKG_VERSION");
48
49/// Default cache TTL in seconds (1 hour)
50pub const DEFAULT_TTL: u64 = 3600;
51
52/// Cache error types
53#[derive(thiserror::Error, Debug)]
54pub enum CacheError {
55    #[error("Redis connection error: {0}")]
56    RedisConnection(String),
57
58    #[error("Redis operation error: {0}")]
59    RedisOperation(String),
60
61    #[error("Serialization error: {0}")]
62    Serialization(String),
63
64    #[error("Deserialization error: {0}")]
65    Deserialization(String),
66
67    #[error("Cache key not found: {0}")]
68    NotFound(String),
69
70    #[error("Cache error: {0}")]
71    Other(String),
72}
73
74/// Result type for cache operations
75pub type CacheResult<T> = Result<T, CacheError>;
76
77/// Cache configuration
78#[derive(Debug, Clone)]
79pub struct CacheConfig {
80    /// TTL in seconds for cache entries
81    pub default_ttl: u64,
82
83    /// Maximum number of entries in memory cache
84    pub max_memory_entries: Option<usize>,
85
86    /// Connection pool size for Redis
87    pub redis_pool_size: Option<u32>,
88
89    /// Key prefix for cache entries
90    pub key_prefix: Option<String>,
91}
92
93impl Default for CacheConfig {
94    fn default() -> Self {
95        Self {
96            default_ttl: DEFAULT_TTL,
97            max_memory_entries: Some(10000),
98            redis_pool_size: Some(10),
99            key_prefix: None,
100        }
101    }
102}
103
104/// Cache key builder utilities
105pub struct CacheKey;
106
107impl CacheKey {
108    /// Build cache key with namespace
109    pub fn build(namespace: &str, key: &str) -> String {
110        format!("{}:{}", namespace, key)
111    }
112
113    /// Build user cache key
114    pub fn user(user_id: &str) -> String {
115        Self::build("user", user_id)
116    }
117
118    /// Build session cache key
119    pub fn session(session_id: &str) -> String {
120        Self::build("session", session_id)
121    }
122
123    /// Build API response cache key
124    pub fn api_response(path: &str, params: &str) -> String {
125        Self::build("api", &format!("{}:{}", path, params))
126    }
127}