1
//! Module for providing cache implementations for the [`http`] module.
2
//!
3
//! Each cache is outlined comprehensively in its own section.
4

            
5
use std::sync::{Arc, Mutex, MutexGuard, Weak};
6

            
7
use rusqlite::{Transaction, params};
8
use weak_table::WeakValueHashMap;
9

            
10
use crate::database::{DatabaseError, DocumentId, sql};
11

            
12
/// Alias to force use of RandomState, regardless of features enabled in `weak_tables`.
13
///
14
/// See <https://github.com/tov/weak-table-rs/issues/23> for discussion.
15
type WeakValueHash<K, V> = weak_table::WeakValueHashMap<K, V, std::hash::RandomState>;
16

            
17
/// Representation of the store cache.
18
///
19
/// The cache serves the purpose to not store the same document multiple times
20
/// in memory, when multiple clients request it simultaneously.
21
///
22
/// It *DOES NOT* serve the purpose to reduce the amount of read system calls.
23
/// We believe that SQLite and the operating system itself do a good job at
24
/// buffering reads for us here.
25
///
26
/// The cache itself is wrapped in a [`Mutex`] to ensure secure access across
27
/// thread boundaries.  Keep in mind, that it is a **synchronous** mutex.
28
///
29
/// All hash lookups in the `store` table should be performed through this
30
/// interface, because it will automatically select them from the database in
31
/// case they are missing.
32
#[derive(Debug)]
33
pub(super) struct StoreCache {
34
    /// The actual data of the cache.
35
    ///
36
    /// We use a [`Mutex`] instead of an [`RwLock`](std::sync::RwLock), because
37
    /// we want to assure that a concurrent cache miss does not lead into two
38
    /// simultaneous database reads and copies into memory.
39
    data: Mutex<WeakValueHashMap<DocumentId, Weak<[u8]>>>,
40
}
41

            
42
impl StoreCache {
43
    /// Creates a new empty [`StoreCache`].
44
    pub(super) fn new() -> Self {
45
        Self {
46
            data: Mutex::new(WeakValueHashMap::new()),
47
        }
48
    }
49

            
50
    /// Removes all mappings whose values have expired.
51
    ///
52
    /// Takes O(n) time.
53
    pub(super) fn gc(&self) {
54
        self.lock().remove_expired();
55
    }
56

            
57
    /// Looks up a [`DocumentId`] in the cache or the database.
58
    ///
59
    /// If we got a cache miss, this function automatically queries the database
60
    /// and inserts the result into the cache, before returning it.
61
    ///
62
    /// We do not keep a lock throughout the entire method.  This risks storing
63
    /// the same document in memory for a very short amount of time, based upon
64
    /// the number of worker threads we are using.  However, this is fine,
65
    /// given that reading from the store table is a large performance bottleneck.
66
    /// Also, the number of simultaneous copies that might be risked by that is
67
    /// limited to the amount of worker threads, which is usually very low
68
    /// compared to the number of async tasks, which might be in the thousands.
69
    pub(super) fn get(
70
        &self,
71
        tx: &Transaction,
72
        docid: DocumentId,
73
    ) -> Result<Arc<[u8]>, DatabaseError> {
74
        // Query the cache for the relevant document.
75
        if let Some(document) = self.lock().get(&docid) {
76
            return Ok(document);
77
        }
78

            
79
        // Cache miss, let us query the database.
80
        let document = Self::get_db(tx, docid)?;
81

            
82
        // Insert it into the cache.
83
        //
84
        // We obtain the lock and check again if it has been added in the
85
        // meantime.  The idea is to only return one copy of it, not two
86
        // simultaneous ones.
87
        Ok(self.lock().entry(docid).or_insert(document))
88
    }
89

            
90
    /// Obtains a [`DocumentId`] from the database without consulting the cache first.
91
    fn get_db(tx: &Transaction, docid: DocumentId) -> Result<Arc<[u8]>, DatabaseError> {
92
        let mut stmt = tx.prepare_cached(sql!("SELECT content FROM store WHERE docid = ?1"))?;
93
        let document: Vec<u8> = stmt.query_one(params![docid], |row| row.get(0))?;
94
        Ok(Arc::from(document))
95
    }
96

            
97
    /// Obtains a lock of the [`WeakValueHashMap`] even if the lock is poisoned.
98
    ///
99
    /// Ignoring the [`PoisonError`](std::sync::PoisonError) is fine here because
100
    /// the only "danger" in the general case of this might be, that certain
101
    /// invariants no longer hold true.  However, unless the poison has been
102
    /// triggered by the implementation of [`WeakValueHashMap`], in which case we
103
    /// would have much larger problems, doing this is fine.
104
    ///
105
    /// TODO DIRMIRROR: Consider cleaning the poison, although that would probably
106
    /// involve much more complexity and wrapping around the parent type.
107
    fn lock(&self) -> MutexGuard<'_, WeakValueHashMap<DocumentId, Weak<[u8]>>> {
108
        self.data.lock().unwrap_or_else(|e| e.into_inner())
109
    }
