node-app-replica 7.7.22

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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! # node-app-replica
//!
//! Change-only replication of app data (Phase 3 of the one-stack design,
//! `docs/superpowers/specs/2026-11-19-one-stack-phase-3-replication.md`).
//!
//! An app backend declares each collection once, as a [`Collection`] bound to
//! its pull capability (`friends.people.pull`), and tells it what changed —
//! either the whole current list ([`Collection::reconcile`]) or one row at a time
//! at its write sites ([`Collection::touch`], [`Collection::remove`]). The helper
//! keeps a small ledger in the app's own database (keys, digests, versions,
//! tombstones; never the rows) and from it answers the node's pull with one of
//! three replies: nothing new, the changes since the caller's version, or a full
//! copy under a new or the same epoch. The app writes no versioning code.
//!
//! ```no_run
//! # #[cfg(feature = "sqlite")]
//! # fn demo(conn: &rusqlite::Connection, request: &serde_json::Value) -> Result<(), String> {
//! use node_app_replica::{Collection, Row};
//! use serde_json::json;
//!
//! static PEOPLE: Collection = Collection::new("friends.people.pull", "friends_", &[1]);
//!
//! PEOPLE.ensure(conn).map_err(|e| e.to_string())?;
//! PEOPLE
//!     .reconcile(conn, &[Row::new("did:key:z6Mk…", json!({ "name": "Alice" }))])
//!     .map_err(|e| e.to_string())?;
//! let reply = PEOPLE.pull(conn, request, |_conn, _keys| {
//!     Ok(vec![Row::new("did:key:z6Mk…", json!({ "name": "Alice" }))])
//! })?;
//! # let _ = reply; Ok(())
//! # }
//! ```
//!
//! The crate depends on `serde`, `serde_json` and `sha2` only (plus `rusqlite`
//! behind the `sqlite` feature) and not on `node-app-sdk-rust`, so an app pinned
//! to any SDK version can use it. [`Announcer`] is the one seam to the node's
//! capability bus; implement it with the SDK's `invoke_capability`.

#![warn(missing_docs)]

pub mod digest;
mod ledger;
#[cfg(feature = "sqlite")]
mod sqlite;
pub mod store;
pub mod wire;

use std::fmt;
use std::hash::{BuildHasher, Hasher};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, PoisonError};
use std::time::{SystemTime, UNIX_EPOCH};

use serde_json::Value;
use sha2::{Digest, Sha256};

pub use ledger::{
    Head, Horizon, ROTATION_MIN_INTERVAL_MS, TOMBSTONE_MAX_AGE_MS, TOMBSTONE_MAX_COUNT,
};
pub use store::{CollectionRecord, LedgerEntry, LedgerStore, LedgerTx, MemoryLedger, Pruned};
pub use wire::{
    Announce, AnnounceReply, HeadsData, PullReply, PullRequest, PushedHead, Row, SyncAnswer,
    SyncEntry, SyncErrorCode, SyncReply, SyncRequest, WindowDays, WindowedAnnounce,
    WindowedPullRequest, WindowedSyncEntry, WindowedSyncRequest,
};

/// Why a ledger operation or a pull failed. `Display` starts with a stable
/// prefix, so the text can go straight into the capability error channel.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReplicaError {
    /// The collection's declaration is unusable (its name or table prefix).
    Config(String),
    /// A row outside the contract's limits, or a key listed twice.
    InvalidRow {
        /// The row's key (its first 64 characters).
        key: String,
        /// What is wrong with it.
        reason: String,
    },
    /// A pull request outside the contract.
    InvalidRequest(String),
    /// The pull asked for a schema this collection does not serve.
    SchemaUnsupported {
        /// The pull capability.
        capability: String,
        /// The schema number asked for.
        schema: u32,
    },
    /// The app's `load` callback failed.
    Load(String),
    /// The ledger's store failed.
    Store(String),
}

