1use async_trait::async_trait;
4use redis::{AsyncCommands, Client};
5use std::collections::HashMap;
6use std::sync::Arc;
7use std::time::{Duration, Instant};
8use tokio::sync::RwLock;
9
10pub type CacheResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
11
12#[async_trait]
14pub trait CacheStore: Send + Sync {
15 async fn get_bytes(&self, key: &str) -> CacheResult<Option<Vec<u8>>>;
16 async fn set_bytes(&self, key: &str, value: &[u8], ttl: Duration) -> CacheResult<()>;
17 async fn delete(&self, key: &str) -> CacheResult<()>;
18}
19
20#[derive(Clone)]
22pub struct CacheNamespace<B> {
23 backend: Arc<B>,
24 namespace: String,
25}
26
27impl<B> CacheNamespace<B>
28where
29 B: CacheStore + 'static,
30{
31 pub fn new(backend: Arc<B>, namespace: impl Into<String>) -> Self {
32 Self {
33 backend,
34 namespace: namespace.into(),
35 }
36 }
37
38 pub fn key(&self, key: &str) -> String {
39 format!("{}:{}", self.namespace, key)
40 }
41
42 pub async fn get_bytes(&self, key: &str) -> CacheResult<Option<Vec<u8>>> {
43 self.backend.get_bytes(&self.key(key)).await
44 }
45
46 pub async fn set_bytes(&self, key: &str, value: &[u8], ttl: Duration) -> CacheResult<()> {
47 self.backend.set_bytes(&self.key(key), value, ttl).await
48 }
49
50 pub async fn delete(&self, key: &str) -> CacheResult<()> {
51 self.backend.delete(&self.key(key)).await
52 }
53}
54
55#[derive(Clone)]
56struct MemoryEntry {
57 value: Vec<u8>,
58 expires_at: Instant,
59}
60
61#[derive(Default)]
63pub struct MemoryCache {
64 entries: RwLock<HashMap<String, MemoryEntry>>,
65}
66
67impl MemoryCache {
68 pub fn new() -> Self {
69 Self::default()
70 }
71
72 pub async fn invalidate_namespace(&self, namespace: &str) {
73 let prefix = format!("{}:", namespace);
74 self.entries
75 .write()
76 .await
77 .retain(|key, _| !key.starts_with(&prefix));
78 }
79
80 async fn purge_expired(&self) {
81 let now = Instant::now();
82 self.entries
83 .write()
84 .await
85 .retain(|_, entry| entry.expires_at > now);
86 }
87}
88
89#[async_trait]
90impl CacheStore for MemoryCache {
91 async fn get_bytes(&self, key: &str) -> CacheResult<Option<Vec<u8>>> {
92 self.purge_expired().await;
93 Ok(self
94 .entries
95 .read()
96 .await
97 .get(key)
98 .map(|entry| entry.value.clone()))
99 }
100
101 async fn set_bytes(&self, key: &str, value: &[u8], ttl: Duration) -> CacheResult<()> {
102 self.entries.write().await.insert(
103 key.to_string(),
104 MemoryEntry {
105 value: value.to_vec(),
106 expires_at: Instant::now() + ttl,
107 },
108 );
109 Ok(())
110 }
111
112 async fn delete(&self, key: &str) -> CacheResult<()> {
113 self.entries.write().await.remove(key);
114 Ok(())
115 }
116}
117
118#[derive(Clone)]
120pub struct Cache {
121 client: Client,
122}
123
124impl Cache {
125 pub async fn new(redis_url: &str) -> Result<Self, redis::RedisError> {
126 let client = Client::open(redis_url)?;
127 Ok(Cache { client })
128 }
129
130 pub async fn get<T: for<'de> serde::Deserialize<'de>>(
131 &self,
132 key: &str,
133 ) -> CacheResult<Option<T>> {
134 let mut conn = self.client.get_async_connection().await?;
135 let value: Option<String> = conn.get(key).await?;
136
137 match value {
138 Some(v) => Ok(Some(serde_json::from_str(&v)?)),
139 None => Ok(None),
140 }
141 }
142
143 pub async fn set<T: serde::Serialize>(
144 &self,
145 key: &str,
146 value: &T,
147 ttl: Duration,
148 ) -> CacheResult<()> {
149 let mut conn = self.client.get_async_connection().await?;
150 let serialized = serde_json::to_string(value)?;
151 let _: () = conn.set_ex(key, serialized, ttl.as_secs() as usize).await?;
152 Ok(())
153 }
154
155 pub async fn delete(&self, key: &str) -> CacheResult<()> {
156 let mut conn = self.client.get_async_connection().await?;
157 let _: () = conn.del(key).await?;
158 Ok(())
159 }
160}
161
162#[async_trait]
163impl CacheStore for Cache {
164 async fn get_bytes(&self, key: &str) -> CacheResult<Option<Vec<u8>>> {
165 let mut conn = self.client.get_async_connection().await?;
166 let value: Option<Vec<u8>> = conn.get(key).await?;
167 Ok(value)
168 }
169
170 async fn set_bytes(&self, key: &str, value: &[u8], ttl: Duration) -> CacheResult<()> {
171 let mut conn = self.client.get_async_connection().await?;
172 let _: () = conn.set_ex(key, value, ttl.as_secs() as usize).await?;
173 Ok(())
174 }
175
176 async fn delete(&self, key: &str) -> CacheResult<()> {
177 self.delete(key).await
178 }
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 #[tokio::test]
186 async fn memory_cache_round_trips_and_expires_values() {
187 let cache = MemoryCache::new();
188 cache
189 .set_bytes("greeting", b"hello", Duration::from_millis(20))
190 .await
191 .unwrap();
192 assert_eq!(
193 cache.get_bytes("greeting").await.unwrap(),
194 Some(b"hello".to_vec())
195 );
196 tokio::time::sleep(Duration::from_millis(30)).await;
197 assert_eq!(cache.get_bytes("greeting").await.unwrap(), None);
198 }
199}