110
}
111

            
112
// The tests are all performed in the parent module, due to existing test
113
// vectors there.
114

            
115
#[cfg(test)]
116
mod test {
117
    // @@ begin test lint list maintained by maint/add_warning @@
118
    #![allow(clippy::bool_assert_comparison)]
119
    #![allow(clippy::clone_on_copy)]
120
    #![allow(clippy::dbg_macro)]
121
    #![allow(clippy::mixed_attributes_style)]
122
    #![allow(clippy::print_stderr)]
123
    #![allow(clippy::print_stdout)]
124
    #![allow(clippy::single_char_pattern)]
125
    #![allow(clippy::unwrap_used)]
126
    #![allow(clippy::unchecked_time_subtraction)]
127
    #![allow(clippy::useless_vec)]
128
    #![allow(clippy::needless_pass_by_value)]
129
    #![allow(clippy::string_slice)] // See arti#2571
130
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
131
    use crate::database;
132

            
133
    use super::super::test::*;
134
    use super::*;
135

            
136
    #[test]
137
    #[ignore] // // TODO DIRMIRROR test is broken, fails after cargo update
138
    fn store_cache() {
139
        let pool = create_test_db_pool();
140
        let cache = StoreCache::new();
141

            
142
        database::read_tx(&pool, |tx| {
143
            // Obtain the lipsum entry.
144
            let entry = cache.get(tx, *IDENTITY_DOCID).unwrap();
145
            assert_eq!(entry.as_ref(), IDENTITY.as_bytes());
146
            assert_eq!(Arc::strong_count(&entry), 1);
147

            
148
            // Obtain the lipsum entry again but ensure it is not copied in memory.
149
            let entry2 = cache.get(tx, *IDENTITY_DOCID).unwrap();
150
            assert_eq!(Arc::strong_count(&entry), 2);
151
            assert_eq!(Arc::as_ptr(&entry), Arc::as_ptr(&entry2));
152
            assert_eq!(entry, entry2);
153

            
154
            // Perform a garbage collection and ensure that entry is not removed.
155
            assert!(cache.data.lock().unwrap().contains_key(&IDENTITY_DOCID));
156
            cache.gc();
157
            assert!(cache.data.lock().unwrap().contains_key(&IDENTITY_DOCID));
158

            
159
            // Now drop entry and entry2 and perform the gc again.
160
            let weak_entry = Arc::downgrade(&entry);
161
            assert_eq!(weak_entry.strong_count(), 2);
162
            drop(entry);
163
            drop(entry2);
164
            assert_eq!(weak_entry.strong_count(), 0);
165

            
166
            // The strong count zero should already make it impossible to access the element ...
167
            assert!(!cache.data.lock().unwrap().contains_key(&IDENTITY_DOCID));
168
            // ... but it should not reduce the total size of the hash map ...
169
            assert_eq!(cache.data.lock().unwrap().len(), 1);
170
            cache.gc();
171
            // ... however, the garbage collection should actually do.
172
            assert_eq!(cache.data.lock().unwrap().len(), 0);
173
        })
174
        .unwrap();
175
    }
176
}