node-app-replica 7.7.25

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
//! The ledger on the app's own SQLite connection (feature `sqlite`).
//!
//! The tables are those of the Phase 3 spec, section 5.1, named with the
//! collection's table prefix. Every ledger write runs in `BEGIN IMMEDIATE`, so
//! two connections to one file serialise on SQLite's write lock instead of both
//! reading the same head; set a busy timeout on the connection so the second
//! writer waits rather than failing. Called inside a transaction the app already
//! holds, the ledger uses a savepoint, and its writes commit or roll back with
//! the app's. Reading the head (`head()`, a pull answered "nothing new") is one
//! `SELECT` and takes no write lock.
//!
//! The layout is versioned: `<prefix>replica_meta` holds the row
//! `('layout', n)`, and `ensure` upgrades an older layout step by step
//! (`UPGRADES`). A ledger written by a newer helper is refused rather than
//! half-understood.

use rusqlite::{params, Connection, OptionalExtension, Row as SqlRow};

use crate::store::{CollectionRecord, LedgerEntry, LedgerStore, LedgerTx, Pruned};
use crate::ReplicaError;

impl From<rusqlite::Error> for ReplicaError {
    fn from(error: rusqlite::Error) -> Self {
        ReplicaError::Store(error.to_string())
    }
}

struct Tables {
    meta: String,
    collections: String,
    rows: String,
}

impl Tables {
    fn new(prefix: &str) -> Self {
        Self {
            meta: format!("{prefix}replica_meta"),
            collections: format!("{prefix}replica_collections"),
            rows: format!("{prefix}replica_rows"),
        }
    }
}

/// The layout this helper writes. Layout 1 (the first release) had no
/// `replica_meta` table; its presence is told by `replica_collections`.
const LAYOUT: i64 = 2;

/// The first layout, created as it shipped; a new ledger is created at layout 1
/// and brought up by the same steps an old one takes.
fn create_layout_1(conn: &Connection, t: &Tables) -> Result<(), ReplicaError> {
    conn.execute_batch(&format!(
        "CREATE TABLE IF NOT EXISTS {c} (
           name          TEXT PRIMARY KEY NOT NULL,
           epoch         TEXT NOT NULL,
           version       INTEGER NOT NULL DEFAULT 0,
           floor         INTEGER NOT NULL DEFAULT 0,
           dirty         INTEGER NOT NULL DEFAULT 1,
           rotated_at    INTEGER NOT NULL DEFAULT 0,
           reconciled_at INTEGER NOT NULL DEFAULT 0
         );
         CREATE TABLE IF NOT EXISTS {r} (
           collection TEXT NOT NULL,
           row_key    TEXT NOT NULL,
           digest     TEXT NOT NULL,
           version    INTEGER NOT NULL,
           deleted    INTEGER NOT NULL DEFAULT 0,
           changed_at INTEGER NOT NULL,
           PRIMARY KEY (collection, row_key)
         );
         CREATE INDEX IF NOT EXISTS idx_{r}_version ON {r} (collection, version);",
        c = t.collections,
        r = t.rows,
    ))?;
    Ok(())
}

/// 1 → 2: the owed rotation, and the two partial indexes that make pruning
/// follow the tombstones instead of scanning every row.
fn upgrade_1_to_2(conn: &Connection, t: &Tables) -> Result<(), ReplicaError> {
    conn.execute_batch(&format!(
        "ALTER TABLE {c} ADD COLUMN rotate_owed INTEGER NOT NULL DEFAULT 0;
         CREATE INDEX IF NOT EXISTS idx_{r}_tombstone_version ON {r} (collection, version)
           WHERE deleted = 1;
         CREATE INDEX IF NOT EXISTS idx_{r}_tombstone_age ON {r} (collection, changed_at)
           WHERE deleted = 1;",
        c = t.collections,
        r = t.rows,
    ))?;
    Ok(())
}

type Upgrade = fn(&Connection, &Tables) -> Result<(), ReplicaError>;

/// `UPGRADES[n - 1]` takes layout `n` to `n + 1`. A new layout adds one step here
/// and raises [`LAYOUT`]; nothing else changes.
const UPGRADES: &[Upgrade] = &[upgrade_1_to_2];

