http_cache_quickcache/
lib.rs

1use http_cache::{CacheManager, HttpResponse, Result};
2
3use std::{fmt, sync::Arc};
4
5use http_cache_semantics::CachePolicy;
6use quick_cache::sync::Cache;
7use serde::{Deserialize, Serialize};
8
9/// Implements [`CacheManager`] with [`quick-cache`](https://github.com/arthurprs/quick-cache) as the backend.
10#[derive(Clone)]
11pub struct QuickManager {
12    /// The instance of `quick_cache::sync::Cache`
13    pub cache: Arc<Cache<String, Arc<Vec<u8>>>>,
14}
15
16impl fmt::Debug for QuickManager {
17    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
18        // need to add more data, anything helpful
19        f.debug_struct("QuickManager").finish_non_exhaustive()
20    }
21}
22
23impl Default for QuickManager {
24    fn default() -> Self {
25        Self::new(Cache::new(42))
26    }
27}
28
29#[derive(Debug, Deserialize, Serialize)]
30struct Store {
31    response: HttpResponse,
32    policy: CachePolicy,
33}
34
35impl QuickManager {
36    /// Create a new manager from a pre-configured Cache
37    pub fn new(cache: Cache<String, Arc<Vec<u8>>>) -> Self {
38        Self { cache: Arc::new(cache) }
39    }
40}
41
42#[async_trait::async_trait]
43impl CacheManager for QuickManager {
44    async fn get(
45        &self,
46        cache_key: &str,
47    ) -> Result<Option<(HttpResponse, CachePolicy)>> {
48        let store: Store = match self.cache.get(cache_key) {
49            Some(d) => bincode::deserialize(&d)?,
50            None => return Ok(None),
51        };
52        Ok(Some((store.response, store.policy)))
53    }
54
55    async fn put(
56        &self,
57        cache_key: String,
58        response: HttpResponse,
59        policy: CachePolicy,
60    ) -> Result<HttpResponse> {
61        let data = Store { response: response.clone(), policy };
62        let bytes = bincode::serialize(&data)?;
63        self.cache.insert(cache_key, Arc::new(bytes));
64        Ok(response)
65    }
66
67    async fn delete(&self, cache_key: &str) -> Result<()> {
68        self.cache.remove(cache_key);
69        Ok(())
70    }
71}
72
73#[cfg(test)]
74mod test;