node-app-replica 7.7.30

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
//! Helpers shared by the integration tests.
#![allow(dead_code)]

use std::collections::{BTreeMap, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;

use node_app_replica::{Collection, Environment, LedgerStore, Row};

/// A clock the test moves by hand, and epochs from a script (then `ep1`, `ep2`, …).
pub struct TestEnv {
    now: AtomicU64,
    scripted: Mutex<VecDeque<String>>,
    counter: AtomicU64,
}

impl TestEnv {
    pub fn leak(start_ms: u64, epochs: &[&str]) -> &'static TestEnv {
        Box::leak(Box::new(TestEnv {
            now: AtomicU64::new(start_ms),
            scripted: Mutex::new(epochs.iter().map(|e| e.to_string()).collect()),
            counter: AtomicU64::new(0),
        }))
    }

    pub fn advance(&self, ms: u64) {
        self.now.fetch_add(ms, Ordering::SeqCst);
    }
}

impl Environment for TestEnv {
    fn now_ms(&self) -> u64 {
        self.now.load(Ordering::SeqCst)
    }

    fn new_epoch(&self) -> String {
        if let Some(epoch) = self.scripted.lock().unwrap().pop_front() {
            return epoch;
        }
        format!("ep{}", self.counter.fetch_add(1, Ordering::SeqCst) + 1)
    }
}

pub const MINUTE: u64 = 60_000;
pub const DAY: u64 = 24 * 60 * MINUTE;
/// An arbitrary "now" well past the epoch, so a minute can be subtracted.
pub const T0: u64 = 1_763_553_296_000;

/// A collection with a test clock and scripted epochs.
pub fn collection(env: &'static TestEnv) -> Collection {
    Collection::new("friends.people.pull", "friends_", &[1]).with_environment(env)
}

pub fn sqlite() -> rusqlite::Connection {
    rusqlite::Connection::open_in_memory().unwrap()
}

/// The app's own data: what `load` reads.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct AppData {
    pub rows: BTreeMap<String, Row>,
}

impl AppData {
    pub fn with(rows: &[Row]) -> Self {
        Self {
            rows: rows.iter().map(|r| (r.key.clone(), r.clone())).collect(),
        }
    }

    pub fn list(&self) -> Vec<Row> {
        self.rows.values().cloned().collect()
    }

    pub fn put(&mut self, row: Row) {
        self.rows.insert(row.key.clone(), row);
    }

    pub fn load(&self, keys: Option<&[String]>) -> Vec<Row> {
        match keys {
            None => self.list(),
            Some(keys) => keys
                .iter()
                .filter_map(|k| self.rows.get(k).cloned())
                .collect(),
        }
    }

    /// A `load` callback over this data, for any store.
    pub fn loader<S: LedgerStore + ?Sized>(
        &self,
    ) -> impl FnMut(&S, Option<&[String]>) -> Result<Vec<Row>, String> + '_ {
        move |_store, keys| Ok(self.load(keys))
    }
}

pub fn row(key: &str, value: serde_json::Value) -> Row {
    Row::new(key, value)
}