xmachines-workflow 6.0.0

The record protocol of a statechart run, as serde types: chunks of events, time and work results in, events, snapshots and rejections out, faults as data
Documentation
//! The protocol types held to the workflow contract's shared fixtures
//! (`fixtures/workflow/`, vendored from the contract's suite, the files
//! `@xmachines/run` of xmachines-js vendors too) and the adversarial cases in
//! their format (`fixtures/workflow-adversarial/`): every chunk and every
//! record reads into the types and writes back the same value, and matches
//! its JSON Schema. Values, not bytes: objects compare without key order.
//! What is no input fails to read, with the words of the contract.

// The tests read the fixtures and the schemas of the repository; the crate's
// own code may not read files (clippy.toml).
#![allow(clippy::disallowed_methods)]

#[path = "../../xmachines-runtime/tests/common/schemas.rs"]
mod schemas;

use std::path::PathBuf;

use schemas::Schemas;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::{json, Value};
use xmachines_workflow::*;

/// Where the fixtures of `folder` are, under the workspace's `fixtures/`.
fn fixtures(folder: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures").join(folder)
}

/// Each fixture `folder/index.json` lists, by name.
fn each(folder: &str) -> Vec<(String, Value)> {
    let index: Vec<String> =
        serde_json::from_str(&std::fs::read_to_string(fixtures(folder).join("index.json")).unwrap()).unwrap();
    assert!(!index.is_empty());
    index
        .into_iter()
        .map(|name| {
            let text = std::fs::read_to_string(fixtures(folder).join(format!("{name}.json"))).unwrap();
            (name, serde_json::from_str(&text).unwrap())
        })
        .collect()
}

/// `value` read as `T` and written back: the same value, or the difference.
fn round_trip<T: Serialize + DeserializeOwned>(value: &Value) -> Result<(), String> {
    let typed: T = serde_json::from_value(value.clone()).map_err(|e| format!("{value} does not read: {e}"))?;
    let back = serde_json::to_value(&typed).unwrap();
    if back == *value {
        Ok(())
    } else {
        Err(format!("{value} writes back as {back}"))
    }
}

/// The chunks, records and questions of `can` of every fixture of `folder`,
/// each a value of the types and of the schemas; how many of each.
fn check(folder: &str) -> (usize, usize) {
    let schemas = Schemas::load();
    let (chunk, record) = (schemas.runtime("chunk.schema.json"), schemas.runtime("record.schema.json"));
    let (mut chunks, mut records, mut wrong) = (0, 0, Vec::new());
    for (name, fixture) in each(folder) {
        let restore = fixture.get("restore");
        let inputs = fixture["inputs"]
            .as_array()
            .unwrap()
            .iter()
            .chain(restore.and_then(|r| r["inputs"].as_array()).into_iter().flatten());
        for input in inputs {
            chunks += 1;
            // The fixtures write a fault's chunk too, which is no input: it must fail as one.
            let invalid = match input {
                Value::Array(items) => items.iter().find_map(invalid),
                one => invalid(one),
            };
            match invalid {
                Some(_) => {
                    if serde_json::from_value::<Chunk>(input.clone()).is_ok() {
                        wrong.push(format!("{name}: {input} reads, though it is no input"));
                    }
                }
                None => {
                    if let Err(e) = round_trip::<Chunk>(input) {
                        wrong.push(format!("{name}: {e}"));
                    }
                    if !chunk.is_valid(input) {
                        wrong.push(format!("{name}: {input} does not match chunk.schema.json"));
                    }
                }
            }
        }
        let all = fixture["records"]
            .as_array()
            .unwrap()
            .iter()
            .chain(restore.and_then(|r| r["records"].as_array()).into_iter().flatten());
        for each in all {
            records += 1;
            if let Err(e) = round_trip::<Record>(each) {
                wrong.push(format!("{name}: {e}"));
            }
            if !record.is_valid(each) {
                wrong.push(format!("{name}: {each} does not match record.schema.json"));
            }
        }
        for question in fixture.get("can").and_then(Value::as_array).into_iter().flatten() {
            if !matches!(serde_json::from_value::<Input>(question["event"].clone()), Ok(Input::Event(_))) {
                wrong.push(format!("{name}: the event of can {} is no event", question["event"]));
            }
        }
    }
    assert!(wrong.is_empty(), "{}", wrong.join("\n"));
    (chunks, records)
}

