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
impl CacheIndexTrait for DeltaMptId {}

struct CacheUtil {
    cache_data: HashMap<
        DeltaMptId,
        (Arc<dyn DeltaDbTrait + Send + Sync>, LRUHandle<u32>),
    >,
}

impl CacheStoreUtil for CacheUtil {
    type CacheAlgoData = LRUHandle<u32>;
    type ElementIndex = DeltaMptId;

    fn get(&self, element_index: DeltaMptId) -> LRUHandle<u32> {
        match self.cache_data.get(&element_index) {
            Some(tuple) => tuple.1,
            None => {
                unreachable!();
            }
        }
    }

    fn set(&mut self, element_index: DeltaMptId, algo_data: &LRUHandle<u32>) {
        match self.cache_data.get_mut(&element_index) {
            Some(tuple) => tuple.1 = *algo_data,
            None => {
                unreachable!();
            }
        }
    }
}

#[derive(Clone)]
pub struct ArcDeltaDbWrapper {
    // inner will always be Some() before drop
    pub inner: Option<Arc<dyn DeltaDbTrait>>,
    pub lru: Option<Weak<Mutex<dyn OnDemandOpenDeltaDbInnerTrait>>>,
    pub mpt_id: DeltaMptId,
}

impl ArcDeltaDbWrapper {
    pub fn db_ref(&self) -> &dyn DeltaDbTrait {
        self.inner.as_ref().unwrap().as_ref()
    }
}

impl Deref for ArcDeltaDbWrapper {
    type Target = dyn DeltaDbTrait;

    fn deref(&self) -> &Self::Target { self.inner.as_ref().unwrap().as_ref() }
}

impl Drop for ArcDeltaDbWrapper {
    fn drop(&mut self) {
        if self.lru.is_none() {
            // TODO: This is for SingleMptState.
            return;
        }
        Weak::upgrade(self.lru.as_ref().unwrap()).map(|lru| {
            let mut lru_lock = lru.lock();
            let maybe_arc_db = self.inner.take();
            let need_release =
                Arc::strong_count(maybe_arc_db.as_ref().unwrap()) == 2;
            drop(maybe_arc_db);
            if need_release {
                lru_lock.release(self.mpt_id, false);
            }
        });
    }
}

impl KeyValueDbTypes for ArcDeltaDbWrapper {
    type ValueType = Box<[u8]>;
}

impl KeyValueDbTraitRead for ArcDeltaDbWrapper {
    fn get(&self, key: &[u8]) -> Result<Option<Self::ValueType>> {
        (**self).get(key)
    }
}

mark_kvdb_multi_reader!(ArcDeltaDbWrapper);

pub trait OnDemandOpenDeltaDbInnerTrait: Send + Sync {
    fn open(&mut self, mpt_id: DeltaMptId) -> Result<ArcDeltaDbWrapper>;
    fn create(
        &mut self, snapshot_epoch_id: &EpochId, mpt_id: DeltaMptId,
        opened_db: Option<Arc<dyn DeltaDbTrait + Send + Sync>>,
    ) -> Result<ArcDeltaDbWrapper>;
    fn release(&mut self, mpt_id: DeltaMptId, destroy: bool);
}

// TODO: Allow pinning the DeltaDb for the latest state.
pub trait OpenableOnDemandOpenDeltaDbTrait: Send + Sync {
    fn open(&self, mpt_id: DeltaMptId) -> Result<ArcDeltaDbWrapper>;
}

pub struct OpenDeltaDbLru<DeltaDbManager: DeltaDbManagerTrait> {
    inner: Arc<Mutex<dyn OnDemandOpenDeltaDbInnerTrait>>,
    phantom: PhantomData<DeltaDbManager>,
}

