Skip to main content

sva_engine/cache/
persist.rs

1// Concern: node values on a backend beneath memory, staged then committed: version, budget, eviction | Non-concern: the bytes' medium (a Backend) | IO: (key) -> Header; samples -> staged; persist()
2
3use std::collections::BTreeMap;
4use std::sync::{Arc, Mutex, MutexGuard};
5
6use sva_formula::Hash;
7use sva_samples::{Buffer, Extent};
8
9use super::codec::{self, STORE_FORMAT};
10use super::index::{Index, key_of, name_of};
11use super::joined;
12use super::stored::{Header, Samples};
13
14pub const DEFAULT_STORE_BYTES: u64 = 2 << 30;
15
16fn version() -> String {
17    format!("sva store format {STORE_FORMAT}")
18}
19
20pub const INDEX_NAME: &str = "index";
21
22/// Kept beside entries by an older format.
23const RETIRED: [&str; 2] = ["version", "recency"];
24
25const META: &str = "meta";
26
27/// Named bytes. A `put` is whole or absent: no reader sees half of one.
28pub trait Backend: Sized {
29    type Lock;
30    /// The one exclusive lock over these names, shared by every store over them.
31    fn lock(&self) -> impl Future<Output = Result<Self::Lock, String>>;
32    fn get(&self, name: &str) -> impl Future<Output = Result<Option<Vec<u8>>, String>>;
33    /// At most `len` bytes from `from` on, fewer where the name ends sooner.
34    fn get_range(
35        &self,
36        name: &str,
37        from: u64,
38        len: u64,
39    ) -> impl Future<Output = Result<Option<Vec<u8>>, String>>;
40    fn put(&self, name: &str, bytes: &[u8]) -> impl Future<Output = Result<(), String>>;
41    /// False where another holder has `name` open, so it stays.
42    fn delete(&self, name: &str) -> impl Future<Output = Result<bool, String>>;
43    /// Each name, with its size in bytes.
44    fn list(&self) -> impl Future<Output = Result<Vec<(String, u64)>, String>>;
45    /// An area beside these names that no other store writes and `list` never names.
46    fn staging(&self) -> impl Future<Output = Result<Self, String>>;
47    /// `name` moved from here into `to` in one step, over whatever `to` held under it; as
48    /// `delete`, false where either is open.
49    fn rename(&self, name: &str, to: &Self) -> impl Future<Output = Result<bool, String>>;
50}
51
52#[derive(Clone, Default)]
53struct Staged {
54    chunks: Vec<(String, Extent)>,
55    meta: bool,
56}
57
58/// Node values under their keys, beneath the memory tier alone: it stages, and only `persist`
59/// commits each value whole by rename, evicting the least recently used past the budget. Every
60/// change to the backend's names runs under its lock; lookups and reads never wait on it.
61pub struct Store<B> {
62    backend: B,
63    staging: B,
64    max_bytes: u64,
65    index: Mutex<Index>,
66    staged: Mutex<BTreeMap<Hash, Staged>>,
67    written: Mutex<u64>,
68}
69
70enum Committed {
71    Moved { bytes: u64 },
72    Busy,
73    Dropped,
74}
75
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
77pub struct Persisted {
78    pub written: usize,
79    pub evicted: usize,
80}
81
82fn locked<T>(held: &Mutex<T>) -> MutexGuard<'_, T> {
83    held.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
84}
85
86impl<B: Backend> Store<B> {
87    /// A store of another format is emptied first.
88    pub async fn open(backend: B, max_bytes: u64) -> Result<Store<B>, String> {
89        let version = version();
90        let held = backend.lock().await?;
91        let found = backend.get(INDEX_NAME).await?;
92        let index = match found.and_then(|text| Index::read(&text, &version)) {
93            Some(index) => index,
94            None => {
95                for (name, _) in backend.list().await? {
96                    if key_of(&name).is_some() || RETIRED.contains(&name.as_str()) {
97                        backend.delete(&name).await?;
98                    }
99                }
100                let empty = Index::default();
101                backend
102                    .put(INDEX_NAME, empty.text(&version).as_bytes())
103                    .await?;
104                empty
105            }
106        };
107        let staging = backend.staging().await?;
108        drop(held);
109        Ok(Store {
110            backend,
111            staging,
112            max_bytes,
113            index: Mutex::new(index),
114            staged: Mutex::new(BTreeMap::new()),
115            written: Mutex::new(0),
116        })
117    }
118
119    pub fn max_bytes(&self) -> u64 {
120        self.max_bytes
121    }
122
123    pub fn bytes(&self) -> u64 {
124        locked(&self.index).bytes
125    }
126
127    pub fn holds(&self, key: Hash) -> bool {
128        locked(&self.index).held.contains_key(&key)
129    }
130
131    /// Reads headers, never a sample; one standing for another's samples reads that one's.
132    pub(crate) async fn lookup(&self, key: Hash) -> Option<Header> {
133        let found = self.written(key).await?;
134        let &Samples::Of { key: of, by } = found.samples() else {
135            return Some(found);
136        };
137        let samples = match self.written(of).await?.into_parts().1 {
138            Samples::Entry { file, runs, .. } => Samples::Entry {
139                file,
140                runs,
141                shift: -by,
142            },
143            Samples::Staged { chunks, .. } => Samples::Staged { chunks, shift: -by },
144            _ => return None,
145        };
146        Some(Header::new(found.into_parts().0, samples))
147    }
148
149    /// Staged first; past the index, the backend, for another store's commits.
150    async fn written(&self, key: Hash) -> Option<Header> {
151        if let Some(staged) = self.staged_value(key).await {
152            return Some(staged);
153        }
154        let name = name_of(key);
155        let Some(mut bytes) = self.backend.get_range(&name, 0, 8).await.ok()? else {
156            locked(&self.index).forget(key);
157            return None;
158        };
159        let rest = codec::head_len(&bytes)? - 8;
160        bytes.extend(self.backend.get_range(&name, 8, rest as u64).await.ok()??);
161        let (found, len) =
162            codec::read_head(&bytes, key).filter(|(found, _)| found.stored().key == key)?;
163        let mut index = locked(&self.index);
164        match index.held.contains_key(&key) {
165            true => index.used(key),
166            false => index.touch(key, len),
167        }
168        Some(found)
169    }
170
171    async fn staged_value(&self, key: Hash) -> Option<Header> {
172        let chunks = {
173            let staged = locked(&self.staged);
174            let held = staged.get(&key).filter(|staged| staged.meta)?;
175            held.chunks.clone()
176        };
177        let meta = self.staging.get(&staged_name(key, META)).await.ok()??;
178        let (found, _) = codec::read_head(&meta, key)?;
179        Some(match found.refers() {
180            true => found,
181            false => Header::new(found.into_parts().0, Samples::Staged { chunks, shift: 0 }),
182        })
183    }
184
185    /// Whole chunks holding `over`; `None` where they are gone or corrupt.
186    pub(crate) async fn read(&self, head: &Header, over: Extent) -> Option<Vec<Buffer>> {
187        let mut out = Vec::new();
188        match head.samples() {
189            Samples::None | Samples::Of { .. } => {}
190            Samples::Entry { file, runs, shift } => {
191                for run in runs {
192                    let met = run.extent().intersect(over.shifted(-shift));
193                    if met.is_empty() {
194                        continue;
195                    }
196                    let chunk = codec::CHUNK as i64;
197                    let from = ((met.start - run.start) / chunk) as usize;
198                    let to = (met.end - run.start).div_euclid(chunk) as usize;
199                    let to = to + usize::from((met.end - run.start) % chunk != 0);
200                    let (at, len) = codec::span_of(run, from, to);
201                    let bytes = self.backend.get_range(&name_of(*file), at, len).await;
202                    let mut samples = codec::read_chunks(&bytes.ok()??, run, from, to)?;
203                    samples.start += shift;
204                    out.push(samples);
205                }
206            }
207            Samples::Staged { chunks, shift } => {
208                for (name, e) in chunks {
209                    if !e.intersect(over.shifted(-shift)).is_empty() {
210                        let bytes = self.staging.get(name).await.ok()??;
211                        let mut samples = codec::read_chunk(&bytes)?;
212                        samples.start += shift;
213                        out.push(samples);
214                    }
215                }
216            }
217        }
218        Some(out)
219    }
220
221    pub(crate) async fn stage(&self, key: Hash, samples: &Buffer) -> Result<(), String> {
222        let n = {
223            let mut written = locked(&self.written);
224            *written += 1;
225            *written
226        };
227        let name = staged_name(key, &n.to_string());
228        self.staging.put(&name, &codec::chunk(samples)).await?;
229        locked(&self.staged)
230            .entry(key)
231            .or_default()
232            .chunks
233            .push((name, samples.extent()));
234        Ok(())
235    }
236
237    pub(crate) async fn stage_meta(&self, key: Hash, head: &Header) -> Result<(), String> {
238        let name = staged_name(key, META);
239        self.staging.put(&name, &codec::entry(head, &[])).await?;
240        locked(&self.staged).entry(key).or_default().meta = true;
241        Ok(())
242    }
243
244    /// A value staged without its meta is dropped. A key leaves the staging record only once
245    /// its files have, so a failed write leaves every later one staged, as does a commit over
246    /// an open entry. An open entry past budget stays for the next persist.
247    pub(crate) async fn persist(&self) -> Result<Persisted, String> {
248        let _held = self.backend.lock().await?;
249        let mut done = Persisted::default();
250        let keys: Vec<Hash> = locked(&self.staged).keys().copied().collect();
251        for key in keys {
252            let Some(held) = locked(&self.staged).get(&key).cloned() else {
253                continue;
254            };
255            match self.committed(key, &held).await? {
256                Committed::Busy => continue,
257                Committed::Moved { bytes } => {
258                    locked(&self.index).touch(key, bytes);
259                    done.written += 1;
260                }
261                Committed::Dropped => {}
262            }
263            for (chunk, _) in &held.chunks {
264                self.staging.delete(chunk).await?;
265            }
266            self.staging.delete(&staged_name(key, META)).await?;
267            locked(&self.staged).remove(&key);
268        }
269        let listed = self.backend.list().await?;
270        let listed = listed
271            .into_iter()
272            .filter_map(|(name, bytes)| Some((key_of(&name)?, bytes)));
273        locked(&self.index).sync(listed.collect());
274        let oldest = locked(&self.index).oldest_first();
275        for key in oldest {
276            if self.bytes() <= self.max_bytes {
277                break;
278            }
279            if self.backend.delete(&name_of(key)).await? {
280                locked(&self.index).forget(key);
281                done.evicted += 1;
282            }
283        }
284        let text = locked(&self.index).text(&version());
285        self.backend.put(INDEX_NAME, text.as_bytes()).await?;
286        Ok(done)
287    }
288
289    /// `key`'s staged value moved whole into the store; none past budget.
290    async fn committed(&self, key: Hash, held: &Staged) -> Result<Committed, String> {
291        let whole = match held.meta {
292            true => self.staged_value_of(key, held).await?,
293            false => None,
294        };
295        let whole = whole.filter(|(head, runs)| !runs.is_empty() || head.refers());
296        let Some((head, runs)) = whole else {
297            return Ok(Committed::Dropped);
298        };
299        let bytes = codec::entry(&head, &runs);
300        if bytes.len() as u64 > self.max_bytes {
301            return Ok(Committed::Dropped);
302        }
303        let name = name_of(key);
304        self.staging.put(&name, &bytes).await?;
305        Ok(match self.staging.rename(&name, &self.backend).await? {
306            true => Committed::Moved {
307                bytes: bytes.len() as u64,
308            },
309            false => Committed::Busy,
310        })
311    }
312
313    async fn staged_value_of(
314        &self,
315        key: Hash,
316        held: &Staged,
317    ) -> Result<Option<(Header, Vec<Buffer>)>, String> {
318        let Some(meta) = self.staging.get(&staged_name(key, META)).await? else {
319            return Ok(None);
320        };
321        let Some((head, _)) = codec::read_head(&meta, key) else {
322            return Ok(None);
323        };
324        let mut runs = Vec::new();
325        for (chunk, _) in &held.chunks {
326            let bytes = self.staging.get(chunk).await?;
327            match bytes.as_deref().and_then(codec::read_chunk) {
328                Some(samples) => joined(&mut runs, vec![Arc::new(samples)]),
329                None => return Ok(None),
330            }
331        }
332        let runs = runs.into_iter().map(Arc::unwrap_or_clone).collect();
333        Ok(Some((head, runs)))
334    }
335}
336
337fn staged_name(key: Hash, part: &str) -> String {
338    format!("{}.{part}", name_of(key))
339}