#[test]
fn every_chunk_and_record_of_the_shared_fixtures_reads_and_writes_back_the_same_value() {
    let (chunks, records) = check("workflow");
    assert!(chunks >= 262 && records >= 467, "{chunks} chunks, {records} records");
}

#[test]
fn every_chunk_and_record_of_the_adversarial_cases_reads_and_writes_back_the_same_value() {
    check("workflow-adversarial");
}

#[test]
fn what_is_no_input_fails_with_the_rule_it_breaks() {
    let cases = [
        (json!(5), "each input is an object, an event or a control input"),
        (json!({ "kind": "time", "now": 10.5 }), "a time input has a now of whole milliseconds"),
        (json!({ "kind": "time", "now": 9007199254740992u64 }), "a time input has a now of whole milliseconds"),
        (json!({ "kind": "time", "now": 1, "type": "x.y" }), "a control input has no type"),
        (json!({ "kind": "work", "outcome": "done" }), "a work result has a string id"),
        (
            json!({ "kind": "work", "id": "a", "outcome": "maybe" }),
            "a work result has an outcome, resolved, rejected or done",
        ),
        (json!({ "kind": "work", "id": "a", "outcome": "done", "data": null }), "a work result of done has no data"),
        (json!({ "kind": "nope" }), "a control input is of kind time or work"),
        (json!({ "now": 1 }), "an event has a string type"),
        (json!({ "type": 5 }), "an event has a string type"),
    ];
    for (input, why) in cases {
        assert_eq!(invalid(&input), Some(why), "{input}");
        let error = serde_json::from_value::<Input>(input.clone()).unwrap_err();
        assert_eq!(error.to_string(), why, "{input}");
        // In a batch, too.
        assert!(serde_json::from_value::<Chunk>(json!([{ "type": "ok" }, input])).is_err());
    }
}

#[test]
fn a_kind_of_time_or_work_marks_a_control_input_and_any_other_kind_is_an_events_own() {
    let book = json!({ "type": "add", "kind": "book" });
    assert_eq!(serde_json::from_value::<Input>(book.clone()).unwrap(), Input::Event(book));
    assert_eq!(
        serde_json::from_value::<Input>(json!({ "kind": "time", "now": 5.0 })).unwrap(),
        Control::time(5).into()
    );
    assert_eq!(
        serde_json::from_value::<Input>(json!({ "kind": "time", "now": -3 })).unwrap(),
        Control::time(-3).into()
    );
    // A key the run does not read is kept, and written back after the keys it reads.
    for input in [
        json!({ "kind": "time", "now": 1, "note": "x" }),
        json!({ "kind": "work", "id": "w", "outcome": "resolved", "data": 1, "via": { "n": 2 } }),
    ] {
        round_trip::<Input>(&input).unwrap();
    }
    // So a rejected batch, and a journal's chunk, hold the inputs as they were written.
    let rejected = json!({ "kind": "rejected", "seq": 1, "batch": [{ "kind": "time", "now": 5, "note": "x" }, { "type": "go" }],
                           "error": { "message": "m" } });
    round_trip::<Record>(&rejected).unwrap();
}

#[test]
fn null_is_kept_apart_from_no_value() {
    let with_null = json!({ "kind": "work", "id": "w", "outcome": "resolved", "data": null });
    let read: Control = serde_json::from_value(with_null.clone()).unwrap();
    assert_eq!(read, Control::resolved("w", Value::Null));
    assert_eq!(serde_json::to_value(&read).unwrap(), with_null);
    let without = json!({ "kind": "work", "id": "w", "outcome": "resolved" });
    assert_eq!(serde_json::to_value(serde_json::from_value::<Control>(without.clone()).unwrap()).unwrap(), without);
    for value in [
        json!({ "kind": "invoke", "id": "w", "actor": "root", "src": "charge", "input": null }),
        json!({ "kind": "action", "id": "w", "actor": "root", "type": "audit", "params": null }),
    ] {
        round_trip::<Work>(&value).unwrap();
    }
    round_trip::<Failure>(&json!({ "message": "m", "data": null })).unwrap();
    let snapshot = json!({ "status": "done", "value": "end", "context": null, "output": null, "time": 0, "work": [] });
    round_trip::<Snapshot>(&snapshot).unwrap();
}

