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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::error::Error;
use std::fmt::Debug;
use std::hash::Hash;
use std::sync::{Arc, Mutex};

use tokio::sync::Mutex as AsyncMutex;
use tokio::time::{Duration, Instant};

use crate::io::Stream;

pub trait CacheKey: Eq + Hash + Debug {}
impl<T: Eq + Hash + Debug> CacheKey for T {}

pub trait StreamCreator: Fn() -> Result<Stream, Box<dyn Error>> + Send + Sync + 'static {}
impl<T: Fn() -> Result<Stream, Box<dyn Error>> + Send + Sync + 'static> StreamCreator for T {}

struct CacheEntry {
    stream: Arc<AsyncMutex<Stream>>,
    last_activity: Instant,
}

const DEFAULT_CLEANUP_INTERVAL: Duration = Duration::from_secs(60);

pub struct StreamsCache<F: StreamCreator, K: CacheKey> {
    new_stream_creator: F,
    entries: Mutex<HashMap<K, CacheEntry>>,
    idle_entry_timeout: Duration,
    cleanup_interval: Duration,
    last_cleanup: Mutex<Instant>,
}

impl<F: StreamCreator, K: CacheKey> StreamsCache<F, K> {
    pub fn new(
        new_stream_creator: F,
        idle_entry_timeout: Duration,
        cleanup_interval: Duration,
    ) -> Self {
        Self {
            new_stream_creator,
            entries: Mutex::new(HashMap::new()),
            idle_entry_timeout,
            cleanup_interval,
            last_cleanup: Mutex::new(Instant::now()),
        }
    }

    pub fn with_default_cleanup_duration(
        new_stream_creator: F,
        idle_entry_timeout: Duration,
    ) -> Self {
        StreamsCache::new(
            new_stream_creator,
            idle_entry_timeout,
            DEFAULT_CLEANUP_INTERVAL,
        )
    }

    pub fn get(&self, key: K, now: Instant) -> Result<Arc<AsyncMutex<Stream>>, Box<dyn Error>> {
        let res = self.get_or_create_stream(key, now);
        let mut last_cleanup = self.last_cleanup.lock().unwrap();
        if now - *last_cleanup > self.cleanup_interval {
            self.cleanup_old_idle_streams(now);
            *last_cleanup = now;
        };
        res
    }

    fn get_or_create_stream(
        &self,
        key: K,
        now: Instant,
    ) -> Result<Arc<AsyncMutex<Stream>>, Box<dyn Error>> {
        let new_stream_creator = &self.new_stream_creator;
        let mut entries = self.entries.lock().unwrap();
        log::debug!("got key {:?}, entries size is {}", key, entries.len());
        let entry = match entries.entry(key) {
            Entry::Occupied(o) => o.into_mut(),
            Entry::Vacant(v) => v.insert(CacheEntry {
                stream: Arc::new(AsyncMutex::new(new_stream_creator()?)),
                last_activity: now,
            }),
        };
        entry.last_activity = now;
        Ok(entry.stream.clone())
    }

    fn cleanup_old_idle_streams(&self, now: Instant) {
        let mut entries = self.entries.lock().unwrap();
        entries.retain(|_, v| now - v.last_activity < self.idle_entry_timeout);
    }
}

#[cfg(test)]
mod tests {
    use tokio::time::Duration;
    use tokio_test::io::Builder;

    use super::*;

    #[test]
    fn stream_cache_get_new_stream_creator_failed() -> Result<(), Box<dyn Error>> {
        let cache = StreamsCache::new(
            || Err(String::from("bla").into()),
            Duration::from_secs(3 * 60),
            Duration::from_secs(60),
        );
        let res = cache.get("bla", Instant::now());
        assert!(res.is_err());
        Ok(())
    }

