remcached 0.3.0

Caching system designed for efficient storage and retrieval of entities from remote repositories (REST APIs, Database, ...etc)
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
414
415
416
417
418
419
420
421
422
423
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::atomic::Ordering::Relaxed;
use std::sync::mpsc::{Sender, SendError};

use dashmap::{DashMap, Entry};

use crate::cache_manager::CacheManager;
use crate::cache_task::{CacheTask, Invalidation};
use crate::async_executor::AsyncExecutor;
use crate::metrics::{async_measure, measure};
use crate::r_cache_config::RCacheConfig;
use crate::r_commands::RCommands;
use crate::types::{GenericError, GenericType};

struct CacheTaskProducer<RC>
where
    RC: RCommands + 'static,
{
    config: RCacheConfig,
    statistics: TaskProducerStatistics,
    tx: Sender<CacheTask>,
    _phantom: PhantomData<RC>,
}

impl<RC> CacheTaskProducer<RC>
where
    RC: RCommands + 'static,
{
    pub fn new(config: RCacheConfig, tx: Sender<CacheTask>) -> Self {
        Self { config, statistics: Default::default(), tx, _phantom: Default::default() }
    }

    pub fn expire(&self, key: RC::Key) -> Result<(), SendError<CacheTask>> {
        let task = CacheTask::entry_expiration(self.config.entry_expires_in(), self.config.cache_id(), key);
        self.send(task)
    }

    fn send(&self, task: CacheTask) -> Result<(), SendError<CacheTask>> {
        let result = self.tx.send(task);
        self.statistics.tasks_produced_total.fetch_add(1, Relaxed);
        if result.is_err() {
            self.statistics.tasks_produced_errors_total.fetch_add(1, Relaxed);
        }

        result
    }
}

#[derive(Default, Debug)]
pub struct TaskProducerStatistics {
    tasks_produced_total: AtomicU64,
    tasks_produced_errors_total: AtomicU64,
}
impl TaskProducerStatistics {
    pub fn tasks_produced_total(&self) -> u64 {
        self.tasks_produced_total.load(Relaxed)
    }
    pub fn tasks_produced_errors_total(&self) -> u64 {
        self.tasks_produced_errors_total.load(Relaxed)
    }
}

#[derive(Default, Debug)]
pub struct CacheStatistics {
    hits_total: AtomicU64,
    hits_time_ms: AtomicU64,
    miss_total: AtomicU64,
    miss_time_ms: AtomicU64,
    gets_errors_total: AtomicU64,
    puts_total: AtomicU64,
    puts_errors_total: AtomicU64,
    puts_time_ms: AtomicU64,
    invalidations_processed_total: AtomicU64,
    invalidations_processed_time_ms: AtomicU64,
    expirations_processed_total: AtomicU64,
    expirations_processed_time_ms: AtomicU64,
}

impl CacheStatistics {
    pub fn hits_total(&self) -> u64 {
        self.hits_total.load(Relaxed)
    }
    pub fn hits_time_ms(&self) -> u64 {
        self.hits_time_ms.load(Relaxed)
    }
    pub fn miss_time_ms(&self) -> u64 {
        self.miss_time_ms.load(Relaxed)
    }
    pub fn puts_total(&self) -> u64 {
        self.puts_total.load(Relaxed)
    }

    pub fn puts_errors_total(&self) -> u64 {
        self.puts_errors_total.load(Relaxed)
    }
    pub fn puts_time_ms(&self) -> u64 {
        self.puts_time_ms.load(Relaxed)
    }
    pub fn miss_total(&self) -> u64 {
        self.miss_total.load(Relaxed)
    }
    pub fn gets_errors_total(&self) -> u64 {
        self.gets_errors_total.load(Relaxed)
    }

    pub fn invalidations_processed_total(&self) -> u64 {
        self.invalidations_processed_total.load(Relaxed)
    }
    pub fn invalidations_processed_time_ms(&self) -> u64 {
        self.invalidations_processed_time_ms.load(Relaxed)
    }
    pub fn expirations_processed_total(&self) -> u64 {
        self.expirations_processed_total.load(Relaxed)
    }
    pub fn expirations_processed_time_ms(&self) -> u64 {
        self.expirations_processed_time_ms.load(Relaxed)
    }
}

pub struct RCache<RC>
where
    RC: RCommands + 'static,
{
    task_producer: CacheTaskProducer<RC>,
    storage: DashMap<RC::Key, RC::Value>,
    statistics: CacheStatistics,
    remote_commands: RC,
    config: RCacheConfig,
    initialized: AtomicBool,
}


