lib/
db_cache.rs

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
use std::any::Any;
use std::error::Error;
use std::marker::PhantomData;
use std::sync::Arc;
use std::sync::mpsc::{Sender, SendError};

use dashmap::DashMap;
use sqlx::Pool;

use crate::cache_manager::CacheManager;
use crate::cache_task::CacheTask;
use crate::db_cache_config::DbCacheConfig;
use crate::db_commands::DbCommands;
use crate::utils::GenericError;

struct CacheEventProcessor<DBC>
where
    DBC: DbCommands + 'static,
{
    db_cache_config: DbCacheConfig,
    tx: Sender<CacheTask>,
    _phantom: PhantomData<DBC>,
}

impl<DBC> CacheEventProcessor<DBC>
where
    DBC: DbCommands + 'static,
{
    pub fn new(db_cache_config: DbCacheConfig, tx: Sender<CacheTask>) -> Self {
        Self { db_cache_config, tx, _phantom: Default::default() }
    }
    pub fn invalidate(&self, key: DBC::Key) -> Result<(), SendError<CacheTask>> {
        let task = CacheTask::invalidation(self.db_cache_config.expires_in(), self.db_cache_config.cache_id(), Box::new(key));
        self.tx.send(task)
    }
}

pub struct DbCache<DBC>
where
    DBC: DbCommands + 'static,
{
    db_pool: Pool<DBC::Db>,
    cache_event_processor: CacheEventProcessor<DBC>,
    db_storage: DashMap<DBC::Key, DBC::Value>,
    config: DbCacheConfig,
}

impl<DBC> DbCache<DBC>
where
    DBC: DbCommands + 'static,
{
    pub fn build(cache_manager: &mut CacheManager, config: DbCacheConfig, db_pool: Pool<DBC::Db>) -> Arc<DbCache<DBC>> {
        let self_ = Arc::new(Self {
            db_pool,
            cache_event_processor: CacheEventProcessor::new(config, cache_manager.sender()),
            db_storage: DashMap::default(),
            config,
        });
        cache_manager.register(self_.clone());
        self_
    }
    pub async fn get(&self, key: &DBC::Key) -> Option<DBC::Value> {
        return match self.db_storage.get(key) {
            None => {
                println!("cache miss for #{key} key");
                let val = match DBC::get(&self.db_pool, key).await {
                    None => {
                        return None;
                    }
                    Some(val) => {
                        val
                    }
                };


                self.db_storage.insert(key.clone(), val.clone());
                if let Err(err) = self.cache_event_processor.invalidate(key.clone()) {
                    println!("Error sending invalidate cache task caused by: {err}");
                    self.db_storage.remove(key);
                }

                Some(val)
            }
            Some(val) => {
                println!("cache hit for #{key} key");
                Some(val.value().clone())
            }
        };
    }


    pub async fn put(&self, key: DBC::Key, value: DBC::Value) -> Result<(), GenericError> {
        DBC::put(&self.db_pool, key.clone(), value.clone()).await?;
        self.db_storage.insert(key.clone(), value);
        if let Err(err) = self.cache_event_processor.invalidate(key.clone()) {
            println!("Error sending invalidate cache task caused by: {err}");
            self.db_storage.remove(&key);
        }

        Ok(())
    }

    pub fn remove(&self, key: &DBC::Key) {
        self.db_storage.remove(key);
    }


    pub fn cache(&self) -> &DashMap<DBC::Key, DBC::Value> {
        &self.db_storage
    }
}


pub trait CacheInvalidator: Send + Sync {
    fn invalidate(&self, key: Box<dyn Any + Send>);
    fn cache_id(&self) -> &'static str;
}


impl<DBC> CacheInvalidator for DbCache<DBC>
where
    DBC: DbCommands,
{
    fn invalidate(&self, key: Box<dyn Any + Send>) {
        let val = match key.downcast::<DBC::Key>() {
            Ok(val) => {
                val
            }
            Err(err) => {
                println!("Error executing invalidation for #{} cache caused by: {err:?}", self.cache_id());
                return;
            }
        };

        println!("Executing invalidation for #{val} key and #{} cache", self.cache_id());
        self.remove(&val);
    }

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