use std::hash::Hash;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
#[cfg(feature = "ahash")]
use ahash::RandomState;
#[cfg(not(feature = "ahash"))]
use std::collections::hash_map::RandomState;
use std::collections::HashMap;
#[cfg(feature = "async_core")]
use crate::ConcurrentCachedAsync;
use crate::time::{Duration, Instant};
use crate::{CacheMetrics, CacheTtl, ConcurrentCached, ConcurrentCloneCached};
use super::{
CachePadded, DefaultShardHasher, Shard, ShardHasher, checked_shard_count, shard_index,
};
use crate::stores::{BuildError, CacheEvict, TimedEntry};
type OnEvict<K, V> = Arc<dyn Fn(&K, &V) + Send + Sync>;
#[allow(clippy::type_complexity)]
struct TtlInner<K, V, H> {
shards: Box<[CachePadded<Shard<HashMap<K, TimedEntry<V>, RandomState>>>]>,
shard_mask: usize,
hasher: H,
on_evict: Option<OnEvict<K, V>>,
ttl_nanos: AtomicU64,
refresh: AtomicBool,
evictions: AtomicU64,
}
pub type ShardedTtlCache<K, V> = ShardedTtlCacheBase<K, V, DefaultShardHasher>;
pub struct ShardedTtlCacheBase<K, V, H = DefaultShardHasher> {
inner: Arc<TtlInner<K, V, H>>,
}
impl<K, V, H> Clone for ShardedTtlCacheBase<K, V, H> {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
}
}
}
impl<K, V, H> std::fmt::Debug for ShardedTtlCacheBase<K, V, H> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let nanos = self.inner.ttl_nanos.load(Ordering::Relaxed);
let ttl = if nanos == 0 {
None
} else {
Some(Duration::from_nanos(nanos))
};
f.debug_struct("ShardedTtlCache")
.field("shards", &self.inner.shards.len())
.field("ttl", &ttl)
.finish_non_exhaustive()
}
}
impl<K, V, H> ShardedTtlCacheBase<K, V, H>
where
K: Hash + Eq,
H: ShardHasher<K>,
{
pub fn builder() -> ShardedTtlCacheBuilder<K, V, DefaultShardHasher> {
ShardedTtlCacheBuilder::default()
}
#[inline]
fn shard_of(&self, k: &K) -> &CachePadded<Shard<HashMap<K, TimedEntry<V>, RandomState>>> {
let h = self.inner.hasher.shard_hash(k);
&self.inner.shards[shard_index(h, self.inner.shard_mask)]
}
#[inline]
fn ttl_duration(&self) -> Option<Duration> {
let nanos = self.inner.ttl_nanos.load(Ordering::Relaxed);
if nanos == 0 {
None
} else {
Some(Duration::from_nanos(nanos))
}
}
#[inline]
fn is_expired(&self, entry: &TimedEntry<V>) -> bool {
match self.ttl_duration() {
None => false,
Some(ttl) => entry.instant.elapsed() >= ttl,
}
}
}
impl<K: Clone + Hash + Eq, V: Clone, H: ShardHasher<K> + Clone> ShardedTtlCacheBase<K, V, H> {
#[must_use]
pub fn deep_clone(&self) -> Self {
let n = self.inner.shards.len();
let shards = (0..n)
.map(|i| {
let guard = self.inner.shards[i].lock.read();
let store_copy = guard.clone();
let hits = self.inner.shards[i].hits.load(Ordering::Relaxed);
let misses = self.inner.shards[i].misses.load(Ordering::Relaxed);
drop(guard);
let shard = Shard {
lock: parking_lot::RwLock::new(store_copy),
hits: AtomicU64::new(hits),
misses: AtomicU64::new(misses),
};
CachePadded(shard)
})
.collect::<Vec<_>>()
.into_boxed_slice();
Self {
inner: Arc::new(TtlInner {
shards,
shard_mask: self.inner.shard_mask,
hasher: self.inner.hasher.clone(),
on_evict: self.inner.on_evict.clone(),
ttl_nanos: AtomicU64::new(self.inner.ttl_nanos.load(Ordering::Relaxed)),
refresh: AtomicBool::new(self.inner.refresh.load(Ordering::Relaxed)),
evictions: AtomicU64::new(self.inner.evictions.load(Ordering::Relaxed)),
}),
}
}
}
impl<K, V, H: ShardHasher<K>> ShardedTtlCacheBase<K, V, H>
where
K: Hash + Eq,
{
#[must_use]
pub fn metrics(&self) -> CacheMetrics {
let mut hits = 0u64;
let mut misses = 0u64;
let mut size = 0usize;
for shard in self.inner.shards.iter() {
hits += shard.hits.load(Ordering::Relaxed);
misses += shard.misses.load(Ordering::Relaxed);
size += shard.lock.read().len();
}
CacheMetrics {
hits: Some(hits),
misses: Some(misses),
evictions: Some(self.inner.evictions.load(Ordering::Relaxed)),
size,
capacity: None,
}
}
#[must_use]
pub fn shards(&self) -> usize {
self.inner.shards.len()
}
#[must_use]
pub fn shard_sizes(&self) -> Vec<usize> {
self.inner
.shards
.iter()
.map(|s| s.lock.read().len())
.collect()
}
#[must_use]
pub fn len(&self) -> usize {
self.inner.shards.iter().map(|s| s.lock.read().len()).sum()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner.shards.iter().all(|s| s.lock.read().is_empty())
}
pub fn clear(&self) {
for shard in self.inner.shards.iter() {
shard.lock.write().clear();
}
}
pub fn cache_clear_with_on_evict(&self) {
if self.inner.on_evict.is_none() {
return self.clear();
}
for shard in self.inner.shards.iter() {
let removed: Vec<(K, TimedEntry<V>)> = shard.lock.write().drain().collect();
if !removed.is_empty() {
self.inner
.evictions
.fetch_add(removed.len() as u64, Ordering::Relaxed);
if let Some(on_evict) = &self.inner.on_evict {
for (k, entry) in &removed {
on_evict(k, &entry.value);
}
}
}
}
}
#[must_use]
pub fn evict(&self) -> usize
where
K: Clone,
{
let ttl = match self.ttl_duration() {
None => return 0,
Some(t) => t,
};
let mut total = 0;
let now = Instant::now();
for shard in self.inner.shards.iter() {
let removed = {
let mut guard = shard.lock.write();
let expired_keys: Vec<K> = guard
.iter()
.filter(|(_, e)| now.saturating_duration_since(e.instant) >= ttl)
.map(|(k, _)| k.clone())
.collect();
let mut removed = Vec::new();
for k in expired_keys {
if let Some((key, entry)) = guard.remove_entry(&k) {
removed.push((key, entry));
}
}
removed
};
total += removed.len();
if !removed.is_empty() {
self.inner
.evictions
.fetch_add(removed.len() as u64, Ordering::Relaxed);
if let Some(cb) = &self.inner.on_evict {
for (k, entry) in &removed {
cb(k, &entry.value);
}
}
}
}
total
}
#[must_use]
pub fn ttl(&self) -> Option<Duration> {
self.ttl_duration()
}
pub fn set_ttl(&self, ttl: Duration) -> Option<Duration> {
assert!(
!ttl.is_zero(),
"TTL must be non-zero; use unset_ttl() to disable expiry"
);
let prev = self.inner.ttl_nanos.swap(
ttl.as_nanos().min(u64::MAX as u128) as u64,
Ordering::Relaxed,
);
if prev == 0 {
None
} else {
Some(Duration::from_nanos(prev))
}
}
pub fn unset_ttl(&self) -> Option<Duration> {
let prev = self.inner.ttl_nanos.swap(0, Ordering::Relaxed);
if prev == 0 {
None
} else {
Some(Duration::from_nanos(prev))
}
}
pub fn set_refresh_on_hit(&self, refresh: bool) -> bool {
self.inner.refresh.swap(refresh, Ordering::Relaxed)
}
#[must_use]
pub fn refresh_on_hit(&self) -> bool {
self.inner.refresh.load(Ordering::Relaxed)
}
}
impl<K, V, H> CacheTtl for ShardedTtlCacheBase<K, V, H>
where
K: Hash + Eq,
H: ShardHasher<K>,
{
fn ttl(&self) -> Option<Duration> {
self.ttl_duration()
}
fn set_ttl(&mut self, ttl: Duration) -> Option<Duration> {
ShardedTtlCacheBase::set_ttl(self, ttl)
}
fn unset_ttl(&mut self) -> Option<Duration> {
ShardedTtlCacheBase::unset_ttl(self)
}
}
impl<K, V, H> CacheEvict for ShardedTtlCacheBase<K, V, H>
where
K: Hash + Eq + Clone,
H: ShardHasher<K>,
{
fn evict(&mut self) -> usize {
ShardedTtlCacheBase::evict(self)
}
}
impl<K, V, H> ConcurrentCached<K, V> for ShardedTtlCacheBase<K, V, H>
where
K: Hash + Eq,
V: Clone,
H: ShardHasher<K>,
{
type Error = std::convert::Infallible;
fn cache_get(&self, k: &K) -> Result<Option<V>, Self::Error> {
let shard = self.shard_of(k);
if self.inner.refresh.load(Ordering::Relaxed) {
let mut guard = shard.lock.write();
match guard.get_mut(k) {
Some(entry) if !self.is_expired(entry) => {
entry.instant = Instant::now();
let value = Some(entry.value.clone());
drop(guard);
shard.hits.fetch_add(1, Ordering::Relaxed);
return Ok(value);
}
Some(_) => {
let removed = guard.remove_entry(k);
drop(guard);
if let Some((stored_k, entry)) = removed {
self.inner.evictions.fetch_add(1, Ordering::Relaxed);
if let Some(cb) = &self.inner.on_evict {
cb(&stored_k, &entry.value);
}
}
shard.misses.fetch_add(1, Ordering::Relaxed);
return Ok(None);
}
None => {
drop(guard);
shard.misses.fetch_add(1, Ordering::Relaxed);
return Ok(None);
}
}
}
let (expired, value) = {
let guard = shard.lock.read();
match guard.get(k) {
None => {
shard.misses.fetch_add(1, Ordering::Relaxed);
return Ok(None);
}
Some(entry) => {
let expired = self.is_expired(entry);
let value = if !expired {
Some(entry.value.clone())
} else {
None
};
(expired, value)
}
}
};
if expired {
let mut guard = shard.lock.write();
let fresh_value = match guard.get(k) {
Some(entry) if !self.is_expired(entry) => Some(entry.value.clone()),
_ => None,
};
if let Some(fresh_value) = fresh_value {
drop(guard);
shard.hits.fetch_add(1, Ordering::Relaxed);
return Ok(Some(fresh_value));
}
let removed = guard.remove_entry(k);
drop(guard);
if let Some((stored_k, entry)) = removed {
self.inner.evictions.fetch_add(1, Ordering::Relaxed);
if let Some(cb) = &self.inner.on_evict {
cb(&stored_k, &entry.value);
}
}
shard.misses.fetch_add(1, Ordering::Relaxed);
return Ok(None);
}
shard.hits.fetch_add(1, Ordering::Relaxed);
Ok(value)
}
fn cache_set(&self, k: K, v: V) -> Result<Option<V>, Self::Error> {
let shard = self.shard_of(&k);
let new_entry = TimedEntry {
instant: Instant::now(),
value: v,
};
let old = shard.lock.write().insert(k, new_entry);
Ok(old.map(|e| e.value))
}
fn cache_remove(&self, k: &K) -> Result<Option<V>, Self::Error> {
let shard = self.shard_of(k);
let removed = shard.lock.write().remove_entry(k);
if let Some((stored_k, entry)) = removed {
self.inner.evictions.fetch_add(1, Ordering::Relaxed);
if let Some(cb) = &self.inner.on_evict {
cb(&stored_k, &entry.value);
}
if self.is_expired(&entry) {
Ok(None)
} else {
Ok(Some(entry.value))
}
} else {
Ok(None)
}
}
fn cache_remove_entry(&self, k: &K) -> Result<Option<(K, V)>, Self::Error> {
let shard = self.shard_of(k);
let removed = shard.lock.write().remove_entry(k);
if let Some((ref stored_k, ref entry)) = removed {
self.inner.evictions.fetch_add(1, Ordering::Relaxed);
if let Some(cb) = &self.inner.on_evict {
cb(stored_k, &entry.value);
}
}
Ok(removed.map(|(k, entry)| (k, entry.value)))
}
fn cache_size(&self) -> Result<Option<usize>, Self::Error> {
Ok(Some(self.len()))
}
fn set_refresh_on_hit(&self, refresh: bool) -> bool {
self.inner.refresh.swap(refresh, Ordering::Relaxed)
}
fn ttl(&self) -> Option<Duration> {
self.ttl_duration()
}
fn set_ttl(&self, ttl: Duration) -> Option<Duration> {
ShardedTtlCacheBase::set_ttl(self, ttl)
}
fn unset_ttl(&self) -> Option<Duration> {
ShardedTtlCacheBase::unset_ttl(self)
}
}
#[cfg(feature = "async_core")]
impl<K, V, H> ConcurrentCachedAsync<K, V> for ShardedTtlCacheBase<K, V, H>
where
K: Hash + Eq + Send + Sync,
V: Clone + Send + Sync,
H: ShardHasher<K>,
{
type Error = std::convert::Infallible;
async fn cache_get(&self, k: &K) -> Result<Option<V>, Self::Error> {
ConcurrentCached::cache_get(self, k)
}
async fn cache_set(&self, k: K, v: V) -> Result<Option<V>, Self::Error> {
ConcurrentCached::cache_set(self, k, v)
}
async fn cache_remove(&self, k: &K) -> Result<Option<V>, Self::Error> {
ConcurrentCached::cache_remove(self, k)
}
async fn cache_remove_entry(&self, k: &K) -> Result<Option<(K, V)>, Self::Error> {
ConcurrentCached::cache_remove_entry(self, k)
}
fn cache_size(&self) -> Result<Option<usize>, Self::Error> {
Ok(Some(self.len()))
}
fn set_refresh_on_hit(&self, b: bool) -> bool {
<Self as ConcurrentCached<K, V>>::set_refresh_on_hit(self, b)
}
fn ttl(&self) -> Option<Duration> {
self.ttl_duration()
}
fn set_ttl(&self, ttl: Duration) -> Option<Duration> {
ShardedTtlCacheBase::set_ttl(self, ttl)
}
fn unset_ttl(&self) -> Option<Duration> {
ShardedTtlCacheBase::unset_ttl(self)
}
}
pub struct ShardedTtlCacheBuilder<K, V, H = DefaultShardHasher> {
shards: Option<usize>,
ttl: Option<Duration>,
refresh: bool,
hasher: Option<H>,
on_evict: Option<OnEvict<K, V>>,
_k: std::marker::PhantomData<K>,
_v: std::marker::PhantomData<V>,
}
impl<K, V> Default for ShardedTtlCacheBuilder<K, V, DefaultShardHasher> {
fn default() -> Self {
Self {
shards: None,
ttl: None,
refresh: false,
hasher: Some(DefaultShardHasher::default()),
on_evict: None,
_k: std::marker::PhantomData,
_v: std::marker::PhantomData,
}
}
}
impl<K, V, H> ShardedTtlCacheBuilder<K, V, H> {
#[must_use]
pub fn ttl(mut self, ttl: Duration) -> Self {
self.ttl = Some(ttl);
self
}
#[must_use]
pub fn shards(mut self, shards: usize) -> Self {
self.shards = Some(shards);
self
}
#[must_use]
pub fn refresh_on_hit(mut self, refresh: bool) -> Self {
self.refresh = refresh;
self
}
#[must_use]
pub fn refresh(self, refresh: bool) -> Self {
self.refresh_on_hit(refresh)
}
#[must_use]
pub fn hasher<H2: ShardHasher<K>>(self, hasher: H2) -> ShardedTtlCacheBuilder<K, V, H2> {
ShardedTtlCacheBuilder {
shards: self.shards,
ttl: self.ttl,
refresh: self.refresh,
hasher: Some(hasher),
on_evict: self.on_evict,
_k: std::marker::PhantomData,
_v: std::marker::PhantomData,
}
}
#[must_use]
pub fn on_evict(mut self, on_evict: impl Fn(&K, &V) + Send + Sync + 'static) -> Self {
self.on_evict = Some(Arc::new(on_evict));
self
}
pub fn build(self) -> Result<ShardedTtlCacheBase<K, V, H>, BuildError>
where
K: Hash + Eq,
H: ShardHasher<K>,
{
let ttl = self.ttl.ok_or(BuildError::MissingRequired("ttl"))?;
crate::stores::validate_ttl(ttl)?;
let n = checked_shard_count(self.shards)?;
let mask = n - 1;
let shards = (0..n)
.map(|_| CachePadded(Shard::new(HashMap::with_hasher(RandomState::new()))))
.collect::<Vec<_>>()
.into_boxed_slice();
Ok(ShardedTtlCacheBase {
inner: Arc::new(TtlInner {
shards,
shard_mask: mask,
hasher: self
.hasher
.expect("hasher is always initialized via Default or .hasher()"),
on_evict: self.on_evict,
ttl_nanos: AtomicU64::new(ttl.as_nanos().min(u64::MAX as u128) as u64),
refresh: AtomicBool::new(self.refresh),
evictions: AtomicU64::new(0),
}),
})
}
#[must_use]
pub fn copy_from<H2: ShardHasher<K>>(
self,
existing: &ShardedTtlCacheBase<K, V, H2>,
) -> ShardedTtlCacheBase<K, V, H>
where
K: Clone + Hash + Eq,
V: Clone,
H: ShardHasher<K>,
{
let new_cache = self
.build()
.unwrap_or_else(|e| panic!("ShardedTtlCache build failed: {e}"));
let existing_ttl = existing.ttl_duration();
for shard in existing.inner.shards.iter() {
let entries: Vec<(K, TimedEntry<V>)> = {
let guard = shard.lock.read();
guard
.iter()
.filter(|(_, entry)| {
match existing_ttl {
None => true,
Some(ttl) => entry.instant.elapsed() < ttl,
}
})
.map(|(k, e)| (k.clone(), e.clone()))
.collect()
};
for (k, entry) in entries {
let new_shard = new_cache.shard_of(&k);
new_shard.lock.write().insert(k, entry);
}
}
new_cache
}
}
impl<K, V, H> ConcurrentCloneCached<K, V> for ShardedTtlCacheBase<K, V, H>
where
K: Hash + Eq,
V: Clone,
H: ShardHasher<K>,
{
fn cache_get_with_expiry_status(&self, k: &K) -> (Option<V>, bool) {
let shard = self.shard_of(k);
if self.inner.refresh.load(Ordering::Relaxed) {
let mut guard = shard.lock.write();
match guard.get_mut(k) {
None => {
drop(guard);
shard.misses.fetch_add(1, Ordering::Relaxed);
(None, false)
}
Some(entry) => {
let expired = self.is_expired(entry);
let value = entry.value.clone();
if !expired {
entry.instant = Instant::now();
}
drop(guard);
if expired {
shard.misses.fetch_add(1, Ordering::Relaxed);
(Some(value), true)
} else {
shard.hits.fetch_add(1, Ordering::Relaxed);
(Some(value), false)
}
}
}
} else {
let guard = shard.lock.read();
match guard.get(k) {
None => {
drop(guard);
shard.misses.fetch_add(1, Ordering::Relaxed);
(None, false)
}
Some(entry) => {
let expired = self.is_expired(entry);
let value = entry.value.clone();
drop(guard);
if expired {
shard.misses.fetch_add(1, Ordering::Relaxed);
(Some(value), true)
} else {
shard.hits.fetch_add(1, Ordering::Relaxed);
(Some(value), false)
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ConcurrentCached as SyncConcurrentCached;
use crate::ConcurrentCloneCached;
#[test]
fn basic_get_set_remove() {
let c = ShardedTtlCache::<u32, u32>::builder()
.ttl(Duration::from_secs(60))
.build()
.unwrap();
assert_eq!(
SyncConcurrentCached::cache_get(&c, &1).expect("cache_get must succeed"),
None
);
assert_eq!(
SyncConcurrentCached::cache_set(&c, 1, 100).expect("insert must succeed"),
None
);
assert_eq!(
SyncConcurrentCached::cache_get(&c, &1).expect("key was just inserted"),
Some(100)
);
assert_eq!(
SyncConcurrentCached::cache_remove(&c, &1).expect("key must be present"),
Some(100)
);
assert_eq!(
SyncConcurrentCached::cache_get(&c, &1).expect("cache_get must succeed"),
None
);
}
#[test]
fn clone_shares_state() {
let c1 = ShardedTtlCache::<u32, u32>::builder()
.ttl(Duration::from_secs(60))
.build()
.unwrap();
let c2 = c1.clone();
SyncConcurrentCached::cache_set(&c1, 1, 10).expect("insert must succeed");
assert_eq!(
SyncConcurrentCached::cache_get(&c2, &1).expect("key was just inserted"),
Some(10)
);
}
#[test]
fn ttl_expiry() {
let c = ShardedTtlCache::<u32, u32>::builder()
.ttl(Duration::from_millis(50))
.build()
.unwrap();
SyncConcurrentCached::cache_set(&c, 1, 100).expect("insert must succeed");
assert_eq!(
SyncConcurrentCached::cache_get(&c, &1).expect("key was just inserted"),
Some(100)
);
std::thread::sleep(std::time::Duration::from_millis(100));
assert_eq!(
SyncConcurrentCached::cache_get(&c, &1).expect("cache_get must succeed"),
None
);
}
#[test]
fn evict_sweeps_expired() {
let c = ShardedTtlCache::<u32, u32>::builder()
.ttl(Duration::from_millis(50))
.build()
.unwrap();
for i in 0..10u32 {
SyncConcurrentCached::cache_set(&c, i, i).expect("insert must succeed");
}
std::thread::sleep(std::time::Duration::from_millis(100));
let removed = c.evict();
assert_eq!(removed, 10);
assert_eq!(c.metrics().evictions, Some(10));
}
#[test]
fn set_ttl_inherent() {
let c = ShardedTtlCache::<u32, u32>::builder()
.ttl(Duration::from_secs(60))
.build()
.unwrap();
let prev = c.set_ttl(Duration::from_secs(30));
assert_eq!(prev, Some(Duration::from_secs(60)));
assert_eq!(c.ttl(), Some(Duration::from_secs(30)));
}
#[test]
fn copy_from_skips_expired() {
let old = ShardedTtlCache::<u32, u32>::builder()
.ttl(Duration::from_millis(50))
.build()
.unwrap();
for i in 0..10u32 {
SyncConcurrentCached::cache_set(&old, i, i).expect("insert must succeed");
}
std::thread::sleep(std::time::Duration::from_millis(100));
let new_cache = ShardedTtlCacheBase::<u32, u32>::builder()
.ttl(Duration::from_secs(60))
.copy_from(&old);
assert_eq!(new_cache.len(), 0);
}
#[test]
fn copy_from_preserves_live_entries() {
let old = ShardedTtlCache::<u32, u32>::builder()
.ttl(Duration::from_secs(60))
.build()
.unwrap();
for i in 0..20u32 {
SyncConcurrentCached::cache_set(&old, i, i * 10).expect("insert must succeed");
}
let new_cache = ShardedTtlCacheBase::<u32, u32>::builder()
.ttl(Duration::from_secs(60))
.copy_from(&old);
for i in 0..20u32 {
assert_eq!(
SyncConcurrentCached::cache_get(&new_cache, &i).expect("key was just inserted"),
Some(i * 10)
);
}
}
#[test]
fn send_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<ShardedTtlCache<u32, u32>>();
}
#[test]
fn build_rejects_zero_ttl() {
let err = ShardedTtlCacheBase::<u32, u32>::builder()
.ttl(Duration::from_nanos(0))
.build();
assert!(
matches!(err, Err(crate::stores::BuildError::InvalidTtl { .. })),
"expected InvalidTtl, got {err:?}",
);
}
#[test]
fn cache_clear_with_on_evict_fires_for_all_entries() {
use std::sync::atomic::{AtomicU64, Ordering};
let count = Arc::new(AtomicU64::new(0));
let count2 = count.clone();
let c = ShardedTtlCacheBase::<u32, u32>::builder()
.ttl(Duration::from_secs(3600))
.on_evict(move |_, _| {
count2.fetch_add(1, Ordering::Relaxed);
})
.build()
.unwrap();
for i in 0..20u32 {
SyncConcurrentCached::cache_set(&c, i, i).expect("insert must succeed");
}
let before = c
.metrics()
.evictions
.expect("eviction-tracking stores report an evictions count");
c.cache_clear_with_on_evict();
assert_eq!(
c.len(),
0,
"cache must be empty after cache_clear_with_on_evict"
);
assert_eq!(
count.load(Ordering::Relaxed),
20,
"on_evict must fire for every entry"
);
assert_eq!(
c.metrics()
.evictions
.expect("eviction-tracking stores report an evictions count")
- before,
20,
"evictions counter must increment for each entry"
);
}
#[test]
fn clear_does_not_fire_on_evict() {
use std::sync::atomic::{AtomicU64, Ordering};
let count = Arc::new(AtomicU64::new(0));
let count2 = count.clone();
let c = ShardedTtlCacheBase::<u32, u32>::builder()
.ttl(Duration::from_secs(3600))
.on_evict(move |_, _| {
count2.fetch_add(1, Ordering::Relaxed);
})
.build()
.unwrap();
for i in 0..10u32 {
SyncConcurrentCached::cache_set(&c, i, i).expect("insert must succeed");
}
c.clear();
assert_eq!(
count.load(Ordering::Relaxed),
0,
"clear must not fire on_evict"
);
}
#[test]
fn cache_remove_entry_returns_some_for_live_entry() {
let c = ShardedTtlCache::<u32, u32>::builder()
.ttl(Duration::from_secs(60))
.build()
.unwrap();
SyncConcurrentCached::cache_set(&c, 1u32, 100u32).expect("insert must succeed");
assert_eq!(
SyncConcurrentCached::cache_remove_entry(&c, &999u32)
.expect("cache_remove_entry must succeed"),
None
);
assert_eq!(
SyncConcurrentCached::cache_remove_entry(&c, &1u32).expect("key must be present"),
Some((1u32, 100u32))
);
assert_eq!(
SyncConcurrentCached::cache_get(&c, &1u32).expect("cache_get must succeed"),
None
);
}
#[test]
fn cache_remove_entry_returns_some_for_expired_entry() {
let c = ShardedTtlCache::<u32, u32>::builder()
.ttl(Duration::from_millis(50))
.build()
.unwrap();
SyncConcurrentCached::cache_set(&c, 1u32, 100u32).expect("insert must succeed");
SyncConcurrentCached::cache_set(&c, 2u32, 200u32).expect("insert must succeed");
std::thread::sleep(std::time::Duration::from_millis(100));
assert_eq!(
SyncConcurrentCached::cache_remove(&c, &1u32).expect("cache_remove must succeed"),
None
);
let removed =
SyncConcurrentCached::cache_remove_entry(&c, &2u32).expect("key must be present");
assert!(
removed.is_some(),
"cache_remove_entry must return Some for expired entry"
);
assert_eq!(removed.expect("must be Some"), (2u32, 200u32));
}
#[test]
fn cache_delete_returns_true_for_expired_entry() {
let c = ShardedTtlCache::<u32, u32>::builder()
.ttl(Duration::from_millis(50))
.build()
.unwrap();
SyncConcurrentCached::cache_set(&c, 1u32, 100u32).expect("insert must succeed");
std::thread::sleep(std::time::Duration::from_millis(100));
assert!(
SyncConcurrentCached::cache_delete(&c, &1u32).expect("cache_delete must succeed"),
"cache_delete must be true for expired entry"
);
assert!(!SyncConcurrentCached::cache_delete(&c, &1u32).expect("cache_delete must succeed"));
}
#[test]
fn cache_remove_entry_fires_on_evict_for_expired() {
use std::sync::atomic::{AtomicU64, Ordering};
let count = Arc::new(AtomicU64::new(0));
let count2 = count.clone();
let c = ShardedTtlCacheBase::<u32, u32>::builder()
.ttl(Duration::from_millis(50))
.shards(1)
.on_evict(move |_, _| {
count2.fetch_add(1, Ordering::Relaxed);
})
.build()
.unwrap();
SyncConcurrentCached::cache_set(&c, 1u32, 10u32).expect("insert must succeed");
std::thread::sleep(std::time::Duration::from_millis(100));
SyncConcurrentCached::cache_remove_entry(&c, &1u32).expect("key must be present");
assert_eq!(
count.load(Ordering::Relaxed),
1,
"on_evict fires for expired entries"
);
SyncConcurrentCached::cache_remove_entry(&c, &999u32)
.expect("cache_remove_entry must succeed");
assert_eq!(count.load(Ordering::Relaxed), 1, "no fire for absent key");
}
#[test]
fn cache_remove_entry_increments_eviction_counter() {
let c = ShardedTtlCacheBase::<u32, u32>::builder()
.ttl(Duration::from_millis(10))
.shards(1)
.build()
.unwrap();
SyncConcurrentCached::cache_set(&c, 1u32, 10u32).expect("insert must succeed");
std::thread::sleep(std::time::Duration::from_millis(100));
let before = c.metrics().evictions.expect("evictions are always tracked");
SyncConcurrentCached::cache_remove_entry(&c, &1u32).expect("key must be present"); SyncConcurrentCached::cache_remove_entry(&c, &999u32)
.expect("cache_remove_entry must succeed"); assert_eq!(
c.metrics().evictions.expect("evictions are always tracked") - before,
1,
"cache_remove_entry must increment evictions for present key only"
);
}
#[test]
fn concurrent_clone_cached_absent_is_none_false() {
let c = ShardedTtlCache::<u32, u32>::builder()
.ttl(Duration::from_secs(60))
.build()
.unwrap();
assert_eq!(
ConcurrentCloneCached::cache_get_with_expiry_status(&c, &1u32),
(None, false),
"absent key must return (None, false)"
);
assert_eq!(
c.metrics().misses,
Some(1),
"absent lookup must increment misses"
);
}
#[test]
fn concurrent_clone_cached_live_entry_is_some_false() {
let c = ShardedTtlCache::<u32, u32>::builder()
.ttl(Duration::from_secs(60))
.build()
.unwrap();
SyncConcurrentCached::cache_set(&c, 1u32, 42u32).expect("insert must succeed");
assert_eq!(
ConcurrentCloneCached::cache_get_with_expiry_status(&c, &1u32),
(Some(42), false),
"live entry must return (Some(v), false)"
);
assert_eq!(c.metrics().hits, Some(1), "live lookup must increment hits");
assert_eq!(
c.metrics().evictions,
Some(0),
"live lookup must not increment evictions"
);
}
#[test]
fn concurrent_clone_cached_expired_returns_stale_no_eviction() {
let c = ShardedTtlCacheBase::<u32, u32>::builder()
.ttl(Duration::from_millis(50))
.shards(1)
.build()
.unwrap();
SyncConcurrentCached::cache_set(&c, 1u32, 99u32).expect("insert must succeed");
std::thread::sleep(std::time::Duration::from_millis(100));
let (val, expired) = ConcurrentCloneCached::cache_get_with_expiry_status(&c, &1u32);
assert_eq!(val, Some(99), "expired entry must return the stale value");
assert!(expired, "expired entry must set the expired flag");
assert_eq!(
c.metrics().misses,
Some(1),
"expired lookup must increment misses"
);
assert_eq!(
c.metrics().evictions,
Some(0),
"expired lookup must NOT increment evictions"
);
let (val2, expired2) = ConcurrentCloneCached::cache_get_with_expiry_status(&c, &1u32);
assert_eq!(
val2,
Some(99),
"entry must still be present after expiry-status lookup"
);
assert!(
expired2,
"entry must still be expired on second expiry-status call"
);
}
}