loco_rs/cache/drivers/null.rs
1//! # Null Cache Driver
2//!
3//! The Null Cache Driver is the default cache driver implemented when the Loco
4//! framework is initialized. The primary purpose of this driver is to simplify
5//! the user workflow by avoiding the need for feature flags or optional cache
6//! driver configurations.
7use std::time::Duration;
8
9use async_trait::async_trait;
10
11use super::CacheDriver;
12use crate::cache::{CacheError, CacheResult};
13
14/// Represents the in-memory cache driver.
15#[derive(Debug)]
16pub struct Null {}
17
18/// Creates a new null cache instance
19///
20/// # Returns
21///
22/// A boxed [`CacheDriver`] instance.
23#[must_use]
24pub fn new() -> Box<dyn CacheDriver> {
25 Box::new(Null {})
26}
27
28#[async_trait]
29impl CacheDriver for Null {
30 /// Pings the cache to check if it is reachable.
31 ///
32 /// # Errors
33 ///
34 /// Returns always error
35 async fn ping(&self) -> CacheResult<()> {
36 Err(CacheError::Any(
37 "Operation not supported by null cache".into(),
38 ))
39 }
40
41 /// Checks if a key exists in the cache.
42 ///
43 /// # Errors
44 ///
45 /// Returns always error
46 async fn contains_key(&self, _key: &str) -> CacheResult<bool> {
47 Err(CacheError::Any(
48 "Operation not supported by null cache".into(),
49 ))
50 }
51
52 /// Retrieves a value from the cache based on the provided key.
53 ///
54 /// # Errors
55 ///
56 /// Returns always error
57 async fn get(&self, _key: &str) -> CacheResult<Option<String>> {
58 Ok(None)
59 }
60
61 /// Inserts a key-value pair into the cache.
62 ///
63 /// # Errors
64 ///
65 /// Returns always error
66 async fn insert(&self, _key: &str, _value: &str) -> CacheResult<()> {
67 Err(CacheError::Any(
68 "Operation not supported by null cache".into(),
69 ))
70 }
71
72 /// Inserts a key-value pair into the cache that expires after the
73 /// provided duration.
74 ///
75 /// # Errors
76 ///
77 /// Returns always error
78 async fn insert_with_expiry(
79 &self,
80 _key: &str,
81 _value: &str,
82 _duration: Duration,
83 ) -> CacheResult<()> {
84 Err(CacheError::Any(
85 "Operation not supported by null cache".into(),
86 ))
87 }
88
89 /// Removes a key-value pair from the cache.
90 ///
91 /// # Errors
92 ///
93 /// Returns always error
94 async fn remove(&self, _key: &str) -> CacheResult<()> {
95 Err(CacheError::Any(
96 "Operation not supported by null cache".into(),
97 ))
98 }
99
100 /// Clears all key-value pairs from the cache.
101 ///
102 /// # Errors
103 ///
104 /// Returns always error
105 async fn clear(&self) -> CacheResult<()> {
106 Err(CacheError::Any(
107 "Operation not supported by null cache".into(),
108 ))
109 }
110}