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