impl<RC> RCache<RC>
where
    RC: RCommands + 'static,
{
    pub fn build<E: AsyncExecutor>(cache_manager: &mut CacheManager<E>, config: RCacheConfig, remote_commands: RC) -> Arc<RCache<RC>> {
        let self_ = Arc::new(Self {
            task_producer: CacheTaskProducer::new(config, cache_manager.sender()),
            storage: DashMap::default(),
            statistics: Default::default(),
            initialized: Default::default(),
            config,
            remote_commands,
        });
        cache_manager.register(RCacheInputValidator::<RC>::new(), RCacheTaskProcessor::new(self_.clone()));
        self_
    }
    pub async fn get(&self, key: &RC::Key) -> Result<Option<RC::Value>, GenericError> {
        if !self.is_initialized() {
            return async_measure(&self.statistics.miss_total, &self.statistics.miss_time_ms, async {
                self.get_internal(key).await
            }).await;
        }

        return match self.storage.get(key) {
            None => {
                async_measure(&self.statistics.miss_total, &self.statistics.miss_time_ms, async {
                    log::trace!("cache miss for #{key} entry and #{} cache", self.cache_id());
                    let val = match self.get_internal(key).await? {
                        None => {
                            return Ok(None);
                        }
                        Some(val) => {
                            val
                        }
                    };

                    match self.storage.entry(key.clone()) {
                        Entry::Occupied(_) => {}
                        Entry::Vacant(entry) => {
                            entry.insert(val.clone());
                            if let Err(err) = self.task_producer.expire(key.clone()) {
                                log::error!("add expiration failed for #{key} entry and #{} cache caused by: {err}", self.cache_id());
                                self.storage.remove(key);
                            }
                        }
                    }


                    Ok(Some(val))
                }).await
            }
            Some(val) => {
                measure(&self.statistics.hits_total, &self.statistics.hits_time_ms, || {
                    log::trace!("cache hit for #{key} entry and #{} cache", self.cache_id());
                    Ok(Some(val.value().clone()))
                })
            }
        };
    }


    pub async fn put(&self, key: &RC::Key, value: &RC::Value) -> Result<(), GenericError> {
        if !self.is_initialized() {
            return async_measure(&self.statistics.puts_total, &self.statistics.puts_time_ms, async {
                self.put_internal(key, value).await
            }).await;
        }

        async_measure(&self.statistics.puts_total, &self.statistics.puts_time_ms, async {
            self.put_internal(key, value).await?;

            self.storage.insert(key.clone(), value.clone());
            if let Err(err) = self.task_producer.expire(key.clone()) {
                log::error!("expiration failed for #{key} entry and #{} cache caused by: {err}", self.cache_id());
                self.storage.remove(key);
            }

            Ok(())
        }).await
    }

    async fn put_internal(&self, key: &RC::Key, value: &RC::Value) -> Result<(), GenericError> {
        let result = self.remote_commands.put(key, value).await;
        if result.is_err() {
            self.statistics.puts_errors_total.fetch_add(1, Relaxed);
            return result;
        }

        result
    }

    async fn get_internal(&self, key: &RC::Key) -> Result<Option<RC::Value>, GenericError> {
        let result = self.remote_commands.get(key).await;
        if result.is_err() {
            log::error!("get failed for #{key} entry and #{} cache", self.cache_id());
            self.statistics.gets_errors_total.fetch_add(1, Relaxed);
        }
        result
    }
    fn is_initialized(&self) -> bool {
        if !self.initialized.load(Ordering::Acquire) {
            log::warn!("#{} cache is not initialized!", self.cache_id());
            return false;
        }

        true
    }
    pub fn statistics(&self) -> &CacheStatistics {
        &self.statistics
    }
    pub fn task_producer_statistics(&self) -> &TaskProducerStatistics {
        &self.task_producer.statistics
    }
    pub fn len(&self) -> usize {
        self.storage.len()
    }
    pub fn is_empty(&self) -> bool {
        self.storage.is_empty()
    }
    pub fn contains_key(&self, key: &RC::Key) -> bool {
        self.storage.contains_key(key)
    }

    pub fn cache_id(&self) -> &'static str {
        self.config.cache_id()
    }
}


pub trait CacheTaskProcessor: Send + Sync {
    fn init(&self);
    fn stop(&self);
    fn flush_all(&self);
    fn expire(&self, key: GenericType);
    fn invalidate_with_properties(&self, invalidation: GenericType);
    fn invalidate(&self, key: GenericType) -> Pin<Box<dyn Future<Output=Result<(), GenericError>> + Send>>;
    fn cache_id(&self) -> &'static str;
}

