Skip to main content

node_app_replica/
store.rs

1//! The storage seam: where the ledger lives.
2//!
3//! The ledger is two small tables in the app's own database (Phase 3 spec,
4//! section 5.1). An app plugs its database in by implementing [`LedgerStore`],
5//! or uses one of the two stores this crate ships:
6//!
7//! - `rusqlite::Connection` (feature `sqlite`): the tables `<prefix>replica_collections`
8//!   and `<prefix>replica_rows`, written in `BEGIN IMMEDIATE` transactions.
9//! - [`MemoryLedger`]: a ledger that lives as long as the process. A new process
10//!   starts a new epoch, so every device takes one full copy after each start.
11//!   For an app with no database of its own.
12//!
13//! The helper's logic sees only [`LedgerTx`]; it never writes SQL.
14
15use std::collections::BTreeMap;
16use std::sync::{Mutex, PoisonError};
17
18use crate::ReplicaError;
19
20/// One collection's ledger header (`replica_collections`).
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct CollectionRecord {
23    /// Which unbroken run of versions this is: `[a-z0-9]{1,16}`.
24    pub epoch: String,
25    /// The head: the version of the latest change; 0 means nothing yet.
26    pub version: u64,
27    /// Deletes at or below this version are forgotten; a device asking from
28    /// below it gets a full copy.
29    pub floor: u64,
30    /// Reconcile before the next pull.
31    pub dirty: bool,
32    /// Unix ms of the last epoch rotation.
33    pub rotated_at: u64,
34    /// Unix ms of the last reconcile.
35    pub reconciled_at: u64,
36    /// A rotation was asked for within a minute of the last one and is still to
37    /// happen. It happens before the next version is assigned, or at the first
38    /// ledger operation once the minute has passed, whichever comes first; it is
39    /// never dropped.
40    pub rotate_owed: bool,
41}
42
43/// One row of the ledger (`replica_rows`): a key and what is known about it,
44/// never its value.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct LedgerEntry {
47    /// The row's key.
48    pub key: String,
49    /// See [`crate::digest::row_digest`]; empty for a delete recorded without
50    /// ever having seen the row.
51    pub digest: String,
52    /// The version at which the row last changed.
53    pub version: u64,
54    /// The row was deleted at `version`: this entry is a tombstone.
55    pub deleted: bool,
56    /// Unix ms; used for the tombstone age only.
57    pub changed_at: u64,
58}
59
60/// What [`LedgerTx::prune_tombstones`] did.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
62pub struct Pruned {
63    /// The highest version among the tombstones removed.
64    pub highest: Option<u64>,
65    /// More than `keep` tombstones are left (a store that could not prune). The
66    /// ledger then rotates the epoch, which drops every tombstone.
67    pub over_keep: bool,
68}
69
70/// Ledger reads and writes inside one write transaction. Keys sort by their
71/// UTF-8 bytes (SQLite's BINARY collation, Rust's `str` order).
72pub trait LedgerTx {
73    /// The collection's header, or `None` before its first write.
74    fn record(&mut self, collection: &str) -> Result<Option<CollectionRecord>, ReplicaError>;
75    /// Creates or replaces the collection's header.
76    fn put_record(
77        &mut self,
78        collection: &str,
79        record: &CollectionRecord,
80    ) -> Result<(), ReplicaError>;
81    /// The entry of one key, tombstone or not.
82    fn entry(&mut self, collection: &str, key: &str) -> Result<Option<LedgerEntry>, ReplicaError>;
83    /// Every entry, tombstones included, in key order.
84    fn entries(&mut self, collection: &str) -> Result<Vec<LedgerEntry>, ReplicaError>;
85    /// Creates or replaces the entry of `entry.key`.
86    fn put_entry(&mut self, collection: &str, entry: &LedgerEntry) -> Result<(), ReplicaError>;
87    /// Removes the entry of one key (a tombstone dropped by a rotation).
88    fn delete_entry(&mut self, collection: &str, key: &str) -> Result<(), ReplicaError>;
89    /// Entries (tombstones included) whose version is above `version`, in
90    /// version order, at most `limit`.
91    fn changes_after(
92        &mut self,
93        collection: &str,
94        version: u64,
95        limit: usize,
96    ) -> Result<Vec<LedgerEntry>, ReplicaError>;
97    /// Live entries whose key sorts after `after` (all of them when `None`), in
98    /// key order, at most `limit`.
99    fn live_after(
100        &mut self,
101        collection: &str,
102        after: Option<&str>,
103        limit: usize,
104    ) -> Result<Vec<LedgerEntry>, ReplicaError>;
105    /// Removes the tombstones that changed before `changed_before` (unix ms), and
106    /// all but the `keep` newest (by version) of the rest. Its cost should follow
107    /// the tombstones, not the live rows: it runs on every write.
108    fn prune_tombstones(
109        &mut self,
110        collection: &str,
111        changed_before: u64,
112        keep: u64,
113    ) -> Result<Pruned, ReplicaError>;
114}
115
116/// A database the ledger can live in.
117///
118/// `prefix` names the tables (`friends_` → `friends_replica_collections`); it is
119/// `[A-Za-z0-9_]{0,48}`, checked before any call.
120pub trait LedgerStore {
121    /// Creates the ledger's tables if they do not exist. Idempotent.
122    fn ensure(&self, prefix: &str) -> Result<(), ReplicaError>;
123
124    /// Runs `work` in one write transaction: everything it wrote is committed when
125    /// it returns `Ok`, and nothing is when it returns `Err`. Two writers on the
126    /// same ledger never interleave. `work` is called exactly once.
127    fn write(
128        &self,
129        prefix: &str,
130        work: &mut dyn FnMut(&mut dyn LedgerTx) -> Result<(), ReplicaError>,
131    ) -> Result<(), ReplicaError>;
132
133    /// The collection's header as last committed, read without taking the write
134    /// lock: `head()` and a pull answered "nothing new" need nothing else. The
135    /// default reads it inside [`LedgerStore::write`]; a store with a cheaper
136    /// read overrides it.
137    fn read_record(
138        &self,
139        prefix: &str,
140        collection: &str,
141    ) -> Result<Option<CollectionRecord>, ReplicaError> {
142        let mut out = None;
143        self.write(prefix, &mut |tx| {
144            out = tx.record(collection)?;
145            Ok(())
146        })?;
147        Ok(out)
148    }
149}
150
151/// One collection's ledger in memory.
152#[derive(Debug, Clone, Default)]
153struct MemoryCollection {
154    record: Option<CollectionRecord>,
155    entries: BTreeMap<String, LedgerEntry>,
156}
157
158type MemoryTables = BTreeMap<(String, String), MemoryCollection>;
159
160/// A ledger held in process memory. Cloning it copies the ledger as it is now.
161#[derive(Debug, Default)]
162pub struct MemoryLedger {
163    tables: Mutex<MemoryTables>,
164}
165
166impl MemoryLedger {
167    /// An empty ledger.
168    pub fn new() -> Self {
169        Self::default()
170    }
171}
172
173impl Clone for MemoryLedger {
174    fn clone(&self) -> Self {
175        // A write works on a copy and swaps it in only on success, so the state
176        // behind a poisoned lock is always a committed one.
177        let tables = self
178            .tables
179            .lock()
180            .unwrap_or_else(PoisonError::into_inner)
181            .clone();
182        Self {
183            tables: Mutex::new(tables),
184        }
185    }
186}
187
188impl LedgerStore for MemoryLedger {
189    fn ensure(&self, _prefix: &str) -> Result<(), ReplicaError> {
190        Ok(())
191    }
192
193    fn write(
194        &self,
195        prefix: &str,
196        work: &mut dyn FnMut(&mut dyn LedgerTx) -> Result<(), ReplicaError>,
197    ) -> Result<(), ReplicaError> {
198        let mut guard = self.tables.lock().unwrap_or_else(PoisonError::into_inner);
199        let mut copy = guard.clone();
200        let mut tx = MemoryTx {
201            prefix,
202            tables: &mut copy,
203        };
204        work(&mut tx)?;
205        *guard = copy;
206        Ok(())
207    }
208
209    fn read_record(
210        &self,
211        prefix: &str,
212        collection: &str,
213    ) -> Result<Option<CollectionRecord>, ReplicaError> {
214        // Only the header is copied, never the entries.
215        let guard = self.tables.lock().unwrap_or_else(PoisonError::into_inner);
216        Ok(guard
217            .get(&(prefix.to_string(), collection.to_string()))
218            .and_then(|c| c.record.clone()))
219    }
220}
221
222struct MemoryTx<'a> {
223    prefix: &'a str,
224    tables: &'a mut MemoryTables,
225}
226
227impl MemoryTx<'_> {
228    fn get(&self, collection: &str) -> Option<&MemoryCollection> {
229        self.tables
230            .get(&(self.prefix.to_string(), collection.to_string()))
231    }
232
233    fn get_mut(&mut self, collection: &str) -> &mut MemoryCollection {
234        self.tables
235            .entry((self.prefix.to_string(), collection.to_string()))
236            .or_default()
237    }
238}
239
240impl LedgerTx for MemoryTx<'_> {
241    fn record(&mut self, collection: &str) -> Result<Option<CollectionRecord>, ReplicaError> {
242        Ok(self.get(collection).and_then(|c| c.record.clone()))
243    }
244
245    fn put_record(
246        &mut self,
247        collection: &str,
248        record: &CollectionRecord,
249    ) -> Result<(), ReplicaError> {
250        self.get_mut(collection).record = Some(record.clone());
251        Ok(())
252    }
253
254    fn entry(&mut self, collection: &str, key: &str) -> Result<Option<LedgerEntry>, ReplicaError> {
255        Ok(self
256            .get(collection)
257            .and_then(|c| c.entries.get(key).cloned()))
258    }
259
260    fn entries(&mut self, collection: &str) -> Result<Vec<LedgerEntry>, ReplicaError> {
261        Ok(self
262            .get(collection)
263            .map(|c| c.entries.values().cloned().collect())
264            .unwrap_or_default())
265    }
266
267    fn put_entry(&mut self, collection: &str, entry: &LedgerEntry) -> Result<(), ReplicaError> {
268        self.get_mut(collection)
269            .entries
270            .insert(entry.key.clone(), entry.clone());
271        Ok(())
272    }
273
274    fn delete_entry(&mut self, collection: &str, key: &str) -> Result<(), ReplicaError> {
275        self.get_mut(collection).entries.remove(key);
276        Ok(())
277    }
278
279    fn changes_after(
280        &mut self,
281        collection: &str,
282        version: u64,
283        limit: usize,
284    ) -> Result<Vec<LedgerEntry>, ReplicaError> {
285        let mut changed: Vec<LedgerEntry> = self
286            .get(collection)
287            .map(|c| {
288                c.entries
289                    .values()
290                    .filter(|e| e.version > version)
291                    .cloned()
292                    .collect()
293            })
294            .unwrap_or_default();
295        changed.sort_by_key(|e| e.version);
296        changed.truncate(limit);
297        Ok(changed)
298    }
299
300    fn live_after(
301        &mut self,
302        collection: &str,
303        after: Option<&str>,
304        limit: usize,
305    ) -> Result<Vec<LedgerEntry>, ReplicaError> {
306        Ok(self
307            .get(collection)
308            .map(|c| {
309                c.entries
310                    .values()
311                    .filter(|e| !e.deleted && after.map_or(true, |a| e.key.as_str() > a))
312                    .take(limit)
313                    .cloned()
314                    .collect()
315            })
316            .unwrap_or_default())
317    }
318
319    fn prune_tombstones(
320        &mut self,
321        collection: &str,
322        changed_before: u64,
323        keep: u64,
324    ) -> Result<Pruned, ReplicaError> {
325        let entries = &mut self.get_mut(collection).entries;
326        let mut tombstones: Vec<(u64, u64, String)> = entries
327            .values()
328            .filter(|e| e.deleted)
329            .map(|e| (e.version, e.changed_at, e.key.clone()))
330            .collect();
331        tombstones.sort();
332        let excess = (tombstones.len() as u64).saturating_sub(keep);
333        let mut highest = None;
334        let mut remaining = 0;
335        for (index, (version, changed_at, key)) in tombstones.into_iter().enumerate() {
336            if (index as u64) < excess || changed_at < changed_before {
337                entries.remove(&key);
338                highest = highest.max(Some(version));
339            } else {
340                remaining += 1;
341            }
342        }
343        Ok(Pruned {
344            highest,
345            over_keep: remaining > keep,
346        })
347    }
348}