Skip to main content

claviron_cache/drivers/
file.rs

1use std::any::Any;
2use std::borrow::Cow;
3use std::path::PathBuf;
4use std::sync::Arc;
5use std::time::Duration;
6
7use async_trait::async_trait;
8use bytes::Bytes;
9
10use crate::config::{CacheStoreConfig, FileCacheStoreConfig};
11use crate::{CacheDriver, CacheEntry, CacheExpiry, CacheStore, Error};
12
13#[derive(Debug, Default)]
14pub struct FileCacheDriver;
15
16#[derive(Debug, Clone)]
17pub struct FileCacheStore {
18    store_name: String,
19    path: PathBuf,
20    prefix: Option<String>,
21}
22
23impl FileCacheStore {
24    pub fn new(
25        store_name: impl Into<String>,
26        path: PathBuf,
27        prefix: Option<String>,
28    ) -> Self {
29        Self { store_name: store_name.into(), path, prefix }
30    }
31
32    pub fn path(&self) -> &PathBuf {
33        &self.path
34    }
35
36    pub fn prefix(&self) -> Option<&str> {
37        self.prefix.as_deref()
38    }
39
40    fn scoped_key(
41        &self,
42        key: &str,
43    ) -> String {
44        match self.prefix() {
45            Some(prefix) => format!("{prefix}{key}"),
46            None => key.to_string(),
47        }
48    }
49}
50
51#[async_trait]
52impl CacheStore for FileCacheStore {
53    fn store_name(&self) -> &str {
54        &self.store_name
55    }
56
57    fn driver_name(&self) -> &str {
58        "file"
59    }
60
61    fn as_any(&self) -> &dyn Any {
62        self
63    }
64
65    fn supports_ttl(&self) -> bool {
66        false
67    }
68
69    async fn get(
70        &self,
71        key: &str,
72    ) -> crate::Result<Option<Bytes>> {
73        match cacache::read(self.path(), self.scoped_key(key)).await {
74            Ok(bytes) => Ok(Some(Bytes::from(bytes))),
75            Err(cacache::Error::EntryNotFound(_, _)) => Ok(None),
76            Err(err) => Err(Error::wrap(
77                format!(
78                    "file cache get failed for store '{}'",
79                    self.store_name
80                ),
81                err,
82            )),
83        }
84    }
85
86    async fn put(
87        &self,
88        key: &str,
89        value: Cow<'_, [u8]>,
90        ttl: Option<Duration>,
91    ) -> crate::Result<()> {
92        if ttl.is_some() {
93            return Err(Error::Rejected(format!(
94                "file cache store '{}' does not support TTL for key '{key}'",
95                self.store_name
96            )));
97        }
98
99        cacache::write(self.path(), self.scoped_key(key), value.as_ref())
100            .await
101            .map_err(|err| {
102                Error::wrap(
103                    format!(
104                        "file cache put failed for store '{}'",
105                        self.store_name
106                    ),
107                    err,
108                )
109            })?;
110        Ok(())
111    }
112
113    async fn get_entry(
114        &self,
115        key: &str,
116    ) -> crate::Result<Option<CacheEntry>> {
117        Ok(self
118            .get(key)
119            .await?
120            .map(|bytes| CacheEntry { bytes, expiry: CacheExpiry::Never }))
121    }
122
123    async fn forget(
124        &self,
125        key: &str,
126    ) -> crate::Result<()> {
127        match cacache::remove(self.path(), self.scoped_key(key)).await {
128            Ok(()) | Err(cacache::Error::EntryNotFound(_, _)) => Ok(()),
129            Err(err) => Err(Error::wrap(
130                format!(
131                    "file cache forget failed for store '{}'",
132                    self.store_name
133                ),
134                err,
135            )),
136        }
137    }
138
139    async fn clear(&self) -> crate::Result<()> {
140        let Some(prefix) =
141            self.prefix.clone().filter(|prefix| !prefix.is_empty())
142        else {
143            if !self.path.try_exists()? {
144                return Ok(());
145            }
146            return cacache::clear(self.path()).await.map_err(|err| {
147                Error::wrap(
148                    format!(
149                        "file cache clear failed for store '{}'",
150                        self.store_name
151                    ),
152                    err,
153                )
154            });
155        };
156
157        let path = self.path.clone();
158        let keys = tokio::task::spawn_blocking(
159            move || -> crate::Result<Vec<String>> {
160                if !path.try_exists()? {
161                    return Ok(Vec::new());
162                }
163                cacache::list_sync(path)
164                    .filter_map(|entry| match entry {
165                        Ok(metadata) if metadata.key.starts_with(&prefix) => {
166                            Some(Ok(metadata.key))
167                        }
168                        Ok(_) => None,
169                        Err(error) => Some(Err(error)),
170                    })
171                    .collect::<cacache::Result<Vec<_>>>()
172                    .map_err(Error::from)
173            },
174        )
175        .await
176        .map_err(|err| {
177            Error::wrap(
178                format!(
179                    "file cache clear scan failed for store '{}'",
180                    self.store_name
181                ),
182                err,
183            )
184        })?
185        .map_err(|err| {
186            Error::wrap(
187                format!(
188                    "file cache clear scan failed for store '{}'",
189                    self.store_name
190                ),
191                err,
192            )
193        })?;
194
195        for key in keys {
196            match cacache::remove(self.path(), key).await {
197                Ok(()) | Err(cacache::Error::EntryNotFound(_, _)) => {}
198                Err(err) => {
199                    return Err(Error::wrap(
200                        format!(
201                            "file cache clear failed for store '{}'",
202                            self.store_name
203                        ),
204                        err,
205                    ));
206                }
207            }
208        }
209        Ok(())
210    }
211}
212
213impl CacheDriver for FileCacheDriver {
214    fn driver_name(&self) -> &'static str {
215        "file"
216    }
217
218    fn create_store(
219        self: Arc<Self>,
220        store_name: &str,
221        store: &CacheStoreConfig,
222    ) -> crate::Result<Arc<dyn CacheStore>> {
223        let config: FileCacheStoreConfig = store.deserialize_options()?;
224        Ok(Arc::new(FileCacheStore::new(
225            store_name,
226            PathBuf::from(config.path),
227            config.prefix,
228        )))
229    }
230}
231
232#[cfg(test)]
233#[path = "../../tests/drivers/file.rs"]
234mod tests;