use std::sync::{Arc, Mutex, MutexGuard, Weak};
use rusqlite::{params, Transaction};
use weak_table::WeakValueHashMap;
use crate::{
database::{sql, DocumentId},
err::DatabaseError,
};
type WeakValueHash<K, V> = weak_table::WeakValueHashMap<K, V, std::hash::RandomState>;
#[derive(Debug)]
pub(super) struct StoreCache {
data: Mutex<WeakValueHashMap<DocumentId, Weak<[u8]>>>,
}
impl StoreCache {
pub(super) fn new() -> Self {
Self {
data: Mutex::new(WeakValueHashMap::new()),
}
}
pub(super) fn gc(&self) {
self.lock().remove_expired();
}
pub(super) fn get(
&self,
tx: &Transaction,
docid: DocumentId,
) -> Result<Arc<[u8]>, DatabaseError> {
if let Some(document) = self.lock().get(&docid) {
return Ok(document);
}
let document = Self::get_db(tx, docid)?;
Ok(self.lock().entry(docid).or_insert(document))
}
fn get_db(tx: &Transaction, docid: DocumentId) -> Result<Arc<[u8]>, DatabaseError> {
let mut stmt = tx.prepare_cached(sql!("SELECT content FROM store WHERE docid = ?1"))?;
let document: Vec<u8> = stmt.query_one(params![docid], |row| row.get(0))?;
Ok(Arc::from(document))
}
fn lock(&self) -> MutexGuard<'_, WeakValueHashMap<DocumentId, Weak<[u8]>>> {
self.data.lock().unwrap_or_else(|e| e.into_inner())
}
}
#[cfg(test)]
mod test {
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::dbg_macro)]
#![allow(clippy::mixed_attributes_style)]
#![allow(clippy::print_stderr)]
#![allow(clippy::print_stdout)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::unchecked_time_subtraction)]
#![allow(clippy::useless_vec)]
#![allow(clippy::needless_pass_by_value)]
#![allow(clippy::string_slice)] use crate::database;
use super::super::test::*;
use super::*;
#[test]
fn store_cache() {
let pool = create_test_db_pool();
let cache = StoreCache::new();
database::read_tx(&pool, |tx| {
let entry = cache.get(tx, *IDENTITY_DOCID).unwrap();
assert_eq!(entry.as_ref(), IDENTITY.as_bytes());
assert_eq!(Arc::strong_count(&entry), 1);
let entry2 = cache.get(tx, *IDENTITY_DOCID).unwrap();
assert_eq!(Arc::strong_count(&entry), 2);
assert_eq!(Arc::as_ptr(&entry), Arc::as_ptr(&entry2));
assert_eq!(entry, entry2);
assert!(cache.data.lock().unwrap().contains_key(&IDENTITY_DOCID));
cache.gc();
assert!(cache.data.lock().unwrap().contains_key(&IDENTITY_DOCID));
let weak_entry = Arc::downgrade(&entry);
assert_eq!(weak_entry.strong_count(), 2);
drop(entry);
drop(entry2);
assert_eq!(weak_entry.strong_count(), 0);
assert!(!cache.data.lock().unwrap().contains_key(&IDENTITY_DOCID));
assert_eq!(cache.data.lock().unwrap().len(), 1);
cache.gc();
assert_eq!(cache.data.lock().unwrap().len(), 0);
})
.unwrap();
}
}