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, 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 forget(
114        &self,
115        key: &str,
116    ) -> crate::Result<()> {
117        match cacache::remove(self.path(), self.scoped_key(key)).await {
118            Ok(()) | Err(cacache::Error::EntryNotFound(_, _)) => Ok(()),
119            Err(err) => Err(Error::wrap(
120                format!(
121                    "file cache forget failed for store '{}'",
122                    self.store_name
123                ),
124                err,
125            )),
126        }
127    }
128
129    async fn clear(&self) -> crate::Result<()> {
130        let Some(prefix) =
131            self.prefix.clone().filter(|prefix| !prefix.is_empty())
132        else {
133            if !self.path.try_exists()? {
134                return Ok(());
135            }
136            return cacache::clear(self.path()).await.map_err(|err| {
137                Error::wrap(
138                    format!(
139                        "file cache clear failed for store '{}'",
140                        self.store_name
141                    ),
142                    err,
143                )
144            });
145        };
146
147        let path = self.path.clone();
148        let keys = tokio::task::spawn_blocking(
149            move || -> crate::Result<Vec<String>> {
150                if !path.try_exists()? {
151                    return Ok(Vec::new());
152                }
153                cacache::list_sync(path)
154                    .filter_map(|entry| match entry {
155                        Ok(metadata) if metadata.key.starts_with(&prefix) => {
156                            Some(Ok(metadata.key))
157                        }
158                        Ok(_) => None,
159                        Err(error) => Some(Err(error)),
160                    })
161                    .collect::<cacache::Result<Vec<_>>>()
162                    .map_err(Error::from)
163            },
164        )
165        .await
166        .map_err(|err| {
167            Error::wrap(
168                format!(
169                    "file cache clear scan failed for store '{}'",
170                    self.store_name
171                ),
172                err,
173            )
174        })?
175        .map_err(|err| {
176            Error::wrap(
177                format!(
178                    "file cache clear scan failed for store '{}'",
179                    self.store_name
180                ),
181                err,
182            )
183        })?;
184
185        for key in keys {
186            match cacache::remove(self.path(), key).await {
187                Ok(()) | Err(cacache::Error::EntryNotFound(_, _)) => {}
188                Err(err) => {
189                    return Err(Error::wrap(
190                        format!(
191                            "file cache clear failed for store '{}'",
192                            self.store_name
193                        ),
194                        err,
195                    ));
196                }
197            }
198        }
199        Ok(())
200    }
201}
202
203impl CacheDriver for FileCacheDriver {
204    fn driver_name(&self) -> &'static str {
205        "file"
206    }
207
208    fn create_store(
209        self: Arc<Self>,
210        store_name: &str,
211        store: &CacheStoreConfig,
212    ) -> crate::Result<Arc<dyn CacheStore>> {
213        let config: FileCacheStoreConfig = store.deserialize_options()?;
214        Ok(Arc::new(FileCacheStore::new(
215            store_name,
216            PathBuf::from(config.path),
217            config.prefix,
218        )))
219    }
220}
221
222#[cfg(test)]
223#[path = "../../tests/drivers/file.rs"]
224mod tests;