Files
nym/explorer-api/src/mix_node/cache.rs
T
Mark Sinclair 4ac95ad8cf Explorer API - add port check and node description/stats proxy (#731)
* explorer-api: move mix node client operations into a package

* explorer-api: add port test for mixnodes with cache for results

* explorer-api: add `humantime-serde` dependency

* explorer-api: mix node API proxy

This fixes mixed-content responses when using the mix node API from the network explorer. An in-memory cache protects the explorer API from over-querying the http API on the mix node.

* explorer-api: adjust naming

* explorer-api: fix up self refs

* explorer-api: add method to state to get a mix node by identity key

* explorer-api: add cached http resource to proxy the `/description` and `/stats` http api resources to allow the network explorer do https requests for the mix node api resource avoid mixed content requests

* explorer-api: set default mix node cache time to 30 minutes

* explorer-api: make clippy happy

* explorer-api: add CORS with wide open configuration

* explorer-api: fixes from review feedback

* explorer-api: move port check test into separate function

* explorer-api: use `rocket-cors` that is pinned in the `validator-api` and remove custom CORS handler
2021-08-10 15:27:17 +01:00

42 lines
1002 B
Rust

use std::collections::HashMap;
use std::time::{Duration, SystemTime};
#[derive(Clone)]
pub(crate) struct Cache<T: Clone> {
inner: HashMap<String, CacheItem<T>>,
}
impl<T: Clone> Cache<T> {
pub(crate) fn new() -> Self {
Cache {
inner: HashMap::new(),
}
}
pub(crate) fn get(&self, identity_key: &str) -> Option<T>
where
T: Clone,
{
self.inner
.get(identity_key)
.filter(|cache_item| cache_item.valid_until > SystemTime::now())
.map(|cache_item| cache_item.value.clone())
}
pub(crate) fn set(&mut self, identity_key: &str, value: T) {
self.inner.insert(
identity_key.to_string(),
CacheItem {
valid_until: SystemTime::now() + Duration::from_secs(60 * 30),
value,
},
);
}
}
#[derive(Clone)]
pub(crate) struct CacheItem<T> {
pub(crate) value: T,
pub(crate) valid_until: std::time::SystemTime,
}