#[test]
fn a_record_writes_kind_first_and_numbers_as_javascript_does() {
    let record = Record::<Value>::Event { seq: 3, event: json!({ "type": "rang" }) };
    assert_eq!(serde_json::to_string(&record).unwrap(), r#"{"kind":"event","seq":3,"event":{"type":"rang"}}"#);
    // A whole number written with a fraction of zero is that number; a fraction or a number past 2^53 - 1 is none.
    let snapshot = |time: Value| json!({ "status": "active", "value": "a", "context": {}, "time": time, "work": [] });
    assert_eq!(serde_json::from_value::<Snapshot>(snapshot(json!(120.0))).unwrap().time, 120);
    assert!(serde_json::from_value::<Snapshot>(snapshot(json!(10.5))).is_err());
    assert!(serde_json::from_value::<Snapshot>(snapshot(json!(9007199254740992u64))).is_err());
    // A time before the epoch is a safe integer too, as JavaScript reads it.
    assert_eq!(serde_json::from_value::<Snapshot>(snapshot(json!(-1))).unwrap().time, -1);
}

#[test]
fn a_fault_is_data_of_a_stable_code() {
    let schemas = Schemas::load();
    let schema = schemas.runtime("fault.schema.json");
    let fault = Fault::new(FaultCode::WorkflowInvalidInput, "Chunk 3: a control input has no type.", 3);
    let value = serde_json::to_value(&fault).unwrap();
    assert_eq!(
        value,
        json!({ "code": "WORKFLOW_INVALID_INPUT", "message": "Chunk 3: a control input has no type.", "seq": 3 })
    );
    schema.check(&value);
    assert!(FaultCode::WorkflowInvalidInput.is_recoverable() && !FaultCode::WorkflowEngineFailed.is_recoverable());
    // Every code reads and writes as the schema names it.
    let codes = schemas::files()
        .into_iter()
        .find(|(path, ..)| path.ends_with("fault.schema.json"))
        .map(|(.., schema)| schema["properties"]["code"]["enum"].clone())
        .unwrap();
    for code in codes.as_array().unwrap() {
        let parsed = FaultCode::parse(code.as_str().unwrap()).unwrap_or_else(|| panic!("{code}"));
        assert_eq!(parsed.as_str(), code);
    }
    assert!(serde_json::from_value::<Fault>(json!({ "code": "NOPE", "message": "", "seq": 0 })).is_err());
    assert!(
        serde_json::from_value::<Fault>(json!({ "code": "WORKFLOW_CLOSED", "message": "", "seq": 0, "x": 1 })).is_err()
    );
    schema.reject(&json!({ "code": "WORKFLOW_CLOSED", "message": "", "seq": 0, "x": 1 }));
}

#[test]
fn a_journal_reads_and_writes_the_entries_of_a_javascript_host() {
    let entries = [
        json!({ "kind": "start", "run": "r1", "actor": "root", "version": "v1", "input": { "n": 1 }, "time": 0, "maxTimers": 1000 }),
        json!({ "kind": "claim", "epoch": 1, "holder": "8a4f" }),
        json!({ "kind": "chunk", "seq": 1, "chunk": [{ "kind": "time", "now": 10 }, { "type": "go" }], "epoch": 1,
                "source": { "producer": "g/orders/0", "offset": "42", "epoch": 1 } }),
        json!({ "kind": "snapshot", "epoch": 1, "published": 1, "seq": 1,
                "positions": { "g/orders/0": { "producer": "g/orders/0", "offset": "42", "epoch": 1 } },
                "snapshot": { "status": "active", "value": "b", "context": {}, "time": 10, "work": [], "state": {} } }),
    ];
    for entry in &entries {
        round_trip::<JournalEntry>(entry).unwrap();
    }
    let checkpoint = json!({
        "seq": 1,
        "snapshot": { "status": "active", "value": "b", "context": {}, "time": 10, "work": [], "state": {} },
        "start": entries[0],
    });
    round_trip::<HostedCheckpoint>(&checkpoint).unwrap();
    let envelope = json!({ "run": "r1", "value": { "kind": "time", "now": 1 }, "replayed": true, "key": "k" });
    round_trip::<Envelope<Input>>(&envelope).unwrap();
    round_trip::<Envelope<Input>>(&json!({ "run": "r1", "value": { "type": "go" } })).unwrap();
}