impl fmt::Display for ReplicaError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ReplicaError::Config(reason) => write!(f, "replica_config_invalid: {reason}"),
            ReplicaError::InvalidRow { key, reason } => {
                write!(f, "replica_row_invalid: row '{key}': {reason}")
            }
            ReplicaError::InvalidRequest(reason) => {
                write!(f, "replica_request_invalid: {reason}")
            }
            ReplicaError::SchemaUnsupported { capability, schema } => write!(
                f,
                "{} schema {schema} is not served by {capability}",
                wire::SCHEMA_UNSUPPORTED_PREFIX
            ),
            ReplicaError::Load(reason) => write!(f, "replica_load_failed: {reason}"),
            ReplicaError::Store(reason) => write!(f, "replica_store_failed: {reason}"),
        }
    }
}

impl std::error::Error for ReplicaError {}

/// Where the helper reads the time and draws new epochs.
pub trait Environment: Sync {
    /// Unix time in milliseconds.
    fn now_ms(&self) -> u64;
    /// A fresh epoch: `[a-z0-9]{1,16}`, different from every earlier one with
    /// overwhelming probability.
    fn new_epoch(&self) -> String;
}

/// The system clock and an 8-character random epoch.
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemEnvironment;

impl Environment for SystemEnvironment {
    fn now_ms(&self) -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX))
            .unwrap_or(0)
    }

    fn new_epoch(&self) -> String {
        random_epoch()
    }
}

/// 8 characters of `[a-z0-9]` (36^8 ≈ 2.8 × 10^12 values). The entropy is the
/// standard library's per-process random hash keys (seeded from the operating
/// system), a process-wide counter, the time and the process id, through
/// SHA-256. An epoch is not a secret; it must only not repeat.
fn random_epoch() -> String {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
    hasher.write_u64(COUNTER.fetch_add(1, Ordering::Relaxed));
    let mut sha = Sha256::new();
    sha.update(hasher.finish().to_le_bytes());
    sha.update(
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|elapsed| elapsed.as_nanos())
            .unwrap_or(0)
            .to_le_bytes(),
    );
    sha.update(std::process::id().to_le_bytes());
    let hash = sha.finalize();
    const ALPHABET: &[u8; 36] = b"abcdefghijklmnopqrstuvwxyz0123456789";
    hash.iter()
        .take(8)
        .map(|byte| char::from(ALPHABET[usize::from(*byte) % ALPHABET.len()]))
        .collect()
}

/// The app's door to the node's capability bus, for `core.replica.announce`.
/// Implement it with the SDK's `invoke_capability`.
pub trait Announcer {
    /// Invokes `capability` with `payload` and returns the reply's payload, or the
    /// error text when the capability failed or does not exist.
    fn invoke(&self, capability: &str, payload: Value) -> Result<Value, String>;
}

/// The result of an announce. An announce never fails the app's own work, but
/// until one lands the node answers a device that holds the head it remembers
/// with "nothing new" without calling the app, so devices do not see the change.
/// The helper does not retry: [`Collection::announce`] is one synchronous call,
/// and the app retries a `Failed` (or `RotationDeferred`) announce on its own
/// schedule (see the README's "Announce").
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AnnounceOutcome {
    /// The node took the head.
    Accepted(Head),
    /// The node remembered a higher version in this epoch (the app's database
    /// went back in time); the helper rotated the epoch and announced the new head.
    Rotated(Head),
    /// The node answered `rotate` again to the head of a fresh epoch, which a
    /// node that keeps its marks never does. The head stays; the next announce
    /// asks again.
    RotationDeferred(Head),
    /// The announce failed. `first` is true for the first failure after a
    /// success (or since start), so the app logs it once.
    Failed {
        /// Why it failed.
        error: String,
        /// The first failure since the last success (or since start).
        first: bool,
    },
}

/// A pull's answer and whether the pull moved the ledger's head (a dirty
/// reconcile, a write the app had not reported, or a rotation): when it did, the
/// app announces, so other devices hear of it.
#[derive(Debug, Clone, PartialEq)]
pub struct Answered {
    /// The reply for the node.
    pub reply: PullReply,
    /// The pull moved the head: announce.
    pub head_moved: bool,
}