impl<T: 'static + DeltaDbManagerTrait + Send + Sync> OpenDeltaDbLru<T>
where T::DeltaDb: 'static + Send + Sync + DeltaDbTrait
{
    pub fn new(delta_db_manager: Arc<T>, capacity: u32) -> Result<Self> {
        Ok(Self {
            inner: Arc::new(Mutex::new(OpenDeltaDbLruInner::new(
                delta_db_manager,
                capacity,
            )?)),
            phantom: PhantomData,
        })
    }

    pub fn create(
        &self, snapshot_epoch_id: &EpochId, mpt_id: DeltaMptId,
    ) -> Result<ArcDeltaDbWrapper> {
        let mut arc_db = self
            .inner
            .lock()
            .create(snapshot_epoch_id, mpt_id, None)
            .unwrap();
        arc_db.lru = Some(Arc::downgrade(&self.inner));
        Ok(arc_db)
    }

    pub fn import(
        &self, snapshot_epoch_id: &EpochId, mpt_id: DeltaMptId,
        opened_db: T::DeltaDb,
    ) -> Result<ArcDeltaDbWrapper> {
        let mut arc_db = self
            .inner
            .lock()
            .create(snapshot_epoch_id, mpt_id, Some(Arc::new(opened_db)))
            .unwrap();
        arc_db.lru = Some(Arc::downgrade(&self.inner));
        Ok(arc_db)
    }

    pub fn release(&self, mpt_id: DeltaMptId, destroy: bool) {
        self.inner.lock().release(mpt_id, destroy);
    }
}

impl<T: 'static + DeltaDbManagerTrait + Send + Sync>
    OpenableOnDemandOpenDeltaDbTrait for OpenDeltaDbLru<T>
where T::DeltaDb: 'static + Send + Sync + DeltaDbTrait
{
    fn open(&self, mpt_id: DeltaMptId) -> Result<ArcDeltaDbWrapper> {
        let mut arc_db = self.inner.lock().open(mpt_id).unwrap();
        arc_db.lru = Some(Arc::downgrade(&self.inner));
        Ok(arc_db)
    }
}

pub struct OpenDeltaDbLruInner<DeltaDbManager: DeltaDbManagerTrait> {
    delta_db_manager: Arc<DeltaDbManager>,
    mpt_id_to_snapshot_epoch_id: HashMap<DeltaMptId, EpochId>,
    cache_util: CacheUtil,
    lru: LRU<u32, DeltaMptId>,
}

impl<T: DeltaDbManagerTrait + Send + Sync> OpenDeltaDbLruInner<T>
where T::DeltaDb: 'static + Send + Sync + DeltaDbTrait
{
    pub fn new(delta_db_manager: Arc<T>, capacity: u32) -> Result<Self> {
        Ok(Self {
            delta_db_manager,
            mpt_id_to_snapshot_epoch_id: HashMap::new(),
            cache_util: CacheUtil {
                cache_data: HashMap::new(),
            },
            lru: LRU::<u32, DeltaMptId>::new(capacity),
        })
    }

    fn lru_access(&mut self, mpt_id: DeltaMptId) {
        match self.lru.access(mpt_id, &mut self.cache_util) {
            CacheAccessResult::MissReplaced {
                evicted: lru_evicted_keys,
                evicted_keep_cache_algo_data: _,
            } => {
                // It's known to contain exactly one item.
                let lru_evicted = unsafe { lru_evicted_keys.get_unchecked(0) };
                self.release(*lru_evicted, false);
            }
            _ => {}
        }
    }
}

impl<T: DeltaDbManagerTrait + Send + Sync> OnDemandOpenDeltaDbInnerTrait
    for OpenDeltaDbLruInner<T>
