node-app-replica 7.7.10

Change-only replication for Node app backends: a per-collection ledger (epoch, version, tombstones) that answers a device's pull with nothing new, the changes, or a full copy
Documentation
//! The storage seam: where the ledger lives.
//!
//! The ledger is two small tables in the app's own database (Phase 3 spec,
//! section 5.1). An app plugs its database in by implementing [`LedgerStore`],
//! or uses one of the two stores this crate ships:
//!
//! - `rusqlite::Connection` (feature `sqlite`): the tables `<prefix>replica_collections`
//!   and `<prefix>replica_rows`, written in `BEGIN IMMEDIATE` transactions.
//! - [`MemoryLedger`]: a ledger that lives as long as the process. A new process
//!   starts a new epoch, so every device takes one full copy after each start.
//!   For an app with no database of its own.
//!
//! The helper's logic sees only [`LedgerTx`]; it never writes SQL.

use std::collections::BTreeMap;
use std::sync::{Mutex, PoisonError};

use crate::ReplicaError;

/// One collection's ledger header (`replica_collections`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CollectionRecord {
    /// Which unbroken run of versions this is: `[a-z0-9]{1,16}`.
    pub epoch: String,
    /// The head: the version of the latest change; 0 means nothing yet.
    pub version: u64,
    /// Deletes at or below this version are forgotten; a device asking from
    /// below it gets a full copy.
    pub floor: u64,
    /// Reconcile before the next pull.
    pub dirty: bool,
    /// Unix ms of the last epoch rotation.
    pub rotated_at: u64,
    /// Unix ms of the last reconcile.
    pub reconciled_at: u64,
    /// A rotation was asked for within a minute of the last one and is still to
    /// happen. It happens before the next version is assigned, or at the first
    /// ledger operation once the minute has passed, whichever comes first; it is
    /// never dropped.
    pub rotate_owed: bool,
}

/// One row of the ledger (`replica_rows`): a key and what is known about it,
/// never its value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LedgerEntry {
    /// The row's key.
    pub key: String,
    /// See [`crate::digest::row_digest`]; empty for a delete recorded without
    /// ever having seen the row.
    pub digest: String,
    /// The version at which the row last changed.
    pub version: u64,
    /// The row was deleted at `version`: this entry is a tombstone.
    pub deleted: bool,
    /// Unix ms; used for the tombstone age only.
    pub changed_at: u64,
}

/// What [`LedgerTx::prune_tombstones`] did.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Pruned {
    /// The highest version among the tombstones removed.
    pub highest: Option<u64>,
    /// More than `keep` tombstones are left (a store that could not prune). The
    /// ledger then rotates the epoch, which drops every tombstone.
    pub over_keep: bool,
}

/// Ledger reads and writes inside one write transaction. Keys sort by their
/// UTF-8 bytes (SQLite's BINARY collation, Rust's `str` order).
pub trait LedgerTx {
    /// The collection's header, or `None` before its first write.
    fn record(&mut self, collection: &str) -> Result<Option<CollectionRecord>, ReplicaError>;
    /// Creates or replaces the collection's header.
    fn put_record(
        &mut self,
        collection: &str,
        record: &CollectionRecord,
    ) -> Result<(), ReplicaError>;
    /// The entry of one key, tombstone or not.
    fn entry(&mut self, collection: &str, key: &str) -> Result<Option<LedgerEntry>, ReplicaError>;
    /// Every entry, tombstones included, in key order.
    fn entries(&mut self, collection: &str) -> Result<Vec<LedgerEntry>, ReplicaError>;
    /// Creates or replaces the entry of `entry.key`.
    fn put_entry(&mut self, collection: &str, entry: &LedgerEntry) -> Result<(), ReplicaError>;
    /// Removes the entry of one key (a tombstone dropped by a rotation).
    fn delete_entry(&mut self, collection: &str, key: &str) -> Result<(), ReplicaError>;
    /// Entries (tombstones included) whose version is above `version`, in
    /// version order, at most `limit`.
    fn changes_after(
        &mut self,
        collection: &str,
        version: u64,
        limit: usize,
    ) -> Result<Vec<LedgerEntry>, ReplicaError>;
    /// Live entries whose key sorts after `after` (all of them when `None`), in
    /// key order, at most `limit`.
    fn live_after(
        &mut self,
        collection: &str,
        after: Option<&str>,
        limit: usize,
    ) -> Result<Vec<LedgerEntry>, ReplicaError>;
    /// Removes the tombstones that changed before `changed_before` (unix ms), and
    /// all but the `keep` newest (by version) of the rest. Its cost should follow
    /// the tombstones, not the live rows: it runs on every write.
    fn prune_tombstones(
        &mut self,
        collection: &str,
        changed_before: u64,
        keep: u64,
    ) -> Result<Pruned, ReplicaError>;
}