fn table_exists(conn: &Connection, name: &str) -> Result<bool, ReplicaError> {
    Ok(conn
        .query_row(
            "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1",
            params![name],
            |_| Ok(()),
        )
        .optional()?
        .is_some())
}

/// Brings the tables to [`LAYOUT`], inside the caller's transaction.
fn bring_up(conn: &Connection, t: &Tables) -> Result<(), ReplicaError> {
    conn.execute_batch(&format!(
        "CREATE TABLE IF NOT EXISTS {m} (
           key   TEXT PRIMARY KEY NOT NULL,
           value INTEGER NOT NULL
         );",
        m = t.meta
    ))?;
    let stored: Option<i64> = conn
        .query_row(
            &format!("SELECT value FROM {} WHERE key = 'layout'", t.meta),
            [],
            |row| row.get(0),
        )
        .optional()?;
    let mut layout = match stored {
        Some(layout) => layout,
        None if table_exists(conn, &t.collections)? => 1,
        None => {
            create_layout_1(conn, t)?;
            1
        }
    };
    if !(1..=LAYOUT).contains(&layout) {
        return Err(ReplicaError::Store(format!(
            "the replica ledger's layout is {layout}; this helper knows layouts 1 to {LAYOUT}"
        )));
    }
    while layout < LAYOUT {
        let step = usize::try_from(layout - 1)
            .ok()
            .and_then(|index| UPGRADES.get(index))
            .ok_or_else(|| ReplicaError::Store(format!("no upgrade from layout {layout}")))?;
        step(conn, t)?;
        layout += 1;
    }
    conn.execute(
        &format!(
            "INSERT INTO {} (key, value) VALUES ('layout', ?1)
             ON CONFLICT(key) DO UPDATE SET value = excluded.value",
            t.meta
        ),
        params![layout],
    )?;
    Ok(())
}

fn to_sql(value: u64) -> Result<i64, ReplicaError> {
    i64::try_from(value).map_err(|_| ReplicaError::Store(format!("{value} does not fit SQLite")))
}

fn from_sql(value: i64) -> Result<u64, ReplicaError> {
    u64::try_from(value)
        .map_err(|_| ReplicaError::Store(format!("negative {value} in the replica ledger")))
}

/// Runs `work` in one transaction: `BEGIN IMMEDIATE`, or a savepoint inside the
/// app's own transaction.
fn in_transaction<R>(
    conn: &Connection,
    work: impl FnOnce() -> Result<R, ReplicaError>,
) -> Result<R, ReplicaError> {
    // Inside the app's own transaction a BEGIN would fail; a savepoint nests.
    let nested = !conn.is_autocommit();
    let (begin, commit, rollback) = if nested {
        (
            "SAVEPOINT node_app_replica",
            "RELEASE node_app_replica",
            "ROLLBACK TO node_app_replica; RELEASE node_app_replica",
        )
    } else {
        ("BEGIN IMMEDIATE", "COMMIT", "ROLLBACK")
    };
    conn.execute_batch(begin)?;
    let outcome = work().and_then(|out| {
        conn.execute_batch(commit)?;
        Ok(out)
    });
    if outcome.is_err() {
        // The work's error is the one worth reporting; a failed rollback leaves
        // SQLite to roll back when the connection next begins or closes.
        let _ = conn.execute_batch(rollback);
    }
    outcome
}

const RECORD_COLUMNS: &str = "epoch, version, floor, dirty, rotated_at, reconciled_at, rotate_owed";

fn read_record(
    conn: &Connection,
    tables: &Tables,
    collection: &str,
) -> Result<Option<CollectionRecord>, ReplicaError> {
    let raw = conn
        .prepare_cached(&format!(
            "SELECT {RECORD_COLUMNS} FROM {} WHERE name = ?1",
            tables.collections
        ))?
        .query_row(params![collection], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, i64>(1)?,
                row.get::<_, i64>(2)?,
                row.get::<_, i64>(3)?,
                row.get::<_, i64>(4)?,
                row.get::<_, i64>(5)?,
                row.get::<_, i64>(6)?,
            ))
        })
        .optional()?;
    raw.map(
        |(epoch, version, floor, dirty, rotated_at, reconciled_at, rotate_owed)| {
            Ok(CollectionRecord {
                epoch,
                version: from_sql(version)?,
                floor: from_sql(floor)?,
                dirty: dirty != 0,
                rotated_at: from_sql(rotated_at)?,
                reconciled_at: from_sql(reconciled_at)?,
                rotate_owed: rotate_owed != 0,
            })
        },
    )
    .transpose()
}