struct RCacheTaskProcessor<RC>
where
    RC: RCommands + 'static,
{
    ref_: Arc<RCache<RC>>,
}

impl<RC> RCacheTaskProcessor<RC>
where
    RC: RCommands + 'static,
{
    pub fn new(ref_: Arc<RCache<RC>>) -> Self {
        Self { ref_ }
    }
}

impl<RC> CacheTaskProcessor for RCacheTaskProcessor<RC>
where
    RC: RCommands,
{
    fn init(&self) {
        self.ref_.initialized.store(true, Ordering::Release);
        log::info!("initialized #{} cache", self.ref_.cache_id());
    }

    fn stop(&self) {
        self.ref_.initialized.store(false, Ordering::Release);
        log::info!("stopped #{} cache", self.ref_.cache_id());
    }

    fn flush_all(&self) {
        self.stop();
        self.ref_.storage.clear();
        log::info!("flushed all entries of #{} cache", self.ref_.cache_id());
        self.init();
    }

    fn expire(&self, key: GenericType) {
        measure(&self.ref_.statistics.expirations_processed_total, &self.ref_.statistics.expirations_processed_time_ms, || {
            let key = key.downcast::<RC::Key>().expect("Key conversion successfully");
            log::trace!("#{key} entry expired successfully for #{} cache", self.ref_.cache_id());
            self.ref_.storage.remove(&key);
        })
    }

    fn invalidate_with_properties(&self, invalidation: GenericType) {
        measure(&self.ref_.statistics.invalidations_processed_total, &self.ref_.statistics.invalidations_processed_time_ms, || {
            let invalidation = invalidation.downcast::<Invalidation<RC::Key, RC::Value>>().expect("Invalidation conversion successfully");

            match self.ref_.storage.entry(invalidation.key().clone()) {
                Entry::Occupied(entry) => {
                    entry.replace_entry(invalidation.value().clone());
                }
                Entry::Vacant(entry) => {
                    log::trace!("#{} entry invalidation skipped due to not found in #{} cache", entry.key(), self.ref_.cache_id());
                    return;
                }
            }

            if self.ref_.task_producer.expire(invalidation.key().clone()).is_err() {
                self.ref_.storage.remove(invalidation.key());
                return;
            }

            log::trace!("#{} entry invalidated with properties successfully for #{} cache", invalidation.key(), self.ref_.cache_id());
        })
    }


    fn invalidate(&self, key: GenericType) -> Pin<Box<dyn Future<Output=Result<(), GenericError>> + Send>> {
        let ref_ = Arc::clone(&self.ref_);
        Box::pin(
            async move {
                let key = key.downcast::<RC::Key>().expect("Key conversion successfully");

                if !ref_.storage.contains_key(&key) {
                    log::trace!("#{} entry invalidation skipped due to not found in #{} cache", key, ref_.cache_id());
                    return Ok(());
                }

                let result = match ref_.get_internal(&key).await? {
                    None => {
                        log::trace!("#{} entry invalidation skipped due to not found in remote repository for #{} cache", key, ref_.cache_id());
                        return Ok(());
                    }
                    Some(result) => {
                        result
                    }
                };

                match ref_.storage.entry(*key.clone()) {
                    Entry::Occupied(entry) => {
                        entry.replace_entry(result);
                    }
                    Entry::Vacant(entry) => {
                        log::trace!("#{} entry invalidation skipped due to not found in #{} cache", entry.key(), ref_.cache_id());
                        return Ok(());
                    }
                }

                if ref_.task_producer.expire(*key.clone()).is_err() {
                    ref_.storage.remove(&key);
                }

                log::trace!("#{} entry invalidated successfully for #{} cache", key, ref_.cache_id());
                Ok(())
            }
        )
    }


    fn cache_id(&self) -> &'static str {
        self.ref_.cache_id()
    }
}


pub trait InputValidator: Send {
    fn validate(&self, input: &GenericType, is_invalidation_with_props: bool) -> bool;
}
struct RCacheInputValidator<RC>
where
    RC: RCommands + 'static,
{
    phantom_: PhantomData<RC>,
}
impl<RC> RCacheInputValidator<RC>
where
    RC: RCommands + 'static,
{
    pub fn new() -> Self {
        Self { phantom_: Default::default() }
    }
}

impl<RC> InputValidator for RCacheInputValidator<RC>
where
    RC: RCommands + 'static,
{
    fn validate(&self, input: &GenericType, is_invalidation: bool) -> bool {
        if !is_invalidation {
            return input.downcast_ref::<RC::Key>().is_some();
        }
        input.downcast_ref::<Invalidation<RC::Key, RC::Value>>().is_some()
    }
}