/// A database the ledger can live in.
///
/// `prefix` names the tables (`friends_` → `friends_replica_collections`); it is
/// `[A-Za-z0-9_]{0,48}`, checked before any call.
pub trait LedgerStore {
    /// Creates the ledger's tables if they do not exist. Idempotent.
    fn ensure(&self, prefix: &str) -> Result<(), ReplicaError>;

    /// Runs `work` in one write transaction: everything it wrote is committed when
    /// it returns `Ok`, and nothing is when it returns `Err`. Two writers on the
    /// same ledger never interleave. `work` is called exactly once.
    fn write(
        &self,
        prefix: &str,
        work: &mut dyn FnMut(&mut dyn LedgerTx) -> Result<(), ReplicaError>,
    ) -> Result<(), ReplicaError>;

    /// The collection's header as last committed, read without taking the write
    /// lock: `head()` and a pull answered "nothing new" need nothing else. The
    /// default reads it inside [`LedgerStore::write`]; a store with a cheaper
    /// read overrides it.
    fn read_record(
        &self,
        prefix: &str,
        collection: &str,
    ) -> Result<Option<CollectionRecord>, ReplicaError> {
        let mut out = None;
        self.write(prefix, &mut |tx| {
            out = tx.record(collection)?;
            Ok(())
        })?;
        Ok(out)
    }
}

/// One collection's ledger in memory.
#[derive(Debug, Clone, Default)]
struct MemoryCollection {
    record: Option<CollectionRecord>,
    entries: BTreeMap<String, LedgerEntry>,
}

type MemoryTables = BTreeMap<(String, String), MemoryCollection>;

/// A ledger held in process memory. Cloning it copies the ledger as it is now.
#[derive(Debug, Default)]
pub struct MemoryLedger {
    tables: Mutex<MemoryTables>,
}

impl MemoryLedger {
    /// An empty ledger.
    pub fn new() -> Self {
        Self::default()
    }
}

impl Clone for MemoryLedger {
    fn clone(&self) -> Self {
        // A write works on a copy and swaps it in only on success, so the state
        // behind a poisoned lock is always a committed one.
        let tables = self
            .tables
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone();
        Self {
            tables: Mutex::new(tables),
        }
    }
}

impl LedgerStore for MemoryLedger {
    fn ensure(&self, _prefix: &str) -> Result<(), ReplicaError> {
        Ok(())
    }

    fn write(
        &self,
        prefix: &str,
        work: &mut dyn FnMut(&mut dyn LedgerTx) -> Result<(), ReplicaError>,
    ) -> Result<(), ReplicaError> {
        let mut guard = self.tables.lock().unwrap_or_else(PoisonError::into_inner);
        let mut copy = guard.clone();
        let mut tx = MemoryTx {
            prefix,
            tables: &mut copy,
        };
        work(&mut tx)?;
        *guard = copy;
        Ok(())
    }

    fn read_record(
        &self,
        prefix: &str,
        collection: &str,
    ) -> Result<Option<CollectionRecord>, ReplicaError> {
        // Only the header is copied, never the entries.
        let guard = self.tables.lock().unwrap_or_else(PoisonError::into_inner);
        Ok(guard
            .get(&(prefix.to_string(), collection.to_string()))
            .and_then(|c| c.record.clone()))
    }
}