/// One replicated collection: its pull capability, the prefix of the ledger's
/// tables, and the schema numbers it serves. Declare it as a `static`.
pub struct Collection {
    name: &'static str,
    table_prefix: &'static str,
    schemas: &'static [u32],
    env: &'static dyn Environment,
    horizon: Horizon,
    announce_failing: AtomicBool,
    /// The highest version this process has handed out (in a pull reply, or in
    /// an announce the node took) or heard the node has (its `rotate`), per
    /// epoch, most recent epoch first. A ledger that reads lower in the same
    /// epoch went back in time.
    handed_out: Mutex<Vec<(String, u64)>>,
}

/// Epochs whose hand-out mark a process keeps; a restore to an epoch older than
/// these is still caught by the node's marks and by devices ahead.
const HANDED_OUT_EPOCHS: usize = 16;

impl fmt::Debug for Collection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Collection")
            .field("name", &self.name)
            .field("table_prefix", &self.table_prefix)
            .field("schemas", &self.schemas)
            .field("horizon", &self.horizon)
            .finish()
    }
}

impl Collection {
    /// `pull_capability` is `<app>.<collection>.pull` and names the collection in
    /// the ledger; `table_prefix` (`[A-Za-z0-9_]{0,48}`) names the ledger's tables
    /// (`friends_` → `friends_replica_collections`, `friends_replica_rows`);
    /// `schemas` are the `N`s of the `.vN` names this app serves.
    pub const fn new(
        pull_capability: &'static str,
        table_prefix: &'static str,
        schemas: &'static [u32],
    ) -> Self {
        Self {
            name: pull_capability,
            table_prefix,
            schemas,
            env: &SystemEnvironment,
            horizon: Horizon::DEFAULT,
            announce_failing: AtomicBool::new(false),
            handed_out: Mutex::new(Vec::new()),
        }
    }

    /// Replaces the clock and the epoch source.
    pub const fn with_environment(mut self, env: &'static dyn Environment) -> Self {
        self.env = env;
        self
    }

    /// Replaces the tombstone horizon (default 30 days and 5,000 per collection).
    pub const fn with_tombstone_horizon(mut self, max_age_ms: u64, max_count: u64) -> Self {
        self.horizon = Horizon {
            max_age_ms,
            max_count,
        };
        self
    }

