typedcache 0.2.1

Concurrent-safe typedcache with expiration capabilities.
Documentation
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use std::{
    collections::HashMap,
    sync::Arc,
    time::{Duration, Instant},
};

use arc_swap::ArcSwap;
use std::sync::RwLock;
use tokio::sync::mpsc::{self, UnboundedSender};

use crate::{
    error::Error,
    item::CacheItem,
    typed::{
        typedkey::{Key, TypedKey, TypedKeyRef},
        TypedMap,
    },
};

/// CacheTable is a table within the cache
#[derive(Clone)]
pub struct CacheTable {
    inner: Arc<CacheTableInner>,
}

struct CacheTableInner {
    /// The table's name.
    name: String,
    /// All cached items.
    items: RwLock<HashMap<TypedKey, CacheItem>>,
    /// The interval for cleaning up expired items.
    clean_up_interval: ArcSwap<Duration>,
    #[allow(clippy::type_complexity)]
    /// Callback method triggered when trying to load a non-existing key.
    load_data: RwLock<Option<Box<dyn Fn(TypedKey) -> Option<CacheItem> + Send + Sync>>>,
    #[allow(clippy::type_complexity)]
    /// Callback methods triggered when an item is added to the cache.
    added_item: RwLock<Vec<Box<dyn Fn(CacheItem) + Send + Sync>>>,
    #[allow(clippy::type_complexity)]
    /// Callback methods triggered when an item is about to be deleted from the cache.
    about_to_delete_item: RwLock<Vec<Box<dyn Fn(CacheItem) + Send + Sync>>>,
    tx: UnboundedSender<()>,
}

