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
use std::{
    collections::HashMap,
    hash::Hash,
    sync::Arc,
    time::{Duration, Instant},
};

use futures_util::Future;
use tokio::sync::Mutex;

struct Item<V> {
    deadline: Instant,
    value: V,
}

struct Inner<K, V> {
    timeout: Duration,
    values: HashMap<K, Item<V>>,
}

#[derive(Clone)]
pub(crate) struct CacheWithKey<K, V> {
    inner: Arc<Mutex<Inner<K, V>>>,
}

impl<K, V> CacheWithKey<K, V>
where
    K: Eq + Hash + Clone,
    V: Clone,
{
    pub(crate) fn new(timeout: Duration) -> Self {
        CacheWithKey {
            inner: Arc::new(Mutex::new(Inner {
                timeout,
                values: HashMap::new(),
            })),
        }
    }

    pub(crate) async fn get_or_update<F, Fut, Err>(&self, key: K, f: F) -> Result<V, Err>
    where
        F: FnOnce(K) -> Fut,
        Fut: Future<Output = Result<V, Err>>,
    {
        let mut inner = self.inner.lock().await;
        match inner.values.get(&key) {
            Some(Item { deadline, value }) if deadline < &Instant::now() => Ok(value.clone()),
            _ => {
                let value = f(key.clone()).await?;
                let deadline = Instant::now() + inner.timeout;
                inner.values.insert(
                    key,
                    Item {
                        deadline,
                        value: value.clone(),
                    },
                );
                Ok(value)
            }
        }
    }
}

#[derive(Clone)]
pub(crate) struct Cache<V> {
    inner: CacheWithKey<(), V>,
}

impl<V> Cache<V>
where
    V: Clone,
{
    pub(crate) fn new(timeout: Duration) -> Self {
        Cache {
            inner: CacheWithKey::new(timeout),
        }
    }

    pub(crate) async fn get_or_update<F, Fut, Err>(&self, f: F) -> Result<V, Err>
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = Result<V, Err>>,
    {
        self.inner.get_or_update((), |_| f()).await
    }
}