Cotton code
383 lines · 13.4 KB · RustRaw
//! Vectors for `schema/codecs.rs`, taken from//! `packages/store/__tests__/codecs.test.ts` and//! `__tests__/schemaRoundtrip.test.ts`, and extended with cases computed by//! running `encodeValue` in node.//!//! The pair must round-trip exactly, because these run on BOTH sides of the//! sync: a value encoded on the phone is decoded on the server and vice versa,//! and any asymmetry shows up as data that mutates slightly every time it//! crosses.use super::*;fn parse(json: &str) -> JsonValue {    serde_json::from_str(json).expect("the vector is valid JSON")}#[test]fn encode_value_matches_the_typescript() {    // `Ok(…)`/`Err(…)` in the generated table read as the TypeScript's own    // outcome: a value it returned, or the message it threw.    #[allow(clippy::type_complexity)]    let cases: &[(Codec, &str, std::result::Result<SqlValue, &str>)] = &[        (            Codec::Text,            "\"hello\"",            Ok(SqlValue::Text("hello".to_string())),        ),        (Codec::Text, "1", Err("expected string, got number")),        (Codec::Text, "true", Err("expected string, got boolean")),        (Codec::Text, "null", Ok(SqlValue::Null)),        (            Codec::Timestamp,            "\"2026-08-23T14:30:00+05:30\"",            Ok(SqlValue::Text("2026-08-23T09:00:00.000Z".to_string())),        ),        (            Codec::Timestamp,            "\"2026-08-23T09:00:00-04:00\"",            Ok(SqlValue::Text("2026-08-23T13:00:00.000Z".to_string())),        ),        (            Codec::Timestamp,            "\"2026-08-23T09:00:00.000Z\"",            Ok(SqlValue::Text("2026-08-23T09:00:00.000Z".to_string())),        ),        (            Codec::Timestamp,            "\"2026-08-23T09:00:00Z\"",            Ok(SqlValue::Text("2026-08-23T09:00:00.000Z".to_string())),        ),        (            Codec::Timestamp,            "\"2026-08-23T09:00:00.123456Z\"",            Ok(SqlValue::Text("2026-08-23T09:00:00.123Z".to_string())),        ),        (            Codec::Timestamp,            "\"2026-08-23T09:00:00.5Z\"",            Ok(SqlValue::Text("2026-08-23T09:00:00.500Z".to_string())),        ),        (            Codec::Timestamp,            "\"2026-08-23T14:30:00\"",            Ok(SqlValue::Text("2026-08-23T14:30:00.000Z".to_string())),        ),        (            Codec::Timestamp,            "\"2026-08-23\"",            Ok(SqlValue::Text("2026-08-23T00:00:00.000Z".to_string())),        ),        (            Codec::Timestamp,            "\"2026-08-23T14:30:00+0530\"",            Ok(SqlValue::Text("2026-08-23T09:00:00.000Z".to_string())),        ),        (            Codec::Timestamp,            "\"garbageZ\"",            Err("expected timestamp, got \"garbageZ\""),        ),        (            Codec::Timestamp,            "\"not a date\"",            Err("expected timestamp, got \"not a date\""),        ),        (            Codec::Timestamp,            "\"2026-02-30T00:00:00Z\"",            Ok(SqlValue::Text("2026-03-02T00:00:00.000Z".to_string())),        ),        (            Codec::Timestamp,            "\"1970-01-01T00:00:00.000Z\"",            Ok(SqlValue::Text("1970-01-01T00:00:00.000Z".to_string())),        ),        (            Codec::Timestamp,            "\"0001-01-01T00:00:00.000Z\"",            Ok(SqlValue::Text("0001-01-01T00:00:00.000Z".to_string())),        ),        (Codec::Timestamp, "5", Err("expected timestamp, got number")),        (Codec::Int, "1", Ok(SqlValue::Integer(1))),        (Codec::Int, "0", Ok(SqlValue::Integer(0))),        (            Codec::Int,            "-12345678901",            Ok(SqlValue::Integer(-12345678901)),        ),        (Codec::Int, "1.5", Err("expected integer, got 1.5")),        (Codec::Int, "\"3\"", Err("expected integer, got 3")),        (Codec::Int, "true", Err("expected integer, got true")),        (Codec::MoneyMinor, "120000", Ok(SqlValue::Integer(120000))),        (Codec::Real, "1.5", Ok(SqlValue::Real(1.5))),        (Codec::Real, "3", Ok(SqlValue::Integer(3))),        (Codec::Real, "\"x\"", Err("expected number, got string")),        (Codec::Bool, "true", Ok(SqlValue::Integer(1))),        (Codec::Bool, "false", Ok(SqlValue::Integer(0))),        (Codec::Bool, "1", Err("expected boolean, got number")),        (            Codec::Json,            "{\"a\":1,\"b\":[1,2],\"c\":null}",            Ok(SqlValue::Text(                "{\"a\":1,\"b\":[1,2],\"c\":null}".to_string(),            )),        ),        (            Codec::Json,            "[1,2,3]",            Ok(SqlValue::Text("[1,2,3]".to_string())),        ),        (            Codec::Json,            "\"plain\"",            Ok(SqlValue::Text("\"plain\"".to_string())),        ),        (Codec::Json, "1", Ok(SqlValue::Text("1".to_string()))),        (Codec::Json, "1.5", Ok(SqlValue::Text("1.5".to_string()))),        (Codec::Json, "true", Ok(SqlValue::Text("true".to_string()))),        (            Codec::Json,            "{\"quote\\\"\":\"tab\\there\\nnewline\"}",            Ok(SqlValue::Text(                "{\"quote\\\"\":\"tab\\there\\nnewline\"}".to_string(),            )),        ),        (            Codec::Json,            "{\"emoji\":\"\u{1f9f5}\",\"jp\":\"\u{65e5}\u{672c}\u{8a9e}\"}",            Ok(SqlValue::Text(                "{\"emoji\":\"\u{1f9f5}\",\"jp\":\"\u{65e5}\u{672c}\u{8a9e}\"}".to_string(),            )),        ),        (            Codec::Json,            "{\"z\":1,\"a\":2}",            Ok(SqlValue::Text("{\"z\":1,\"a\":2}".to_string())),        ),        (            Codec::DecimalText,            "\"1.50\"",            Ok(SqlValue::Text("1.50".to_string())),        ),        (            Codec::DecimalText,            "1.5",            Ok(SqlValue::Text("1.5".to_string())),        ),        (Codec::DecimalText, "3", Ok(SqlValue::Text("3".to_string()))),        (            Codec::DecimalText,            "1e+21",            Ok(SqlValue::Text("1e+21".to_string())),        ),        (            Codec::DecimalText,            "1e-7",            Ok(SqlValue::Text("1e-7".to_string())),        ),        (            Codec::DecimalText,            "0.1",            Ok(SqlValue::Text("0.1".to_string())),        ),        (Codec::DecimalText, "0", Ok(SqlValue::Text("0".to_string()))),        (            Codec::DecimalText,            "true",            Err("expected decimal, got boolean"),        ),    ];    for (codec, json, expected) in cases {        let actual = encode_value(*codec, &parse(json));        match expected {            std::result::Result::Ok(value) => assert_eq!(                actual.as_ref().expect("the TypeScript encoded it"),                value,                "encodeValue({codec:?}, {json})"            ),            std::result::Result::Err(message) => {                let error = actual.expect_err("the TypeScript threw");                assert_eq!(                    &error.to_string(),                    message,                    "encodeValue({codec:?}, {json})"                );            }        }    }}#[test]fn null_maps_to_null_for_every_codec() {    for codec in [        Codec::Text,        Codec::Int,        Codec::Real,        Codec::Bool,        Codec::Json,        Codec::MoneyMinor,        Codec::DecimalText,        Codec::Timestamp,    ] {        assert_eq!(            encode_value(codec, &JsonValue::Null).expect("null encodes"),            SqlValue::Null        );        assert_eq!(            decode_value(codec, &SqlValue::Null).expect("null decodes"),            JsonValue::Null        );    }}#[test]fn a_canonicalised_pair_orders_the_way_the_instants_actually_run() {    // The point of the whole codec, asserted directly: string order IS time    // order. Raw, `"…T09:00:00.500Z" < "…T09:00:00Z"`.    let earlier = to_utc_instant("2026-08-23T09:00:00Z").expect("parses");    let later = to_utc_instant("2026-08-23T09:00:00.500Z").expect("parses");    assert!(earlier < later, "{earlier} !< {later}");}#[test]fn the_timestamp_codec_is_idempotent() {    let once = to_utc_instant("2026-08-23T14:30:00+05:30").expect("parses");    assert_eq!(to_utc_instant(&once).expect("parses"), once);}const COLUMNS: &[(&str, Codec)] = &[    ("id", Codec::Text),    ("title", Codec::Text),    ("notes", Codec::Text),    ("done", Codec::Bool),    ("due_at", Codec::Timestamp),];fn patch(json: &str) -> Map<String, JsonValue> {    match parse(json) {        JsonValue::Object(fields) => fields,        other => panic!("the vector is not an object: {other}"),    }}#[test]fn a_key_the_patch_does_not_carry_is_simply_absent() {    // JSON has no `undefined`: `JSON.stringify({notes: undefined})` drops the    // key, and the protocol's reading is the same — absent means "not part of    // this patch", an explicit null means "clear the column".    let encoded = encode_row(COLUMNS, &patch(r#"{"title":"renamed"}"#)).expect("encodes");    assert_eq!(        encoded,        vec![("title".to_string(), SqlValue::Text("renamed".to_string()))]    );}#[test]fn an_explicit_null_is_kept_because_null_means_clear_the_column() {    let encoded = encode_row(COLUMNS, &patch(r#"{"notes":null}"#)).expect("encodes");    assert_eq!(encoded, vec![("notes".to_string(), SqlValue::Null)]);}#[test]fn encode_row_refuses_an_unknown_column() {    let error = encode_row(COLUMNS, &patch(r#"{"nope":1}"#)).expect_err("refuses");    assert_eq!(error.to_string(), "unknown column: nope");    // And a misspelling mixed into an otherwise-valid patch still fails loudly.    let error = encode_row(COLUMNS, &patch(r#"{"title":"ok","nope":null}"#)).expect_err("refuses");    assert_eq!(error.to_string(), "unknown column: nope");}#[test]fn encodes_domain_booleans_to_storage_form() {    assert_eq!(        encode_row(COLUMNS, &patch(r#"{"done":true}"#)).expect("encodes"),        vec![("done".to_string(), SqlValue::Integer(1))]    );    assert_eq!(        encode_row(COLUMNS, &patch(r#"{"done":false}"#)).expect("encodes"),        vec![("done".to_string(), SqlValue::Integer(0))]    );}#[test]fn decode_row_skips_protocol_bookkeeping_and_unknown_columns() {    let row = vec![        ("id".to_string(), SqlValue::Text("todo-1".to_string())),        ("done".to_string(), SqlValue::Integer(1)),        (            "_hlc".to_string(),            SqlValue::Text("1700000000000:0000:d".to_string()),        ),        ("gone".to_string(), SqlValue::Text("dropped".to_string())),    ];    let decoded = decode_row(COLUMNS, &row).expect("decodes");    assert_eq!(decoded.len(), 2);    assert_eq!(decoded["id"], JsonValue::String("todo-1".to_string()));    assert_eq!(decoded["done"], JsonValue::Bool(true));    assert!(!decoded.contains_key("_hlc"));    assert!(!decoded.contains_key("gone"));}#[test]fn money_minor_units_stay_exact_integers_through_a_round_trip() {    // `schemaRoundtrip.test.ts` — a paise value larger than 32 bits must come    // back as the same integer, not a float that nearly is one.    let encoded =        encode_value(Codec::MoneyMinor, &JsonValue::from(-12_345_678_901i64)).expect("encodes");    assert_eq!(encoded, SqlValue::Integer(-12_345_678_901));    let decoded = decode_value(Codec::MoneyMinor, &encoded).expect("decodes");    assert_eq!(decoded, JsonValue::from(-12_345_678_901i64));    assert!(decoded.is_i64(), "an integer must come back an integer");}#[test]fn every_codec_round_trips() {    let cases: &[(Codec, &str)] = &[        (Codec::Text, r#""hello""#),        (Codec::Text, r#""""#),        (Codec::Timestamp, r#""2026-08-23T09:00:00.000Z""#),        (Codec::Int, "0"),        (Codec::Int, "-1"),        (Codec::Int, "9007199254740991"),        (Codec::MoneyMinor, "120000"),        (Codec::Real, "1.5"),        (Codec::Real, "-0.25"),        (Codec::Bool, "true"),        (Codec::Bool, "false"),        (Codec::Json, r#"{"a":1,"b":[1,2],"c":null}"#),        (Codec::Json, "[1,2,3]"),        (Codec::Json, r#""plain""#),        (Codec::DecimalText, r#""1.50""#),    ];    for (codec, json) in cases {        let original = parse(json);        let encoded = encode_value(*codec, &original).expect("encodes");        let decoded = decode_value(*codec, &encoded).expect("decodes");        assert_eq!(&decoded, &original, "round trip of {codec:?} {json}");    }}#[test]fn a_decimal_never_becomes_a_float_on_the_way_in() {    // The whole point of the codec: a bank's "1.50" must not be stored as 1.5.    assert_eq!(        encode_value(Codec::DecimalText, &parse(r#""1.50""#)).expect("encodes"),        SqlValue::Text("1.50".to_string())    );}/// RULE: Money minor units never pass through a float, because an integer above 2^53 would silently gain or lose a unit on every write and sync.#[test]fn money_minor_units_keep_all_signed_integer_bits() {    for amount in [9_007_199_254_740_993i64, i64::MAX, i64::MIN] {        let value = JsonValue::from(amount);        let stored = encode_value(Codec::MoneyMinor, &value).expect("exact integer");        assert_eq!(stored, SqlValue::Integer(amount));        assert_eq!(decode_value(Codec::MoneyMinor, &stored).unwrap(), value);    }    let fractional = serde_json::from_str::<JsonValue>("1.25").unwrap();    assert!(encode_value(Codec::MoneyMinor, &fractional).is_err());    let outside = serde_json::from_str::<JsonValue>("9223372036854775808").unwrap();    assert!(encode_value(Codec::MoneyMinor, &outside).is_err());}