Skip to main content

node_app_replica/
lib.rs

1//! # node-app-replica
2//!
3//! Change-only replication of app data (Phase 3 of the one-stack design,
4//! `docs/superpowers/specs/2026-11-19-one-stack-phase-3-replication.md`).
5//!
6//! An app backend declares each collection once, as a [`Collection`] bound to
7//! its pull capability (`friends.people.pull`), and tells it what changed —
8//! either the whole current list ([`Collection::reconcile`]) or one row at a time
9//! at its write sites ([`Collection::touch`], [`Collection::remove`]). The helper
10//! keeps a small ledger in the app's own database (keys, digests, versions,
11//! tombstones; never the rows) and from it answers the node's pull with one of
12//! three replies: nothing new, the changes since the caller's version, or a full
13//! copy under a new or the same epoch. The app writes no versioning code.
14//!
15//! ```no_run
16//! # #[cfg(feature = "sqlite")]
17//! # fn demo(conn: &rusqlite::Connection, request: &serde_json::Value) -> Result<(), String> {
18//! use node_app_replica::{Collection, Row};
19//! use serde_json::json;
20//!
21//! static PEOPLE: Collection = Collection::new("friends.people.pull", "friends_", &[1]);
22//!
23//! PEOPLE.ensure(conn).map_err(|e| e.to_string())?;
24//! PEOPLE
25//!     .reconcile(conn, &[Row::new("did:key:z6Mk…", json!({ "name": "Alice" }))])
26//!     .map_err(|e| e.to_string())?;
27//! let reply = PEOPLE.pull(conn, request, |_conn, _keys| {
28//!     Ok(vec![Row::new("did:key:z6Mk…", json!({ "name": "Alice" }))])
29//! })?;
30//! # let _ = reply; Ok(())
31//! # }
32//! ```
33//!
34//! The crate depends on `serde`, `serde_json` and `sha2` only (plus `rusqlite`
35//! behind the `sqlite` feature) and not on `node-app-sdk-rust`, so an app pinned
36//! to any SDK version can use it. [`Announcer`] is the one seam to the node's
37//! capability bus; implement it with the SDK's `invoke_capability`.
38
39#![warn(missing_docs)]
40
41pub mod digest;
42mod ledger;
43#[cfg(feature = "sqlite")]
44mod sqlite;
45pub mod store;
46pub mod wire;
47
48use std::fmt;
49use std::hash::{BuildHasher, Hasher};
50use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
51use std::sync::{Mutex, PoisonError};
52use std::time::{SystemTime, UNIX_EPOCH};
53
54use serde_json::Value;
55use sha2::{Digest, Sha256};
56
57pub use ledger::{
58    Head, Horizon, ROTATION_MIN_INTERVAL_MS, TOMBSTONE_MAX_AGE_MS, TOMBSTONE_MAX_COUNT,
59};
60pub use store::{CollectionRecord, LedgerEntry, LedgerStore, LedgerTx, MemoryLedger, Pruned};
61pub use wire::{
62    Announce, AnnounceReply, HeadsData, PullReply, PullRequest, PushedHead, Row, SyncAnswer,
63    SyncEntry, SyncErrorCode, SyncReply, SyncRequest, WindowDays, WindowedAnnounce,
64    WindowedPullRequest, WindowedSyncEntry, WindowedSyncRequest,
65};
66
67/// Why a ledger operation or a pull failed. `Display` starts with a stable
68/// prefix, so the text can go straight into the capability error channel.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum ReplicaError {
71    /// The collection's declaration is unusable (its name or table prefix).
72    Config(String),
73    /// A row outside the contract's limits, or a key listed twice.
74    InvalidRow {
75        /// The row's key (its first 64 characters).
76        key: String,
77        /// What is wrong with it.
78        reason: String,
79    },
80    /// A pull request outside the contract.
81    InvalidRequest(String),
82    /// The pull asked for a schema this collection does not serve.
83    SchemaUnsupported {
84        /// The pull capability.
85        capability: String,
86        /// The schema number asked for.
87        schema: u32,
88    },
89    /// The app's `load` callback failed.
90    Load(String),
91    /// The ledger's store failed.
92    Store(String),
93}
94
95impl fmt::Display for ReplicaError {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        match self {
98            ReplicaError::Config(reason) => write!(f, "replica_config_invalid: {reason}"),
99            ReplicaError::InvalidRow { key, reason } => {
100                write!(f, "replica_row_invalid: row '{key}': {reason}")
101            }
102            ReplicaError::InvalidRequest(reason) => {
103                write!(f, "replica_request_invalid: {reason}")
104            }
105            ReplicaError::SchemaUnsupported { capability, schema } => write!(
106                f,
107                "{} schema {schema} is not served by {capability}",
108                wire::SCHEMA_UNSUPPORTED_PREFIX
109            ),
110            ReplicaError::Load(reason) => write!(f, "replica_load_failed: {reason}"),
111            ReplicaError::Store(reason) => write!(f, "replica_store_failed: {reason}"),
112        }
113    }
114}
115
116impl std::error::Error for ReplicaError {}
117
118/// Where the helper reads the time and draws new epochs.
119pub trait Environment: Sync {
120    /// Unix time in milliseconds.
121    fn now_ms(&self) -> u64;
122    /// A fresh epoch: `[a-z0-9]{1,16}`, different from every earlier one with
123    /// overwhelming probability.
124    fn new_epoch(&self) -> String;
125}
126
127/// The system clock and an 8-character random epoch.
128#[derive(Debug, Clone, Copy, Default)]
129pub struct SystemEnvironment;
130
131impl Environment for SystemEnvironment {
132    fn now_ms(&self) -> u64 {
133        SystemTime::now()
134            .duration_since(UNIX_EPOCH)
135            .map(|elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX))
136            .unwrap_or(0)
137    }
138
139    fn new_epoch(&self) -> String {
140        random_epoch()
141    }
142}
143
144/// 8 characters of `[a-z0-9]` (36^8 ≈ 2.8 × 10^12 values). The entropy is the
145/// standard library's per-process random hash keys (seeded from the operating
146/// system), a process-wide counter, the time and the process id, through
147/// SHA-256. An epoch is not a secret; it must only not repeat.
148fn random_epoch() -> String {
149    static COUNTER: AtomicU64 = AtomicU64::new(0);
150    let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
151    hasher.write_u64(COUNTER.fetch_add(1, Ordering::Relaxed));
152    let mut sha = Sha256::new();
153    sha.update(hasher.finish().to_le_bytes());
154    sha.update(
155        SystemTime::now()
156            .duration_since(UNIX_EPOCH)
157            .map(|elapsed| elapsed.as_nanos())
158            .unwrap_or(0)
159            .to_le_bytes(),
160    );
161    sha.update(std::process::id().to_le_bytes());
162    let hash = sha.finalize();
163    const ALPHABET: &[u8; 36] = b"abcdefghijklmnopqrstuvwxyz0123456789";
164    hash.iter()
165        .take(8)
166        .map(|byte| char::from(ALPHABET[usize::from(*byte) % ALPHABET.len()]))
167        .collect()
168}
169
170/// The app's door to the node's capability bus, for `core.replica.announce`.
171/// Implement it with the SDK's `invoke_capability`.
172pub trait Announcer {
173    /// Invokes `capability` with `payload` and returns the reply's payload, or the
174    /// error text when the capability failed or does not exist.
175    fn invoke(&self, capability: &str, payload: Value) -> Result<Value, String>;
176}
177
178/// The result of an announce. An announce never fails the app's own work, but
179/// until one lands the node answers a device that holds the head it remembers
180/// with "nothing new" without calling the app, so devices do not see the change.
181/// The helper does not retry: [`Collection::announce`] is one synchronous call,
182/// and the app retries a `Failed` (or `RotationDeferred`) announce on its own
183/// schedule (see the README's "Announce").
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub enum AnnounceOutcome {
186    /// The node took the head.
187    Accepted(Head),
188    /// The node remembered a higher version in this epoch (the app's database
189    /// went back in time); the helper rotated the epoch and announced the new head.
190    Rotated(Head),
191    /// The node answered `rotate` again to the head of a fresh epoch, which a
192    /// node that keeps its marks never does. The head stays; the next announce
193    /// asks again.
194    RotationDeferred(Head),
195    /// The announce failed. `first` is true for the first failure after a
196    /// success (or since start), so the app logs it once.
197    Failed {
198        /// Why it failed.
199        error: String,
200        /// The first failure since the last success (or since start).
201        first: bool,
202    },
203}
204
205/// A pull's answer and whether the pull moved the ledger's head (a dirty
206/// reconcile, a write the app had not reported, or a rotation): when it did, the
207/// app announces, so other devices hear of it.
208#[derive(Debug, Clone, PartialEq)]
209pub struct Answered {
210    /// The reply for the node.
211    pub reply: PullReply,
212    /// The pull moved the head: announce.
213    pub head_moved: bool,
214}
215
216/// One replicated collection: its pull capability, the prefix of the ledger's
217/// tables, and the schema numbers it serves. Declare it as a `static`.
218pub struct Collection {
219    name: &'static str,
220    table_prefix: &'static str,
221    schemas: &'static [u32],
222    env: &'static dyn Environment,
223    horizon: Horizon,
224    announce_failing: AtomicBool,
225    /// The highest version this process has handed out (in a pull reply, or in
226    /// an announce the node took) or heard the node has (its `rotate`), per
227    /// epoch, most recent epoch first. A ledger that reads lower in the same
228    /// epoch went back in time.
229    handed_out: Mutex<Vec<(String, u64)>>,
230}
231
232/// Epochs whose hand-out mark a process keeps; a restore to an epoch older than
233/// these is still caught by the node's marks and by devices ahead.
234const HANDED_OUT_EPOCHS: usize = 16;
235
236impl fmt::Debug for Collection {
237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238        f.debug_struct("Collection")
239            .field("name", &self.name)
240            .field("table_prefix", &self.table_prefix)
241            .field("schemas", &self.schemas)
242            .field("horizon", &self.horizon)
243            .finish()
244    }
245}
246
247impl Collection {
248    /// `pull_capability` is `<app>.<collection>.pull` and names the collection in
249    /// the ledger; `table_prefix` (`[A-Za-z0-9_]{0,48}`) names the ledger's tables
250    /// (`friends_` → `friends_replica_collections`, `friends_replica_rows`);
251    /// `schemas` are the `N`s of the `.vN` names this app serves.
252    pub const fn new(
253        pull_capability: &'static str,
254        table_prefix: &'static str,
255        schemas: &'static [u32],
256    ) -> Self {
257        Self {
258            name: pull_capability,
259            table_prefix,
260            schemas,
261            env: &SystemEnvironment,
262            horizon: Horizon::DEFAULT,
263            announce_failing: AtomicBool::new(false),
264            handed_out: Mutex::new(Vec::new()),
265        }
266    }
267
268    /// Replaces the clock and the epoch source.
269    pub const fn with_environment(mut self, env: &'static dyn Environment) -> Self {
270        self.env = env;
271        self
272    }
273
274    /// Replaces the tombstone horizon (default 30 days and 5,000 per collection).
275    pub const fn with_tombstone_horizon(mut self, max_age_ms: u64, max_count: u64) -> Self {
276        self.horizon = Horizon {
277            max_age_ms,
278            max_count,
279        };
280        self
281    }
282
283    /// The pull capability.
284    pub fn name(&self) -> &'static str {
285        self.name
286    }
287
288    /// The schema numbers this collection serves.
289    pub fn schemas(&self) -> &'static [u32] {
290        self.schemas
291    }
292
293    fn spec(&self) -> ledger::Spec<'_> {
294        ledger::Spec {
295            name: self.name,
296            schemas: self.schemas,
297            env: self.env,
298            horizon: self.horizon,
299        }
300    }
301
302    fn check(&self) -> Result<(), ReplicaError> {
303        let segments: Vec<&str> = self.name.split('.').collect();
304        let segment_ok = |segment: &&str| {
305            let mut chars = segment.chars();
306            chars.next().is_some_and(|c| c.is_ascii_lowercase())
307                && chars
308                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
309        };
310        if segments.len() < 3
311            || segments.last() != Some(&"pull")
312            || !segments.iter().all(segment_ok)
313        {
314            return Err(ReplicaError::Config(format!(
315                "'{}' is not a pull capability '<app>.<collection>.pull'",
316                self.name
317            )));
318        }
319        if self.name.starts_with("core.") {
320            return Err(ReplicaError::Config(format!(
321                "'{}' is in the reserved 'core.' namespace",
322                self.name
323            )));
324        }
325        // The prefix starts SQL identifiers (`<prefix>replica_rows`), which may not
326        // start with a digit.
327        if self.table_prefix.len() > 48
328            || self.table_prefix.starts_with(|c: char| c.is_ascii_digit())
329            || !self
330                .table_prefix
331                .bytes()
332                .all(|b| b.is_ascii_alphanumeric() || b == b'_')
333        {
334            return Err(ReplicaError::Config(format!(
335                "table prefix '{}' must be [A-Za-z_][A-Za-z0-9_]{{0,47}} or empty",
336                self.table_prefix
337            )));
338        }
339        if self.horizon.max_count == 0 {
340            return Err(ReplicaError::Config(
341                "the tombstone horizon must keep at least one tombstone".to_string(),
342            ));
343        }
344        Ok(())
345    }
346
347    /// The hand-out mark of `epoch` in this process.
348    fn handed_out(&self, epoch: &str) -> Option<u64> {
349        let marks = self
350            .handed_out
351            .lock()
352            .unwrap_or_else(PoisonError::into_inner);
353        marks.iter().find(|(e, _)| e == epoch).map(|(_, v)| *v)
354    }
355
356    /// Records that this process handed out `version` of `epoch` (a pull reply
357    /// was returned, or the node took an announce).
358    fn note_handed_out(&self, epoch: &str, version: u64) {
359        let mut marks = self
360            .handed_out
361            .lock()
362            .unwrap_or_else(PoisonError::into_inner);
363        let mark = match marks.iter().position(|(e, _)| e == epoch) {
364            Some(index) => marks.remove(index).1.max(version),
365            None => version,
366        };
367        marks.insert(0, (epoch.to_string(), mark));
368        marks.truncate(HANDED_OUT_EPOCHS);
369    }
370
371    /// The ledger reads below what this process handed out in its epoch: the
372    /// database went back in time (a restore, while the app kept running).
373    fn went_back(&self, record: &CollectionRecord) -> bool {
374        self.handed_out(&record.epoch)
375            .is_some_and(|mark| mark > record.version)
376    }
377
378    /// Runs `work` on this collection's record in one write transaction and
379    /// writes the record back. Before the work, a database that went back in time
380    /// rotates the epoch, and so does an owed rotation whose minute has passed;
381    /// `work` is told whether that happened.
382    fn with_record<S, R>(
383        &self,
384        store: &S,
385        mut work: impl FnMut(
386            &mut dyn LedgerTx,
387            &ledger::Spec<'_>,
388            &mut CollectionRecord,
389            bool,
390        ) -> Result<R, ReplicaError>,
391    ) -> Result<R, ReplicaError>
392    where
393        S: LedgerStore + ?Sized,
394    {
395        self.check()?;
396        let spec = self.spec();
397        let mut out = None;
398        store.write(self.table_prefix, &mut |tx| {
399            let mut record = ledger::open(tx, &spec)?;
400            let before = record.clone();
401            let went_back = self.went_back(&record);
402            let rotated = ledger::begin(tx, &spec, &mut record, went_back)?;
403            let result = work(tx, &spec, &mut record, rotated)?;
404            if record != before {
405                tx.put_record(spec.name, &record)?;
406            }
407            out = Some(result);
408            Ok(())
409        })?;
410        out.ok_or_else(|| ReplicaError::Store("the store did not run the ledger work".to_string()))
411    }
412
413    /// The committed record when a read can stand for a write: it exists, did not
414    /// go back in time, and no owed rotation is due. `None` sends the caller to
415    /// the write path.
416    fn read_settled<S: LedgerStore + ?Sized>(
417        &self,
418        store: &S,
419    ) -> Result<Option<CollectionRecord>, ReplicaError> {
420        self.check()?;
421        let record = store.read_record(self.table_prefix, self.name)?;
422        Ok(record
423            .filter(|record| !self.went_back(record) && ledger::nothing_due(&self.spec(), record)))
424    }
425
426    /// Creates the ledger's tables if they do not exist. Call it where the app
427    /// creates its own tables, on every start: it is idempotent.
428    pub fn ensure<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<(), ReplicaError> {
429        self.check()?;
430        store.ensure(self.table_prefix)
431    }
432
433    /// Whole-list mode: hand over every current row; the helper finds what
434    /// changed. Returns the new head version when the head moved. Rows are checked
435    /// against the contract's limits first; one bad row refuses the whole list.
436    pub fn reconcile<S: LedgerStore + ?Sized>(
437        &self,
438        store: &S,
439        rows: &[Row],
440    ) -> Result<Option<u64>, ReplicaError> {
441        self.with_record(store, |tx, spec, record, _| {
442            let before = Head::from(&*record);
443            ledger::reconcile(tx, spec, record, rows)?;
444            Ok((Head::from(&*record) != before).then_some(record.version))
445        })
446    }
447
448    /// Records one row written at a write site. Returns the head version.
449    pub fn touch<S: LedgerStore + ?Sized>(
450        &self,
451        store: &S,
452        row: &Row,
453    ) -> Result<u64, ReplicaError> {
454        self.with_record(store, |tx, spec, record, _| {
455            ledger::touch(tx, spec, record, row)?;
456            Ok(record.version)
457        })
458    }
459
460    /// Records one row deleted at a write site. Returns the head version.
461    pub fn remove<S: LedgerStore + ?Sized>(
462        &self,
463        store: &S,
464        key: &str,
465    ) -> Result<u64, ReplicaError> {
466        self.with_record(store, |tx, spec, record, _| {
467            ledger::remove(tx, spec, record, key)?;
468            Ok(record.version)
469        })
470    }
471
472    /// "Something may have changed": the next pull reconciles before answering.
473    pub fn mark_dirty<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<(), ReplicaError> {
474        self.with_record(store, |_tx, _spec, record, _| {
475            record.dirty = true;
476            Ok(())
477        })
478    }
479
480    /// Starts a new epoch (the app's data was replaced) and marks the collection
481    /// dirty. Every device takes one full copy. Returns whether it rotated now;
482    /// within a minute of the last rotation the rotation is owed instead (it
483    /// happens before the next version is assigned, or at the first ledger
484    /// operation after the minute). The collection is marked dirty either way.
485    ///
486    /// A database restored from a backup needs no call: the helper finds that
487    /// out by itself (a device ahead of the head, the node's `rotate`, or this
488    /// process having handed out more) and rotates at once.
489    pub fn reset<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<bool, ReplicaError> {
490        self.with_record(store, |tx, spec, record, rotated| {
491            let rotated = rotated || ledger::request_rotation(tx, spec, record)?;
492            record.dirty = true;
493            Ok(rotated)
494        })
495    }
496
497    /// The ledger's head: what an announce reports. A plain read of the committed
498    /// header (no write lock), unless the ledger has none yet, went back in time
499    /// or owes a rotation that is due: then the write path settles that first.
500    pub fn head<S: LedgerStore + ?Sized>(&self, store: &S) -> Result<Head, ReplicaError> {
501        if let Some(record) = self.read_settled(store)? {
502            return Ok(Head::from(&record));
503        }
504        self.with_record(store, |_tx, _spec, record, _| Ok(Head::from(&*record)))
505    }
506
507    /// Answers one pull. `load` returns the app's current rows: every row for
508    /// `None`, else the rows of the given keys (keys with no row are left out).
509    /// It runs inside the ledger's write transaction, so on SQLite it reads the
510    /// same snapshot the ledger does; it must not call this collection again.
511    pub fn answer<S, L>(
512        &self,
513        store: &S,
514        request: &PullRequest,
515        mut load: L,
516    ) -> Result<Answered, ReplicaError>
517    where
518        S: LedgerStore + ?Sized,
519        L: FnMut(&S, Option<&[String]>) -> Result<Vec<Row>, String>,
520    {
521        ledger::check_request(&self.spec(), request)?;
522        // The common case, a device at the head, is one read and no write lock.
523        if request.resume.is_none() {
524            if let Some(record) = self.read_settled(store)? {
525                if !record.dirty
526                    && record.epoch == request.epoch
527                    && record.version == request.version
528                {
529                    self.note_handed_out(&record.epoch, record.version);
530                    return Ok(Answered {
531                        reply: PullReply::NothingNew {
532                            epoch: record.epoch,
533                            version: record.version,
534                        },
535                        head_moved: false,
536                    });
537                }
538            }
539        }
540        let (answered, head) = self.with_record(store, |tx, spec, record, rotated| {
541            let before = Head::from(&*record);
542            let mut load_rows =
543                |keys: Option<&[String]>| load(store, keys).map_err(ReplicaError::Load);
544            let reply = ledger::answer(tx, spec, record, request, &mut load_rows)?;
545            let head = Head::from(&*record);
546            Ok((
547                Answered {
548                    reply,
549                    head_moved: rotated || head != before,
550                },
551                head,
552            ))
553        })?;
554        // Every reply may carry rows up to the head (a later page of a full copy
555        // carries rows newer than its version), so the head is what was handed out.
556        self.note_handed_out(&head.epoch, head.version);
557        Ok(answered)
558    }
559
560    /// The pull capability's handler: parses the payload (ignoring the keys the
561    /// router stamps in), answers, and returns the reply object. The error text
562    /// starts with a stable prefix (`replica_schema_unsupported:` and others).
563    ///
564    /// A `Value` object keeps `serde_json`'s key order, not the contract's; the
565    /// node decodes it into [`PullReply`] and writes the device's bytes from the
566    /// typed form. Use [`Collection::answer`] for the typed reply.
567    pub fn pull<S, L>(&self, store: &S, request: &Value, load: L) -> Result<Value, String>
568    where
569        S: LedgerStore + ?Sized,
570        L: FnMut(&S, Option<&[String]>) -> Result<Vec<Row>, String>,
571    {
572        let request: PullRequest = serde_json::from_value(request.clone())
573            .map_err(|error| ReplicaError::InvalidRequest(error.to_string()).to_string())?;
574        let answered = self
575            .answer(store, &request, load)
576            .map_err(|error| error.to_string())?;
577        serde_json::to_value(&answered.reply)
578            .map_err(|error| ReplicaError::Store(error.to_string()).to_string())
579    }
580
581    /// Tells the node this collection's head (`core.replica.announce`). Call it
582    /// after a write that moved the head and once at app start. When the node
583    /// answers `{"rotate":true}` the helper rotates the epoch and announces again.
584    pub fn announce<S: LedgerStore + ?Sized>(
585        &self,
586        store: &S,
587        bus: &dyn Announcer,
588    ) -> AnnounceOutcome {
589        let outcome = self.announce_inner(store, bus);
590        if outcome.is_ok() {
591            self.announce_failing.store(false, Ordering::Relaxed);
592        }
593        outcome.unwrap_or_else(|error| AnnounceOutcome::Failed {
594            error,
595            first: !self.announce_failing.swap(true, Ordering::Relaxed),
596        })
597    }
598
599    fn announce_inner<S: LedgerStore + ?Sized>(
600        &self,
601        store: &S,
602        bus: &dyn Announcer,
603    ) -> Result<AnnounceOutcome, String> {
604        let head = self.head(store).map_err(|error| error.to_string())?;
605        if send_announce(self.name, &head, bus)? == AnnounceReply::Ok {
606            self.note_handed_out(&head.epoch, head.version);
607            return Ok(AnnounceOutcome::Accepted(head));
608        }
609        // The node has handed out a higher version of this epoch: the database
610        // went back in time. That rotates at once, whatever the rate limit says
611        // (`ledger::rotate_now`). When another writer rotated since the head was
612        // read, that already answers the node. The process keeps what it learnt,
613        // so a later restore to this epoch, before any announce, is caught too.
614        self.note_handed_out(&head.epoch, head.version.saturating_add(1));
615        let new_head = self
616            .with_record(store, |tx, spec, record, rotated| {
617                if !rotated && record.epoch == head.epoch {
618                    ledger::rotate_now(tx, spec, record)?;
619                }
620                Ok(Head::from(&*record))
621            })
622            .map_err(|error| error.to_string())?;
623        match send_announce(self.name, &new_head, bus)? {
624            AnnounceReply::Ok => {
625                self.note_handed_out(&new_head.epoch, new_head.version);
626                Ok(AnnounceOutcome::Rotated(new_head))
627            }
628            // A fresh epoch cannot be behind anything the node remembers; a node
629            // that still says so is answered on the next announce.
630            AnnounceReply::Rotate => Ok(AnnounceOutcome::RotationDeferred(new_head)),
631        }
632    }
633
634    /// The description for this capability's `provided_capabilities` entry.
635    pub fn description(&self) -> String {
636        let schemas = self
637            .schemas
638            .iter()
639            .map(u32::to_string)
640            .collect::<Vec<_>>()
641            .join(", ");
642        format!(
643            "Replicated collection served by node-app-replica (Phase 3 contract). Request \
644             {{\"e\":<epoch held, \"\" for none>,\"v\":<version held>,\"s\":<schema>,\"l\":<row limit, \
645             at most 500>,\"a\":<resume key, optional>}}. Reply {{\"e\",\"v\"}} when nothing is new; \
646             {{\"e\",\"v\",\"u\":[[key,value,ord?,part?]...],\"x\":[key...],\"m\":1?}} with the \
647             changes since v; or {{\"e\",\"v\",\"f\":1,\"u\":[...],\"n\":<next key>?}}, a full copy in \
648             key order. Schemas served: {schemas}. Called by the node (core.replica.sync), not by devices."
649        )
650    }
651}
652
653fn send_announce(
654    capability: &str,
655    head: &Head,
656    bus: &dyn Announcer,
657) -> Result<AnnounceReply, String> {
658    let payload = Announce {
659        capability: capability.to_string(),
660        epoch: head.epoch.clone(),
661        version: head.version,
662    };
663    let payload = serde_json::to_value(&payload).map_err(|error| error.to_string())?;
664    let reply = bus.invoke(wire::ANNOUNCE_CAPABILITY, payload)?;
665    serde_json::from_value(reply).map_err(|error| format!("unexpected announce reply: {error}"))
666}