Skip to main content

heika_state_transition/executor/
source.rs

1//! メモリにない状態を読む口。ブロックを当てる前と、当てて足りなかったときに、キーを指定して読むので同期にする
2//! (ブラウザでは、OPFS を専用の Worker から同期で使う前提)。
3
4use std::collections::{BTreeMap, HashMap};
5use std::sync::{Arc, Mutex};
6
7use super::ExecError;
8
9/// 今の状態の行と木のノードを読む口
10pub trait StateSource {
11    /// 状態の行 `key`([`super::persist::row_key`])。なければ `None`
12    fn row(&self, key: &[u8]) -> Result<Option<Vec<u8>>, ExecError>;
13    /// 木のノード `key`([`crate::tree::node_key`])。なければ `None`
14    fn node(&self, key: &[u8]) -> Result<Option<Vec<u8>>, ExecError>;
15    /// キーが `prefix` で始まる状態の行を、キーの順に `visit` に渡す。全部を一度にメモリに置かない
16    fn for_each_row(
17        &self,
18        prefix: &[u8],
19        visit: &mut dyn FnMut(&[u8], &[u8]),
20    ) -> Result<(), ExecError>;
21}
22
23/// 分け合っている読み口。ほかのスレッドと同じ DB を読むとき
24impl<S: StateSource + ?Sized> StateSource for Arc<S> {
25    fn row(&self, key: &[u8]) -> Result<Option<Vec<u8>>, ExecError> {
26        (**self).row(key)
27    }
28
29    fn node(&self, key: &[u8]) -> Result<Option<Vec<u8>>, ExecError> {
30        (**self).node(key)
31    }
32
33    fn for_each_row(
34        &self,
35        prefix: &[u8],
36        visit: &mut dyn FnMut(&[u8], &[u8]),
37    ) -> Result<(), ExecError> {
38        (**self).for_each_row(prefix, visit)
39    }
40}
41
42/// [`StateSource`] を包み、読んだ行と木のノード(なかったことも)を覚えておくキャッシュ。要るものだけを読む
43/// [`super::Executor`] は、ブロックをコミットするたびに読み込んだものを手放す
44/// ([`super::Executor::release_loaded`])ので、ブロックをまたいで持っておくのはここだけになる。
45///
46/// 覚える量は、キーと値のバイト数で決め、超えたら長く使っていないものから捨てる。コミットで変わった行と
47/// ノードは [`CachedSource::record`] で、巻き戻したら [`CachedSource::clear`] で伝える。前方一致の走査
48/// ([`StateSource::for_each_row`])は覚えずに、包んだ読み口にそのまま渡す。
49pub struct CachedSource<S> {
50    inner: S,
51    cache: Mutex<Cache>,
52}
53
54/// キャッシュの様子
55#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
56pub struct CacheStats {
57    /// 覚えているもののバイト数(見積もり)と数
58    pub bytes: usize,
59    pub entries: usize,
60    /// 覚えていたものを返した数と、包んだ読み口に読みに行った数
61    pub hits: u64,
62    pub misses: u64,
63}
64
65#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
66enum Kind {
67    Row,
68    Node,
69}
70
71type Key = (Kind, Vec<u8>);
72
73/// 1件あたりに足すバイト数の見積もり(表の入れ物と、新しさの順の分)
74const ENTRY_OVERHEAD: usize = 96;
75
76#[derive(Default)]
77struct Cache {
78    /// 値(なかったら `None`)と、最後に使った順番
79    entries: HashMap<Key, (Option<Vec<u8>>, u64)>,
80    /// 使った順番から、キー。古いものから捨てる
81    recency: BTreeMap<u64, Key>,
82    next: u64,
83    capacity: usize,
84    stats: CacheStats,
85}
86
87fn size(key: &Key, value: &Option<Vec<u8>>) -> usize {
88    key.1.len() + value.as_ref().map_or(0, Vec::len) + ENTRY_OVERHEAD
89}
90
91impl Cache {
92    fn get(&mut self, key: &Key) -> Option<Option<Vec<u8>>> {
93        let next = self.next;
94        let Some((value, used)) = self.entries.get_mut(key) else {
95            self.stats.misses += 1;
96            return None;
97        };
98        self.recency.remove(used);
99        *used = next;
100        self.recency.insert(next, key.clone());
101        self.next += 1;
102        self.stats.hits += 1;
103        Some(value.clone())
104    }
105
106    fn put(&mut self, key: Key, value: Option<Vec<u8>>) {
107        if let Some((old, used)) = self.entries.remove(&key) {
108            self.recency.remove(&used);
109            self.stats.bytes -= size(&key, &old);
110        }
111        self.stats.bytes += size(&key, &value);
112        self.recency.insert(self.next, key.clone());
113        self.entries.insert(key, (value, self.next));
114        self.next += 1;
115        while self.stats.bytes > self.capacity {
116            let Some((_, oldest)) = self.recency.pop_first() else {
117                break;
118            };
119            if let Some((old, _)) = self.entries.remove(&oldest) {
120                self.stats.bytes -= size(&oldest, &old);
121            }
122        }
123        self.stats.entries = self.entries.len();
124    }
125}
126
127impl<S> CachedSource<S> {
128    /// `inner` を包み、最大 `capacity` バイトまで覚える
129    pub fn new(inner: S, capacity: usize) -> Self {
130        Self {
131            inner,
132            cache: Mutex::new(Cache {
133                capacity,
134                ..Cache::default()
135            }),
136        }
137    }
138
139    pub fn inner(&self) -> &S {
140        &self.inner
141    }
142
143    /// 包んだ読み口を変えるときに使う。変えた行とノードは [`CachedSource::record`] で伝えること
144    pub fn inner_mut(&mut self) -> &mut S {
145        &mut self.inner
146    }
147
148    pub fn into_inner(self) -> S {
149        self.inner
150    }
151
152    /// コミットで変わった行([`super::persist::row_key`])と木のノード([`crate::tree::node_key`])。`None` は消えた。
153    /// 覚えているものは新しい値にし、覚えていないものも、すぐまた読まれやすいので覚える
154    pub fn record(
155        &self,
156        rows: impl IntoIterator<Item = (Vec<u8>, Option<Vec<u8>>)>,
157        nodes: impl IntoIterator<Item = (Vec<u8>, Option<Vec<u8>>)>,
158    ) {
159        let mut cache = self.cache.lock().expect("not poisoned");
160        for (key, value) in rows {
161            cache.put((Kind::Row, key), value);
162        }
163        for (key, value) in nodes {
164            cache.put((Kind::Node, key), value);
165        }
166    }
167
168    /// 覚えたものを全部捨てる。巻き戻したとき
169    pub fn clear(&self) {
170        let mut cache = self.cache.lock().expect("not poisoned");
171        cache.entries.clear();
172        cache.recency.clear();
173        cache.stats.bytes = 0;
174        cache.stats.entries = 0;
175    }
176
177    pub fn stats(&self) -> CacheStats {
178        self.cache.lock().expect("not poisoned").stats
179    }
180
181    fn cached(
182        &self,
183        key: Key,
184        read: impl FnOnce() -> Result<Option<Vec<u8>>, ExecError>,
185    ) -> Result<Option<Vec<u8>>, ExecError> {
186        if let Some(value) = self.cache.lock().expect("not poisoned").get(&key) {
187            return Ok(value);
188        }
189        // 読むあいだはロックを放す(読み口が遅くても、ほかの読みを止めない)
190        let value = read()?;
191        self.cache
192            .lock()
193            .expect("not poisoned")
194            .put(key, value.clone());
195        Ok(value)
196    }
197}
198
199impl<S: StateSource> StateSource for CachedSource<S> {
200    fn row(&self, key: &[u8]) -> Result<Option<Vec<u8>>, ExecError> {
201        self.cached((Kind::Row, key.to_vec()), || self.inner.row(key))
202    }
203
204    fn node(&self, key: &[u8]) -> Result<Option<Vec<u8>>, ExecError> {
205        self.cached((Kind::Node, key.to_vec()), || self.inner.node(key))
206    }
207
208    fn for_each_row(
209        &self,
210        prefix: &[u8],
211        visit: &mut dyn FnMut(&[u8], &[u8]),
212    ) -> Result<(), ExecError> {
213        self.inner.for_each_row(prefix, visit)
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use std::cell::Cell;
220
221    use super::*;
222
223    /// 読まれた回数を数える読み口
224    #[derive(Default)]
225    struct Counting {
226        rows: BTreeMap<Vec<u8>, Vec<u8>>,
227        reads: Cell<usize>,
228    }
229
230    impl StateSource for Counting {
231        fn row(&self, key: &[u8]) -> Result<Option<Vec<u8>>, ExecError> {
232            self.reads.set(self.reads.get() + 1);
233            Ok(self.rows.get(key).cloned())
234        }
235
236        fn node(&self, _: &[u8]) -> Result<Option<Vec<u8>>, ExecError> {
237            Ok(None)
238        }
239
240        fn for_each_row(&self, _: &[u8], _: &mut dyn FnMut(&[u8], &[u8])) -> Result<(), ExecError> {
241            Ok(())
242        }
243    }
244
245    #[test]
246    fn remembers_values_and_absence_and_follows_commits() {
247        let mut inner = Counting::default();
248        inner.rows.insert(vec![1], vec![10]);
249        let cached = CachedSource::new(inner, 1 << 20);
250        for _ in 0..3 {
251            assert_eq!(cached.row(&[1]).unwrap(), Some(vec![10]));
252            assert_eq!(cached.row(&[2]).unwrap(), None);
253        }
254        // なかったことも覚えるので、読みに行くのは 1 回ずつ
255        assert_eq!(cached.inner().reads.get(), 2);
256        assert_eq!(cached.stats().hits, 4);
257        // コミットで変わったものは、読み直さずに新しい値を返す
258        cached.record([(vec![1], None), (vec![2], Some(vec![20]))], []);
259        assert_eq!(cached.row(&[1]).unwrap(), None);
260        assert_eq!(cached.row(&[2]).unwrap(), Some(vec![20]));
261        assert_eq!(cached.inner().reads.get(), 2);
262        cached.clear();
263        assert_eq!(cached.row(&[1]).unwrap(), Some(vec![10]));
264        assert_eq!(cached.inner().reads.get(), 3);
265    }
266
267    #[test]
268    fn drops_the_least_recently_used_beyond_the_capacity() {
269        let mut inner = Counting::default();
270        for key in 0..10u8 {
271            inner.rows.insert(vec![key], vec![key; 100]);
272        }
273        // 3 件ぶんだけ覚えられる
274        let cached = CachedSource::new(inner, 3 * (1 + 100 + ENTRY_OVERHEAD));
275        for key in [0, 1, 2] {
276            cached.row(&[key]).unwrap();
277        }
278        // 0 を使い直すと、次に足したときに捨てられるのは 1
279        cached.row(&[0]).unwrap();
280        cached.row(&[3]).unwrap();
281        let reads = cached.inner().reads.get();
282        cached.row(&[0]).unwrap();
283        cached.row(&[2]).unwrap();
284        cached.row(&[3]).unwrap();
285        assert_eq!(cached.inner().reads.get(), reads);
286        cached.row(&[1]).unwrap();
287        assert_eq!(cached.inner().reads.get(), reads + 1);
288        assert!(cached.stats().bytes <= 3 * (1 + 100 + ENTRY_OVERHEAD));
289        assert_eq!(cached.stats().entries, 3);
290    }
291}