1
use std::{any::Any, sync::Arc};
2

            
3
use lru::LruCache;
4
use parking_lot::Mutex;
5

            
6
use crate::ArcBytes;
7

            
8
/// A configurable cache that operates at the "chunk" level.
9
///
10
/// While writing databases, individual portions of data are often written as a
11
/// single chunk. These chunks may be stored encrypted on-disk, but the
12
/// in-memory cache will be after decryption.
13
///
14
/// To keep memory usage low, the maximum size for a cached value can be set. It
15
/// is important that this value be large enough to fit most B-Tree nodes, and
16
/// that size will depend on how big the tree grows.
17
10
#[derive(Clone, Debug)]
18
#[must_use]
19
pub struct ChunkCache {
20
    max_block_length: usize,
21
    cache: Arc<Mutex<LruCache<ChunkKey, CacheEntry>>>,
22
}
23

            
24
pub trait AnySendSync: Any + Send + Sync {
25
    fn as_any(&self) -> &dyn Any;
26
    fn as_any_mut(&mut self) -> &mut dyn Any;
27
}
28

            
29
impl<T> AnySendSync for T
30
where
31
    T: Any + Send + Sync,
32
{
33
190916
    fn as_any(&self) -> &dyn Any {
34
190916
        self
35
190916
    }
36

            
37
    fn as_any_mut(&mut self) -> &mut dyn Any {
38
        self
39
    }
40
}
41

            
42
1804112
#[derive(Hash, Eq, PartialEq, Debug)]
43
pub struct ChunkKey {
44
    position: u64,
45
    file_id: u64,
46
}
47

            
48
impl ChunkCache {
49
    /// Create a new cache with a maximum number of entries (`capacity`) and
50
    /// `max_chunk_length`. Any chunks longer than `max_chunk_length` will not
51
    /// be cached. The maximum memory usage of this cache can be calculated as
52
    /// `capacity * max_chunk_length`, although the actual memory usage will
53
    /// likely be much smaller as many chunks are small.
54
10
    pub fn new(capacity: usize, max_chunk_length: usize) -> Self {
55
10
        Self {
56
10
            max_block_length: max_chunk_length,
57
10
            cache: Arc::new(Mutex::new(LruCache::new(capacity))),
58
10
        }
59
10
    }
60

            
61
    /// Returns the maximum size of data that can be cached.
62
    #[must_use]
63
276897
    pub const fn max_chunk_size(&self) -> usize {
64
276897
        self.max_block_length
65
276897
    }
66

            
67
    /// Adds a new cached chunk for `file_path` at `position`.
68
481654
    pub fn insert(&self, file_id: u64, position: u64, buffer: ArcBytes<'static>) {
69
481654
        if buffer.len() <= self.max_block_length {
70
481654
            let mut cache = self.cache.lock();
71
481654
            cache.put(ChunkKey { position, file_id }, CacheEntry::ArcBytes(buffer));
72
481654
        }
73
481654
    }
74

            
75
    /// Adds a new cached chunk for `file_path` at `position`.
76
184897
    pub fn replace_with_decoded<T: AnySendSync + 'static>(
77
184897
        &self,
78
184897
        file_id: u64,
79
184897
        position: u64,
80
184897
        value: T,
81
184897
    ) {
82
184897
        let mut cache = self.cache.lock();
83
184897
        cache.put(
84
184897
            ChunkKey { position, file_id },
85
184897
            CacheEntry::Decoded(Arc::new(value)),
86
184897
        );
87
184897
    }
88

            
89
    /// Looks up a previously read chunk for `file_path` at `position`,
90
    #[must_use]
91
330155
    pub fn get(&self, file_id: u64, position: u64) -> Option<CacheEntry> {
92
330155
        let mut cache = self.cache.lock();
93
330155
        cache.get(&ChunkKey { position, file_id }).cloned()
94
330155
    }
95
}
96

            
97
/// A cached chunk of data that has possibly been decoded already.
98
207398
#[derive(Clone)]
99
pub enum CacheEntry {
100
    /// A buffer of bytes that has been cached.
101
    ArcBytes(ArcBytes<'static>),
102
    /// A previously decoded value that was stored using
103
    /// [`ChunkCache::replace_with_decoded()`].
104
    Decoded(Arc<dyn AnySendSync>),
105
}