Cotton code
184 lines · 7.8 KB · RustRaw
//! The canonical form, pinned. A vector here is frozen: if one changes, every//! receipt already stored stops matching its own re-encoding, so a change is//! a new encoder, not a fix.use std::collections::BTreeMap;use serde_json::{json, Value as JsonValue};use super::{    after_codec, canonical_json, canonical_value, decode, encode, Kind, Receipt, EXACT_INTEGER_LIMIT,};use crate::error::StoreError;use crate::schema::decl::Codec;fn receipt(fields: &[(&str, JsonValue)]) -> Receipt {    Receipt {        table: "cotton_todos".to_string(),        row_id: "r1".to_string(),        kind: Kind::Create,        stamp: "0000001700000000:0000:device:a".to_string(),        author: "device:a".to_string(),        actor: "owner:device:a".to_string(),        schema: 7,        restamps: None,        erase: None,        undo: None,        fields: fields            .iter()            // As a caller hands them (`json!(1.0)` is an f64): the receipt            // holds the canonical value, so the comparison below is by value.            .map(|(k, v)| (k.to_string(), canonical_value(v).unwrap_or_else(|_| v.clone())))            .collect::<BTreeMap<_, _>>(),    }}/// The frozen vector: every rule in one receipt. Keys sorted (`done` before/// `title`, `actor` first), no white space, `null` carried, the integral/// real as `1`, the fraction shortest, the op id absent, the schema inside.#[test]fn frozen_receipt_vector() {    let r = receipt(&[        ("title", json!("Buy milk")),        ("done", json!(0)),        ("weight", json!(1.5)),        ("note", JsonValue::Null),        ("count", json!(1.0)),    ]);    let bytes = encode(&r).expect("encodes");    assert_eq!(        String::from_utf8(bytes.clone()).expect("utf-8"),        r#"{"actor":"owner:device:a","author":"device:a","fields":{"count":1,"done":0,"note":null,"title":"Buy milk","weight":1.5},"kind":"create","row":"r1","schema":7,"stamp":"0000001700000000:0000:device:a","table":"cotton_todos"}"#    );    assert_eq!(decode(&bytes).expect("decodes"), r);    assert_eq!(encode(&decode(&bytes).expect("decodes")).expect("re-encodes"), bytes);}#[test]fn a_retract_names_no_field_and_still_carries_its_eight_keys() {    let mut r = receipt(&[]);    r.kind = Kind::Retract;    let bytes = encode(&r).expect("encodes");    assert_eq!(        String::from_utf8(bytes.clone()).expect("utf-8"),        r#"{"actor":"owner:device:a","author":"device:a","fields":{},"kind":"retract","row":"r1","schema":7,"stamp":"0000001700000000:0000:device:a","table":"cotton_todos"}"#    );    assert_eq!(decode(&bytes).expect("decodes"), r);}/// An erase is a retract that says why, in its bytes, between `author` and/// `fields`; no other kind carries the key.#[test]fn an_erase_names_its_reason_and_only_a_retract_carries_one() {    let mut r = receipt(&[]);    r.kind = Kind::Retract;    r.erase = Some("source:gmail".to_string());    let bytes = encode(&r).expect("encodes");    assert_eq!(        String::from_utf8(bytes.clone()).expect("utf-8"),        r#"{"actor":"owner:device:a","author":"device:a","erase":"source:gmail","fields":{},"kind":"retract","row":"r1","schema":7,"stamp":"0000001700000000:0000:device:a","table":"cotton_todos"}"#    );    assert_eq!(decode(&bytes).expect("decodes"), r);    r.kind = Kind::Change;    assert!(encode(&r).is_err(), "a change carried an erase");    let forged = String::from_utf8(bytes).expect("utf-8").replace("\"retract\"", "\"change\"");    assert!(decode(forged.as_bytes()).is_err(), "a change decoded with an erase");}/// Frozen vectors for the value rules, one line each.#[test]fn frozen_value_vectors() {    let cases: &[(JsonValue, &str)] = &[        (json!({"b": 1, "a": 2}), r#"{"a":2,"b":1}"#),        (json!({"z": {"y": [3, {"x": null}]}}), r#"{"z":{"y":[3,{"x":null}]}}"#),        (json!(1.0), "1"),        (json!(-0.0), "0"),        (json!(0.1), "0.1"),        (json!(1e21), "1e+21"),        (json!(1e-7), "1e-7"),        (json!(123456789012.5), "123456789012.5"),        (json!(9007199254740992i64), "9007199254740992"),        (json!(-9007199254740992i64), "-9007199254740992"),        (json!(true), "true"),        (json!("tab\tquote\"back\\slash\u{1}"), r#""tab\tquote\"back\\slash\u0001""#),        // `e` + combining acute (U+0301) is composed to U+00E9 (NFC).        (json!("caf\u{65}\u{301}"), "\"caf\u{e9}\""),        // A key is normalised too, and sorts by its NFC bytes.        (json!({"\u{65}\u{301}": 1, "f": 2}), "{\"f\":2,\"\u{e9}\":1}"),        // Keys sort by byte order, not by code point or locale: "B" < "a".        (json!({"a": 1, "B": 2}), r#"{"B":2,"a":1}"#),    ];    for (value, expected) in cases {        assert_eq!(&canonical_json(value).expect("encodes"), expected, "{value}");    }}#[test]fn an_integer_beyond_what_an_f64_holds_exactly_is_refused() {    for value in [        json!(EXACT_INTEGER_LIMIT + 1),        json!(-(EXACT_INTEGER_LIMIT + 1)),        json!(u64::MAX),        json!(i64::MAX),    ] {        match canonical_json(&value) {            Err(StoreError::Encode(message)) => assert!(message.contains("2^53"), "{message}"),            other => panic!("{value} was not refused: {other:?}"),        }    }    assert_eq!(canonical_json(&json!(EXACT_INTEGER_LIMIT)).expect("the limit itself is exact"), "9007199254740992");    // A field inside a receipt is refused the same way.    let r = receipt(&[("n", json!(EXACT_INTEGER_LIMIT + 1))]);    assert!(matches!(encode(&r), Err(StoreError::Encode(_))));}#[test]fn bytes_that_are_not_canonical_are_refused_by_decode() {    let r = receipt(&[("a", json!(1)), ("b", json!("x"))]);    let canonical = String::from_utf8(encode(&r).expect("encodes")).expect("utf-8");    let not_canonical = [        // white space        canonical.replace(":", ": "),        // keys out of order        canonical.replace(r#""a":1,"b":"x""#, r#""b":"x","a":1"#),        // an op id smuggled inside the bytes        canonical.replace(r#"{"actor""#, r#"{"opId":"01H","actor""#),        // a `.0`        canonical.replace(r#""a":1"#, r#""a":1.0"#),        // a non-NFC string        canonical.replace(r#""x""#, "\"\u{65}\u{301}\""),        // a ninth key        canonical.replace(r#","table""#, r#","sig":"","table""#),    ];    for bytes in &not_canonical {        assert_ne!(bytes, &canonical, "the case must differ");        assert!(            matches!(decode(bytes.as_bytes()), Err(StoreError::Encode(_))),            "decoded although not canonical: {bytes}"        );    }    assert_eq!(decode(canonical.as_bytes()).expect("the canonical bytes decode"), r);}#[test]fn a_value_after_its_codec_is_what_sqlite_would_store() {    assert_eq!(after_codec(Codec::Bool, &json!(true)).expect("bool"), json!(1));    assert_eq!(after_codec(Codec::Bool, &json!(false)).expect("bool"), json!(0));    assert_eq!(after_codec(Codec::Int, &json!(3.0)).expect("int"), json!(3));    assert_eq!(after_codec(Codec::Real, &json!(2.5)).expect("real"), json!(2.5));    assert_eq!(after_codec(Codec::Real, &json!(2.0)).expect("real"), json!(2));    assert_eq!(        after_codec(Codec::Timestamp, &json!("2026-08-23T14:30:00+05:30")).expect("timestamp"),        json!("2026-08-23T09:00:00.000Z")    );    assert_eq!(        after_codec(Codec::Json, &json!({"b": 1, "a": [1, 2]})).expect("json"),        json!(r#"{"b":1,"a":[1,2]}"#),        "a JSON column's stored form is its text, as the codec writes it"    );    assert_eq!(after_codec(Codec::DecimalText, &json!(12.5)).expect("decimal"), json!("12.5"));    assert_eq!(after_codec(Codec::Text, &json!("caf\u{65}\u{301}")).expect("text"), json!("caf\u{e9}"));    assert_eq!(after_codec(Codec::Text, &JsonValue::Null).expect("null"), JsonValue::Null);    assert!(after_codec(Codec::Int, &json!("3")).is_err(), "the codec's own refusal stands");    assert!(after_codec(Codec::Int, &json!(EXACT_INTEGER_LIMIT + 1)).is_err());}