node-app-replica 7.7.47

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! A pass that changes nothing writes nothing (ADR-367 Amendment 1). On the
//! SQLite store, on a WAL file that is never checkpointed: a reconcile of the
//! same rows, a pull answered from a clean ledger and a touch of an unchanged row
//! make no ledger write, leave `total_changes()` where it was and add no WAL
//! frame. Every pass that does change the ledger still writes.

mod common;

use std::cell::Cell;
use std::path::PathBuf;

use common::*;
use node_app_replica::{
    Collection, CollectionRecord, LedgerEntry, LedgerStore, LedgerTx, Pruned, PullReply,
    PullRequest, ReplicaError,
};
use serde_json::json;

/// What the store shows after a pass: the ledger writes the helper made, SQLite's
/// `total_changes()` on the connection, and the WAL file's length.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Marks {
    writes: u64,
    changes: i64,
    wal_bytes: u64,
}

/// The SQLite store on a WAL file, counting the ledger's writes.
struct Watched {
    conn: rusqlite::Connection,
    wal: PathBuf,
    writes: Cell<u64>,
    /// Pruning answers that more tombstones are left than it may keep (a store
    /// that could not prune), which asks for a rotation.
    stuck: Cell<bool>,
    _dir: tempfile::TempDir,
}

impl Watched {
    fn new() -> Self {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("app.db");
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.pragma_update(None, "journal_mode", "WAL").unwrap();
        // Never checkpointed: every commit adds frames, and the file only grows.
        conn.pragma_update(None, "wal_autocheckpoint", 0).unwrap();
        Self {
            conn,
            wal: dir.path().join("app.db-wal"),
            writes: Cell::new(0),
            stuck: Cell::new(false),
            _dir: dir,
        }
    }

    fn marks(&self) -> Marks {
        Marks {
            writes: self.writes.get(),
            changes: self
                .conn
                .query_row("SELECT total_changes()", [], |r| r.get(0))
                .unwrap(),
            wal_bytes: std::fs::metadata(&self.wal).map_or(0, |m| m.len()),
        }
    }

    fn record(&self) -> CollectionRecord {
        self.read_record("friends_", "friends.people.pull")
            .unwrap()
            .unwrap()
    }
}

impl LedgerStore for Watched {
    fn ensure(&self, prefix: &str) -> Result<(), ReplicaError> {
        LedgerStore::ensure(&self.conn, prefix)
    }

    fn write(
        &self,
        prefix: &str,
        work: &mut dyn FnMut(&mut dyn LedgerTx) -> Result<(), ReplicaError>,
    ) -> Result<(), ReplicaError> {
        LedgerStore::write(&self.conn, prefix, &mut |tx| {
            work(&mut Counting {
                inner: tx,
                store: self,
            })
        })
    }

    fn read_record(
        &self,
        prefix: &str,
        collection: &str,
    ) -> Result<Option<CollectionRecord>, ReplicaError> {
        LedgerStore::read_record(&self.conn, prefix, collection)
    }
}

struct Counting<'a, 'b> {
    inner: &'a mut (dyn LedgerTx + 'b),
    store: &'a Watched,
}

impl Counting<'_, '_> {
    fn wrote(&self) {
        self.store.writes.set(self.store.writes.get() + 1);
    }
}

impl LedgerTx for Counting<'_, '_> {
    fn record(&mut self, collection: &str) -> Result<Option<CollectionRecord>, ReplicaError> {
        self.inner.record(collection)
    }

    fn put_record(
        &mut self,
        collection: &str,
        record: &CollectionRecord,
    ) -> Result<(), ReplicaError> {
        self.wrote();
        self.inner.put_record(collection, record)
    }

    fn entry(&mut self, collection: &str, key: &str) -> Result<Option<LedgerEntry>, ReplicaError> {
        self.inner.entry(collection, key)
    }

    fn entries(&mut self, collection: &str) -> Result<Vec<LedgerEntry>, ReplicaError> {
        self.inner.entries(collection)
    }

    fn put_entry(&mut self, collection: &str, entry: &LedgerEntry) -> Result<(), ReplicaError> {
        self.wrote();
        self.inner.put_entry(collection, entry)
    }

