launchdarkly_server_sdk/stores/
persistent_store_cache.rs

1use std::collections::HashMap;
2use std::hash::Hash;
3use std::time::Duration;
4
5use moka::sync::Cache;
6
7use super::store_types::StorageItem;
8
9pub(super) struct CachePair<T> {
10    all: Cache<String, HashMap<String, StorageItem<T>>>,
11    single: Cache<String, StorageItem<T>>,
12    cache_name: String,
13}
14
15impl<T: 'static + Sync + Send + Clone> CachePair<T> {
16    pub fn new(cache_name: String, cache_ttl: Option<Duration>) -> CachePair<T> {
17        match cache_ttl {
18            Some(ttl) => CachePair {
19                all: Cache::builder().time_to_live(ttl).build(),
20                single: Cache::builder().time_to_live(ttl).build(),
21                cache_name,
22            },
23            None => CachePair {
24                all: Cache::builder().build(),
25                single: Cache::builder().build(),
26                cache_name,
27            },
28        }
29    }
30
31    pub fn cache_is_infinite(&self) -> bool {
32        self.all.policy().time_to_live().is_none()
33    }
34
35    pub fn get_all(&self) -> Option<HashMap<String, StorageItem<T>>> {
36        self.all.get(&self.all_key())
37    }
38
39    pub fn get_one(&self, key: &str) -> Option<StorageItem<T>> {
40        self.single.get(&self.single_key(key))
41    }
42
43    pub fn insert_single(&self, item: StorageItem<T>, key: &str) {
44        self.insert_into_cache(&self.single, self.single_key(key), item)
45    }
46
47    pub fn insert_all(&self, data: HashMap<String, StorageItem<T>>) {
48        self.insert_into_cache(&self.all, self.all_key(), data)
49    }
50
51    fn insert_into_cache<K, V>(&self, cache: &Cache<K, V>, key: K, value: V)
52    where
53        K: Hash + Eq + Send + Sync + 'static,
54        V: Clone + Send + Sync + 'static,
55    {
56        match cache.policy().time_to_live() {
57            None => cache.insert(key, value),
58            Some(duration) if !duration.is_zero() => cache.insert(key, value),
59            _ => (),
60        }
61    }
62
63    fn all_key(&self) -> String {
64        format!("all:{}", self.cache_name)
65    }
66
67    fn single_key(&self, key: &str) -> String {
68        format!("{}:{}", self.cache_name, key)
69    }
70
71    pub fn invalidate_all(&self) {
72        self.all.invalidate_all();
73    }
74
75    pub fn invalidate_single(&self, key: &str) {
76        self.single.invalidate(&self.single_key(key));
77    }
78
79    pub fn invalidate_everything(&self) {
80        self.all.invalidate_all();
81        self.single.invalidate_all();
82    }
83}