impl LedgerStore for Connection {
    fn ensure(&self, prefix: &str) -> Result<(), ReplicaError> {
        let t = Tables::new(prefix);
        in_transaction(self, || bring_up(self, &t))
    }

    fn write(
        &self,
        prefix: &str,
        work: &mut dyn FnMut(&mut dyn LedgerTx) -> Result<(), ReplicaError>,
    ) -> Result<(), ReplicaError> {
        in_transaction(self, || {
            let mut tx = SqliteTx {
                conn: self,
                tables: Tables::new(prefix),
            };
            work(&mut tx)
        })
    }

    fn read_record(
        &self,
        prefix: &str,
        collection: &str,
    ) -> Result<Option<CollectionRecord>, ReplicaError> {
        // One statement: SQLite reads it in its own read transaction (or in the
        // app's, when one is open), without the write lock.
        read_record(self, &Tables::new(prefix), collection)
    }
}

struct SqliteTx<'c> {
    conn: &'c Connection,
    tables: Tables,
}

const ENTRY_COLUMNS: &str = "row_key, digest, version, deleted, changed_at";

fn read_entry(row: &SqlRow<'_>) -> rusqlite::Result<(String, String, i64, i64, i64)> {
    Ok((
        row.get(0)?,
        row.get(1)?,
        row.get(2)?,
        row.get(3)?,
        row.get(4)?,
    ))
}

fn into_entry(raw: (String, String, i64, i64, i64)) -> Result<LedgerEntry, ReplicaError> {
    let (key, digest, version, deleted, changed_at) = raw;
    Ok(LedgerEntry {
        key,
        digest,
        version: from_sql(version)?,
        deleted: deleted != 0,
        changed_at: from_sql(changed_at)?,
    })
}