    fn delete_entry(&mut self, collection: &str, key: &str) -> Result<(), ReplicaError> {
        self.wrote();
        self.inner.delete_entry(collection, key)
    }

    fn changes_after(
        &mut self,
        collection: &str,
        version: u64,
        limit: usize,
    ) -> Result<Vec<LedgerEntry>, ReplicaError> {
        self.inner.changes_after(collection, version, limit)
    }

    fn live_after(
        &mut self,
        collection: &str,
        after: Option<&str>,
        limit: usize,
    ) -> Result<Vec<LedgerEntry>, ReplicaError> {
        self.inner.live_after(collection, after, limit)
    }

    fn prune_tombstones(
        &mut self,
        collection: &str,
        changed_before: u64,
        keep: u64,
    ) -> Result<Pruned, ReplicaError> {
        if self.store.stuck.get() {
            return Ok(Pruned {
                highest: None,
                over_keep: true,
            });
        }
        self.inner
            .prune_tombstones(collection, changed_before, keep)
    }
}

/// Runs `pass` and checks that it wrote nothing at all.
fn quiet<R>(store: &Watched, what: &str, pass: impl FnOnce() -> R) -> R {
    let before = store.marks();
    let out = pass();
    assert_eq!(store.marks(), before, "{what} wrote");
    out
}

/// Runs `pass` and checks that it committed a write; returns its result and how
/// many ledger writes it made.
fn written<R>(store: &Watched, what: &str, pass: impl FnOnce() -> R) -> (R, u64) {
    let before = store.marks();
    let out = pass();
    let after = store.marks();
    assert!(after.writes > before.writes, "{what} made no ledger write");
    assert!(
        after.changes > before.changes,
        "{what} changed no SQLite row"
    );
    assert!(
        after.wal_bytes > before.wal_bytes,
        "{what} added no WAL frame"
    );
    (out, after.writes - before.writes)
}

fn req(epoch: &str, version: u64, limit: u32) -> PullRequest {
    PullRequest {
        epoch: epoch.into(),
        version,
        schema: 1,
        limit,
        resume: None,
    }
}

fn people(names: &[&str]) -> AppData {
    AppData::with(
        &names
            .iter()
            .map(|n| row(n, json!({ "name": n.to_uppercase() })))
            .collect::<Vec<_>>(),
    )
}

fn setup(epochs: &[&str], names: &[&str]) -> (Watched, &'static TestEnv, Collection, AppData) {
    let store = Watched::new();
    let env = TestEnv::leak(T0, epochs);
    let c = collection(env);
    c.ensure(&store).unwrap();
    let data = people(names);
    c.reconcile(&store, &data.list()).unwrap();
    (store, env, c, data)
}

#[test]
fn reconciling_the_same_rows_again_writes_nothing() {
    let (store, env, c, data) = setup(&["k3f9a2c1"], &["a", "b", "c"]);
    let record = store.record();
    assert_eq!(
        (record.version, record.dirty, record.reconciled_at),
        (3, false, T0)
    );
    for _ in 0..3 {
        // A later pass would stamp a later time.
        env.advance(MINUTE);
        let moved = quiet(&store, "a reconcile of the same rows", || {
            c.reconcile(&store, &data.list()).unwrap()
        });
        assert_eq!(moved, None);
    }
    // `reconciled_at` is the last pass that changed something.
    assert_eq!(store.record(), record);
}

#[test]
fn a_pull_answered_from_a_clean_ledger_writes_nothing() {
    let (store, env, c, mut data) = setup(&["k3f9a2c1"], &["a", "b", "c"]);
    data.put(row("d", json!("D")));
    c.touch(&store, &data.rows["d"]).unwrap();
    env.advance(MINUTE);
    let requests = [
        // At the head: the read path.
        req("k3f9a2c1", 4, 500),
        // A new device, another epoch: full copies on the write path.
        req("", 0, 500),
        req("zz99", 2, 500),
        // Behind: the changes, whole and cut.
        req("k3f9a2c1", 1, 500),
        req("k3f9a2c1", 1, 1),
        // A later page of a full copy.
        PullRequest {
            resume: Some("b".into()),
            ..req("k3f9a2c1", 4, 2)
        },
    ];
    for request in &requests {
        let answered = quiet(&store, &format!("the pull {request:?}"), || {
            c.answer(&store, request, data.loader()).unwrap()
        });
        assert!(!answered.head_moved, "{request:?}");
    }
}

