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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
mod async_cache;

use std::marker::PhantomData;
use std::collections::HashMap;
use std::future::Future;

use async_cache::Cache;
use std::pin::Pin;

pub struct Cacher<T> {
    cache_map: HashMap<String, Cache<T>>,
    _mark: PhantomData<T>,
}

impl<T> Cacher<T> {
    pub fn new() -> Self {
        Self {
            cache_map: HashMap::new(),
            _mark: PhantomData,
        }
    }
    pub async fn fetch(&mut self, key: &str, expires_in_secs: u64, calculation: impl Fn() -> Pin<Box<dyn Future<Output = anyhow::Result<T>>>> + 'static) -> anyhow::Result<&T> {
        let cache: Cache<T> = Cache::new(expires_in_secs, calculation);
        if self.cache_map.get(key).is_none() {
            self.cache_map.insert(key.to_string(), cache);
            let in_cache = self.cache_map.get_mut(key).unwrap();
            return in_cache.value().await
        } else {
            let in_cache = self.cache_map.get_mut(key).unwrap();
            if in_cache.is_value_expires() {
                *in_cache = cache
            }
            return in_cache.value().await
        }
    }
    pub async fn force_fetch(&mut self, key: &str, expires_in_secs: u64, calculation: impl Fn() -> Pin<Box<dyn Future<Output = anyhow::Result<T>>>> + 'static) -> anyhow::Result<&T> {
        let cache: Cache<T> = Cache::new(expires_in_secs, calculation);
        self.cache_map.insert(key.to_string(), cache);
        self.cache_map.get_mut(key).unwrap().value().await
    }
    pub async fn read(&mut self, key: &str) -> anyhow::Result<&T> {
        match self.cache_map.get_mut(key) {
            Some(cache) => {
                cache.value().await
            },
            None => Err(anyhow::anyhow!("cache not exists"))
        }
    }
    pub fn write(&mut self, key: &str, value: T) -> anyhow::Result<()> {
        match self.cache_map.get_mut(key) {
            Some(cache) => {
                cache.update_value(value);
                Ok(())
            },
            None => Err(anyhow::anyhow!("cache not exists"))
        }
    }
    pub fn expire(&mut self, key: &str) -> anyhow::Result<()> {
        match self.cache_map.get_mut(key) {
            Some(cache) => {
                cache.expire_value();
                Ok(())
            },
            None => Err(anyhow::anyhow!("cache not exists"))
        }
    }
    pub fn delete(&mut self, key: &str) -> Option<Cache<T>> {
        self.cache_map.remove(key)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{thread, time};

    async fn test_fetch() -> anyhow::Result<()> {
        let mut i32_cacher = Cacher::<i32>::new();
        {
            let v1 = i32_cacher.fetch("v1", 10, || Box::pin(async { Ok(1)})).await?;
            assert_eq!(v1, &1);
        }
         //  expires
         {
            let v1 = i32_cacher.fetch("v1_expires", 3, || Box::pin(async { Ok(1)})).await?;
            assert_eq!(v1, &1);
            let v1 = i32_cacher.fetch("v1_expires", 0, || Box::pin(async { Ok(2)})).await?;
            assert_eq!(v1, &1); // 数据未过期,继续使用旧数据
            let three_secs = time::Duration::from_secs(3);
            thread::sleep(three_secs);
            let v1 = i32_cacher.fetch("v1_expires", 0, || Box::pin(async { Ok(3)})).await?; // 0 立即失效
            assert_eq!(v1, &3);
            let v1 = i32_cacher.fetch("v1_expires", 0, || Box::pin(async { Ok(4)})).await?;
            assert_eq!(v1, &4);
        }
        let mut string_cacher = Cacher::<String>::new();
        {
            let v1 = string_cacher.fetch("v1", 10, || Box::pin(async { Ok("1".to_string())})).await?;
            assert_eq!(v1, "1");
        }

        Ok(())
    }

    async fn test_force_fetch() -> anyhow::Result<()> {
        let mut i32_cacher = Cacher::<i32>::new();
        let v1 = i32_cacher.force_fetch("v1", 10, || Box::pin(async { Ok(1)})).await?;
        assert_eq!(v1, &1);
        let v1 = i32_cacher.fetch("v1", 10, || Box::pin(async { Ok(3)})).await?;
        assert_eq!(v1, &1);
        let v1 = i32_cacher.force_fetch("v1", 10, || Box::pin(async { Ok(2)})).await?;
        assert_eq!(v1, &2);
        let v1 = i32_cacher.fetch("v1", 10, || Box::pin(async { Ok(3)})).await?;
        assert_eq!(v1, &2);

        Ok(())
    }

    async fn test_read() -> anyhow::Result<()> {
        let mut i32_cacher = Cacher::<i32>::new();
        let v1 = i32_cacher.force_fetch("v1", 10, || Box::pin(async { Ok(1)})).await?;
        assert_eq!(v1, &1);
        let v1 = i32_cacher.read("v1").await;
        assert_eq!(v1.unwrap(), &1);
        let v1 = i32_cacher.read("v2").await;
        assert!(v1.is_err());

        Ok(())
    }

    async fn test_write() -> anyhow::Result<()> {
        let mut i32_cacher = Cacher::<i32>::new();
        let v1 = i32_cacher.fetch("v1", 10, || Box::pin(async { Ok(1)})).await?;
        assert_eq!(v1, &1);
        i32_cacher.write("v1", 3).unwrap();
        let v1 = i32_cacher.fetch("v1", 10, || Box::pin(async { Ok(1)})).await?;
        assert_eq!(v1, &3);

        Ok(())
    }

    async fn test_expire() -> anyhow::Result<()> {
        let mut i32_cacher = Cacher::<i32>::new();
        let v1 = i32_cacher.fetch("v1", 10, || Box::pin(async { Ok(1)})).await?;
        assert_eq!(v1, &1);
        i32_cacher.expire("v1").unwrap();
        let v1 = i32_cacher.fetch("v1", 10, || Box::pin(async { Ok(2)})).await?;
        assert_eq!(v1, &2);

        Ok(())
    }

    async fn test_delete() -> anyhow::Result<()> {
        let mut i32_cacher = Cacher::<i32>::new();
        let v1 = i32_cacher.force_fetch("v1", 10, || Box::pin(async { Ok(1)})).await?;
        assert_eq!(v1, &1);
        let v1 = i32_cacher.delete("v1");
        assert!(v1.is_some());

        Ok(())
    }

    #[test]
    fn test_cacher() {

        async fn test_all() -> anyhow::Result<()> {
            test_fetch().await?;
            test_force_fetch().await?;
            test_read().await?;
            test_write().await?;
            test_expire().await?;
            test_delete().await?;

            Ok(())
        }


        assert!(
            match tokio_test::block_on(test_all()) {
                Ok(()) => Ok(()),
                Err(e) => {
                    eprintln!("err: {:?}", e);
                    Err(e)
                }
            }.is_ok());
    }

}