impl SqliteTx<'_> {
    fn query_entries(
        &self,
        sql: &str,
        params: &[&dyn rusqlite::ToSql],
    ) -> Result<Vec<LedgerEntry>, ReplicaError> {
        let mut statement = self.conn.prepare_cached(sql)?;
        let raw = statement
            .query_map(params, read_entry)?
            .collect::<rusqlite::Result<Vec<_>>>()?;
        raw.into_iter().map(into_entry).collect()
    }
}

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

    fn put_record(
        &mut self,
        collection: &str,
        record: &CollectionRecord,
    ) -> Result<(), ReplicaError> {
        self.conn
            .prepare_cached(&format!(
                "INSERT INTO {} (name, {RECORD_COLUMNS})
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
                 ON CONFLICT(name) DO UPDATE SET epoch = excluded.epoch, version = excluded.version,
                   floor = excluded.floor, dirty = excluded.dirty, rotated_at = excluded.rotated_at,
                   reconciled_at = excluded.reconciled_at, rotate_owed = excluded.rotate_owed",
                self.tables.collections
            ))?
            .execute(params![
                collection,
                record.epoch,
                to_sql(record.version)?,
                to_sql(record.floor)?,
                i64::from(record.dirty),
                to_sql(record.rotated_at)?,
                to_sql(record.reconciled_at)?,
                i64::from(record.rotate_owed),
            ])?;
        Ok(())
    }

    fn entry(&mut self, collection: &str, key: &str) -> Result<Option<LedgerEntry>, ReplicaError> {
        let raw = self
            .conn
            .prepare_cached(&format!(
                "SELECT {ENTRY_COLUMNS} FROM {} WHERE collection = ?1 AND row_key = ?2",
                self.tables.rows
            ))?
            .query_row(params![collection, key], read_entry)
            .optional()?;
        raw.map(into_entry).transpose()
    }

    fn entries(&mut self, collection: &str) -> Result<Vec<LedgerEntry>, ReplicaError> {
        let sql = format!(
            "SELECT {ENTRY_COLUMNS} FROM {} WHERE collection = ?1 ORDER BY row_key",
            self.tables.rows
        );
        self.query_entries(&sql, &[&collection])
    }

    fn put_entry(&mut self, collection: &str, entry: &LedgerEntry) -> Result<(), ReplicaError> {
        self.conn
            .prepare_cached(&format!(
                "INSERT INTO {} (collection, row_key, digest, version, deleted, changed_at)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)
                 ON CONFLICT(collection, row_key) DO UPDATE SET digest = excluded.digest,
                   version = excluded.version, deleted = excluded.deleted,
                   changed_at = excluded.changed_at",
                self.tables.rows
            ))?
            .execute(params![
                collection,
                entry.key,
                entry.digest,
                to_sql(entry.version)?,
                i64::from(entry.deleted),
                to_sql(entry.changed_at)?,
            ])?;
        Ok(())
    }

    fn delete_entry(&mut self, collection: &str, key: &str) -> Result<(), ReplicaError> {
        self.conn
            .prepare_cached(&format!(
                "DELETE FROM {} WHERE collection = ?1 AND row_key = ?2",
                self.tables.rows
            ))?
            .execute(params![collection, key])?;
        Ok(())
    }

    fn changes_after(
        &mut self,
        collection: &str,
        version: u64,
        limit: usize,
    ) -> Result<Vec<LedgerEntry>, ReplicaError> {
        let sql = format!(
            "SELECT {ENTRY_COLUMNS} FROM {} WHERE collection = ?1 AND version > ?2
             ORDER BY version LIMIT ?3",
            self.tables.rows
        );
        let limit = to_sql(limit as u64)?;
        self.query_entries(&sql, &[&collection, &to_sql(version)?, &limit])
    }

    fn live_after(
        &mut self,
        collection: &str,
        after: Option<&str>,
        limit: usize,
    ) -> Result<Vec<LedgerEntry>, ReplicaError> {
        let limit = to_sql(limit as u64)?;
        match after {
            Some(after) => {
                let sql = format!(
                    "SELECT {ENTRY_COLUMNS} FROM {} WHERE collection = ?1 AND deleted = 0
                     AND row_key > ?2 ORDER BY row_key LIMIT ?3",
                    self.tables.rows
                );
                self.query_entries(&sql, &[&collection, &after, &limit])
            }
            None => {
                let sql = format!(
                    "SELECT {ENTRY_COLUMNS} FROM {} WHERE collection = ?1 AND deleted = 0
                     ORDER BY row_key LIMIT ?2",
                    self.tables.rows
                );
                self.query_entries(&sql, &[&collection, &limit])
            }
        }
    }

    fn prune_tombstones(
        &mut self,
        collection: &str,
        changed_before: u64,
        keep: u64,
    ) -> Result<Pruned, ReplicaError> {
        // Every statement here reads one of the partial indexes on deleted rows
        // (`idx_<rows>_tombstone_age`, `idx_<rows>_tombstone_version`), so the
        // cost follows the tombstones, never the live rows.
        let rows = &self.tables.rows;
        let changed_before = to_sql(changed_before)?;
        // By age: a range of the age index, as long as what is removed.
        let by_age: Option<i64> = self
            .conn
            .prepare_cached(&format!(
                "SELECT MAX(version) FROM {rows} WHERE collection = ?1 AND deleted = 1
                 AND changed_at < ?2"
            ))?
            .query_row(params![collection, changed_before], |row| row.get(0))?;
        if by_age.is_some() {
            self.conn
                .prepare_cached(&format!(
                    "DELETE FROM {rows} WHERE collection = ?1 AND deleted = 1 AND changed_at < ?2"
                ))?
                .execute(params![collection, changed_before])?;
        }
        // By count: the newest `keep` stay; the one after them (if any) is the
        // highest version to remove.
        let by_count: Option<i64> = self
            .conn
            .prepare_cached(&format!(
                "SELECT version FROM {rows} WHERE collection = ?1 AND deleted = 1
                 ORDER BY version DESC LIMIT 1 OFFSET ?2"
            ))?
            .query_row(params![collection, to_sql(keep)?], |row| row.get(0))
            .optional()?;
        if let Some(cut) = by_count {
            self.conn
                .prepare_cached(&format!(
                    "DELETE FROM {rows} WHERE collection = ?1 AND deleted = 1 AND version <= ?2"
                ))?
                .execute(params![collection, cut])?;
        }
        Ok(Pruned {
            highest: by_age.max(by_count).map(from_sql).transpose()?,
            // At most `keep` are left by construction.
            over_keep: false,
        })
    }
}