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
// Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use crate::store::storage::Value;

use serde::{Deserialize, Serialize};

use std::{
    collections::{hash_map::Entry, HashMap},
    fmt::Debug,
    hash::Hash,
    time::{Duration, SystemTime},
};

/// The [`Cache`] struct used to store the data in an ordered format.
// #[deprecated(note = "use [`stronghold_iota_new::client_new::types::cache::Cache")]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Cache<K, V>
where
    K: Hash + Eq + Clone,
    V: Clone + Debug,
{
    // hashmap of data.
    table: HashMap<K, Value<V>>,
    // the scan frequency for removing data based on the expiration time.
    scan_freq: Option<Duration>,
    // a created at timestamp.
    created_at: SystemTime,
    // a last scan timestamp.
    last_scan_at: Option<SystemTime>,
}

impl<K: Hash + Eq + Clone, V: Clone + Debug> Cache<K, V> {
    /// creates a new empty [`Cache`]
    /// # Example
    /// ```
    /// use engine::store::Cache;
    /// use std::time::Duration;
    ///
    /// let mut cache = Cache::new();
    ///
    /// let key: Vec<u8> = b"key".to_vec();
    /// let value: Vec<u8> = b"value".to_vec();
    ///
    /// cache.insert(key.clone(), value.clone(), None);
    ///
    /// assert_eq!(cache.get(&key), Some(&value))
    /// ```
    pub fn new() -> Self {
        Self {
            table: HashMap::new(),
            scan_freq: None,
            created_at: SystemTime::now(),
            last_scan_at: None,
        }
    }

    /// creates an empty [`Cache`] with a periodic scanner which identifies expired entries.
    ///
    /// # Example
    /// ```
    /// use engine::store::Cache;
    /// use std::time::Duration;
    ///
    /// let scan_freq = Duration::from_secs(60);
    ///
    /// let mut cache = Cache::create_with_scanner(scan_freq);
    ///
    /// let key: &'static str = "key";
    /// let value: &'static str = "value";
    ///
    /// cache.insert(key, value, None);
    ///
    /// assert_eq!(cache.get(&key), Some(&value));
    /// ```
    pub fn create_with_scanner(scan_freq: Duration) -> Self {
        Self {
            table: HashMap::new(),
            scan_freq: Some(scan_freq),
            created_at: SystemTime::now(),
            last_scan_at: None,
        }
    }

    /// Gets the value associated with the specified key.
    ///
    /// # Example
    /// ```
    /// use engine::store::Cache;
    /// use std::time::Duration;
    ///
    /// let mut cache = Cache::new();
    ///
    /// let key: &'static str = "key";
    /// let value: &'static str = "value";
    ///
    /// cache.insert(key, value, None);
    ///
    /// assert_eq!(cache.get(&key), Some(&value))
    /// ```
    pub fn get(&self, key: &K) -> Option<&V> {
        let now = SystemTime::now();

        self.table
            .get(key)
            .filter(|value| !value.has_expired(now))
            .map(|value| &value.val)
    }

    /// Gets the value associated with the specified key.  If the key could not be found in the [`Cache`], creates and
    /// inserts the value using a specified `func` function. # Example
    /// ```
    /// use engine::store::Cache;
    /// use std::time::Duration;
    ///
    /// let mut cache = Cache::new();
    ///
    /// let key = "key";
    /// let value = "value";
    ///
    /// assert_eq!(cache.get_or_insert(key, move || value, None), &value);
    /// assert!(cache.contains_key(&key));
    /// ```
    pub fn get_or_insert<F>(&mut self, key: K, func: F, lifetime: Option<Duration>) -> &V
    where
        F: Fn() -> V,
    {
        let now = SystemTime::now();

        self.try_remove_expired_items(now);

        match self.table.entry(key) {
            Entry::Occupied(mut occ) => {
                if occ.get().has_expired(now) {
                    occ.insert(Value::new(func(), lifetime));
                }

                &occ.into_mut().val
            }
            Entry::Vacant(vac) => &vac.insert(Value::new(func(), lifetime)).val,
        }
    }

