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