    /// The pull capability.
    pub fn name(&self) -> &'static str {
        self.name
    }

    /// The schema numbers this collection serves.
    pub fn schemas(&self) -> &'static [u32] {
        self.schemas
    }

    fn spec(&self) -> ledger::Spec<'_> {
        ledger::Spec {
            name: self.name,
            schemas: self.schemas,
            env: self.env,
            horizon: self.horizon,
        }
    }

    fn check(&self) -> Result<(), ReplicaError> {
        let segments: Vec<&str> = self.name.split('.').collect();
        let segment_ok = |segment: &&str| {
            let mut chars = segment.chars();
            chars.next().is_some_and(|c| c.is_ascii_lowercase())
                && chars
                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
        };
        if segments.len() < 3
            || segments.last() != Some(&"pull")
            || !segments.iter().all(segment_ok)
        {
            return Err(ReplicaError::Config(format!(
                "'{}' is not a pull capability '<app>.<collection>.pull'",
                self.name
            )));
        }
        if self.name.starts_with("core.") {
            return Err(ReplicaError::Config(format!(
                "'{}' is in the reserved 'core.' namespace",
                self.name
            )));
        }
        // The prefix starts SQL identifiers (`<prefix>replica_rows`), which may not
        // start with a digit.
        if self.table_prefix.len() > 48
            || self.table_prefix.starts_with(|c: char| c.is_ascii_digit())
            || !self
                .table_prefix
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'_')
        {
            return Err(ReplicaError::Config(format!(
                "table prefix '{}' must be [A-Za-z_][A-Za-z0-9_]{{0,47}} or empty",
                self.table_prefix
            )));
        }
        if self.horizon.max_count == 0 {
            return Err(ReplicaError::Config(
                "the tombstone horizon must keep at least one tombstone".to_string(),
            ));
        }
        Ok(())
    }

    /// The hand-out mark of `epoch` in this process.
    fn handed_out(&self, epoch: &str) -> Option<u64> {
        let marks = self
            .handed_out
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        marks.iter().find(|(e, _)| e == epoch).map(|(_, v)| *v)
    }

    /// Records that this process handed out `version` of `epoch` (a pull reply
    /// was returned, or the node took an announce).
    fn note_handed_out(&self, epoch: &str, version: u64) {
        let mut marks = self
            .handed_out
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        let mark = match marks.iter().position(|(e, _)| e == epoch) {
            Some(index) => marks.remove(index).1.max(version),
            None => version,
        };
        marks.insert(0, (epoch.to_string(), mark));
        marks.truncate(HANDED_OUT_EPOCHS);
    }

    /// The ledger reads below what this process handed out in its epoch: the
    /// database went back in time (a restore, while the app kept running).
    fn went_back(&self, record: &CollectionRecord) -> bool {
        self.handed_out(&record.epoch)
            .is_some_and(|mark| mark > record.version)
    }

    /// Runs `work` on this collection's record in one write transaction and
    /// writes the record back. Before the work, a database that went back in time
    /// rotates the epoch, and so does an owed rotation whose minute has passed;
    /// `work` is told whether that happened.
    fn with_record<S, R>(
        &self,
        store: &S,
        mut work: impl FnMut(
            &mut dyn LedgerTx,
            &ledger::Spec<'_>,
            &mut CollectionRecord,
            bool,
        ) -> Result<R, ReplicaError>,
    ) -> Result<R, ReplicaError>
    where
        S: LedgerStore + ?Sized,
    {
        self.check()?;
        let spec = self.spec();
        let mut out = None;
        store.write(self.table_prefix, &mut |tx| {
            let mut record = ledger::open(tx, &spec)?;
            let before = record.clone();
            let went_back = self.went_back(&record);
            let rotated = ledger::begin(tx, &spec, &mut record, went_back)?;
            let result = work(tx, &spec, &mut record, rotated)?;
            if record != before {
                tx.put_record(spec.name, &record)?;
            }
            out = Some(result);
            Ok(())
        })?;
        out.ok_or_else(|| ReplicaError::Store("the store did not run the ledger work".to_string()))
    }

    /// The committed record when a read can stand for a write: it exists, did not
    /// go back in time, and no owed rotation is due. `None` sends the caller to
    /// the write path.
    fn read_settled<S: LedgerStore + ?Sized>(
        &self,
        store: &S,
    ) -> Result<Option<CollectionRecord>, ReplicaError> {
        self.check()?;
        let record = store.read_record(self.table_prefix, self.name)?;
        Ok(record
            .filter(|record| !self.went_back(record) && ledger::nothing_due(&self.spec(), record)))
    }

    /// Creates the ledger's tables if they do not exist. Call it where the app
    /// creates its own tables, on every start: it is idempotent.
    pub fn ensure<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<(), ReplicaError> {
        self.check()?;
        store.ensure(self.table_prefix)
    }

    /// Whole-list mode: hand over every current row; the helper finds what
    /// changed. Returns the new head version when the head moved. Rows are checked
    /// against the contract's limits first; one bad row refuses the whole list.
    pub fn reconcile<S: LedgerStore + ?Sized>(
        &self,
        store: &S,
        rows: &[Row],
    ) -> Result<Option<u64>, ReplicaError> {
        self.with_record(store, |tx, spec, record, _| {
            let before = Head::from(&*record);
            ledger::reconcile(tx, spec, record, rows)?;
            Ok((Head::from(&*record) != before).then_some(record.version))
        })
    }

    /// Records one row written at a write site. Returns the head version.
    pub fn touch<S: LedgerStore + ?Sized>(
        &self,
        store: &S,
        row: &Row,
    ) -> Result<u64, ReplicaError> {
        self.with_record(store, |tx, spec, record, _| {
            ledger::touch(tx, spec, record, row)?;
            Ok(record.version)
        })
    }

    /// Records one row deleted at a write site. Returns the head version.
    pub fn remove<S: LedgerStore + ?Sized>(
        &self,
        store: &S,
        key: &str,
    ) -> Result<u64, ReplicaError> {
        self.with_record(store, |tx, spec, record, _| {
            ledger::remove(tx, spec, record, key)?;
            Ok(record.version)
        })
    }

    /// "Something may have changed": the next pull reconciles before answering.
    pub fn mark_dirty<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<(), ReplicaError> {
        self.with_record(store, |_tx, _spec, record, _| {
            record.dirty = true;
            Ok(())
        })
    }

    /// Starts a new epoch (the app's data was replaced) and marks the collection
    /// dirty. Every device takes one full copy. Returns whether it rotated now;
    /// within a minute of the last rotation the rotation is owed instead (it
    /// happens before the next version is assigned, or at the first ledger
    /// operation after the minute). The collection is marked dirty either way.
    ///
    /// A database restored from a backup needs no call: the helper finds that
    /// out by itself (a device ahead of the head, the node's `rotate`, or this
    /// process having handed out more) and rotates at once.
    pub fn reset<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<bool, ReplicaError> {
        self.with_record(store, |tx, spec, record, rotated| {
            let rotated = rotated || ledger::request_rotation(tx, spec, record)?;
            record.dirty = true;
            Ok(rotated)
        })
    }

    /// The ledger's head: what an announce reports. A plain read of the committed
    /// header (no write lock), unless the ledger has none yet, went back in time
    /// or owes a rotation that is due: then the write path settles that first.
    pub fn head<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<Head, ReplicaError> {
        if let Some(record) = self.read_settled(store)? {
            return Ok(Head::from(&record));
        }
        self.with_record(store, |_tx, _spec, record, _| Ok(Head::from(&*record)))
    }

    /// Answers one pull. `load` returns the app's current rows: every row for
    /// `None`, else the rows of the given keys (keys with no row are left out).
    /// It runs inside the ledger's write transaction, so on SQLite it reads the
    /// same snapshot the ledger does; it must not call this collection again.
    pub fn answer<S, L>(
        &self,
        store: &S,
        request: &PullRequest,
        mut load: L,
    ) -> Result<Answered, ReplicaError>
    where
        S: LedgerStore + ?Sized,
        L: FnMut(&S, Option<&[String]>) -> Result<Vec<Row>, String>,
    {
        ledger::check_request(&self.spec(), request)?;
        // The common case, a device at the head, is one read and no write lock.
        if request.resume.is_none() {
            if let Some(record) = self.read_settled(store)? {
                if !record.dirty
                    && record.epoch == request.epoch
                    && record.version == request.version
                {
                    self.note_handed_out(&record.epoch, record.version);
                    return Ok(Answered {
                        reply: PullReply::NothingNew {
                            epoch: record.epoch,
                            version: record.version,
                        },
                        head_moved: false,
                    });
                }
            }
        }
        let (answered, head) = self.with_record(store, |tx, spec, record, rotated| {
            let before = Head::from(&*record);
            let mut load_rows =
                |keys: Option<&[String]>| load(store, keys).map_err(ReplicaError::Load);
            let reply = ledger::answer(tx, spec, record, request, &mut load_rows)?;
            let head = Head::from(&*record);
            Ok((
                Answered {
                    reply,
                    head_moved: rotated || head != before,
                },
                head,
            ))
        })?;
        // Every reply may carry rows up to the head (a later page of a full copy
        // carries rows newer than its version), so the head is what was handed out.
        self.note_handed_out(&head.epoch, head.version);
        Ok(answered)
    }

    /// The pull capability's handler: parses the payload (ignoring the keys the
    /// router stamps in), answers, and returns the reply object. The error text
    /// starts with a stable prefix (`replica_schema_unsupported:` and others).
    ///
    /// A `Value` object keeps `serde_json`'s key order, not the contract's; the
    /// node decodes it into [`PullReply`] and writes the device's bytes from the
    /// typed form. Use [`Collection::answer`] for the typed reply.
    pub fn pull<S, L>(&self, store: &S, request: &Value, load: L) -> Result<Value, String>
    where
        S: LedgerStore + ?Sized,
        L: FnMut(&S, Option<&[String]>) -> Result<Vec<Row>, String>,
    {
        let request: PullRequest = serde_json::from_value(request.clone())
            .map_err(|error| ReplicaError::InvalidRequest(error.to_string()).to_string())?;
        let answered = self
            .answer(store, &request, load)
            .map_err(|error| error.to_string())?;
        serde_json::to_value(&answered.reply)
            .map_err(|error| ReplicaError::Store(error.to_string()).to_string())
    }

    /// Tells the node this collection's head (`core.replica.announce`). Call it
    /// after a write that moved the head and once at app start. When the node
    /// answers `{"rotate":true}` the helper rotates the epoch and announces again.
    pub fn announce<S: LedgerStore + ?Sized>(
        &self,
        store: &S,
        bus: &dyn Announcer,
    ) -> AnnounceOutcome {
        let outcome = self.announce_inner(store, bus);
        if outcome.is_ok() {
            self.announce_failing.store(false, Ordering::Relaxed);
        }
        outcome.unwrap_or_else(|error| AnnounceOutcome::Failed {
            error,
            first: !self.announce_failing.swap(true, Ordering::Relaxed),
        })
    }

    fn announce_inner<S: LedgerStore + ?Sized>(
        &self,
        store: &S,
        bus: &dyn Announcer,
    ) -> Result<AnnounceOutcome, String> {
        let head = self.head(store).map_err(|error| error.to_string())?;
        if send_announce(self.name, &head, bus)? == AnnounceReply::Ok {
            self.note_handed_out(&head.epoch, head.version);
            return Ok(AnnounceOutcome::Accepted(head));
        }
        // The node has handed out a higher version of this epoch: the database
        // went back in time. That rotates at once, whatever the rate limit says
        // (`ledger::rotate_now`). When another writer rotated since the head was
        // read, that already answers the node. The process keeps what it learnt,
        // so a later restore to this epoch, before any announce, is caught too.
        self.note_handed_out(&head.epoch, head.version.saturating_add(1));
        let new_head = self
            .with_record(store, |tx, spec, record, rotated| {
                if !rotated && record.epoch == head.epoch {
                    ledger::rotate_now(tx, spec, record)?;
                }
                Ok(Head::from(&*record))
            })
            .map_err(|error| error.to_string())?;
        match send_announce(self.name, &new_head, bus)? {
            AnnounceReply::Ok => {
                self.note_handed_out(&new_head.epoch, new_head.version);
                Ok(AnnounceOutcome::Rotated(new_head))
            }
            // A fresh epoch cannot be behind anything the node remembers; a node
            // that still says so is answered on the next announce.
            AnnounceReply::Rotate => Ok(AnnounceOutcome::RotationDeferred(new_head)),
        }
    }

    /// The description for this capability's `provided_capabilities` entry.
    pub fn description(&self) -> String {
        let schemas = self
            .schemas
            .iter()
            .map(u32::to_string)
            .collect::<Vec<_>>()
            .join(", ");
        format!(
            "Replicated collection served by node-app-replica (Phase 3 contract). Request \
             {{\"e\":<epoch held, \"\" for none>,\"v\":<version held>,\"s\":<schema>,\"l\":<row limit, \
             at most 500>,\"a\":<resume key, optional>}}. Reply {{\"e\",\"v\"}} when nothing is new; \
             {{\"e\",\"v\",\"u\":[[key,value,ord?,part?]...],\"x\":[key...],\"m\":1?}} with the \
             changes since v; or {{\"e\",\"v\",\"f\":1,\"u\":[...],\"n\":<next key>?}}, a full copy in \
             key order. Schemas served: {schemas}. Called by the node (core.replica.sync), not by devices."
        )
    }
}

fn send_announce(
    capability: &str,
    head: &Head,
    bus: &dyn Announcer,
) -> Result<AnnounceReply, String> {
    let payload = Announce {
        capability: capability.to_string(),
        epoch: head.epoch.clone(),
        version: head.version,
    };
    let payload = serde_json::to_value(&payload).map_err(|error| error.to_string())?;
    let reply = bus.invoke(wire::ANNOUNCE_CAPABILITY, payload)?;
    serde_json::from_value(reply).map_err(|error| format!("unexpected announce reply: {error}"))
}