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/// 层级归属路径。`app` / `window` / `feature` 由应用按窗口与功能域分配;
25/// 框架只负责传播规则,不持有第二套窗口或组件树。
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27pub struct ScopePath {
28    pub app: u64,
29    pub window: u64,
30    pub feature: u64,
31}
32
33impl ScopePath {
34    pub const fn new(app: u64, window: u64, feature: u64) -> Self {
35        Self { app, window, feature }
36    }
37}
38
39/// 失效作用域。`All` / `Key` / `Group` 保持 0.7 语义;新增层级变体表达
40/// app → window → feature → key 的父子传播:失效父级覆盖子级,失效子级不影响父级。
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum InvalidationScope {
43    All,
44    Key(QueryKey),
45    Group(u64),
46    App(u64),
47    Window { app: u64, window: u64 },
48    Feature { app: u64, window: u64, feature: u64 },
49    KeyIn { path: ScopePath, key: QueryKey },
50}
51
52impl InvalidationScope {
53    /// 兼容 0.7 的扁平分组判定。
54    pub fn matches(self, key: QueryKey, group: u64) -> bool {
55        self.matches_scope(key, Self::Group(group))
56    }
57
58    /// 层级判定:`self` 是失效请求,`entry_scope` 是缓存条目归属。
59    pub fn matches_scope(self, key: QueryKey, entry_scope: Self) -> bool {
60        match self {
61            Self::All => true,
62            Self::Key(k) => k == key || matches!(entry_scope, Self::KeyIn { key: ek, .. } if ek == k),
63            Self::Group(g) => entry_scope == Self::Group(g),
64            Self::App(app) => match entry_scope {
65                Self::App(ea) => ea == app,
66                Self::Window { app: ea, .. } => ea == app,
67                Self::Feature { app: ea, .. } => ea == app,
68                Self::KeyIn { path, .. } => path.app == app,
69                _ => false,
70            },
71            Self::Window { app, window } => match entry_scope {
72                Self::Window { app: ea, window: ew } => ea == app && ew == window,
73                Self::Feature { app: ea, window: ew, .. } => ea == app && ew == window,
74                Self::KeyIn { path, .. } => path.app == app && path.window == window,
75                _ => false,
76            },
77            Self::Feature { app, window, feature } => match entry_scope {
78                Self::Feature { app: ea, window: ew, feature: ef } => ea == app && ew == window && ef == feature,
79                Self::KeyIn { path, .. } => path.app == app && path.window == window && path.feature == feature,
80                _ => false,
81            },
82            Self::KeyIn { path, key } => entry_scope == Self::KeyIn { path, key },
83        }
84    }
85}
86
87/// 缓存查询结果。fresh 可直接展示;stale 只能先展示再后台刷新。
88#[derive(Debug, PartialEq)]
89pub enum DataCacheLookup<T> {
90    Fresh(Rc<T>),
91    Stale(Rc<T>),
92    Miss,
93}
94
95struct CacheEntry<T> {
96    value: Rc<T>,
97    bytes: usize,
98    scope: InvalidationScope,
99    stale: bool,
100    last_used: u64,
101}
102
103struct CacheInner<T> {
104    entries: HashMap<QueryKey, CacheEntry<T>>,
105    limit_entries: usize,
106    max_bytes: usize,
107    bytes: usize,
108    clock: u64,
109    stats: DataCacheStats,
110    estimate: Rc<dyn Fn(&T) -> usize>,
111}
112
113/// 应用持有、可 Clone 共享的有界数据缓存。
114pub struct QueryCache<T>
115where
116    T: 'static,
117{
118    inner: Rc<RefCell<CacheInner<T>>>,
119}
120
121impl<T> Clone for QueryCache<T>
122where
123    T: 'static,
124{
125    fn clone(&self) -> Self {
126        Self { inner: self.inner.clone() }
127    }
128}
129
130impl<T> std::fmt::Debug for QueryCache<T>
131where
132    T: 'static,
133{
134    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135        f.debug_struct("QueryCache")
136            .field("entries", &self.inner.borrow().entries.len())
137            .field("bytes", &self.inner.borrow().bytes)
138            .field("stats", &self.inner.borrow().stats)
139            .finish()
140    }
141}
142
143impl<T> QueryCache<T>
144where
145    T: 'static,
146{
147    /// 创建有界缓存。缓存大小以应用提供的 `estimate` 为准,框架不猜泛型大小。
148    pub fn new(limit_entries: usize, max_bytes: usize, estimate: impl Fn(&T) -> usize + 'static) -> Self {
149        Self {
150            inner: Rc::new(RefCell::new(CacheInner {
151                entries: HashMap::new(),
152                limit_entries: limit_entries.max(1),
153                max_bytes,
154                bytes: 0,
155                clock: 0,
156                stats: DataCacheStats::default(),
157                estimate: Rc::new(estimate),
158            })),
159        }
160    }
161
162    /// 兼容 0.7 的扁平分组写入。
163    pub fn insert(&self, key: QueryKey, value: Rc<T>, group: u64) {
164        self.insert_with_scope(key, value, InvalidationScope::Group(group));
165    }
166
167    /// 按层级作用域写入缓存;失效传播由 `InvalidationScope::matches_scope` 决定。
168    pub fn insert_with_scope(&self, key: QueryKey, value: Rc<T>, scope: InvalidationScope) {
169        let mut inner = self.inner.borrow_mut();
170        inner.clock = inner.clock.wrapping_add(1);
171        inner.stats.inserts = inner.stats.inserts.saturating_add(1);
172        let bytes = (inner.estimate)(value.as_ref());
173        let clock = inner.clock;
174        if let Some(old) = inner.entries.remove(&key) {
175            inner.bytes = inner.bytes.saturating_sub(old.bytes);
176        }
177        inner.entries.insert(key, CacheEntry { value, bytes, scope, stale: false, last_used: clock });
178        inner.bytes = inner.bytes.saturating_add(bytes);
179        inner.evict();
180    }
181
182    pub fn lookup(&self, key: QueryKey) -> DataCacheLookup<T> {
183        let mut inner = self.inner.borrow_mut();
184        inner.clock = inner.clock.wrapping_add(1);
185        let clock = inner.clock;
186        let Some((stale, value)) = (|| {
187            let entry = inner.entries.get_mut(&key)?;
188            entry.last_used = clock;
189            Some((entry.stale, entry.value.clone()))
190        })() else {
191            inner.stats.misses = inner.stats.misses.saturating_add(1);
192            return DataCacheLookup::Miss;
193        };
194        if stale {
195            inner.stats.stale_hits = inner.stats.stale_hits.saturating_add(1);
196            DataCacheLookup::Stale(value)
197        } else {
198            inner.stats.fresh_hits = inner.stats.fresh_hits.saturating_add(1);
199            DataCacheLookup::Fresh(value)
200        }
201    }
202
203    /// 命中旧数据时只标 stale,不删除;UI 可继续展示并由 QueryStore 后台刷新。
204    pub fn invalidate(&self, scope: InvalidationScope) -> u32 {
205        let mut inner = self.inner.borrow_mut();
206        let mut count = 0;
207        for (key, entry) in inner.entries.iter_mut() {
208            if scope.matches_scope(*key, entry.scope) && !entry.stale {
209                entry.stale = true;
210                count += 1;
211            }
212        }
213        inner.stats.invalidations = inner.stats.invalidations.saturating_add(count);
214        count
215    }
216
217    pub fn stats(&self) -> DataCacheStats {
218        self.inner.borrow().stats
219    }
220
221    pub fn take_stats(&self) -> DataCacheStats {
222        let mut inner = self.inner.borrow_mut();
223        let out = inner.stats;
224        inner.stats = DataCacheStats::default();
225        out
226    }
227
228    pub fn len(&self) -> usize {
229        self.inner.borrow().entries.len()
230    }
231
232    pub fn is_empty(&self) -> bool {
233        self.len() == 0
234    }
235
236    pub fn clear(&self) {
237        let mut inner = self.inner.borrow_mut();
238        inner.entries.clear();
239        inner.bytes = 0;
240    }
241}
242
243impl<T> CacheInner<T>
244where
245    T: 'static,
246{
247    fn evict(&mut self) {
248        while self.entries.len() > self.limit_entries || self.bytes > self.max_bytes {
249            let Some((key, bytes)) = self.entries.iter().min_by_key(|(_, e)| e.last_used).map(|(k, e)| (*k, e.bytes))
250            else {
251                break;
252            };
253            self.entries.remove(&key);
254            self.bytes = self.bytes.saturating_sub(bytes);
255            self.stats.evictions = self.stats.evictions.saturating_add(1);
256        }
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    fn cache() -> QueryCache<Vec<u32>> {
265        QueryCache::new(8, 1024, |v: &Vec<u32>| v.len() * 4)
266    }
267
268    #[test]
269    fn fresh_lookup_does_not_become_stale() {
270        let cache = cache();
271        let key = QueryKey::new(1);
272        cache.insert(key, Rc::new(vec![1, 2]), 0);
273        assert_eq!(cache.lookup(key), DataCacheLookup::Fresh(Rc::new(vec![1, 2])));
274    }
275
276    #[test]
277    fn invalidation_marks_scope_stale_not_missing() {
278        let cache = cache();
279        let a = QueryKey::new(1);
280        let b = QueryKey::new(2);
281        cache.insert(a, Rc::new(vec![1]), 10);
282        cache.insert(b, Rc::new(vec![2]), 20);
283        assert_eq!(cache.invalidate(InvalidationScope::Group(10)), 1);
284        assert!(matches!(cache.lookup(a), DataCacheLookup::Stale(_)));
285        assert!(matches!(cache.lookup(b), DataCacheLookup::Fresh(_)));
286    }
287
288    #[test]
289    fn eviction_bounds_entries_and_bytes() {
290        let cache = QueryCache::new(2, 8, |v: &Vec<u32>| v.len() * 4);
291        cache.insert(QueryKey::new(1), Rc::new(vec![1]), 0);
292        cache.insert(QueryKey::new(2), Rc::new(vec![2]), 0);
293        cache.insert(QueryKey::new(3), Rc::new(vec![3]), 0);
294        assert!(cache.len() <= 2);
295        assert!(cache.inner.borrow().bytes <= 8);
296        assert!(cache.stats().evictions > 0);
297    }
298
299    #[test]
300    fn hierarchical_invalidation_follows_parent_to_children() {
301        let cache = cache();
302        let p1 = ScopePath::new(1, 1, 1);
303        let p2 = ScopePath::new(1, 2, 1);
304        let p3 = ScopePath::new(2, 1, 1);
305
306        let legacy = QueryKey::new(1);
307        let a1 = QueryKey::new(2);
308        let a2 = QueryKey::new(3);
309        let b1 = QueryKey::new(4);
310
311        cache.insert(legacy, Rc::new(vec![0]), 7);
312        cache.insert_with_scope(a1, Rc::new(vec![1]), InvalidationScope::KeyIn { path: p1, key: a1 });
313        cache.insert_with_scope(a2, Rc::new(vec![2]), InvalidationScope::KeyIn { path: p2, key: a2 });
314        cache.insert_with_scope(b1, Rc::new(vec![3]), InvalidationScope::KeyIn { path: p3, key: b1 });
315
316        assert_eq!(cache.invalidate(InvalidationScope::App(1)), 2);
317        assert!(matches!(cache.lookup(legacy), DataCacheLookup::Fresh(_)));
318        assert!(matches!(cache.lookup(a1), DataCacheLookup::Stale(_)));
319        assert!(matches!(cache.lookup(a2), DataCacheLookup::Stale(_)));
320        assert!(matches!(cache.lookup(b1), DataCacheLookup::Fresh(_)));
321    }
322
323    #[test]
324    fn child_invalidation_does_not_touch_ancestor_or_sibling() {
325        let cache = cache();
326        let p1 = ScopePath::new(1, 1, 1);
327        let p2 = ScopePath::new(1, 2, 1);
328        let p3 = ScopePath::new(2, 1, 1);
329
330        let k1 = QueryKey::new(1);
331        let k2 = QueryKey::new(2);
332        let k3 = QueryKey::new(3);
333        let k4 = QueryKey::new(4);
334
335        cache.insert_with_scope(k1, Rc::new(vec![1]), InvalidationScope::KeyIn { path: p1, key: k1 });
336        cache.insert_with_scope(k2, Rc::new(vec![2]), InvalidationScope::KeyIn { path: p2, key: k2 });
337        cache.insert_with_scope(k3, Rc::new(vec![3]), InvalidationScope::App(1));
338        cache.insert_with_scope(k4, Rc::new(vec![4]), InvalidationScope::KeyIn { path: p3, key: k4 });
339
340        assert_eq!(cache.invalidate(InvalidationScope::Window { app: 1, window: 1 }), 1);
341        assert!(matches!(cache.lookup(k1), DataCacheLookup::Stale(_)));
342        assert!(matches!(cache.lookup(k2), DataCacheLookup::Fresh(_)));
343        assert!(matches!(cache.lookup(k3), DataCacheLookup::Fresh(_)), "子节点失效不得污染 app 级祖先");
344        assert!(matches!(cache.lookup(k4), DataCacheLookup::Fresh(_)));
345
346        assert_eq!(cache.invalidate(InvalidationScope::Feature { app: 1, window: 2, feature: 1 }), 1);
347        assert_eq!(cache.invalidate(InvalidationScope::Key(k4)), 1);
348        assert!(matches!(cache.lookup(k2), DataCacheLookup::Stale(_)));
349        assert!(matches!(cache.lookup(k4), DataCacheLookup::Stale(_)));
350    }
351}