    #[test]
    fn stream_cache_get_new_stream_success() -> Result<(), Box<dyn Error>> {
        let cache = StreamsCache::new(
            || Ok(Stream::new(Builder::new().build(), Builder::new().build())),
            Duration::from_secs(3 * 60),
            Duration::from_secs(60),
        );

        let now = Instant::now();
        cache.get("bla", now)?;

        let entries = cache.entries.lock().unwrap();
        assert_eq!(entries.len(), 1);
        assert!(entries.contains_key("bla"));
        assert_eq!(entries.get("bla").unwrap().last_activity, now);
        let last_cleanup = cache.last_cleanup.lock().unwrap();
        assert_ne!(*last_cleanup, now);
        Ok(())
    }

    #[test]
    fn stream_cache_get_new_stream_another_exists() -> Result<(), Box<dyn Error>> {
        let t1 = Instant::now();
        let cache = StreamsCache::new(
            || Ok(Stream::new(Builder::new().build(), Builder::new().build())),
            Duration::from_secs(3 * 60),
            Duration::from_secs(60),
        );
        {
            let mut entries = cache.entries.lock().unwrap();
            let entry = CacheEntry {
                stream: Arc::new(AsyncMutex::new(Stream::new(
                    Builder::new().build(),
                    Builder::new().build(),
                ))),
                last_activity: t1,
            };
            entries.insert("bli", entry);
        }

        let mut t2 = t1.clone();
        t2 += Duration::from_secs(1);
        cache.get("bla", t2)?;

        let entries = cache.entries.lock().unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.contains_key("bla"));
        assert_eq!(entries.get("bla").unwrap().last_activity, t2);
        assert!(entries.contains_key("bli"));
        assert_eq!(entries.get("bli").unwrap().last_activity, t1);
        let last_cleanup = cache.last_cleanup.lock().unwrap();
        assert_ne!(*last_cleanup, t2);
        Ok(())
    }

    #[test]
    fn stream_cache_get_existing_stream_success() -> Result<(), Box<dyn Error>> {
        let mut now = Instant::now();
        let cache = StreamsCache::new(
            || Err(String::from("bla").into()),
            Duration::from_secs(3 * 60),
            Duration::from_secs(60),
        );
        {
            let mut entries = cache.entries.lock().unwrap();
            let entry = CacheEntry {
                stream: Arc::new(AsyncMutex::new(Stream::new(
                    Builder::new().build(),
                    Builder::new().build(),
                ))),
                last_activity: now,
            };
            entries.insert("bla", entry);
        }

        now += Duration::from_secs(1);
        cache.get("bla", now)?;

        let entries = cache.entries.lock().unwrap();
        assert_eq!(entries.len(), 1);
        assert!(entries.contains_key("bla"));
        assert_eq!(entries.get("bla").unwrap().last_activity, now);
        let last_cleanup = cache.last_cleanup.lock().unwrap();
        assert_ne!(*last_cleanup, now);
        Ok(())
    }

    #[test]
    fn stream_cache_get_auto_cleanup() -> Result<(), Box<dyn Error>> {
        let mut now = Instant::now();
        let cache = StreamsCache::new(
            || Ok(Stream::new(Builder::new().build(), Builder::new().build())),
            Duration::from_secs(1),
            Duration::from_secs(1),
        );
        {
            let mut entries = cache.entries.lock().unwrap();
            let entry = CacheEntry {
                stream: Arc::new(AsyncMutex::new(Stream::new(
                    Builder::new().build(),
                    Builder::new().build(),
                ))),
                last_activity: now,
            };
            entries.insert("bli", entry);
        }

        now += Duration::from_secs(5);
        cache.get("bla", now)?;

        let entries = cache.entries.lock().unwrap();
        assert_eq!(entries.len(), 1);
        assert!(entries.contains_key("bla"));
        assert_eq!(entries.get("bla").unwrap().last_activity, now);
        let last_cleanup = cache.last_cleanup.lock().unwrap();
        assert_eq!(*last_cleanup, now);
        Ok(())
    }
}