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
//! A run as JSON text, as a host in another language drives it across a
//! WIT or a Node-API boundary: options and chunks in, records and faults out,
//! each one string. A fault is the contract's `{ "code", "message", "seq" }`
//! (`fault.schema.json`), a record `record.schema.json`, a checkpoint
//! `{ "seq", "snapshot" }`. The WASI components and the Node addons of the
//! runtime share it, so each only adapts the calls.

use std::sync::Arc;

use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use xmachines_runtime::{EventType, Machine};

use crate::input::Chunk;
use crate::record::{Fault, FaultCode};
use crate::step::{Options, Run, Stepper};

/// A fault as JSON text.
pub fn fault_json(fault: &Fault) -> String {
    serde_json::to_string(fault).unwrap_or_default()
}

/// Run options of JSON text (`workflow-options.schema.json`), empty for
/// none. Options that do not parse are `WORKFLOW_INVALID_INPUT`, of no chunk.
pub fn parse_options(text: &str) -> Result<Options, Fault> {
    if text.trim().is_empty() {
        return Ok(Options::default());
    }
    serde_json::from_str(text)
        .map_err(|e| Fault::new(FaultCode::WorkflowInvalidInput, format!("The run options do not parse: {e}."), 0))
}

/// Opens a run of `machine` with run options of JSON text: the run, and its
/// opening records as JSON text. `max_timers` and `max_steps` are what the
/// options take when they name none, as the load options of a machine give
/// them. The error is a fault as JSON text.
pub fn open<C, E>(
    machine: Arc<Machine<C, E>>,
    options: &str,
    max_timers: usize,
    max_steps: usize,
) -> Result<(Run<C, E>, Vec<String>), String>
where
    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
    E: EventType + Send + Sync,
{
    let mut options = parse_options(options).map_err(|f| fault_json(&f))?;
    options.max_timers.get_or_insert(max_timers as u64);
    options.max_steps.get_or_insert(max_steps as u64);
    let (run, opening) = Run::open(machine, options).map_err(|f| fault_json(&f))?;
    Ok((run, opening.iter().map(|r| serde_json::to_string(r).unwrap_or_default()).collect()))
}

impl<C, E> Run<C, E>
where
    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
    E: EventType + Send + Sync,
{
    /// [`Stepper::apply`] of a chunk of JSON text (`chunk.schema.json`): its
    /// records, each JSON text, or its fault as JSON text. Text that is not
    /// JSON is a chunk that is no input, `WORKFLOW_INVALID_INPUT`, of the
    /// chunk's `seq`, and the run goes on.
    pub fn apply_text(&mut self, chunk: &str) -> Result<Vec<String>, String> {
        let chunk: Chunk<Value> = match serde_json::from_str::<Value>(chunk) {
            Ok(Value::Array(items)) => Chunk::Batch(items),
            Ok(one) => Chunk::One(one),
            Err(_) => Chunk::One(Value::Null),
        };
        let mut records = Vec::new();
        self.apply(chunk, &mut records).map_err(|f| fault_json(&f))?;
        Ok(records.iter().map(|r| serde_json::to_string(r).unwrap_or_default()).collect())
    }

    /// [`Run::can`] of an event of JSON text: `false` of text that is no
    /// event.
    pub fn can_text(&self, event: &str) -> bool {
        serde_json::from_str::<Value>(event).is_ok_and(|event| self.can(&event))
    }

    /// [`Run::checkpoint`] as JSON text.
    pub fn checkpoint_text(&self) -> String {
        serde_json::to_string(&self.checkpoint()).unwrap_or_default()
    }
}