use std::{future::Future, time::*, collections::HashMap, hash::Hash};
use reqwest::StatusCode;
#[derive(Debug)]
pub struct AsyncCache<K, V, F> {
func: F,
cache: HashMap<K, (Instant, V)>,
interval: Duration
}
impl<K, V, F, Fut> AsyncCache<K, V, F>
where
for<'a> F: FnMut(&'a K) -> Fut + 'a,
K: Hash + PartialEq + Eq + Clone,
Fut: Future<Output = Result<V, (StatusCode, &'static str)>> + Send + Sync
{
pub fn new(interval: Duration, func: F) -> Self {
Self{
cache: HashMap::new(),
interval, func
}
}
pub async fn get(&mut self, key: &K) -> Result<&V, (StatusCode, &'static str)> {
if self.is_stale(&key) {
log::trace!(target: "lfm::cache", "MISS : interval = {:?}", self.interval);
self.renew(&key).await
} else {
log::trace!(target: "lfm::cache", "HIT : interval = {:?}", self.interval);
Ok(&self.cache.get(&key).unwrap().1)
}
}
pub async fn renew(&mut self, key: &K) -> Result<&V, (StatusCode, &'static str)> {
let val = (self.func)(&key).await?;
self.cache.insert(key.clone(), (Instant::now(), val));
Ok(&self.cache.get(key).unwrap().1)
}
pub fn is_stale(&self, key: &K) -> bool {
if let Some((last_update, _)) = self.cache.get(key) {
let now = Instant::now();
log::trace!(target: "lfm::cache", "Key exists, last update {:?} ago.", now - *last_update);
now > (*last_update + self.interval)
}
else { true }
}
pub async fn get_opt(&self, key: &K) -> Option<&V> {
if self.is_stale(key) {
self.cache.get(key).map(|(_, v)| v)
}
else { None }
}
pub fn interval(&self) -> Duration { self.interval }
}
impl<K, V, F, Fut> AsyncCache<K, V, F>
where
for<'a> F: FnMut(&'a K) -> Fut + 'a,
K: Hash + PartialEq + Eq + Clone,
V: Clone,
Fut: Future<Output = Result<V, (StatusCode, &'static str)>> + Send + Sync
{
pub async fn get_owned(&mut self, key: &K) -> Result<V, (StatusCode, &'static str)> {
self.get(key).await.cloned()
}
}