struct MemoryTx<'a> {
    prefix: &'a str,
    tables: &'a mut MemoryTables,
}

impl MemoryTx<'_> {
    fn get(&self, collection: &str) -> Option<&MemoryCollection> {
        self.tables
            .get(&(self.prefix.to_string(), collection.to_string()))
    }

    fn get_mut(&mut self, collection: &str) -> &mut MemoryCollection {
        self.tables
            .entry((self.prefix.to_string(), collection.to_string()))
            .or_default()
    }
}

impl LedgerTx for MemoryTx<'_> {
    fn record(&mut self, collection: &str) -> Result<Option<CollectionRecord>, ReplicaError> {
        Ok(self.get(collection).and_then(|c| c.record.clone()))
    }

    fn put_record(
        &mut self,
        collection: &str,
        record: &CollectionRecord,
    ) -> Result<(), ReplicaError> {
        self.get_mut(collection).record = Some(record.clone());
        Ok(())
    }

    fn entry(&mut self, collection: &str, key: &str) -> Result<Option<LedgerEntry>, ReplicaError> {
        Ok(self
            .get(collection)
            .and_then(|c| c.entries.get(key).cloned()))
    }

    fn entries(&mut self, collection: &str) -> Result<Vec<LedgerEntry>, ReplicaError> {
        Ok(self
            .get(collection)
            .map(|c| c.entries.values().cloned().collect())
            .unwrap_or_default())
    }

    fn put_entry(&mut self, collection: &str, entry: &LedgerEntry) -> Result<(), ReplicaError> {
        self.get_mut(collection)
            .entries
            .insert(entry.key.clone(), entry.clone());
        Ok(())
    }

    fn delete_entry(&mut self, collection: &str, key: &str) -> Result<(), ReplicaError> {
        self.get_mut(collection).entries.remove(key);
        Ok(())
    }

    fn changes_after(
        &mut self,
        collection: &str,
        version: u64,
        limit: usize,
    ) -> Result<Vec<LedgerEntry>, ReplicaError> {
        let mut changed: Vec<LedgerEntry> = self
            .get(collection)
            .map(|c| {
                c.entries
                    .values()
                    .filter(|e| e.version > version)
                    .cloned()
                    .collect()
            })
            .unwrap_or_default();
        changed.sort_by_key(|e| e.version);
        changed.truncate(limit);
        Ok(changed)
    }

    fn live_after(
        &mut self,
        collection: &str,
        after: Option<&str>,
        limit: usize,
    ) -> Result<Vec<LedgerEntry>, ReplicaError> {
        Ok(self
            .get(collection)
            .map(|c| {
                c.entries
                    .values()
                    .filter(|e| !e.deleted && after.map_or(true, |a| e.key.as_str() > a))
                    .take(limit)
                    .cloned()
                    .collect()
            })
            .unwrap_or_default())
    }

    fn prune_tombstones(
        &mut self,
        collection: &str,
        changed_before: u64,
        keep: u64,
    ) -> Result<Pruned, ReplicaError> {
        let entries = &mut self.get_mut(collection).entries;
        let mut tombstones: Vec<(u64, u64, String)> = entries
            .values()
            .filter(|e| e.deleted)
            .map(|e| (e.version, e.changed_at, e.key.clone()))
            .collect();
        tombstones.sort();
        let excess = (tombstones.len() as u64).saturating_sub(keep);
        let mut highest = None;
        let mut remaining = 0;
        for (index, (version, changed_at, key)) in tombstones.into_iter().enumerate() {
            if (index as u64) < excess || changed_at < changed_before {
                entries.remove(&key);
                highest = highest.max(Some(version));
            } else {
                remaining += 1;
            }
        }
        Ok(Pruned {
            highest,
            over_keep: remaining > keep,
        })
    }
}