where T::DeltaDb: 'static + Send + Sync + DeltaDbTrait
{
    fn open(&mut self, mpt_id: DeltaMptId) -> Result<ArcDeltaDbWrapper> {
        match self.cache_util.cache_data.get(&mpt_id) {
            Some(tuple) => {
                let arc_db = tuple.0.clone();
                self.lru_access(mpt_id);
                Ok(ArcDeltaDbWrapper {
                    inner: Some(arc_db),
                    lru: None,
                    mpt_id,
                })
            }
            None => {
                let snapshot_epoch_id =
                    self.mpt_id_to_snapshot_epoch_id.get(&mpt_id).unwrap();
                let arc_db = Arc::new(
                    self.delta_db_manager
                        .get_delta_db(
                            &self
                                .delta_db_manager
                                .get_delta_db_name(snapshot_epoch_id),
                        )?
                        .unwrap(),
                );
                self.cache_util.cache_data.insert(
                    mpt_id,
                    (arc_db.clone(), LRUHandle::<u32>::default()),
                );
                self.lru_access(mpt_id);
                Ok(ArcDeltaDbWrapper {
                    inner: Some(arc_db),
                    lru: None,
                    mpt_id,
                })
            }
        }
    }

    fn create(
        &mut self, snapshot_epoch_id: &EpochId, mpt_id: DeltaMptId,
        opened_db: Option<Arc<dyn DeltaDbTrait + Send + Sync>>,
    ) -> Result<ArcDeltaDbWrapper> {
        match self.mpt_id_to_snapshot_epoch_id.get(&mpt_id) {
            Some(epoch_id) => {
                debug_assert!(snapshot_epoch_id == epoch_id);
                match opened_db {
                    Some(_arc) => unreachable!(),
                    None => self.open(mpt_id),
                }
            }
            None => {
                let arc_db = match opened_db {
                    Some(arc) => arc,
                    None => Arc::new(
                        self.delta_db_manager.new_empty_delta_db(
                            &self
                                .delta_db_manager
                                .get_delta_db_name(snapshot_epoch_id),
                        )?,
                    ),
                };
                self.mpt_id_to_snapshot_epoch_id
                    .insert(mpt_id, snapshot_epoch_id.clone());
                self.cache_util.cache_data.insert(
                    mpt_id,
                    (arc_db.clone(), LRUHandle::<u32>::default()),
                );
                self.lru_access(mpt_id);
                Ok(ArcDeltaDbWrapper {
                    inner: Some(arc_db),
                    lru: None,
                    mpt_id,
                })
            }
        }
    }

    // Release function is to close opened dbs which are not in lru and
    // are not using. With destroy = true, it will delete db in disk.

    // Lru will hold arc db which is_hit() == true, so if no one holds
    // related ArcDeltaDbWrapper, ref count of arc is always 1. And
    // for evicted arc db, lru will immediately drop it only if ref count
    // == 1, to avoid double open db error. Otherwise, lru will still
    // hold evicted arc db until last drop of related ArcDeltaDbWrapper.
    fn release(&mut self, mpt_id: DeltaMptId, destroy: bool) {
        match self.cache_util.cache_data.get(&mpt_id) {
            Some(tuple) => {
                let strong_count = Arc::strong_count(&tuple.0);
                if destroy {
                    debug_assert!(strong_count == 1);
                }
                if destroy || (strong_count == 1 && !tuple.1.is_hit()) {
                    // If is_hit() == false, lru.delete will do nothing
                    self.lru.delete(mpt_id, &mut self.cache_util);
                    self.cache_util.cache_data.remove(&mpt_id);
                }
            }
            None => {}
        }
        if destroy {
            self.mpt_id_to_snapshot_epoch_id.remove(&mpt_id);
        }
    }
}

use crate::{
    impls::{
        delta_mpt::{
            cache::algorithm::{
                lru::{LRUHandle, LRU},
                CacheAccessResult, CacheAlgorithm, CacheIndexTrait,
                CacheStoreUtil,
            },
            node_ref_map::DeltaMptId,
        },
        errors::*,
    },
    storage_db::{key_value_db::*, DeltaDbManagerTrait, DeltaDbTrait},
};
use parking_lot::Mutex;
use primitives::EpochId;
use std::{
    collections::HashMap,
    marker::PhantomData,
    ops::Deref,
    sync::{Arc, Weak},
};