1use std::any::Any;
2use std::borrow::Cow;
3use std::collections::HashMap;
4use std::sync::Arc;
5use std::time::{Duration, Instant};
6
7use async_trait::async_trait;
8use bytes::Bytes;
9
10use crate::config::CacheStoreConfig;
11use crate::{CacheValue, Error};
12
13#[derive(Clone, Copy, Debug)]
15pub enum CacheExpiry {
16 Unknown,
17 Never,
18 At(Instant),
19}
20
21pub struct CacheEntry {
22 pub bytes: Bytes,
23 pub expiry: CacheExpiry,
24}
25
26#[async_trait]
31pub trait CacheStore: Any + Send + Sync + 'static {
32 fn store_name(&self) -> &str;
33 fn driver_name(&self) -> &str;
34 fn as_any(&self) -> &dyn Any;
35 fn supports_ttl(&self) -> bool;
36 async fn get(
39 &self,
40 key: &str,
41 ) -> crate::Result<Option<Bytes>>;
42
43 async fn get_entry(
46 &self,
47 key: &str,
48 ) -> crate::Result<Option<CacheEntry>> {
49 Ok(self
50 .get(key)
51 .await?
52 .map(|bytes| CacheEntry { bytes, expiry: CacheExpiry::Unknown }))
53 }
54 async fn put(
57 &self,
58 key: &str,
59 value: Cow<'_, [u8]>,
60 ttl: Option<Duration>,
61 ) -> crate::Result<()>;
62 async fn forget(
63 &self,
64 key: &str,
65 ) -> crate::Result<()>;
66
67 async fn clear(&self) -> crate::Result<()> {
68 Err(Error::Rejected(format!(
69 "cache store '{}' with driver '{}' does not support clearing its namespace",
70 self.store_name(),
71 self.driver_name()
72 )))
73 }
74}
75
76pub trait CacheStoreResolver {
82 fn store(
83 &self,
84 name: &str,
85 ) -> crate::Result<Arc<dyn CacheStore>>;
86}
87
88impl CacheStoreResolver for HashMap<String, Arc<dyn CacheStore>> {
89 fn store(
90 &self,
91 name: &str,
92 ) -> crate::Result<Arc<dyn CacheStore>> {
93 self.get(name).cloned().ok_or_else(|| {
94 Error::Missing(format!("cache store '{name}' is not registered"))
95 })
96 }
97}
98
99pub trait CacheDriver: Any + Send + Sync + 'static {
106 fn driver_name(&self) -> &'static str;
107
108 fn create_store(
109 self: Arc<Self>,
110 store_name: &str,
111 config: &CacheStoreConfig,
112 ) -> crate::Result<Arc<dyn CacheStore>>;
113
114 fn create_reload_store(
120 self: Arc<Self>,
121 store_name: &str,
122 config: &CacheStoreConfig,
123 ) -> crate::Result<Arc<dyn CacheStore>> {
124 self.create_store(store_name, config)
125 }
126
127 fn finish_store(
129 &self,
130 _store: &Arc<dyn CacheStore>,
131 _stores: &dyn CacheStoreResolver,
132 ) -> crate::Result<()> {
133 Ok(())
134 }
135}
136
137pub struct CacheRepository {
142 store: Arc<dyn CacheStore>,
143}
144
145impl CacheRepository {
146 pub(crate) fn new(store: Arc<dyn CacheStore>) -> Self {
147 Self { store }
148 }
149
150 pub fn store_name(&self) -> &str {
151 self.store.store_name()
152 }
153
154 pub fn driver_name(&self) -> &str {
155 self.store.driver_name()
156 }
157
158 pub fn supports_ttl(&self) -> bool {
159 self.store.supports_ttl()
160 }
161
162 pub fn as_any(&self) -> &dyn Any {
163 self.store.as_any()
164 }
165
166 pub fn store(&self) -> Arc<dyn CacheStore> {
167 self.store.clone()
168 }
169
170 pub async fn get(
173 &self,
174 key: &str,
175 ) -> crate::Result<Option<Bytes>> {
176 self.store.get(key).await
177 }
178
179 pub async fn put<'v>(
180 &self,
181 key: &str,
182 value: impl Into<Cow<'v, [u8]>>,
183 ttl: Option<Duration>,
184 ) -> crate::Result<()> {
185 self.store.put(key, value.into(), ttl).await
186 }
187
188 pub async fn get_value(
189 &self,
190 key: &str,
191 ) -> crate::Result<Option<CacheValue>> {
192 self.get(key)
193 .await?
194 .map(|bytes| CacheValue::decode(&bytes).map_err(Error::from))
195 .transpose()
196 }
197
198 pub async fn put_value(
199 &self,
200 key: &str,
201 value: CacheValue,
202 ttl: Option<Duration>,
203 ) -> crate::Result<()> {
204 let encoded = value.encode().map_err(Error::from)?;
205 self.put(key, encoded, ttl).await
206 }
207
208 pub async fn forget(
209 &self,
210 key: &str,
211 ) -> crate::Result<()> {
212 self.store.forget(key).await
213 }
214
215 pub async fn clear(&self) -> crate::Result<()> {
216 self.store.clear().await
217 }
218}