Skip to main content

crates_docs/cache/
mod.rs

1//! Cache module
2//!
3//! Provides memory cache and Redis cache support.
4//!
5//! # Features
6//!
7//! - **Memory cache**: High-performance memory cache based on `moka`, supporting `TinyLFU` eviction strategy
8//! - **Redis cache**: Supports distributed deployment (requires `cache-redis` feature)
9//!
10//! # Examples
11//!
12//! ```rust,no_run
13//! use crates_docs::cache::{Cache, CacheConfig, create_cache};
14//!
15//! let config = CacheConfig::default();
16//! let cache = create_cache(&config).expect("Failed to create cache");
17//! ```
18
19#[cfg(feature = "cache-memory")]
20pub mod memory;
21
22#[cfg(feature = "cache-redis")]
23pub mod redis;
24
25use std::sync::Arc;
26use std::time::Duration;
27
28/// Default memory cache capacity
29///
30/// # Value
31///
32/// 1000 entries
33///
34/// # Rationale
35///
36/// Provides good balance between memory usage and cache hit rate for typical workloads.
37/// Configurable via `CacheConfig::memory_size`.
38const DEFAULT_MEMORY_CACHE_SIZE: usize = 1000;
39
40/// Default crate documentation TTL in seconds
41///
42/// # Value
43///
44/// 3600 seconds (1 hour)
45///
46/// # Rationale
47///
48/// Reused from ttl.rs for consistency. Crate documentation changes infrequently.
49/// Configurable via `CacheConfig::crate_docs_ttl_secs`.
50const DEFAULT_CRATE_DOCS_TTL_SECS: u64 = 3600;
51
52/// Default item documentation TTL in seconds
53///
54/// # Value
55///
56/// 1800 seconds (30 minutes)
57///
58/// # Rationale
59///
60/// Reused from ttl.rs for consistency. Item documentation changes moderately often.
61/// Configurable via `CacheConfig::item_docs_ttl_secs`.
62const DEFAULT_ITEM_DOCS_TTL_SECS: u64 = 1800;
63
64/// Default search results TTL in seconds
65///
66/// # Value
67///
68/// 300 seconds (5 minutes)
69///
70/// # Rationale
71///
72/// Reused from ttl.rs for consistency. Search results change frequently.
73/// Configurable via `CacheConfig::search_results_ttl_secs`.
74const DEFAULT_SEARCH_RESULTS_TTL_SECS: u64 = 300;
75
76/// Cache trait
77///
78/// Defines basic cache operation interface, supporting async read/write, TTL expiration, and bulk cleanup.
79///
80/// # Implementations
81///
82/// - `memory::MemoryCache`: Memory cache implementation
83/// - `redis::RedisCache`: Redis cache implementation (requires `cache-redis` feature)
84#[async_trait::async_trait]
85pub trait Cache: Send + Sync {
86    /// Get cache value
87    ///
88    /// # Arguments
89    ///
90    /// * `key` - Cache key
91    ///
92    /// # Returns
93    ///
94    /// If key exists and not expired, returns `Arc<str>` to avoid cloning; otherwise returns `None`
95    async fn get(&self, key: &str) -> Option<Arc<str>>;
96
97    /// Set cache value
98    ///
99    /// # Arguments
100    ///
101    /// * `key` - Cache key
102    /// * `value` - Cache value
103    /// * `ttl` - Optional expiration time
104    ///
105    /// # Errors
106    ///
107    /// Returns error if cache operation fails
108    async fn set(
109        &self,
110        key: String,
111        value: String,
112        ttl: Option<Duration>,
113    ) -> crate::error::Result<()>;
114
115    /// Delete cache value
116    ///
117    /// # Arguments
118    ///
119    /// * `key` - Cache key
120    ///
121    /// # Errors
122    ///
123    /// Returns error if cache operation fails
124    async fn delete(&self, key: &str) -> crate::error::Result<()>;
125
126    /// Clear all cache entries
127    ///
128    /// Clears only cache entries with configured prefix.
129    ///
130    /// # Errors
131    ///
132    /// Returns error if cache operation fails
133    async fn clear(&self) -> crate::error::Result<()>;
134
135    /// Check if key exists
136    ///
137    /// # Arguments
138    ///
139    /// * `key` - Cache key
140    ///
141    /// # Returns
142    ///
143    /// Returns `true` if key exists, otherwise `false`
144    async fn exists(&self, key: &str) -> bool;
145
146    /// Convert to Any for downcasting (used in tests)
147    ///
148    /// This method allows downcasting the cache to its concrete type
149    /// for accessing test-only methods like `run_pending_tasks`.
150    fn as_any(&self) -> &dyn std::any::Any;
151}
152
153/// Cache configuration
154///
155/// Configure cache type, size, TTL, and other parameters.
156///
157/// # Fields
158///
159/// - `cache_type`: Cache type, `"memory"` or `"redis"`
160/// - `memory_size`: Memory cache size(number of entries)
161/// - `redis_url`: Redis connection URL
162/// - `key_prefix`: Key prefix (used to isolate caches of different services)
163/// - `default_ttl`: Default TTL (seconds)
164/// - `crate_docs_ttl_secs`: Crate document cache TTL (seconds)
165/// - `item_docs_ttl_secs`: Item document cache TTL (seconds)
166/// - `search_results_ttl_secs`: Search result cache TTL (seconds)
167///
168/// # Hot reload support
169///
170/// ## Hot reload supported fields ✅
171///
172/// TTL-related fields can be dynamically updated at runtime (affecting newly written cache entries):
173/// - `default_ttl`: Default TTL (seconds)
174/// - `crate_docs_ttl_secs`: Crate document cache TTL (seconds)
175/// - `item_docs_ttl_secs`: Item document cache TTL (seconds)
176/// - `search_results_ttl_secs`: Search result cache TTL (seconds)
177///
178/// ## Hot reload NOT supported fields ❌
179///
180/// The following fields require server restart to take effect:
181/// - `cache_type`: Cache type (involves cache instance creation)
182/// - `memory_size`: Memory cache size(initialization parameter)
183/// - `redis_url`: Redis connection URL(connection pool initialization)
184/// - `key_prefix`: Cache key prefix(initialization parameter)
185///
186/// Reason: These configurations involve initialization of cache backend (memory/Redis) and connection pool creation.
187#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
188pub struct CacheConfig {
189    /// Cache type: `memory` or `redis`
190    pub cache_type: String,
191
192    /// Memory cache size(number of entries)
193    pub memory_size: Option<usize>,
194
195    /// Redis connection URL
196    pub redis_url: Option<String>,
197
198    /// Redis cache key prefix (used to isolate caches of different services)
199    #[serde(default = "default_key_prefix")]
200    pub key_prefix: String,
201
202    /// Default TTL (seconds)
203    pub default_ttl: Option<u64>,
204
205    /// Crate document cache TTL (seconds)
206    #[serde(default = "default_crate_docs_ttl")]
207    pub crate_docs_ttl_secs: Option<u64>,
208
209    /// Item document cache TTL (seconds)
210    #[serde(default = "default_item_docs_ttl")]
211    pub item_docs_ttl_secs: Option<u64>,
212
213    /// Search result cache TTL (seconds)
214    #[serde(default = "default_search_results_ttl")]
215    pub search_results_ttl_secs: Option<u64>,
216}
217
218/// Default crate document TTL (1 hour)
219#[must_use]
220pub fn default_crate_docs_ttl() -> Option<u64> {
221    Some(DEFAULT_CRATE_DOCS_TTL_SECS)
222}
223
224/// Default item document TTL (30 minutes)
225#[must_use]
226pub fn default_item_docs_ttl() -> Option<u64> {
227    Some(DEFAULT_ITEM_DOCS_TTL_SECS)
228}
229
230/// Default search result TTL (5 minutes)
231#[must_use]
232pub fn default_search_results_ttl() -> Option<u64> {
233    Some(DEFAULT_SEARCH_RESULTS_TTL_SECS)
234}
235
236/// Default key prefix
237#[must_use]
238pub fn default_key_prefix() -> String {
239    String::new()
240}
241
242impl Default for CacheConfig {
243    fn default() -> Self {
244        Self {
245            cache_type: "memory".to_string(),
246            memory_size: Some(DEFAULT_MEMORY_CACHE_SIZE),
247            redis_url: None,
248            key_prefix: String::new(),
249            default_ttl: Some(DEFAULT_CRATE_DOCS_TTL_SECS),
250            crate_docs_ttl_secs: default_crate_docs_ttl(),
251            item_docs_ttl_secs: default_item_docs_ttl(),
252            search_results_ttl_secs: default_search_results_ttl(),
253        }
254    }
255}
256
257/// Create cache instance
258///
259/// # Arguments
260///
261/// * `config` - Cache configuration
262///
263/// # Errors
264///
265/// Returns error if cache type is not supported or configuration is invalid
266///
267/// # Examples
268///
269/// ```rust,no_run
270/// use crates_docs::cache::{CacheConfig, create_cache};
271///
272/// let config = CacheConfig::default();
273/// let cache = create_cache(&config).expect("Failed to create cache");
274/// ```
275pub fn create_cache(config: &CacheConfig) -> Result<Box<dyn Cache>, crate::error::Error> {
276    match config.cache_type.as_str() {
277        "memory" => {
278            #[cfg(feature = "cache-memory")]
279            {
280                let size = config.memory_size.unwrap_or(DEFAULT_MEMORY_CACHE_SIZE);
281                Ok(Box::new(memory::MemoryCache::new(size)))
282            }
283            #[cfg(not(feature = "cache-memory"))]
284            {
285                Err(crate::error::Error::config(
286                    "cache_type",
287                    "memory cache feature is not enabled",
288                ))
289            }
290        }
291        "redis" => {
292            #[cfg(feature = "cache-redis")]
293            {
294                // Note: Redis cache requires async initialization, this returns a placeholder
295                // In practice, use the create_cache_async function
296                Err(crate::error::Error::config(
297                    "cache_type",
298                    "Redis cache requires async initialization. Use create_cache_async instead.",
299                ))
300            }
301            #[cfg(not(feature = "cache-redis"))]
302            {
303                Err(crate::error::Error::config(
304                    "cache_type",
305                    "redis cache feature is not enabled",
306                ))
307            }
308        }
309        _ => Err(crate::error::Error::config(
310            "cache_type",
311            format!("unsupported cache type: {}", config.cache_type),
312        )),
313    }
314}
315
316/// Async create cache instance
317///
318/// Supports async initialization for Redis cache.
319///
320/// # Arguments
321///
322/// * `config` - Cache configuration
323///
324/// # Errors
325///
326/// Returns error if cache type is not supported or configuration is invalid
327///
328/// # Examples
329///
330/// ```rust,no_run
331/// use crates_docs::cache::{CacheConfig, create_cache_async};
332///
333/// #[tokio::main]
334/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
335///     let config = CacheConfig::default();
336///     let cache = create_cache_async(&config).await?;
337///     Ok(())
338/// }
339/// ```
340#[cfg(feature = "cache-redis")]
341pub async fn create_cache_async(
342    config: &CacheConfig,
343) -> Result<Box<dyn Cache>, crate::error::Error> {
344    match config.cache_type.as_str() {
345        "memory" => {
346            let size = config.memory_size.unwrap_or(DEFAULT_MEMORY_CACHE_SIZE);
347            Ok(Box::new(memory::MemoryCache::new(size)))
348        }
349        "redis" => {
350            let url = config
351                .redis_url
352                .as_ref()
353                .ok_or_else(|| crate::error::Error::config("redis_url", "redis_url is required"))?;
354            Ok(Box::new(
355                redis::RedisCache::new(url, config.key_prefix.clone()).await?,
356            ))
357        }
358        _ => Err(crate::error::Error::config(
359            "cache_type",
360            format!("unsupported cache type: {}", config.cache_type),
361        )),
362    }
363}