node-app-replica 7.7.13

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
//! The golden wire fixtures in `tests/fixtures/` (shared with the TypeScript
//! helper and the client kernel): each decodes to its type and encodes back to
//! the same bytes, the ledger produces the pull replies byte for byte, and the
//! "nothing new" exchange has the sizes the contract states (section 4.3).

mod common;

use std::path::PathBuf;

use common::*;
use node_app_replica::wire::{
    Announce, AnnounceReply, HeadsData, PullReply, PullRequest, SyncAnswer, SyncReply, SyncRequest,
};
use node_app_replica::{Collection, Row};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::json;

/// The exact bytes of a fixture: one line of compact JSON and a newline.
fn fixture(name: &str) -> String {
    let path: PathBuf = [env!("CARGO_MANIFEST_DIR"), "tests", "fixtures", name]
        .iter()
        .collect();
    let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{name}: {e}"));
    let body = text
        .strip_suffix('\n')
        .unwrap_or_else(|| panic!("{name} must end in one newline"));
    assert!(!body.contains('\n'), "{name} must be one line");
    body.to_string()
}

fn encode<T: Serialize>(value: &T) -> String {
    serde_json::to_string(value).unwrap()
}

/// Decodes a fixture as `T` and checks it encodes back to the same bytes.
fn round_trip<T: Serialize + DeserializeOwned + std::fmt::Debug>(name: &str) -> T {
    let bytes = fixture(name);
    let value: T = serde_json::from_str(&bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
    assert_eq!(encode(&value), bytes, "{name} does not round-trip");
    value
}

const INVOKE_PREFIX: &str = r#"{"capability":"core.replica.sync","payload":"#;
const REPLY_PREFIX: &str =
    r#"{"success":true,"data":{"capability":"core.replica.sync","provider":"core","result":"#;
const REPLY_SUFFIX: &str = r#"},"timestamp":"2026-11-19T12:34:56.789012345Z"}"#;

/// The existing invoke door's request envelope around a `core.replica.sync` payload.
fn invoke_envelope(payload: &SyncRequest) -> String {
    format!("{INVOKE_PREFIX}{}}}", encode(payload))
}

/// The existing invoke door's reply envelope around a `core.replica.sync` result.
fn reply_envelope(result: &SyncReply) -> String {
    format!("{REPLY_PREFIX}{}{REPLY_SUFFIX}", encode(result))
}

#[test]
fn every_fixture_round_trips_byte_for_byte() {
    round_trip::<PullRequest>("pull-request.json");
    round_trip::<PullRequest>("pull-request-initial.json");
    round_trip::<PullRequest>("pull-request-resume.json");
    let nothing: PullReply = round_trip("pull-reply-nothing-new.json");
    assert!(matches!(nothing, PullReply::NothingNew { version: 41, .. }));
    let changes: PullReply = round_trip("pull-reply-changes.json");
    assert!(matches!(changes, PullReply::Changes { more: false, .. }));
    let more: PullReply = round_trip("pull-reply-changes-more.json");
    assert!(more.is_truncated());
    let page: PullReply = round_trip("pull-reply-full-copy-page.json");
    assert!(matches!(page, PullReply::FullCopy { next: Some(ref n), .. } if n == "b"));
    let last: PullReply = round_trip("pull-reply-full-copy-last.json");
    assert!(!last.is_truncated());
    let later: PullReply = round_trip("pull-reply-full-copy-later-page.json");
    assert_eq!((later.version(), later.handed_out()), (7, 8));
    let announce: Announce = round_trip("announce.json");
    assert_eq!(announce.version, 42);
    assert_eq!(
        round_trip::<AnnounceReply>("announce-reply-ok.json"),
        AnnounceReply::Ok
    );
    assert_eq!(
        round_trip::<AnnounceReply>("announce-reply-rotate.json"),
        AnnounceReply::Rotate
    );
    let mixed: SyncReply = round_trip("sync-result-mixed.json");
    assert_eq!(mixed.answers.len(), 8);
    assert_eq!(mixed.answers[0], SyncAnswer::NothingNew);
    let resume: SyncRequest = round_trip("sync-request-resume.json");
    assert_eq!(resume.entries[0].resume.as_deref(), Some("b"));
    assert_eq!(resume.origin.as_deref(), Some("background"));
}

#[test]
fn the_sync_envelopes_round_trip_byte_for_byte() {
    let request = fixture("sync-request-two.json");
    let payload = request
        .strip_prefix(INVOKE_PREFIX)
        .and_then(|rest| rest.strip_suffix('}'))
        .unwrap();
    let payload: SyncRequest = serde_json::from_str(payload).unwrap();
    assert_eq!(invoke_envelope(&payload), request);

    let reply = fixture("sync-reply-nothing-new-two.json");
    let result = reply
        .strip_prefix(REPLY_PREFIX)
        .and_then(|rest| rest.strip_suffix(REPLY_SUFFIX))
        .unwrap();
    let result: SyncReply = serde_json::from_str(result).unwrap();
    assert_eq!(
        result.answers,
        [SyncAnswer::NothingNew, SyncAnswer::NothingNew]
    );
    assert_eq!(reply_envelope(&result), reply);

    let heads = fixture("heads.json");
    let data = heads
        .strip_prefix(r#"{"type":"replica.heads","data":"#)
        .and_then(|rest| rest.strip_suffix('}'))
        .unwrap();
    let data: HeadsData = serde_json::from_str(data).unwrap();
    assert_eq!(
        format!(r#"{{"type":"replica.heads","data":{}}}"#, encode(&data)),
        heads
    );
}

#[test]
fn a_nothing_new_exchange_has_the_contracts_sizes() {
    // Section 4.3: two collections (Friends) are 141 bytes out and 142 back.
    let request: SyncRequest = {
        let bytes = fixture("sync-request-two.json");
        let payload = &bytes[INVOKE_PREFIX.len()..bytes.len() - 1];
        serde_json::from_str(payload).unwrap()
    };
    assert_eq!(invoke_envelope(&request).len(), 141);
    let two = SyncReply {
        answers: vec![SyncAnswer::NothingNew; 2],
    };
    assert_eq!(reply_envelope(&two).len(), 142);
    // One collection: 92 and 140.
    let one = SyncRequest {
        entries: request.entries[..1].to_vec(),
        origin: None,
    };
    assert_eq!(invoke_envelope(&one).len(), 92);
    let one_reply = SyncReply {
        answers: vec![SyncAnswer::NothingNew],
    };
    assert_eq!(reply_envelope(&one_reply).len(), 140);
    // Under 200 bytes for up to 30 collections.
    let thirty = SyncReply {
        answers: vec![SyncAnswer::NothingNew; 30],
    };
    assert!(reply_envelope(&thirty).len() < 200);
    // Section 4.4 and 4.5: the announce is 49 bytes, a one-head push 77.
    assert_eq!(fixture("announce.json").len(), 49);
    assert_eq!(fixture("heads.json").len(), 77);
}

/// Scenario A: epoch `k3f9a2c1`, rows `r01`…`r41` at versions 1…41.
fn scenario_a() -> (rusqlite::Connection, Collection, AppData) {
    let conn = sqlite();
    let c = collection(TestEnv::leak(T0, &["k3f9a2c1"]));
    c.ensure(&conn).unwrap();
    let rows: Vec<Row> = (1..=41)
        .map(|i| row(&format!("r{i:02}"), json!(i)))
        .collect();
    let data = AppData::with(&rows);
    assert_eq!(c.reconcile(&conn, &data.list()).unwrap(), Some(41));
    (conn, c, data)
}

/// The typed reply's bytes; also checks that the `Value` handler (whose key
/// order is `serde_json`'s map order, not the contract's) says the same.
fn answer(c: &Collection, conn: &rusqlite::Connection, data: &AppData, request: &str) -> String {
    let typed: PullRequest = serde_json::from_str(request).unwrap();
    let reply = c.answer(conn, &typed, data.loader()).unwrap().reply;
    let value = c
        .pull(conn, &serde_json::from_str(request).unwrap(), data.loader())
        .unwrap();
    assert_eq!(value, serde_json::to_value(&reply).unwrap());
    encode(&reply)
}

#[test]
fn the_ledger_produces_the_pull_fixtures() {
    let (conn, c, mut data) = scenario_a();
    let request = fixture("pull-request.json");
    // Nothing new: the device holds the head.
    assert_eq!(
        answer(&c, &conn, &data, &request),
        fixture("pull-reply-nothing-new.json")
    );
    // Alice added (42), r07 removed (43).
    data.put(row("alice", json!({"name": "Alice"})));
    c.touch(&conn, &data.rows["alice"]).unwrap();
    data.rows.remove("r07");
    c.remove(&conn, "r07").unwrap();
    assert_eq!(
        answer(&c, &conn, &data, &request),
        fixture("pull-reply-changes.json")
    );
    let one_at_a_time = request.replace("\"l\":500", "\"l\":1");
    assert_eq!(
        answer(&c, &conn, &data, &one_at_a_time),
        fixture("pull-reply-changes-more.json")
    );

    // Scenario B: epoch p0q9r8s7, head 7, live rows a, b, c.
    let conn = sqlite();
    let c = collection(TestEnv::leak(T0, &["p0q9r8s7"]));
    c.ensure(&conn).unwrap();
    let mut data = AppData::with(&[
        row("a", json!({"n": 1})).with_ord(5).with_part("g1"),
        row("b", json!({"n": 2})).with_ord(-1),
        row("c", json!({"n": 3})),
    ]);
    c.reconcile(&conn, &data.list()).unwrap(); // 1…3
    c.touch(&conn, &row("c", json!({"n": 0}))).unwrap(); // 4
    c.touch(&conn, &data.rows["c"]).unwrap(); // 5
    data.put(row("d", json!(null)));
    c.touch(&conn, &data.rows["d"]).unwrap(); // 6
    data.rows.remove("d");
    c.remove(&conn, "d").unwrap(); // 7
    assert_eq!(
        answer(
            &c,
            &conn,
            &data,
            &fixture("pull-request-initial.json").replace("500", "2")
        ),
        fixture("pull-reply-full-copy-page.json")
    );
    assert_eq!(
        answer(&c, &conn, &data, &fixture("pull-request-resume.json")),
        fixture("pull-reply-full-copy-last.json")
    );
    // c changes while the device pages: the later page carries it as it is now,
    // keeps the copy's version, and tells the node the head it was read at.
    data.put(row("c", json!({"n": 4})));
    c.touch(&conn, &data.rows["c"]).unwrap(); // 8
    assert_eq!(
        answer(&c, &conn, &data, &fixture("pull-request-resume.json")),
        fixture("pull-reply-full-copy-later-page.json")
    );
}

#[test]
fn the_node_turns_pull_replies_into_sync_answers() {
    let decode = |name: &str| -> PullReply { serde_json::from_str(&fixture(name)).unwrap() };
    let result = SyncReply {
        answers: vec![
            decode("pull-reply-nothing-new.json").into(),
            decode("pull-reply-changes.json").into(),
            PullReply::Changes {
                epoch: "k3f9a2c1".into(),
                version: 44,
                upserts: vec![],
                deletes: vec!["r08".into()],
                more: true,
            }
            .into(),
            decode("pull-reply-full-copy-page.json").into(),
            SyncAnswer::Error(node_app_replica::SyncErrorCode::Unknown),
            SyncAnswer::Error(node_app_replica::SyncErrorCode::Schema),
            SyncAnswer::Error(node_app_replica::SyncErrorCode::Unavailable),
            SyncAnswer::Error(node_app_replica::SyncErrorCode::Busy),
        ],
    };
    assert_eq!(encode(&result), fixture("sync-result-mixed.json"));
    // "h" is for the node: the device gets the page without it.
    let later: SyncAnswer = decode("pull-reply-full-copy-later-page.json").into();
    assert_eq!(
        encode(&later),
        r#"{"e":"p0q9r8s7","v":7,"f":1,"u":[["c",{"n":4}]]}"#
    );
    // Each entry of a check becomes exactly the pull request the app's
    // capability receives.
    let request: SyncRequest =
        serde_json::from_str(&fixture("sync-request-two.json")[INVOKE_PREFIX.len()..141 - 1])
            .unwrap();
    assert_eq!(
        encode(&request.entries[0].pull_request(500)),
        fixture("pull-request.json")
    );
}

#[test]
fn decoding_accepts_the_short_forms_and_refuses_the_wrong_shapes() {
    // The router stamps caller fields into every payload; they are ignored.
    let request: PullRequest = serde_json::from_str(
        r#"{"e":"k3f9a2c1","v":41,"s":1,"caller":"core","caller_ingress":"core"}"#,
    )
    .unwrap();
    assert_eq!(request.limit, 500);
    let row: Row = serde_json::from_str(r#"["k",{"a":1}]"#).unwrap();
    assert_eq!((row.ord, row.part.as_str()), (0, ""));
    let row: Row = serde_json::from_str(r#"["k",1,7]"#).unwrap();
    assert_eq!(row.ord, 7);
    // Defaults are dropped again on the way out.
    assert_eq!(encode(&Row::new("k", json!(1)).with_part("")), r#"["k",1]"#);
    assert_eq!(
        encode(&Row::new("k", json!(1)).with_part("p")),
        r#"["k",1,0,"p"]"#
    );
    // A key order the build may not preserve is written sorted.
    let unsorted: serde_json::Value = serde_json::from_str(r#"{"z":1,"a":{"y":2,"b":3}}"#).unwrap();
    assert_eq!(
        encode(&Row::new("k", unsorted)),
        r#"["k",{"a":{"b":3,"y":2},"z":1}]"#
    );

    for bad in [
        r#"["k"]"#,
        r#"["k",1,0,"p","extra"]"#,
        r#"["k",1,"0"]"#,
        r#"[1,1]"#,
    ] {
        assert!(serde_json::from_str::<Row>(bad).is_err(), "{bad}");
    }
    for bad in [
        r#"{"e":"k","v":1,"f":2,"u":[]}"#,
        r#"{"e":"k","v":1,"u":[],"m":0}"#,
        r#"{"v":1}"#,
    ] {
        assert!(serde_json::from_str::<PullReply>(bad).is_err(), "{bad}");
    }
    for bad in [r#"1"#, r#"{"err":"nope"}"#, r#""0""#] {
        assert!(serde_json::from_str::<SyncAnswer>(bad).is_err(), "{bad}");
    }
    assert!(
        serde_json::from_str::<SyncRequest>(r#"{"c":[["a.b.pull",1,"e",1,"k","x"]]}"#).is_err()
    );
    assert!(serde_json::from_str::<AnnounceReply>(r#"{"ok":false}"#).is_err());
}