1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use crate::{CacheManager, HttpResponse, Result};
use std::{fmt, sync::Arc};
use http_cache_semantics::CachePolicy;
use moka::future::{Cache, ConcurrentCacheExt};
use serde::{Deserialize, Serialize};
use url::Url;
#[cfg_attr(docsrs, doc(cfg(feature = "manager-moka")))]
#[derive(Clone)]
pub struct MokaManager {
pub cache: Arc<Cache<String, Arc<Vec<u8>>>>,
}
impl fmt::Debug for MokaManager {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("MokaManager").finish_non_exhaustive()
}
}
impl Default for MokaManager {
fn default() -> Self {
Self::new(Cache::new(42))
}
}
#[derive(Debug, Deserialize, Serialize)]
struct Store {
response: HttpResponse,
policy: CachePolicy,
}
fn req_key(method: &str, url: &Url) -> String {
format!("{}:{}", method, url)
}
impl MokaManager {
pub fn new(cache: Cache<String, Arc<Vec<u8>>>) -> Self {
Self { cache: Arc::new(cache) }
}
pub async fn clear(&self) -> Result<()> {
self.cache.invalidate_all();
self.cache.sync();
Ok(())
}
}
#[async_trait::async_trait]
impl CacheManager for MokaManager {
async fn get(
&self,
method: &str,
url: &Url,
) -> Result<Option<(HttpResponse, CachePolicy)>> {
let store: Store = match self.cache.get(&req_key(method, url)) {
Some(d) => bincode::deserialize(&d)?,
None => return Ok(None),
};
Ok(Some((store.response, store.policy)))
}
async fn put(
&self,
method: &str,
url: &Url,
response: HttpResponse,
policy: CachePolicy,
) -> Result<HttpResponse> {
let data = Store { response: response.clone(), policy };
let bytes = bincode::serialize(&data)?;
self.cache.insert(req_key(method, url), Arc::new(bytes)).await;
self.cache.sync();
Ok(response)
}
async fn delete(&self, method: &str, url: &Url) -> Result<()> {
self.cache.invalidate(&req_key(method, url)).await;
self.cache.sync();
Ok(())
}
}