use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use crate::QueryKey;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DataCacheStats {
pub fresh_hits: u32,
pub stale_hits: u32,
pub misses: u32,
pub inserts: u32,
pub invalidations: u32,
pub evictions: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ScopePath {
pub app: u64,
pub window: u64,
pub feature: u64,
}
impl ScopePath {
pub const fn new(app: u64, window: u64, feature: u64) -> Self {
Self { app, window, feature }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InvalidationScope {
All,
Key(QueryKey),
Group(u64),
App(u64),
Window { app: u64, window: u64 },
Feature { app: u64, window: u64, feature: u64 },
KeyIn { path: ScopePath, key: QueryKey },
}
impl InvalidationScope {
pub fn matches(self, key: QueryKey, group: u64) -> bool {
self.matches_scope(key, Self::Group(group))
}
pub fn matches_scope(self, key: QueryKey, entry_scope: Self) -> bool {
match self {
Self::All => true,
Self::Key(k) => k == key || matches!(entry_scope, Self::KeyIn { key: ek, .. } if ek == k),
Self::Group(g) => entry_scope == Self::Group(g),
Self::App(app) => match entry_scope {
Self::App(ea) => ea == app,
Self::Window { app: ea, .. } => ea == app,
Self::Feature { app: ea, .. } => ea == app,
Self::KeyIn { path, .. } => path.app == app,
_ => false,
},
Self::Window { app, window } => match entry_scope {
Self::Window { app: ea, window: ew } => ea == app && ew == window,
Self::Feature { app: ea, window: ew, .. } => ea == app && ew == window,
Self::KeyIn { path, .. } => path.app == app && path.window == window,
_ => false,
},
Self::Feature { app, window, feature } => match entry_scope {
Self::Feature { app: ea, window: ew, feature: ef } => ea == app && ew == window && ef == feature,
Self::KeyIn { path, .. } => path.app == app && path.window == window && path.feature == feature,
_ => false,
},
Self::KeyIn { path, key } => entry_scope == Self::KeyIn { path, key },
}
}
}
#[derive(Debug, PartialEq)]
pub enum DataCacheLookup<T> {
Fresh(Rc<T>),
Stale(Rc<T>),
Miss,
}
struct CacheEntry<T> {
value: Rc<T>,
bytes: usize,
scope: InvalidationScope,
stale: bool,
last_used: u64,
}
struct CacheInner<T> {
entries: HashMap<QueryKey, CacheEntry<T>>,
limit_entries: usize,
max_bytes: usize,
bytes: usize,
clock: u64,
stats: DataCacheStats,
estimate: Rc<dyn Fn(&T) -> usize>,
}
pub struct QueryCache<T>
where
T: 'static,
{
inner: Rc<RefCell<CacheInner<T>>>,
}
impl<T> Clone for QueryCache<T>
where
T: 'static,
{
fn clone(&self) -> Self {
Self { inner: self.inner.clone() }
}
}
impl<T> std::fmt::Debug for QueryCache<T>
where
T: 'static,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("QueryCache")
.field("entries", &self.inner.borrow().entries.len())
.field("bytes", &self.inner.borrow().bytes)
.field("stats", &self.inner.borrow().stats)
.finish()
}
}
impl<T> QueryCache<T>
where
T: 'static,
{
pub fn new(limit_entries: usize, max_bytes: usize, estimate: impl Fn(&T) -> usize + 'static) -> Self {
Self {
inner: Rc::new(RefCell::new(CacheInner {
entries: HashMap::new(),
limit_entries: limit_entries.max(1),
max_bytes,
bytes: 0,
clock: 0,
stats: DataCacheStats::default(),
estimate: Rc::new(estimate),
})),
}
}
pub fn insert(&self, key: QueryKey, value: Rc<T>, group: u64) {
self.insert_with_scope(key, value, InvalidationScope::Group(group));
}
pub fn insert_with_scope(&self, key: QueryKey, value: Rc<T>, scope: InvalidationScope) {
let mut inner = self.inner.borrow_mut();
inner.clock = inner.clock.wrapping_add(1);
inner.stats.inserts = inner.stats.inserts.saturating_add(1);
let bytes = (inner.estimate)(value.as_ref());
let clock = inner.clock;
if let Some(old) = inner.entries.remove(&key) {
inner.bytes = inner.bytes.saturating_sub(old.bytes);
}
inner.entries.insert(key, CacheEntry { value, bytes, scope, stale: false, last_used: clock });
inner.bytes = inner.bytes.saturating_add(bytes);
inner.evict();
}
pub fn lookup(&self, key: QueryKey) -> DataCacheLookup<T> {
let mut inner = self.inner.borrow_mut();
inner.clock = inner.clock.wrapping_add(1);
let clock = inner.clock;
let Some((stale, value)) = (|| {
let entry = inner.entries.get_mut(&key)?;
entry.last_used = clock;
Some((entry.stale, entry.value.clone()))
})() else {
inner.stats.misses = inner.stats.misses.saturating_add(1);
return DataCacheLookup::Miss;
};
if stale {
inner.stats.stale_hits = inner.stats.stale_hits.saturating_add(1);
DataCacheLookup::Stale(value)
} else {
inner.stats.fresh_hits = inner.stats.fresh_hits.saturating_add(1);
DataCacheLookup::Fresh(value)
}
}
pub fn invalidate(&self, scope: InvalidationScope) -> u32 {
let mut inner = self.inner.borrow_mut();
let mut count = 0;
for (key, entry) in inner.entries.iter_mut() {
if scope.matches_scope(*key, entry.scope) && !entry.stale {
entry.stale = true;
count += 1;
}
}
inner.stats.invalidations = inner.stats.invalidations.saturating_add(count);
count
}
pub fn stats(&self) -> DataCacheStats {
self.inner.borrow().stats
}
pub fn take_stats(&self) -> DataCacheStats {
let mut inner = self.inner.borrow_mut();
let out = inner.stats;
inner.stats = DataCacheStats::default();
out
}
pub fn len(&self) -> usize {
self.inner.borrow().entries.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn clear(&self) {
let mut inner = self.inner.borrow_mut();
inner.entries.clear();
inner.bytes = 0;
}
}
impl<T> CacheInner<T>
where
T: 'static,
{
fn evict(&mut self) {
while self.entries.len() > self.limit_entries || self.bytes > self.max_bytes {
let Some((key, bytes)) = self.entries.iter().min_by_key(|(_, e)| e.last_used).map(|(k, e)| (*k, e.bytes))
else {
break;
};
self.entries.remove(&key);
self.bytes = self.bytes.saturating_sub(bytes);
self.stats.evictions = self.stats.evictions.saturating_add(1);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cache() -> QueryCache<Vec<u32>> {
QueryCache::new(8, 1024, |v: &Vec<u32>| v.len() * 4)
}
#[test]
fn fresh_lookup_does_not_become_stale() {
let cache = cache();
let key = QueryKey::new(1);
cache.insert(key, Rc::new(vec![1, 2]), 0);
assert_eq!(cache.lookup(key), DataCacheLookup::Fresh(Rc::new(vec![1, 2])));
}
#[test]
fn invalidation_marks_scope_stale_not_missing() {
let cache = cache();
let a = QueryKey::new(1);
let b = QueryKey::new(2);
cache.insert(a, Rc::new(vec![1]), 10);
cache.insert(b, Rc::new(vec![2]), 20);
assert_eq!(cache.invalidate(InvalidationScope::Group(10)), 1);
assert!(matches!(cache.lookup(a), DataCacheLookup::Stale(_)));
assert!(matches!(cache.lookup(b), DataCacheLookup::Fresh(_)));
}
#[test]
fn eviction_bounds_entries_and_bytes() {
let cache = QueryCache::new(2, 8, |v: &Vec<u32>| v.len() * 4);
cache.insert(QueryKey::new(1), Rc::new(vec![1]), 0);
cache.insert(QueryKey::new(2), Rc::new(vec![2]), 0);
cache.insert(QueryKey::new(3), Rc::new(vec![3]), 0);
assert!(cache.len() <= 2);
assert!(cache.inner.borrow().bytes <= 8);
assert!(cache.stats().evictions > 0);
}
#[test]
fn hierarchical_invalidation_follows_parent_to_children() {
let cache = cache();
let p1 = ScopePath::new(1, 1, 1);
let p2 = ScopePath::new(1, 2, 1);
let p3 = ScopePath::new(2, 1, 1);
let legacy = QueryKey::new(1);
let a1 = QueryKey::new(2);
let a2 = QueryKey::new(3);
let b1 = QueryKey::new(4);
cache.insert(legacy, Rc::new(vec![0]), 7);
cache.insert_with_scope(a1, Rc::new(vec![1]), InvalidationScope::KeyIn { path: p1, key: a1 });
cache.insert_with_scope(a2, Rc::new(vec![2]), InvalidationScope::KeyIn { path: p2, key: a2 });
cache.insert_with_scope(b1, Rc::new(vec![3]), InvalidationScope::KeyIn { path: p3, key: b1 });
assert_eq!(cache.invalidate(InvalidationScope::App(1)), 2);
assert!(matches!(cache.lookup(legacy), DataCacheLookup::Fresh(_)));
assert!(matches!(cache.lookup(a1), DataCacheLookup::Stale(_)));
assert!(matches!(cache.lookup(a2), DataCacheLookup::Stale(_)));
assert!(matches!(cache.lookup(b1), DataCacheLookup::Fresh(_)));
}
#[test]
fn child_invalidation_does_not_touch_ancestor_or_sibling() {
let cache = cache();
let p1 = ScopePath::new(1, 1, 1);
let p2 = ScopePath::new(1, 2, 1);
let p3 = ScopePath::new(2, 1, 1);
let k1 = QueryKey::new(1);
let k2 = QueryKey::new(2);
let k3 = QueryKey::new(3);
let k4 = QueryKey::new(4);
cache.insert_with_scope(k1, Rc::new(vec![1]), InvalidationScope::KeyIn { path: p1, key: k1 });
cache.insert_with_scope(k2, Rc::new(vec![2]), InvalidationScope::KeyIn { path: p2, key: k2 });
cache.insert_with_scope(k3, Rc::new(vec![3]), InvalidationScope::App(1));
cache.insert_with_scope(k4, Rc::new(vec![4]), InvalidationScope::KeyIn { path: p3, key: k4 });
assert_eq!(cache.invalidate(InvalidationScope::Window { app: 1, window: 1 }), 1);
assert!(matches!(cache.lookup(k1), DataCacheLookup::Stale(_)));
assert!(matches!(cache.lookup(k2), DataCacheLookup::Fresh(_)));
assert!(matches!(cache.lookup(k3), DataCacheLookup::Fresh(_)), "子节点失效不得污染 app 级祖先");
assert!(matches!(cache.lookup(k4), DataCacheLookup::Fresh(_)));
assert_eq!(cache.invalidate(InvalidationScope::Feature { app: 1, window: 2, feature: 1 }), 1);
assert_eq!(cache.invalidate(InvalidationScope::Key(k4)), 1);
assert!(matches!(cache.lookup(k2), DataCacheLookup::Stale(_)));
assert!(matches!(cache.lookup(k4), DataCacheLookup::Stale(_)));
}
}