Example 7: Identity

  • file format 6
  • Rust SDK 1.0 preview

Needs the Rust SDK

Canonical JSON, a record's keys, an opaque record that round-trips, and two spellings of one record that share a key.

This program also needs serde_json = "1.0" under [dependencies] in its Cargo.toml.

07_identity.rsrust
// Identity: the canonical JSON form, and the keys that decide whether
// two records are "the same record".
use plxi_sdk::{canonical_json, Record};

fn main() -> Result<(), plxi_sdk::Error> {
    // canonical_json sorts object members by name, keeps array order
    // and removes insignificant whitespace.
    let value = serde_json::json!({
        "z": [3, 1.5, -0.0],
        "a": {"y": null, "b": true}
    });
    let canon = r#"{"a":{"b":true,"y":null},"z":[3,1.5,-0.0]}"#;
    assert_eq!(canonical_json(&value), canon);

    // A typed record's key is (kind, primary id).
    let line = r#"{"k":"ent","id":"e1","t":"Person"}"#;
    let ent = Record::from_json_line(line)?;
    let parts = (ent.kind(), ent.version(), ent.primary_id());
    assert_eq!(parts, ("ent", 1, "e1"));
    assert_eq!(ent.dedup_key(), ("ent".to_string(), "e1".to_string()));
    assert_eq!(ent.sort_key(), (3, "ent".to_string(), "e1".to_string()));

    // A kind this SDK has no schema for is kept as written ("opaque"),
    // so a newer writer's records survive a round trip through an
    // older reader.
    let line = r#"{"k":"x-future","v":7,"id":"n1","z":{"b":1,"a":2}}"#;
    let opaque = Record::from_json_line(line)?;
    assert_eq!(opaque.json_line(), line);
    let canon = r#"{"id":"n1","k":"x-future","v":7,"z":{"a":2,"b":1}}"#;
    assert_eq!(opaque.canonical_json(), canon);
    assert_eq!(opaque.sort_key().0, u32::MAX); // unknown kinds sort last

    // Two spellings of one object are one record: an opaque record
    // with no id member is keyed by its canonical form.
    let a = r#"{"k":"x-note","b":1,"a":{"y":2.0,"x":1}}"#;
    let b = r#"{"a":{"x":1,"y":2.00},"b":1,"k":"x-note"}"#;
    let a = Record::from_json_line(a)?;
    let b = Record::from_json_line(b)?;
    assert_ne!(a.json_line(), b.json_line());
    assert_eq!(a.dedup_key(), b.dedup_key());
    println!("{}", a.primary_id());
    Ok(())
}
Output
{"a":{"x":1,"y":2.0},"b":1,"k":"x-note"}

Ran with cargo run --example 07_identity · exit status 0

Explained in: Identity and order

Sections