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
22const META: &str = "meta";
23
24/// Named bytes. A `put` is whole or absent: no reader sees half of one.
25pub trait Backend: Sized {
26    type Lock;
27    /// The one exclusive lock over these names, shared by every store over them.
28    fn lock(&self) -> impl Future<Output = Result<Self::Lock, String>>;
29    fn get(&self, name: &str) -> impl Future<Output = Result<Option<Vec<u8>>, String>>;
30    /// At most `len` bytes from `from` on, fewer where the name ends sooner.
31    fn get_range(
32        &self,
33        name: &str,
34        from: u64,
35        len: u64,
36    ) -> impl Future<Output = Result<Option<Vec<u8>>, String>>;
37    fn put(&self, name: &str, bytes: &[u8]) -> impl Future<Output = Result<(), String>>;
38    /// False where another holder has `name` open, so it stays.
39    fn delete(&self, name: &str) -> impl Future<Output = Result<bool, String>>;
40    /// Each name, with its size in bytes.
41    fn list(&self) -> impl Future<Output = Result<Vec<(String, u64)>, String>>;
42    /// An area beside these names that no other store writes and `list` never names.
43    fn staging(&self) -> impl Future<Output = Result<Self, String>>;
44    /// `name` moved from here into `to` in one step, over whatever `to` held under it; as
45    /// `delete`, false where either is open.
46    fn rename(&self, name: &str, to: &Self) -> impl Future<Output = Result<bool, String>>;
47}
48
49#[derive(Clone, Default)]
50struct Staged {
51    chunks: Vec<(String, Extent)>,
52    meta: bool,
53}
54
55/// Node values under their keys, beneath the memory tier alone: it stages, and only `persist`
56/// commits each value whole by rename, evicting the least recently used past the budget. Every
57/// change to the backend's names runs under its lock; lookups and reads never wait on it.
58pub struct Store<B> {
59    backend: B,
60    staging: B,
61    max_bytes: u64,
62    index: Mutex<Index>,
63    staged: Mutex<BTreeMap<Hash, Staged>>,
64    written: Mutex<u64>,
65}
66
67enum Prepared {
68    Ready { bytes: u64 },
69    Dropped,
70    Refused,
71}
72
73#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
74pub struct Persisted {
75    pub written: usize,
76    pub evicted: usize,
77    /// Values larger than the whole budget.
78    pub refused: usize,
79}
80
81fn locked<T>(held: &Mutex<T>) -> MutexGuard<'_, T> {
82    held.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
83}
84
85impl<B: Backend> Store<B> {
86    /// Over another format's index, a fresh one: what that format left is neither read nor
87    /// removed, nor counted against the budget.
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                let empty = Index::default();
96                backend
97                    .put(INDEX_NAME, empty.text(&version).as_bytes())
98                    .await?;
99                empty
100            }
101        };
102        let staging = backend.staging().await?;
103        drop(held);
104        Ok(Store {
105            backend,
106            staging,
107            max_bytes,
108            index: Mutex::new(index),
109            staged: Mutex::new(BTreeMap::new()),
110            written: Mutex::new(0),
111        })
112    }
113
114    pub fn max_bytes(&self) -> u64 {
115        self.max_bytes
116    }
117
118    pub fn bytes(&self) -> u64 {
119        locked(&self.index).bytes
120    }
121
122    pub fn holds(&self, key: Hash) -> bool {
123        locked(&self.index).held.contains_key(&key)
124    }
125
126    pub(crate) fn used(&self, key: Hash) {
127        locked(&self.index).used(key);
128    }
129
130    /// Reads headers, never a sample; one standing for another's samples reads that one's.
131    pub(crate) async fn lookup(&self, key: Hash) -> Option<Header> {
132        let found = self.written(key).await?;
133        let &Samples::Of { key: of, by } = found.samples() else {
134            return Some(found);
135        };
136        let samples = match self.written(of).await?.into_parts().1 {
137            Samples::Entry { file, runs, .. } => Samples::Entry {
138                file,
139                runs,
140                shift: -by,
141            },
142            Samples::Staged { chunks, .. } => Samples::Staged { chunks, shift: -by },
143            _ => return None,
144        };
145        Some(Header::new(found.into_parts().0, samples))
146    }
147
148    /// Staged first; past the index, the backend, for another store's commits.
149    async fn written(&self, key: Hash) -> Option<Header> {
150        if let Some(staged) = self.staged_value(key).await {
151            return Some(staged);
152        }
153        let name = name_of(key);
154        let Some(mut bytes) = self.backend.get_range(&name, 0, 8).await.ok()? else {
155            locked(&self.index).forget(key);
156            return None;
157        };
158        let rest = codec::head_len(&bytes)? - 8;
159        bytes.extend(self.backend.get_range(&name, 8, rest as u64).await.ok()??);
160        let (found, len) =
161            codec::read_head(&bytes, key).filter(|(found, _)| found.stored().key == key)?;
162        let mut index = locked(&self.index);
163        match index.held.contains_key(&key) {
164            true => index.used(key),
165            false => index.touch(key, len),
166        }
167        Some(found)
168    }
169
170    async fn staged_value(&self, key: Hash) -> Option<Header> {
171        let chunks = {
172            let staged = locked(&self.staged);
173            let held = staged.get(&key).filter(|staged| staged.meta)?;
174            held.chunks.clone()
175        };
176        let meta = self.staging.get(&staged_name(key, META)).await.ok()??;
177        let (found, _) = codec::read_head(&meta, key)?;
178        Some(match found.refers() {
179            true => found,
180            false => Header::new(found.into_parts().0, Samples::Staged { chunks, shift: 0 }),
181        })
182    }
183
184    /// Whole chunks holding `over`; `None` where they are gone or corrupt.
185    pub(crate) async fn read(&self, head: &Header, over: Extent) -> Option<Vec<Buffer>> {
186        let mut out = Vec::new();
187        match head.samples() {
188            Samples::None | Samples::Of { .. } => {}
189            Samples::Entry { file, runs, shift } => {
190                for run in runs {
191                    let met = run.extent().intersect(over.shifted(-shift));
192                    if met.is_empty() {
193                        continue;
194                    }
195                    let chunk = codec::CHUNK as i64;
196                    let from = ((met.start - run.start) / chunk) as usize;
197                    let to = (met.end - run.start).div_euclid(chunk) as usize;
198                    let to = to + usize::from((met.end - run.start) % chunk != 0);
199                    let (at, len) = codec::span_of(run, from, to);
200                    let bytes = self.backend.get_range(&name_of(*file), at, len).await;
201                    let mut samples = codec::read_chunks(&bytes.ok()??, run, from, to)?;
202                    samples.start += shift;
203                    out.push(samples);
204                }
205            }
206            Samples::Staged { chunks, shift } => {
207                for (name, e) in chunks {
208                    if !e.intersect(over.shifted(-shift)).is_empty() {
209                        let bytes = self.staging.get(name).await.ok()??;
210                        let mut samples = codec::read_chunk(&bytes)?;
211                        samples.start += shift;
212                        out.push(samples);
213                    }
214                }
215            }
216        }
217        Some(out)
218    }
219
220    pub(crate) async fn stage(&self, key: Hash, samples: &Buffer) -> Result<(), String> {
221        let n = {
222            let mut written = locked(&self.written);
223            *written += 1;
224            *written
225        };
226        let name = staged_name(key, &n.to_string());
227        self.staging.put(&name, &codec::chunk(samples)).await?;
228        locked(&self.staged)
229            .entry(key)
230            .or_default()
231            .chunks
232            .push((name, samples.extent()));
233        Ok(())
234    }
235
236    pub(crate) async fn stage_meta(&self, key: Hash, head: &Header) -> Result<(), String> {
237        let name = staged_name(key, META);
238        self.staging.put(&name, &codec::entry(head, &[])).await?;
239        locked(&self.staged).entry(key).or_default().meta = true;
240        Ok(())
241    }
242
243    /// Free while nothing is staged or used since and the budget holds. The index file is
244    /// every store's account and names each value before it moves: one cut short leaves a
245    /// gone entry named, never one unnamed. A value staged without its meta is dropped; one
246    /// failed or over an open entry stays staged.
247    pub(crate) async fn persist(&self) -> Result<Persisted, String> {
248        let idle = {
249            let index = locked(&self.index);
250            index.bytes <= self.max_bytes && index.unsynced().is_empty()
251        };
252        if idle && locked(&self.staged).is_empty() {
253            return Ok(Persisted::default());
254        }
255        let _held = self.backend.lock().await?;
256        let (mut index, seen) = self.current().await?;
257        let mut done = Persisted::default();
258        let mut moving = Vec::new();
259        let keys: Vec<Hash> = locked(&self.staged).keys().copied().collect();
260        for key in keys {
261            let Some(held) = locked(&self.staged).get(&key).cloned() else {
262                continue;
263            };
264            match self.prepared(key, &held).await? {
265                Prepared::Ready { bytes } => {
266                    moving.push((key, held, bytes));
267                    continue;
268                }
269                Prepared::Dropped => {}
270                Prepared::Refused => done.refused += 1,
271            }
272            self.unstaged(key, &held).await?;
273        }
274        if !moving.is_empty() {
275            let mut naming = index.clone();
276            for (key, _, bytes) in &moving {
277                naming.touch(*key, *bytes);
278            }
279            let text = naming.text(&version());
280            self.backend.put(INDEX_NAME, text.as_bytes()).await?;
281        }
282        for (key, held, bytes) in moving {
283            if !self.staging.rename(&name_of(key), &self.backend).await? {
284                continue;
285            }
286            index.touch(key, bytes);
287            done.written += 1;
288            self.unstaged(key, &held).await?;
289        }
290        for key in index.oldest_first() {
291            if index.bytes <= self.max_bytes {
292                break;
293            }
294            if self.backend.delete(&name_of(key)).await? {
295                index.forget(key);
296                done.evicted += 1;
297            }
298        }
299        self.backend
300            .put(INDEX_NAME, index.text(&version()).as_bytes())
301            .await?;
302        index.synced();
303        let mut local = locked(&self.index);
304        for key in local.used_since(seen) {
305            index.used(key);
306        }
307        *local = index;
308        Ok(done)
309    }
310
311    /// The index file, or else the directory listed, with this store's uses since; its clock.
312    async fn current(&self) -> Result<(Index, u64), String> {
313        let found = self.backend.get(INDEX_NAME).await?;
314        let mut index = match found.and_then(|text| Index::read(&text, &version())) {
315            Some(index) => index,
316            None => {
317                let listed = self.backend.list().await?;
318                let listed = listed
319                    .into_iter()
320                    .filter_map(|(name, bytes)| Some((key_of(&name)?, bytes)));
321                Index::listed(listed.collect(), &locked(&self.index))
322            }
323        };
324        let local = locked(&self.index);
325        for key in local.unsynced() {
326            index.used(key);
327        }
328        Ok((index, local.clock()))
329    }
330
331    async fn unstaged(&self, key: Hash, held: &Staged) -> Result<(), String> {
332        for (chunk, _) in &held.chunks {
333            self.staging.delete(chunk).await?;
334        }
335        self.staging.delete(&staged_name(key, META)).await?;
336        locked(&self.staged).remove(&key);
337        Ok(())
338    }
339
340    /// `key`'s staged value joined with its entry's, whole in staging under the entry's name.
341    async fn prepared(&self, key: Hash, held: &Staged) -> Result<Prepared, String> {
342        let whole = match held.meta {
343            true => self.staged_value_of(key, held).await?,
344            false => None,
345        };
346        let whole = whole.filter(|(head, runs)| !runs.is_empty() || head.refers());
347        let Some((head, mut runs)) = whole else {
348            return Ok(Prepared::Dropped);
349        };
350        let name = name_of(key);
351        if !head.refers() {
352            let held = self.backend.get(&name).await?;
353            if let Some(held) = held.and_then(|bytes| codec::read_runs(&bytes, key)) {
354                runs = joined_runs(runs, held);
355            }
356        }
357        let bytes = codec::entry(&head, &runs);
358        if bytes.len() as u64 > self.max_bytes {
359            return Ok(Prepared::Refused);
360        }
361        self.staging.put(&name, &bytes).await?;
362        Ok(Prepared::Ready {
363            bytes: bytes.len() as u64,
364        })
365    }
366
367    async fn staged_value_of(
368        &self,
369        key: Hash,
370        held: &Staged,
371    ) -> Result<Option<(Header, Vec<Buffer>)>, String> {
372        let Some(meta) = self.staging.get(&staged_name(key, META)).await? else {
373            return Ok(None);
374        };
375        let Some((head, _)) = codec::read_head(&meta, key) else {
376            return Ok(None);
377        };
378        let mut runs = Vec::new();
379        for (chunk, _) in &held.chunks {
380            let bytes = self.staging.get(chunk).await?;
381            match bytes.as_deref().and_then(codec::read_chunk) {
382                Some(samples) => joined(&mut runs, vec![Arc::new(samples)]),
383                None => return Ok(None),
384            }
385        }
386        let runs = runs.into_iter().map(Arc::unwrap_or_clone).collect();
387        Ok(Some((head, runs)))
388    }
389}
390
391fn joined_runs(staged: Vec<Buffer>, held: Vec<Buffer>) -> Vec<Buffer> {
392    let mut runs: Vec<Arc<Buffer>> = held.into_iter().map(Arc::new).collect();
393    joined(&mut runs, staged.into_iter().map(Arc::new).collect());
394    runs.into_iter().map(Arc::unwrap_or_clone).collect()
395}
396
397fn staged_name(key: Hash, part: &str) -> String {
398    format!("{}.{part}", name_of(key))
399}