Skip to main content

xmachines_workflow/
text.rs

1//! A run as JSON text, as a host in another language drives it across a
2//! WIT or a Node-API boundary: options and chunks in, records and faults out,
3//! each one string. A fault is the contract's `{ "code", "message", "seq" }`
4//! (`fault.schema.json`), a record `record.schema.json`, a checkpoint
5//! `{ "seq", "snapshot" }`. The WASI components and the Node addons of the
6//! runtime share it, so each only adapts the calls.
7
8use std::sync::Arc;
9
10use serde::de::DeserializeOwned;
11use serde::Serialize;
12use serde_json::Value;
13use xmachines_runtime::{EventType, Machine};
14
15use crate::input::Chunk;
16use crate::record::{Fault, FaultCode};
17use crate::step::{Options, Run, Stepper};
18
19/// A fault as JSON text.
20pub fn fault_json(fault: &Fault) -> String {
21    serde_json::to_string(fault).unwrap_or_default()
22}
23
24/// Run options of JSON text (`workflow-options.schema.json`), empty for
25/// none. Options that do not parse are `WORKFLOW_INVALID_INPUT`, of no chunk.
26pub fn parse_options(text: &str) -> Result<Options, Fault> {
27    if text.trim().is_empty() {
28        return Ok(Options::default());
29    }
30    serde_json::from_str(text)
31        .map_err(|e| Fault::new(FaultCode::WorkflowInvalidInput, format!("The run options do not parse: {e}."), 0))
32}
33
34/// Opens a run of `machine` with run options of JSON text: the run, and its
35/// opening records as JSON text. `max_timers` and `max_steps` are what the
36/// options take when they name none, as the load options of a machine give
37/// them. The error is a fault as JSON text.
38pub fn open<C, E>(
39    machine: Arc<Machine<C, E>>,
40    options: &str,
41    max_timers: usize,
42    max_steps: usize,
43) -> Result<(Run<C, E>, Vec<String>), String>
44where
45    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
46    E: EventType + Send + Sync,
47{
48    let mut options = parse_options(options).map_err(|f| fault_json(&f))?;
49    options.max_timers.get_or_insert(max_timers as u64);
50    options.max_steps.get_or_insert(max_steps as u64);
51    let (run, opening) = Run::open(machine, options).map_err(|f| fault_json(&f))?;
52    Ok((run, opening.iter().map(|r| serde_json::to_string(r).unwrap_or_default()).collect()))
53}
54
55impl<C, E> Run<C, E>
56where
57    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
58    E: EventType + Send + Sync,
59{
60    /// [`Stepper::apply`] of a chunk of JSON text (`chunk.schema.json`): its
61    /// records, each JSON text, or its fault as JSON text. Text that is not
62    /// JSON is a chunk that is no input, `WORKFLOW_INVALID_INPUT`, of the
63    /// chunk's `seq`, and the run goes on.
64    pub fn apply_text(&mut self, chunk: &str) -> Result<Vec<String>, String> {
65        let chunk: Chunk<Value> = match serde_json::from_str::<Value>(chunk) {
66            Ok(Value::Array(items)) => Chunk::Batch(items),
67            Ok(one) => Chunk::One(one),
68            Err(_) => Chunk::One(Value::Null),
69        };
70        let mut records = Vec::new();
71        self.apply(chunk, &mut records).map_err(|f| fault_json(&f))?;
72        Ok(records.iter().map(|r| serde_json::to_string(r).unwrap_or_default()).collect())
73    }
74
75    /// [`Run::can`] of an event of JSON text: `false` of text that is no
76    /// event.
77    pub fn can_text(&self, event: &str) -> bool {
78        serde_json::from_str::<Value>(event).is_ok_and(|event| self.can(&event))
79    }
80
81    /// [`Run::checkpoint`] as JSON text.
82    pub fn checkpoint_text(&self) -> String {
83        serde_json::to_string(&self.checkpoint()).unwrap_or_default()
84    }
85}