Skip to main content

mgui_core/
data_cache.rs

1//! 应用级数据缓存的纯契约(0.7 M3)。
2//!
3//! 这里只定义 key、失效作用域、统计与有界容器;执行桥在 `mgui-store::QueryStore`。
4//! 缓存不持有 Widget/Element/RO,只存 `Rc<T>` 快照与 generation/作用域标记。
5//! 不使用墙钟 TTL:刷新时机由显式失效与 stale 命中后的后台重取决定,方便 Agent replay。
6
7use std::cell::RefCell;
8use std::collections::HashMap;
9use std::rc::Rc;
10
11use crate::QueryKey;
12
13/// 缓存命中/失效统计。同一统计归应用持有的 cache 实例所有。
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub struct DataCacheStats {
16    pub fresh_hits: u32,
17    pub stale_hits: u32,
18    pub misses: u32,
19    pub inserts: u32,
20    pub invalidations: u32,
21    pub evictions: u32,
22}
23
24/// 失效作用域。`All` 与 `Key` 足够覆盖单 key store;`Group` 由应用给相关 key 分组。
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum InvalidationScope {
27    All,
28    Key(QueryKey),
29    Group(u64),
30}
31
32impl InvalidationScope {
33    pub fn matches(self, key: QueryKey, group: u64) -> bool {
34        match self {
35            Self::All => true,
36            Self::Key(k) => k == key,
37            Self::Group(g) => g == group,
38        }
39    }
40}
41
42/// 缓存查询结果。fresh 可直接展示;stale 只能先展示再后台刷新。
43#[derive(Debug, PartialEq)]
44pub enum DataCacheLookup<T> {
45    Fresh(Rc<T>),
46    Stale(Rc<T>),
47    Miss,
48}
49
50struct CacheEntry<T> {
51    value: Rc<T>,
52    bytes: usize,
53    group: u64,
54    stale: bool,
55    last_used: u64,
56}
57
58struct CacheInner<T> {
59    entries: HashMap<QueryKey, CacheEntry<T>>,
60    limit_entries: usize,
61    max_bytes: usize,
62    bytes: usize,
63    clock: u64,
64    stats: DataCacheStats,
65    estimate: Rc<dyn Fn(&T) -> usize>,
66}
67
68/// 应用持有、可 Clone 共享的有界数据缓存。
69pub struct QueryCache<T>
70where
71    T: 'static,
72{
73    inner: Rc<RefCell<CacheInner<T>>>,
74}
75
76impl<T> Clone for QueryCache<T>
77where
78    T: 'static,
79{
80    fn clone(&self) -> Self {
81        Self { inner: self.inner.clone() }
82    }
83}
84
85impl<T> std::fmt::Debug for QueryCache<T>
86where
87    T: 'static,
88{
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        f.debug_struct("QueryCache")
91            .field("entries", &self.inner.borrow().entries.len())
92            .field("bytes", &self.inner.borrow().bytes)
93            .field("stats", &self.inner.borrow().stats)
94            .finish()
95    }
96}
97
98impl<T> QueryCache<T>
99where
100    T: 'static,
101{
102    /// 创建有界缓存。缓存大小以应用提供的 `estimate` 为准,框架不猜泛型大小。
103    pub fn new(limit_entries: usize, max_bytes: usize, estimate: impl Fn(&T) -> usize + 'static) -> Self {
104        Self {
105            inner: Rc::new(RefCell::new(CacheInner {
106                entries: HashMap::new(),
107                limit_entries: limit_entries.max(1),
108                max_bytes,
109                bytes: 0,
110                clock: 0,
111                stats: DataCacheStats::default(),
112                estimate: Rc::new(estimate),
113            })),
114        }
115    }
116
117    pub fn insert(&self, key: QueryKey, value: Rc<T>, group: u64) {
118        let mut inner = self.inner.borrow_mut();
119        inner.clock = inner.clock.wrapping_add(1);
120        inner.stats.inserts = inner.stats.inserts.saturating_add(1);
121        let bytes = (inner.estimate)(value.as_ref());
122        let clock = inner.clock;
123        if let Some(old) = inner.entries.remove(&key) {
124            inner.bytes = inner.bytes.saturating_sub(old.bytes);
125        }
126        inner.entries.insert(key, CacheEntry { value, bytes, group, stale: false, last_used: clock });
127        inner.bytes = inner.bytes.saturating_add(bytes);
128        inner.evict();
129    }
130
131    pub fn lookup(&self, key: QueryKey) -> DataCacheLookup<T> {
132        let mut inner = self.inner.borrow_mut();
133        inner.clock = inner.clock.wrapping_add(1);
134        let clock = inner.clock;
135        let Some((stale, value)) = (|| {
136            let entry = inner.entries.get_mut(&key)?;
137            entry.last_used = clock;
138            Some((entry.stale, entry.value.clone()))
139        })() else {
140            inner.stats.misses = inner.stats.misses.saturating_add(1);
141            return DataCacheLookup::Miss;
142        };
143        if stale {
144            inner.stats.stale_hits = inner.stats.stale_hits.saturating_add(1);
145            DataCacheLookup::Stale(value)
146        } else {
147            inner.stats.fresh_hits = inner.stats.fresh_hits.saturating_add(1);
148            DataCacheLookup::Fresh(value)
149        }
150    }
151
152    /// 命中旧数据时只标 stale,不删除;UI 可继续展示并由 QueryStore 后台刷新。
153    pub fn invalidate(&self, scope: InvalidationScope) -> u32 {
154        let mut inner = self.inner.borrow_mut();
155        let mut count = 0;
156        for (key, entry) in inner.entries.iter_mut() {
157            if scope.matches(*key, entry.group) && !entry.stale {
158                entry.stale = true;
159                count += 1;
160            }
161        }
162        inner.stats.invalidations = inner.stats.invalidations.saturating_add(count);
163        count
164    }
165
166    pub fn stats(&self) -> DataCacheStats {
167        self.inner.borrow().stats
168    }
169
170    pub fn take_stats(&self) -> DataCacheStats {
171        let mut inner = self.inner.borrow_mut();
172        let out = inner.stats;
173        inner.stats = DataCacheStats::default();
174        out
175    }
176
177    pub fn len(&self) -> usize {
178        self.inner.borrow().entries.len()
179    }
180
181    pub fn is_empty(&self) -> bool {
182        self.len() == 0
183    }
184
185    pub fn clear(&self) {
186        let mut inner = self.inner.borrow_mut();
187        inner.entries.clear();
188        inner.bytes = 0;
189    }
190}
191
192impl<T> CacheInner<T>
193where
194    T: 'static,
195{
196    fn evict(&mut self) {
197        while self.entries.len() > self.limit_entries || self.bytes > self.max_bytes {
198            let Some((key, bytes)) = self.entries.iter().min_by_key(|(_, e)| e.last_used).map(|(k, e)| (*k, e.bytes))
199            else {
200                break;
201            };
202            self.entries.remove(&key);
203            self.bytes = self.bytes.saturating_sub(bytes);
204            self.stats.evictions = self.stats.evictions.saturating_add(1);
205        }
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    fn cache() -> QueryCache<Vec<u32>> {
214        QueryCache::new(8, 1024, |v: &Vec<u32>| v.len() * 4)
215    }
216
217    #[test]
218    fn fresh_lookup_does_not_become_stale() {
219        let cache = cache();
220        let key = QueryKey::new(1);
221        cache.insert(key, Rc::new(vec![1, 2]), 0);
222        assert_eq!(cache.lookup(key), DataCacheLookup::Fresh(Rc::new(vec![1, 2])));
223    }
224
225    #[test]
226    fn invalidation_marks_scope_stale_not_missing() {
227        let cache = cache();
228        let a = QueryKey::new(1);
229        let b = QueryKey::new(2);
230        cache.insert(a, Rc::new(vec![1]), 10);
231        cache.insert(b, Rc::new(vec![2]), 20);
232        assert_eq!(cache.invalidate(InvalidationScope::Group(10)), 1);
233        assert!(matches!(cache.lookup(a), DataCacheLookup::Stale(_)));
234        assert!(matches!(cache.lookup(b), DataCacheLookup::Fresh(_)));
235    }
236
237    #[test]
238    fn eviction_bounds_entries_and_bytes() {
239        let cache = QueryCache::new(2, 8, |v: &Vec<u32>| v.len() * 4);
240        cache.insert(QueryKey::new(1), Rc::new(vec![1]), 0);
241        cache.insert(QueryKey::new(2), Rc::new(vec![2]), 0);
242        cache.insert(QueryKey::new(3), Rc::new(vec![3]), 0);
243        assert!(cache.len() <= 2);
244        assert!(cache.inner.borrow().bytes <= 8);
245        assert!(cache.stats().evictions > 0);
246    }
247}