    /// Insert a key-value pair into the cache.
    /// If key was not present, a [`None`] is returned, else the value is updated and the old value is returned.  
    ///
    /// # Example
    /// ```
    /// use engine::store::Cache;
    /// use std::time::Duration;
    ///
    /// let mut cache = Cache::new();
    ///
    /// let key: &'static str = "key";
    /// let value: &'static str = "value";
    ///
    /// let insert = cache.insert(key, value, None);
    ///
    /// assert_eq!(cache.get(&key), Some(&value));
    /// assert!(insert.is_none());
    /// ```
    pub fn insert(&mut self, key: K, value: V, lifetime: Option<Duration>) -> Option<V> {
        let now = SystemTime::now();

        self.try_remove_expired_items(now);

        self.table
            .insert(key, Value::new(value, lifetime))
            .filter(|value| !value.has_expired(now))
            .map(|value| value.val)
    }

    /// Removes a key from the cache.  Returns the value from the key if the key existed in the cache.
    ///
    /// # Example
    ///
    /// ```
    /// use engine::store::Cache;
    /// use std::time::Duration;
    ///
    /// let mut cache = Cache::new();
    ///
    /// let key: &'static str = "key";
    /// let value: &'static str = "value";
    ///
    /// let insert = cache.insert(key, value, None);
    /// assert_eq!(cache.remove(&key), Some(value));
    /// assert!(!cache.contains_key(&key));
    /// ```
    pub fn remove(&mut self, key: &K) -> Option<V> {
        let now = SystemTime::now();

        self.try_remove_expired_items(now);

        self.table
            .remove(key)
            .filter(|value| !value.has_expired(now))
            .map(|value| value.val)
    }

    // Check if the [`Cache<K, V>`] contains a specific key.
    pub fn contains_key(&self, key: &K) -> bool {
        let now = SystemTime::now();

        self.table.get(key).filter(|value| !value.has_expired(now)).is_some()
    }

    // Get the last scanned at time.
    pub fn get_last_scanned_at(&self) -> Option<SystemTime> {
        self.last_scan_at
    }

    /// Get the cache's scan frequency.
    ///
    /// # Example
    /// ```
    /// use engine::store::Cache;
    /// use std::time::Duration;
    ///
    /// let scan_freq = Duration::from_secs(60);
    ///
    /// let mut cache = Cache::create_with_scanner(scan_freq);
    ///
    /// let key: &'static str = "key";
    /// let value: &'static str = "value";
    ///
    /// cache.insert(key, value, None);
    ///
    /// assert_eq!(cache.get_scan_freq(), Some(scan_freq));
    /// ```
    pub fn get_scan_freq(&self) -> Option<Duration> {
        self.scan_freq
    }

    /// Clear the stored cache and reset.
    pub fn clear(&mut self) {
        self.table.clear();
        self.scan_freq = None;
        self.created_at = SystemTime::now();
        self.last_scan_at = None;
    }

    /// Returns a list of all keys inside the [`Cache`] as references
    pub fn keys(&self) -> Vec<K> {
        self.table.keys().cloned().collect()
    }

    /// attempts to remove expired items based on the current system time provided.
    fn try_remove_expired_items(&mut self, now: SystemTime) {
        if let Some(frequency) = self.scan_freq {
            let since = now
                .duration_since(self.last_scan_at.unwrap_or(self.created_at))
                .expect("System time is before the scanned time");

            if since >= frequency {
                self.table.retain(|_, value| !value.has_expired(now));

                self.last_scan_at = Some(now)
            }
        }
    }
}

/// Default implementation for [`Cache<K, V>`]
impl<K: Hash + Eq + Clone, V: Clone + Debug> Default for Cache<K, V> {
    fn default() -> Self {
        Cache::new()
    }
}