avoid overhead when cache sizes are zero

Don't even try taking locks, inserting or removing anything, etc.
This commit is contained in:
Charles Hall 2024-10-08 22:28:52 -07:00
parent 1148c6004f
commit d42a5ec1f0
No known key found for this signature in database
GPG key ID: 7B8E0645816E07CF
5 changed files with 184 additions and 174 deletions

View file

@ -21,8 +21,9 @@ pub(crate) use data::Data;
pub(crate) struct Service {
db: &'static dyn Data,
#[allow(clippy::type_complexity)]
auth_chain_cache:
Mutex<LruCache<Vec<ShortEventId>, Arc<HashSet<ShortEventId>>>>,
Option<Mutex<LruCache<Vec<ShortEventId>, Arc<HashSet<ShortEventId>>>>>,
}
impl Service {
@ -32,7 +33,8 @@ impl Service {
) -> Self {
Self {
db,
auth_chain_cache: Mutex::new(LruCache::new(auth_chain_cache_size)),
auth_chain_cache: (auth_chain_cache_size > 0)
.then(|| Mutex::new(LruCache::new(auth_chain_cache_size))),
}
}
@ -42,10 +44,11 @@ impl Service {
) -> Result<Option<Arc<HashSet<ShortEventId>>>> {
let lookup = Lookup::AuthChain;
if let Some(result) = self.auth_chain_cache.lock().unwrap().get_mut(key)
{
METRICS.record_lookup(lookup, FoundIn::Cache);
return Ok(Some(Arc::clone(result)));
if let Some(cache) = &self.auth_chain_cache {
if let Some(result) = cache.lock().unwrap().get_mut(key) {
METRICS.record_lookup(lookup, FoundIn::Cache);
return Ok(Some(Arc::clone(result)));
}
}
let Some(chain) = self.db.get_cached_eventid_authchain(key)? else {
@ -56,10 +59,9 @@ impl Service {
METRICS.record_lookup(lookup, FoundIn::Database);
let chain = Arc::new(chain);
self.auth_chain_cache
.lock()
.unwrap()
.insert(vec![key[0]], Arc::clone(&chain));
if let Some(cache) = &self.auth_chain_cache {
cache.lock().unwrap().insert(vec![key[0]], Arc::clone(&chain));
}
Ok(Some(chain))
}
@ -71,7 +73,9 @@ impl Service {
auth_chain: Arc<HashSet<ShortEventId>>,
) -> Result<()> {
self.db.cache_auth_chain(&key, &auth_chain)?;
self.auth_chain_cache.lock().unwrap().insert(key, auth_chain);
if let Some(cache) = &self.auth_chain_cache {
cache.lock().unwrap().insert(key, auth_chain);
}
Ok(())
}