#[test]
fn a_touch_of_an_unchanged_row_writes_nothing() {
    let (store, env, c, data) = setup(&["k3f9a2c1"], &["a", "b"]);
    env.advance(MINUTE);
    let head = quiet(&store, "a touch of an unchanged row", || {
        c.touch(&store, &data.rows["a"]).unwrap()
    });
    assert_eq!(head, 2);
    // So is a remove of a key the ledger does not hold, or holds as a tombstone.
    quiet(&store, "a remove of an unknown key", || {
        c.remove(&store, "zz").unwrap()
    });
    written(&store, "a remove", || c.remove(&store, "b").unwrap());
    env.advance(MINUTE);
    quiet(&store, "a remove of a tombstone", || {
        c.remove(&store, "b").unwrap()
    });
}

#[test]
fn clearing_dirty_is_written_once_and_the_next_pass_writes_nothing() {
    let (store, env, c, data) = setup(&["k3f9a2c1"], &["a", "b", "c"]);
    let start = store.record();
    // By a reconcile.
    written(&store, "mark_dirty", || c.mark_dirty(&store).unwrap());
    env.advance(MINUTE);
    let (moved, writes) = written(&store, "the reconcile that clears dirty", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
    assert_eq!((moved, writes), (None, 1), "only the record");
    let cleared = store.record();
    assert!(!cleared.dirty);
    assert_eq!(
        (&cleared.epoch, cleared.version),
        (&start.epoch, start.version)
    );
    assert_eq!(cleared.reconciled_at, T0 + MINUTE);
    env.advance(MINUTE);
    quiet(&store, "the reconcile after it", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
    assert_eq!(store.record(), cleared);
    // By a pull.
    written(&store, "mark_dirty", || c.mark_dirty(&store).unwrap());
    env.advance(MINUTE);
    let (answered, writes) = written(&store, "the pull that clears dirty", || {
        c.answer(&store, &req("k3f9a2c1", 3, 500), data.loader())
            .unwrap()
    });
    assert!(!answered.head_moved);
    assert_eq!(writes, 1, "only the record");
    assert!(!store.record().dirty);
    env.advance(MINUTE);
    quiet(&store, "the pull after it", || {
        c.answer(&store, &req("", 0, 500), data.loader()).unwrap()
    });
}

#[test]
fn a_real_change_still_writes_and_moves_the_head() {
    let (store, env, c, mut data) = setup(&["k3f9a2c1"], &["a", "b", "c"]);
    env.advance(MINUTE);
    data.put(row("b", json!("B2")));
    let (moved, writes) = written(&store, "a reconcile with a changed row", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
    assert_eq!((moved, writes), (Some(4), 2), "one entry and the record");
    let record = store.record();
    assert_eq!((record.version, record.reconciled_at), (4, T0 + MINUTE));
    let reply = c
        .answer(&store, &req("k3f9a2c1", 3, 500), data.loader())
        .unwrap()
        .reply;
    assert_eq!(
        serde_json::to_string(&reply).unwrap(),
        r#"{"e":"k3f9a2c1","v":4,"u":[["b","B2"]],"x":[]}"#
    );
    data.put(row("c", json!("C2")));
    let (head, _) = written(&store, "a touch of a changed row", || {
        c.touch(&store, &data.rows["c"]).unwrap()
    });
    assert_eq!(head, 5);
    data.rows.remove("a");
    let (moved, _) = written(&store, "a reconcile without a row", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
    assert_eq!(moved, Some(6));
}

#[test]
fn an_owed_rotation_is_written_once_its_minute_has_passed() {
    let (store, env, c, data) = setup(&["k3f9a2c1", "p0q9r8s7"], &["a", "b"]);
    // Created at T0, which counts as a rotation: a reset 30 s later is owed.
    env.advance(30_000);
    let (now, _) = written(&store, "a reset within the minute", || {
        c.reset(&store).unwrap()
    });
    assert!(!now);
    assert!(store.record().rotate_owed);
    written(&store, "the reconcile that clears dirty", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
    env.advance(1_000);
    quiet(&store, "a reconcile while the rotation is owed", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
    assert_eq!(store.record().epoch, "k3f9a2c1");
    // Allowed now: the next pass rotates, and that is written.
    env.advance(MINUTE);
    written(&store, "the pass that rotates", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
    let record = store.record();
    assert_eq!(
        (record.epoch.as_str(), record.version, record.rotate_owed),
        ("p0q9r8s7", 2, false)
    );
    env.advance(1_000);
    quiet(&store, "the reconcile after the rotation", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
}

#[test]
fn a_prune_that_raises_the_floor_is_written() {
    let (store, env, c, mut data) = setup(&["k3f9a2c1"], &["a", "b", "c"]);
    data.rows.remove("a");
    c.remove(&store, "a").unwrap(); // a@4
                                    // Past the 30-day horizon a reconcile of the same rows prunes a's tombstone.
    env.advance(30 * DAY + 1);
    let (moved, _) = written(&store, "the reconcile that prunes", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
    assert_eq!(moved, None);
    assert_eq!(store.record().floor, 4);
    env.advance(1_000);
    quiet(&store, "the reconcile after it", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
    // A touch of an unchanged row prunes too.
    data.rows.remove("b");
    c.remove(&store, "b").unwrap(); // b@5
    env.advance(30 * DAY + 1);
    written(&store, "the touch that prunes", || {
        c.touch(&store, &data.rows["c"]).unwrap()
    });
    assert_eq!(store.record().floor, 5);
    env.advance(1_000);
    quiet(&store, "the touch after it", || {
        c.touch(&store, &data.rows["c"]).unwrap()
    });
}

#[test]
fn the_rotation_a_store_that_could_not_prune_asks_for_is_written() {
    let (store, env, c, data) = setup(&["g1", "g2"], &["a", "b"]);
    env.advance(2 * MINUTE);
    store.stuck.set(true);
    written(&store, "the pass that rotates", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
    assert_eq!(store.record().epoch, "g2");
    // Within the minute of that rotation the next one is owed, and that is written once.
    env.advance(1_000);
    written(&store, "the pass that owes a rotation", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
    assert!(store.record().rotate_owed);
    env.advance(1_000);
    quiet(&store, "a pass that owes it again", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
    store.stuck.set(false);
    quiet(&store, "a pass once the store prunes", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
}

#[test]
fn the_rotation_for_a_database_that_went_back_is_written() {
    let (store, env, c, mut data) = setup(&["q1", "q2"], &["a"]);
    env.advance(5 * MINUTE);
    let saved = data.clone();
    save(&store.conn);
    data.put(row("b", json!("B")));
    c.touch(&store, &data.rows["b"]).unwrap();
    let reply = c
        .answer(&store, &req("", 0, 500), data.loader())
        .unwrap()
        .reply;
    assert!(matches!(reply, PullReply::FullCopy { version: 2, .. }));
    // Restored to (q1, 1), below the version 2 this process handed out.
    data = saved;
    restore(&store.conn);
    env.advance(1_000);
    written(&store, "the pass after the restore", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
    let record = store.record();
    assert_eq!((record.epoch.as_str(), record.version), ("q2", 1));
    env.advance(1_000);
    quiet(&store, "the reconcile after the rotation", || {
        c.reconcile(&store, &data.list()).unwrap()
    });
}

/// Saves the ledger's tables (a backup).
fn save(conn: &rusqlite::Connection) {
    conn.execute_batch(
        "DROP TABLE IF EXISTS saved_c; DROP TABLE IF EXISTS saved_r;
         CREATE TABLE saved_c AS SELECT * FROM friends_replica_collections;
         CREATE TABLE saved_r AS SELECT * FROM friends_replica_rows;",
    )
    .unwrap();
}

/// Puts the ledger's tables back to the last [`save`] (a restore from backup).
fn restore(conn: &rusqlite::Connection) {
    conn.execute_batch(
        "DELETE FROM friends_replica_collections;
         INSERT INTO friends_replica_collections SELECT * FROM saved_c;
         DELETE FROM friends_replica_rows;
         INSERT INTO friends_replica_rows SELECT * FROM saved_r;",
    )
    .unwrap();
}