http_cache/managers/
cacache.rs1use std::path::PathBuf;
2
3use crate::{CacheManager, HttpResponse, Result};
4
5use http_cache_semantics::CachePolicy;
6use serde::{Deserialize, Serialize};
7
8#[cfg_attr(docsrs, doc(cfg(feature = "manager-cacache")))]
10#[derive(Debug, Clone)]
11pub struct CACacheManager {
12 pub path: PathBuf,
14}
15
16impl Default for CACacheManager {
17 fn default() -> Self {
18 Self { path: "./http-cacache".into() }
19 }
20}
21
22#[derive(Debug, Deserialize, Serialize)]
23struct Store {
24 response: HttpResponse,
25 policy: CachePolicy,
26}
27
28#[allow(dead_code)]
29impl CACacheManager {
30 pub async fn clear(&self) -> Result<()> {
32 cacache::clear(&self.path).await?;
33 Ok(())
34 }
35}
36
37#[async_trait::async_trait]
38impl CacheManager for CACacheManager {
39 async fn get(
40 &self,
41 cache_key: &str,
42 ) -> Result<Option<(HttpResponse, CachePolicy)>> {
43 let store: Store = match cacache::read(&self.path, cache_key).await {
44 Ok(d) => bincode::deserialize(&d)?,
45 Err(_e) => {
46 return Ok(None);
47 }
48 };
49 Ok(Some((store.response, store.policy)))
50 }
51
52 async fn put(
53 &self,
54 cache_key: String,
55 response: HttpResponse,
56 policy: CachePolicy,
57 ) -> Result<HttpResponse> {
58 let data = Store { response: response.clone(), policy };
59 let bytes = bincode::serialize(&data)?;
60 cacache::write(&self.path, cache_key, bytes).await?;
61 Ok(response)
62 }
63
64 async fn delete(&self, cache_key: &str) -> Result<()> {
65 Ok(cacache::remove(&self.path, cache_key).await?)
66 }
67}