aboutsummaryrefslogtreecommitdiffstats
path: root/src/cache.rs
blob: 0c254cb1474534d0943b71b421e5828ca6d9569c (plain) (blame)
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
88
89
// SPDX-License-Identifier: AGPL-3.0-only
pub mod font;
pub mod user;

use std::future::Future;
use std::time::*;
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::Arc;
use std::pin::Pin;

use tokio::sync::RwLock;
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!("MISS : interval = {:?}", self.interval);
      self.renew(key).await
    } else {
      log::trace!("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!("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()
  }
}

pub type CacheFuture<Output> = Pin<Box<(dyn Future<Output = Result<Output, (StatusCode, &'static str)>> + Send + Sync)>>;
pub type CacheGetter<Output> = fn(&String) -> CacheFuture<Output>;
pub type Cache<Output>       = Arc<RwLock<AsyncCache<String, Output, CacheGetter<Output>>>>;

pub fn touch() {
  user::touch();
  font::touch();
}