node-app-replica 7.7.7

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
//! Row digests (Phase 3 spec, section 5.1).
//!
//! The ledger keeps a digest of each row instead of the row: SHA-256 of the
//! canonical JSON of `[value, ord, part]`, truncated to 16 bytes and written as
//! 32 hex characters. Canonical JSON is compact and sorts object keys by their
//! UTF-8 bytes; strings are escaped exactly as `serde_json` escapes them, so the
//! canonical length of a value is also its compact encoded size. The digest
//! never leaves the app.

use std::fmt::Write as _;

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

use crate::wire::Row;

/// Appends the canonical JSON of `value` to `out`.
pub fn write_canonical(value: &Value, out: &mut String) {
    match value {
        Value::Null => out.push_str("null"),
        Value::Bool(true) => out.push_str("true"),
        Value::Bool(false) => out.push_str("false"),
        Value::Number(number) => {
            // Writing to a String cannot fail.
            let _ = write!(out, "{number}");
        }
        Value::String(text) => write_json_string(text, out),
        Value::Array(items) => {
            out.push('[');
            for (index, item) in items.iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                write_canonical(item, out);
            }
            out.push(']');
        }
        Value::Object(object) => {
            // serde_json's default map is already sorted; with `preserve_order`
            // unified into the build it is not, and the entries are sorted here.
            let sorted = object.keys().zip(object.keys().skip(1)).all(|(a, b)| a < b);
            out.push('{');
            if sorted {
                write_entries(object.iter(), out);
            } else {
                let mut entries: Vec<(&String, &Value)> = object.iter().collect();
                entries.sort_by(|a, b| a.0.cmp(b.0));
                write_entries(entries.into_iter(), out);
            }
            out.push('}');
        }
    }
}

fn write_entries<'v>(entries: impl Iterator<Item = (&'v String, &'v Value)>, out: &mut String) {
    for (index, (key, item)) in entries.enumerate() {
        if index > 0 {
            out.push(',');
        }
        write_json_string(key, out);
        out.push(':');
        write_canonical(item, out);
    }
}

/// The canonical JSON of `value`.
pub fn canonical_json(value: &Value) -> String {
    let mut out = String::new();
    write_canonical(value, &mut out);
    out
}

/// The canonical (and compact) encoded size of `value`, in bytes.
pub fn canonical_len(value: &Value) -> usize {
    match value {
        Value::Null => 4,
        Value::Bool(true) => 4,
        Value::Bool(false) => 5,
        Value::Number(number) => number.to_string().len(),
        Value::String(text) => json_len_of_str(text),
        Value::Array(items) => {
            2 + items.iter().map(canonical_len).sum::<usize>() + items.len().saturating_sub(1)
        }
        Value::Object(object) => {
            2 + object
                .iter()
                .map(|(key, item)| json_len_of_str(key) + 1 + canonical_len(item))
                .sum::<usize>()
                + object.len().saturating_sub(1)
        }
    }
}

/// `serde_json`'s escaping: `"` and `\`, the short forms `\b \f \n \r \t`, and
/// `\u00XX` for the other control characters below 0x20. Everything else, DEL
/// and non-ASCII included, is written as is.
fn write_json_string(text: &str, out: &mut String) {
    out.push('"');
    if !text.bytes().any(|b| b == b'"' || b == b'\\' || b < 0x20) {
        out.push_str(text);
        out.push('"');
        return;
    }
    for ch in text.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\u{08}' => out.push_str("\\b"),
            '\u{0c}' => out.push_str("\\f"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            ch if (ch as u32) < 0x20 => {
                out.push_str("\\u00");
                out.push(hex_digit((ch as u32 >> 4) as u8));
                out.push(hex_digit((ch as u32 & 0xf) as u8));
            }
            ch => out.push(ch),
        }
    }
    out.push('"');
}

/// The encoded size of a JSON string, quotes included.
pub(crate) fn json_len_of_str(text: &str) -> usize {
    2 + text
        .chars()
        .map(|ch| match ch {
            '"' | '\\' | '\u{08}' | '\u{0c}' | '\n' | '\r' | '\t' => 2,
            ch if (ch as u32) < 0x20 => 6,
            ch => ch.len_utf8(),
        })
        .sum::<usize>()
}

fn hex_digit(nibble: u8) -> char {
    char::from(b"0123456789abcdef"[usize::from(nibble & 0xf)])
}

/// The ledger digest of a row: what changes when its value, order or group does.
pub fn row_digest(row: &Row) -> String {
    digest_and_value_len(row).0
}

/// The row's digest and its value's canonical (encoded) size, from one pass over
/// the value: a whole-list reconcile computes both for every row.
pub(crate) fn digest_and_value_len(row: &Row) -> (String, usize) {
    let mut canonical = String::with_capacity(256);
    canonical.push('[');
    write_canonical(&row.value, &mut canonical);
    let value_len = canonical.len() - 1;
    let _ = write!(canonical, ",{},", row.ord);
    write_json_string(&row.part, &mut canonical);
    canonical.push(']');
    let hash = Sha256::digest(canonical.as_bytes());
    let mut out = String::with_capacity(32);
    for byte in hash.iter().take(16) {
        out.push(hex_digit(byte >> 4));
        out.push(hex_digit(*byte));
    }
    (out, value_len)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn canonical_json_sorts_keys_and_matches_compact_serde_for_strings() {
        let value = json!({"b": [1, 2.5, "x\"\\\n\u{1}\u{7f}é"], "a": {"d": null, "c": true}});
        assert_eq!(
            canonical_json(&value),
            "{\"a\":{\"c\":true,\"d\":null},\"b\":[1,2.5,\"x\\\"\\\\\\n\\u0001\u{7f}é\"]}"
        );
        // Same bytes as serde_json for the string, whatever the map order.
        let text = Value::String("x\"\\\n\u{1}\u{8}\u{c}\t\r\u{1f}\u{7f}é".into());
        assert_eq!(canonical_json(&text), serde_json::to_string(&text).unwrap());
        assert_eq!(canonical_len(&value), canonical_json(&value).len());
        assert_eq!(canonical_len(&text), canonical_json(&text).len());
    }

    #[test]
    fn digest_ignores_key_order_and_sees_value_ord_and_part() {
        let a = Row::new("k", json!({"x": 1, "y": 2}));
        let b = Row::new("k", serde_json::from_str("{\"y\":2,\"x\":1}").unwrap());
        assert_eq!(row_digest(&a), row_digest(&b));
        assert_eq!(row_digest(&a).len(), 32);
        assert_ne!(row_digest(&a), row_digest(&a.clone().with_ord(1)));
        assert_ne!(row_digest(&a), row_digest(&a.clone().with_part("p")));
        assert_ne!(
            row_digest(&a),
            row_digest(&Row::new("k", json!({"x": 1, "y": 3})))
        );
        // The key is not part of the digest: it is the ledger row's identity.
        assert_eq!(
            row_digest(&a),
            row_digest(&Row::new("other", a.value.clone()))
        );
    }
}