summaryrefslogtreecommitdiff
path: root/src/modules/cache.rs
diff options
context:
space:
mode:
authormetamuffin <metamuffin@disroot.org>2024-08-25 01:13:23 +0200
committermetamuffin <metamuffin@disroot.org>2024-08-25 01:13:23 +0200
commit1063e44e625d72a78ef57eaadfcf5ce8c1678e27 (patch)
tree6b8f65942f4b58f206177768e5ec62fb17b4a2a2 /src/modules/cache.rs
parentecb3378d29a4f53604a9287ef7027a299f3d45d5 (diff)
downloadgnix-1063e44e625d72a78ef57eaadfcf5ce8c1678e27.tar
gnix-1063e44e625d72a78ef57eaadfcf5ce8c1678e27.tar.bz2
gnix-1063e44e625d72a78ef57eaadfcf5ce8c1678e27.tar.zst
very bad basic caching
Diffstat (limited to 'src/modules/cache.rs')
-rw-r--r--src/modules/cache.rs28
1 files changed, 22 insertions, 6 deletions
diff --git a/src/modules/cache.rs b/src/modules/cache.rs
index d306ed1..03dc1be 100644
--- a/src/modules/cache.rs
+++ b/src/modules/cache.rs
@@ -14,11 +14,12 @@ use crate::{config::DynNode, error::ServiceError};
use anyhow::Result;
use bytes::Bytes;
use http::Response;
-use http_body_util::BodyExt;
+use http_body_util::{BodyExt, Full};
use serde::Deserialize;
use serde_yaml::Value;
use sha2::{Digest, Sha256};
use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc};
+use tokio::sync::RwLock;
pub struct CacheKind;
@@ -28,7 +29,7 @@ struct CacheConfig {
}
struct Cache {
- entries: HashMap<[u8; 32], Response<Bytes>>,
+ entries: RwLock<HashMap<[u8; 32], Response<Bytes>>>,
config: CacheConfig,
}
@@ -40,7 +41,7 @@ impl NodeKind for CacheKind {
let config = serde_yaml::from_value::<CacheConfig>(config)?;
Ok(Arc::new(Cache {
config,
- entries: HashMap::new(),
+ entries: HashMap::new().into(),
}))
}
}
@@ -60,13 +61,28 @@ impl Node for Cache {
}
let key: [u8; 32] = hasher.finalize().try_into().unwrap();
- if let Some(resp) = self.entries.get(&key) {
- // Ok(resp.to_owned().map(|b| b.map_err(|e| match e {}).boxed()))
+ if let Some(resp) = self.entries.read().await.get(&key) {
+ return Ok(resp
+ .to_owned()
+ .map(|b| Full::new(b).map_err(|e| match e {}).boxed()));
}
let response = self.config.next.handle(context, request).await?;
- Ok(response)
+ let h = response.headers().to_owned();
+ let s = response.status().to_owned();
+ let body = response.collect().await?.to_bytes();
+
+ let mut r1 = Response::new(Full::new(body.clone()).map_err(|e| match e {}).boxed());
+ *r1.headers_mut() = h.clone();
+ *r1.status_mut() = s.clone();
+
+ let mut r2 = Response::new(body);
+ *r2.headers_mut() = h;
+ *r2.status_mut() = s;
+ self.entries.write().await.insert(key, r2);
+
+ Ok(r1)
})
}
}