impl CacheTable {
    #[must_use]
    pub fn new(name: String) -> Self {
        let (tx, mut rx) = mpsc::unbounded_channel::<()>();
        let cache_table = Self {
            inner: Arc::new(CacheTableInner {
                name,
                items: RwLock::new(HashMap::new()),
                clean_up_interval: ArcSwap::from_pointee(Duration::ZERO),
                load_data: RwLock::new(None),
                added_item: RwLock::new(Vec::new()),
                about_to_delete_item: RwLock::new(Vec::new()),
                tx,
            }),
        };
        tokio::spawn({
            let cache_table = cache_table.clone();
            async move {
                let mut clean_up_timer = Duration::MAX;
                loop {
                    tokio::select! {
                        _ = tokio::time::sleep(clean_up_timer) => {
                            tracing::trace!("Expiration check triggered after {:?} for table {}", clean_up_timer, cache_table.inner.name);
                            let mut smallest_duration = Duration::from_secs(0);
                            {
                                let now = Instant::now();
                                let mut to_remove = Vec::new();
                                let mut w = cache_table.inner.items.write().unwrap();

                                for (_, item) in w.iter() {
                                    let life_span = item.life_span();
                                    let accessed_on = item.accessed_on();
                                    if life_span == Duration::ZERO {
                                        continue;
                                    }
                                    if now.duration_since(accessed_on) >= life_span {
                                        to_remove.push(item.clone());
                                    } else {
                                        let duration = life_span - now.duration_since(accessed_on);
                                        if smallest_duration == Duration::from_secs(0) || duration < smallest_duration {
                                            smallest_duration = duration;
                                        }
                                    }
                                }

                                for item in to_remove {
                                    if let Some(item) = w.remove(item.key()) {
                                        {
                                            let about_to_delete_item = cache_table.inner.about_to_delete_item.read().unwrap();
                                            if !about_to_delete_item.is_empty() {
                                                for callback in about_to_delete_item.iter() {
                                                    callback(item.clone());
                                                }
                                            }
                                        }

                                        {
                                            let about_to_expire = item.inner.about_to_expire.read().unwrap();
                                            if !about_to_expire.is_empty() {
                                                for callback in about_to_expire.iter() {
                                                    callback(item.key());
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if smallest_duration <= Duration::ZERO {
                                clean_up_timer = Duration::MAX;
                                cache_table.inner.clean_up_interval.store(Arc::new(Duration::ZERO));
                            } else {
                                clean_up_timer = smallest_duration;
                                cache_table.inner.clean_up_interval.store(Arc::new(smallest_duration));
                            }
                        }
                        r = rx.recv() => {
                            if r.is_some() {
                                clean_up_timer = Duration::ZERO;
                            } else {
                                tracing::trace!("Cache table {} is closed", cache_table.inner.name);
                                break;
                            }
                        }
                    }
                }
            }
        });

        cache_table
    }

    /// Return how many items are currently stored in the cache.
    pub fn count(&self) -> usize {
        self.inner.items.read().unwrap().len()
    }

    /// Trans all items
    pub fn foreach(&self, trans: impl Fn(&TypedKey, CacheItem)) {
        let items = self.inner.items.read().unwrap();
        for (k, v) in items.iter() {
            trans(k, v.clone());
        }
    }

    /// Configures a data-loader callback, which will be called when trying to access a non-existing key.
    pub fn set_data_loader(
        &mut self,
        f: impl Fn(TypedKey) -> Option<CacheItem> + Send + Sync + 'static,
    ) {
        *self.inner.load_data.write().unwrap() = Some(Box::new(f));
    }

    /// Configures a callback, which will be called when an item is added to the cache.
    pub fn set_added_item_callback(&mut self, f: impl Fn(CacheItem) + Send + Sync + 'static) {
        if !self.inner.added_item.read().unwrap().is_empty() {
            self.remove_added_item_callbacks();
        }
        self.inner.added_item.write().unwrap().push(Box::new(f));
    }

    /// Appends a new callback to the added_item queue.
    pub fn add_added_item_callback(&mut self, f: impl Fn(CacheItem) + Send + Sync + 'static) {
        self.inner.added_item.write().unwrap().push(Box::new(f));
    }

    /// Removes all added_item callbacks.
    pub fn remove_added_item_callbacks(&mut self) {
        self.inner.added_item.write().unwrap().clear();
    }

    /// Configures a callback, which will be called when an item is about to be deleted from the cache.
    pub fn set_about_to_delete_item_callback(
        &mut self,
        f: impl Fn(CacheItem) + Send + Sync + 'static,
    ) {
        if !self.inner.about_to_delete_item.read().unwrap().is_empty() {
            self.remove_about_to_delete_item_callbacks();
        }
        self.inner
            .about_to_delete_item
            .write()
            .unwrap()
            .push(Box::new(f));
    }

    pub fn add_about_to_delete_item_callback(
        &mut self,
        f: impl Fn(CacheItem) + Send + Sync + 'static,
    ) {
        self.inner
            .about_to_delete_item
            .write()
            .unwrap()
            .push(Box::new(f));
    }

    /// Removes all about_to_delete_item callbacks.
    pub fn remove_about_to_delete_item_callbacks(&mut self) {
        self.inner.about_to_delete_item.write().unwrap().clear();
    }

    /// Adds a key/value pair to the cache.
    ///
    /// Parameter key is the item's cache-key.
    /// Parameter life_span determines after which time period without an access the item will get removed from the cache.
    /// Parameter value is the item's value.
    pub fn add<K: 'static + TypedMap + Send + Sync + Clone>(
        &self,
        key: K,
        life_span: Duration,
        value: K::Value,
    ) -> Option<CacheItem>
    where
        K::Value: Send + Sync,
    {
        let item = CacheItem::new(key.clone(), life_span, value);
        self.add_internal(key, item)
    }

    fn add_internal<K: 'static + TypedMap + Send + Sync + Clone>(
        &self,
        key: K,
        item: CacheItem,
    ) -> Option<CacheItem>
    where
        K::Value: Send + Sync,
    {
        tracing::trace!(
            "Adding item with lifespan of {:?} to table {}",
            item.life_span(),
            self.inner.name
        );
        let ret = self
            .inner
            .items
            .write()
            .unwrap()
            .insert(TypedKey::from_key(key), item.clone());

        {
            let added_item = self.inner.added_item.read().unwrap();
            if !added_item.is_empty() {
                for callback in added_item.iter() {
                    callback(item.clone());
                }
            }
        }

        let exp_dur = self.inner.clean_up_interval.load();
        if item.life_span() > Duration::ZERO
            && (**exp_dur == Duration::ZERO || item.life_span() < **exp_dur)
        {
            match self.inner.tx.send(()) {
                Ok(_) => {}
                Err(e) => {
                    tracing::error!("Error sending to channel for clean_up: {}", e);
                }
            }
        }

        ret
    }

    /// Returns the value of the item with the given key.
    pub fn get<K: 'static + TypedMap + Send + Sync + Clone>(&self, key: &K) -> Option<CacheItem>
    where
        K::Value: Send + Sync,
    {
        let typed_key_ref = TypedKeyRef::from_key_ref(key);
        self.inner
            .items
            .read()
            .unwrap()
            .get(&typed_key_ref as &dyn Key)
            .cloned()
    }

    /// Deletes the item with the given key from the cache.
    pub fn delete<K: 'static + TypedMap + Send + Sync + Clone>(
        &self,
        key: &K,
    ) -> Result<CacheItem, Error>
    where
        K::Value: Send + Sync,
    {
        self.delete_internal(key)
    }

    fn delete_internal<K: 'static + TypedMap + Send + Sync + Clone>(
        &self,
        key: &K,
    ) -> Result<CacheItem, Error>
    where
        K::Value: Send + Sync,
    {
        let typed_key_ref = TypedKeyRef::from_key_ref(key);
        if let Some(item) = self
            .inner
            .items
            .write()
            .unwrap()
            .remove(&typed_key_ref as &dyn Key)
        {
            tracing::trace!(
                "Deleting item created on {:?} and hit {} times from table {}",
                item.created_on(),
                item.access_count(),
                self.inner.name
            );

            {
                let about_to_delete_item = self.inner.about_to_delete_item.read().unwrap();
                if !about_to_delete_item.is_empty() {
                    for callback in about_to_delete_item.iter() {
                        callback(item.clone());
                    }
                }
            }

            {
                let about_to_expire = item.inner.about_to_expire.read().unwrap();
                if !about_to_expire.is_empty() {
                    for callback in about_to_expire.iter() {
                        callback(item.key());
                    }
                }
            }

            Ok(item)
        } else {
            Err(Error::KeyNotFound)
        }
    }

    /// Returns whether an item exists in the cache.
    ///
    /// Unlike the value method, exists neither tries to fetch data via the loadData callback nor does it keep the item alive in the cache.
    pub fn exists<K: 'static + TypedMap + Send + Sync + Clone>(&self, key: K) -> bool
    where
        K::Value: Send + Sync,
    {
        self.inner
            .items
            .read()
            .unwrap()
            .contains_key(&TypedKey::from_key(key))
    }

    /// Checks whether an item is not yet cached.
    ///
    /// Unlike the exists method this also adds data if the key could not be found.
    pub fn not_found_add<K: 'static + TypedMap + Send + Sync + Clone>(
        &self,
        key: K,
        life_span: Duration,
        value: K::Value,
    ) -> bool
    where
        K::Value: Send + Sync,
    {
        if self
            .inner
            .items
            .write()
            .unwrap()
            .contains_key(&TypedKey::from_key(key.clone()))
        {
            return false;
        }
        let item = CacheItem::new(key.clone(), life_span, value);
        self.add_internal(key, item);
        true
    }

    /// Returns an item from the cache and marks it to be kept alive.
    pub fn value<K: 'static + TypedMap + Send + Sync + Clone>(
        &self,
        key: K,
    ) -> Result<CacheItem, Error>
    where
        K::Value: Send + Sync,
    {
        let typed_key = TypedKey::from_key(key.clone());
        let items = self.inner.items.read().unwrap();
        if let Some(item) = items.get(&typed_key) {
            item.keep_alive();
            Ok(item.clone())
        } else {
            drop(items);
            let load_data = self.inner.load_data.read().unwrap();
            if let Some(load_data) = load_data.as_ref() {
                if let Some(item) = load_data(typed_key) {
                    self.add_internal(key, item.clone());
                    return Ok(item);
                }
                Err(Error::KeyNotFoundOrLoadable)
            } else {
                Err(Error::KeyNotFound)
            }
        }
    }

    /// Deletes all items from this cache table.
    pub fn flush(&self) {
        tracing::trace!("Flushing table {}", self.inner.name);
        self.inner.items.write().unwrap().clear();
        self.inner.clean_up_interval.store(Arc::new(Duration::ZERO));
    }
}