Skip to main content

xmachines_runtime/
host.rs

1//! What the hosts in other languages share: the WASI components
2//! (`xmachines-runtime-wasi`, `xmachines-machine-wasi`) and the Node addons (`xmachines-runtime-node`,
3//! `xmachines-machine-node`) take their options and chunks and return their steps as JSON text, the same
4//! way: a machine is loaded once with [`LoadOptions`], its actors start with [`StartOptions`] or
5//! restore from a snapshot alone, and [`apply_json`] is [`Actor::apply`] on JSON text. A refused
6//! chunk is the workflow contract's error ([`ApplyError`], [`apply_error_json`]): a rejection,
7//! `{ "rejected": { "message", "data"? } }`, or a fault, `{ "code", "message" }`. A load, a start
8//! or a restore that fails is a fault too: `WORKFLOW_INVALID_MACHINE` of a definition that does not
9//! compile, `WORKFLOW_INVALID_INPUT` of options that do not parse or a start's time past
10//! `2^53 - 1`, `WORKFLOW_MACHINE_FAILED` of a root that fails as it starts, and
11//! `WORKFLOW_INVALID_SNAPSHOT` of a snapshot that does not restore.
12
13use std::sync::Arc;
14
15use serde::de::DeserializeOwned;
16use serde::Serialize;
17use serde_json::{json, Map, Value};
18
19use crate::actor::RestoreOptions;
20use crate::event::EventType;
21use crate::machine::Machine;
22use crate::system::{ActorRef, InitOptions, Status, DEFAULT_MAX_STEPS};
23use crate::work::{ApplyError, Step, DEFAULT_MAX_TIMERS, MAX_TIME};
24use crate::{Actor, HostActions};
25
26/// The root's actor id of a start that names none, the workflow contract's:
27/// a work's `actor` is `root`, or a child's address under it, as `root/charge`.
28pub const ROOT_ID: &str = "root";
29
30/// Parses `text` as JSON; `what` names it in the error.
31pub fn parse_json(what: &str, text: &str) -> Result<Value, String> {
32    serde_json::from_str(text).map_err(|e| format!("invalid {what} JSON: {e}"))
33}
34
35/// The options a machine is loaded with (JSON, all optional), which every
36/// actor started or restored from it shares, so a restore needs only the
37/// snapshot:
38///
39/// ```text
40/// { "children": { "<src>": MachineJSON }, // child machines for `invoke.src` (generic hosts)
41///   "maxSteps": number,                   // bound on work per call (default DEFAULT_MAX_STEPS, 10000)
42///   "maxTimers": number,                  // timers a time input fires at most in a chunk of control inputs alone (default 1000)
43///   "observeSystemEmitted": bool,         // every actor's emitted events, from the start or restore
44///   "hostActions": true | [string] }      // custom actions left to the host (generic hosts)
45/// ```
46///
47/// `maxTimers` is the workflow contract's run option ([`Actor::set_max_timers`]): every actor
48/// started or restored from the machine takes it, so a run and its restore fire the same timers.
49#[derive(Debug, Clone)]
50pub struct LoadOptions {
51    pub children: Map<String, Value>,
52    pub max_steps: usize,
53    pub max_timers: usize,
54    pub observe_system_emitted: bool,
55    /// `true` is [`HostActions::Unimplemented`]: a generic host binds every
56    /// custom action to the host's `action` implementation otherwise, so it
57    /// binds none then, and every custom action is the host's. A list is
58    /// [`HostActions::Named`]; `false` or `null` is [`HostActions::None`].
59    pub host_actions: HostActions,
60}
61
62impl Default for LoadOptions {
63    fn default() -> Self {
64        Self {
65            children: Map::new(),
66            max_steps: DEFAULT_MAX_STEPS,
67            max_timers: DEFAULT_MAX_TIMERS,
68            observe_system_emitted: false,
69            host_actions: HostActions::None,
70        }
71    }
72}
73
74impl LoadOptions {
75    /// Parses load options from `text` (empty for none). `generic` says
76    /// whether this host loads definitions at run time and so takes
77    /// `children` and `hostActions` (a typed machine compiles its children
78    /// and actions in); an option it does not take is an error.
79    pub fn parse(text: &str, generic: bool) -> Result<Self, String> {
80        let mut options = Self::default();
81        let Some(mut o) = object(text)? else { return Ok(options) };
82        if generic {
83            match o.remove("children") {
84                None | Some(Value::Null) => {}
85                Some(Value::Object(c)) => options.children = c,
86                Some(_) => return Err("options.children must map invoke sources to machine definitions".into()),
87            }
88            options.host_actions = match o.remove("hostActions") {
89                None | Some(Value::Null | Value::Bool(false)) => HostActions::None,
90                Some(Value::Bool(true)) => HostActions::Unimplemented,
91                Some(Value::Array(names)) => HostActions::Named(
92                    names
93                        .into_iter()
94                        .map(|n| match n {
95                            Value::String(n) => Ok(n),
96                            _ => Err("options.hostActions must be true or a list of action names".to_owned()),
97                        })
98                        .collect::<Result<_, _>>()?,
99                ),
100                Some(_) => return Err("options.hostActions must be true or a list of action names".into()),
101            };
102        }
103        match o.remove("maxSteps") {
104            None | Some(Value::Null) => {}
105            // Saturated, not truncated: a usize is 32 bits on wasm32. JSON
106            // does not tell `5` from `5.0`, so a whole float is an integer.
107            Some(v) => {
108                options.max_steps = v
109                    .as_u64()
110                    .or_else(|| v.as_f64().filter(|f| f.fract() == 0.0 && *f >= 0.0).map(|f| f as u64))
111                    .filter(|&n| n > 0)
112                    .map(|n| usize::try_from(n).unwrap_or(usize::MAX))
113                    .ok_or("options.maxSteps must be a positive integer")?
114            }
115        }
116        match o.remove("maxTimers") {
117            None | Some(Value::Null) => {}
118            Some(v) => {
119                options.max_timers = v
120                    .as_u64()
121                    .or_else(|| v.as_f64().filter(|f| f.fract() == 0.0 && *f >= 1.0).map(|f| f as u64))
122                    .filter(|&n| (1..=crate::work::MAX_TIME).contains(&n))
123                    .map(|n| usize::try_from(n).unwrap_or(usize::MAX))
124                    .ok_or("options.maxTimers must be a whole number of timers, 1 or more")?
125            }
126        }
127        match o.remove("observeSystemEmitted") {
128            None | Some(Value::Null) => {}
129            Some(Value::Bool(b)) => options.observe_system_emitted = b,
130            Some(_) => return Err("options.observeSystemEmitted must be a boolean".into()),
131        }
132        unknown(&o)?;
133        Ok(options)
134    }
135
136    /// [`LoadOptions::parse`] as a host's load reports it: options that do
137    /// not parse are `WORKFLOW_INVALID_INPUT`.
138    pub fn parse_contract(text: &str, generic: bool) -> Result<Self, ApplyError> {
139        Self::parse(text, generic).map_err(ApplyError::invalid_input)
140    }
141
142    /// Starts `machine` at `now` with these options and the start's,
143    /// taking the input rather than copying it, as the workflow contract
144    /// starts a run: the root's id is [`ROOT_ID`] unless the start names
145    /// one, the actor takes `maxTimers`, and a start whose root fails, so the
146    /// run has no state to go on from, is `WORKFLOW_MACHINE_FAILED` and no
147    /// actor. A `now` past `2^53 - 1` ([`MAX_TIME`]), which JavaScript does
148    /// not hold exactly, is `WORKFLOW_INVALID_INPUT`, as a time input past it
149    /// is.
150    pub fn start<C, E>(
151        &self,
152        machine: Arc<Machine<C, E>>,
153        start: StartOptions,
154        now: u64,
155    ) -> Result<Actor<C, E>, ApplyError>
156    where
157        C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
158        E: EventType + Send + Sync,
159    {
160        if now > MAX_TIME {
161            return Err(ApplyError::invalid_input("A start's now is whole milliseconds, at most 2^53 - 1."));
162        }
163        let init = InitOptions {
164            input: start.input,
165            id: Some(start.id.unwrap_or_else(|| ROOT_ID.to_owned())),
166            time: now,
167            max_steps: self.max_steps,
168            observe_system_emitted: self.observe_system_emitted,
169            ..Default::default()
170        };
171        let mut actor = Actor::start_with(machine, init).map_err(|e| ApplyError::start_failed(e.to_string()))?;
172        if actor.status() == Status::Error {
173            let message = actor.error().map_or_else(|| "The machine failed as it started.".to_owned(), message_of);
174            return Err(ApplyError::start_failed(message));
175        }
176        actor.set_max_timers(self.max_timers);
177        Ok(actor)
178    }
179
180    /// [`LoadOptions::start`] of start options as JSON text (see
181    /// [`StartOptions::parse`]); the error is [`apply_error_json`] text,
182    /// options that do not parse `WORKFLOW_INVALID_INPUT`.
183    pub fn start_json<C, E>(&self, machine: Arc<Machine<C, E>>, options: &str, now: u64) -> Result<Actor<C, E>, String>
184    where
185        C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
186        E: EventType + Send + Sync,
187    {
188        let start = StartOptions::parse(options).map_err(|e| apply_error_json(&ApplyError::invalid_input(e)))?;
189        self.start(machine, start, now).map_err(|e| apply_error_json(&e))
190    }
191
192    /// Restores `machine` from `snapshot` with these options. A snapshot
193    /// that does not restore is `WORKFLOW_INVALID_SNAPSHOT`, and no actor.
194    pub fn restore<C, E>(&self, machine: Arc<Machine<C, E>>, snapshot: &Value) -> Result<Actor<C, E>, ApplyError>
195    where
196        C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
197        E: EventType + Send + Sync,
198    {
199        let options = RestoreOptions { max_steps: self.max_steps, observe_system_emitted: self.observe_system_emitted };
200        let mut actor =
201            Actor::restore_with(machine, snapshot, options).map_err(|e| ApplyError::invalid_snapshot(e.to_string()))?;
202        actor.set_max_timers(self.max_timers);
203        Ok(actor)
204    }
205
206    /// [`LoadOptions::restore`] of a snapshot as JSON text; the error is
207    /// [`apply_error_json`] text, `WORKFLOW_INVALID_SNAPSHOT` also of text
208    /// that is not JSON.
209    pub fn restore_json<C, E>(&self, machine: Arc<Machine<C, E>>, snapshot: &str) -> Result<Actor<C, E>, String>
210    where
211        C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
212        E: EventType + Send + Sync,
213    {
214        let snapshot =
215            parse_json("snapshot", snapshot).map_err(|e| apply_error_json(&ApplyError::invalid_snapshot(e)))?;
216        self.restore(machine, &snapshot).map_err(|e| apply_error_json(&e))
217    }
218}
219
220/// The message of a root's error: an `Error`'s, as XState persists one, or
221/// the error itself as JSON.
222fn message_of(error: &Value) -> String {
223    match error {
224        Value::String(message) => message.clone(),
225        _ => error.get("message").and_then(Value::as_str).map_or_else(|| error.to_string(), str::to_owned),
226    }
227}
228
229/// The options of a start (JSON, all optional): what differs from one actor
230/// of a machine to the next, and what a snapshot holds, so a restore takes
231/// none.
232///
233/// ```text
234/// { "input": any,  // the root's input
235///   "id": string } // the root's actor id (default `root`, ROOT_ID)
236/// ```
237#[derive(Debug, Clone, Default)]
238pub struct StartOptions {
239    pub input: Option<Value>,
240    pub id: Option<String>,
241}
242
243impl StartOptions {
244    /// Parses start options from `text` (empty for none). A `null` `input` is
245    /// an input; a `null` `id` is no id.
246    pub fn parse(text: &str) -> Result<Self, String> {
247        let mut options = Self::default();
248        let Some(mut o) = object(text)? else { return Ok(options) };
249        options.input = o.remove("input");
250        match o.remove("id") {
251            None | Some(Value::Null) => {}
252            Some(Value::String(s)) => options.id = Some(s),
253            Some(_) => return Err("options.id must be a string".into()),
254        }
255        unknown(&o)?;
256        Ok(options)
257    }
258}
259
260/// The JSON object of options in `text`, or `None` for an empty or blank
261/// string.
262fn object(text: &str) -> Result<Option<Map<String, Value>>, String> {
263    if text.trim().is_empty() {
264        return Ok(None);
265    }
266    match parse_json("options", text)? {
267        Value::Object(o) => Ok(Some(o)),
268        _ => Err("options must be a JSON object".into()),
269    }
270}
271
272/// Fails on the first key the options parse left.
273fn unknown(o: &Map<String, Value>) -> Result<(), String> {
274    match o.keys().next() {
275        Some(k) => Err(format!("unknown option \"{k}\"")),
276        None => Ok(()),
277    }
278}
279
280/// Parses a chunk of [`Actor::apply`] from `text`: a JSON array of inputs, or
281/// one input object as a chunk of one. Anything else, or text that is not
282/// JSON, is a [`WORKFLOW_INVALID_INPUT`](ApplyError::invalid_input).
283pub fn parse_batch(text: &str) -> Result<Vec<Value>, ApplyError> {
284    match serde_json::from_str(text) {
285        Ok(Value::Array(inputs)) => Ok(inputs),
286        Ok(input @ Value::Object(_)) => Ok(vec![input]),
287        Ok(_) => Err(ApplyError::invalid_input("A chunk is an array of inputs, or one input object.")),
288        Err(e) => Err(ApplyError::invalid_input(format!("A chunk is JSON: {e}."))),
289    }
290}
291
292/// A [`Step`] as JSON text, its root's context and output with numbers
293/// written as JavaScript writes them.
294pub fn step_json(mut step: Step) -> String {
295    crate::js_numbers(&mut step.root.context);
296    if let Some(output) = &mut step.root.output {
297        crate::js_numbers(output);
298    }
299    serde_json::to_string(&step).unwrap_or_default()
300}
301
302/// An [`ApplyError`] as JSON text: a rejection,
303/// `{ "rejected": { "message", "data"? } }`, or a fault, `{ "code", "message" }`.
304pub fn apply_error_json(error: &ApplyError) -> String {
305    serde_json::to_string(error).unwrap_or_default()
306}
307
308/// [`Actor::apply`] on JSON text: the chunk in (see [`parse_batch`]), the
309/// step out ([`step_json`]), or the error ([`apply_error_json`]).
310pub fn apply_json<C, E>(actor: &mut Actor<C, E>, batch: &str) -> Result<String, String>
311where
312    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
313    E: EventType + Send + Sync,
314{
315    let batch = parse_batch(batch).map_err(|e| apply_error_json(&e))?;
316    actor.apply(&batch).map(step_json).map_err(|e| apply_error_json(&e))
317}
318
319/// [`crate::Actor::take_system_emitted`] as JSON text, one
320/// `{ "actor": { "@actor", "incarnation" }, "event": ... }` per event.
321pub fn system_emitted_json(emitted: Vec<(ActorRef, Value)>) -> Vec<String> {
322    emitted.into_iter().map(|(actor, event)| json!({ "actor": actor.to_json(), "event": event }).to_string()).collect()
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    #[test]
330    fn load_and_start_options() {
331        let o = LoadOptions::parse(r#"{ "maxSteps": 5, "observeSystemEmitted": true }"#, false).unwrap();
332        assert_eq!((o.max_steps, o.observe_system_emitted), (5, true));
333        assert_eq!(LoadOptions::parse("", true).unwrap().max_steps, DEFAULT_MAX_STEPS);
334        let o = LoadOptions::parse(r#"{ "maxSteps": 4294967299 }"#, true).unwrap();
335        assert!(o.max_steps >= 4_294_967_295);
336        assert_eq!(LoadOptions::parse(r#"{ "maxSteps": 5.0 }"#, true).unwrap().max_steps, 5);
337        assert!(LoadOptions::parse(r#"{ "maxSteps": 1e300 }"#, true).unwrap().max_steps >= 4_294_967_295);
338        assert_eq!(
339            LoadOptions::parse(r#"{ "hostActions": true }"#, true).unwrap().host_actions,
340            HostActions::Unimplemented
341        );
342        assert_eq!(
343            LoadOptions::parse(r#"{ "hostActions": ["a"] }"#, true).unwrap().host_actions,
344            HostActions::Named(vec!["a".into()])
345        );
346        assert_eq!(LoadOptions::parse(r#"{ "hostActions": false }"#, true).unwrap().host_actions, HostActions::None);
347        let o = StartOptions::parse(r#"{ "input": 1, "id": "x" }"#).unwrap();
348        assert_eq!((o.input, o.id.as_deref()), (Some(json!(1)), Some("x")));
349        assert_eq!(StartOptions::parse(r#"{ "id": null }"#).unwrap().id, None);
350
351        let err = |text, generic| LoadOptions::parse(text, generic).unwrap_err();
352        assert_eq!(err(r#"{ "children": {} }"#, false), "unknown option \"children\"");
353        assert_eq!(err(r#"{ "hostActions": true }"#, false), "unknown option \"hostActions\"");
354        assert_eq!(
355            err(r#"{ "hostActions": [1] }"#, true),
356            "options.hostActions must be true or a list of action names"
357        );
358        assert_eq!(err(r#"{ "input": 1 }"#, true), "unknown option \"input\"");
359        assert_eq!(err(r#"{ "maxSteps": 0 }"#, false), "options.maxSteps must be a positive integer");
360        assert_eq!(err(r#"{ "observeSystemEmitted": 1 }"#, true), "options.observeSystemEmitted must be a boolean");
361        assert_eq!(LoadOptions::parse("", true).unwrap().max_timers, DEFAULT_MAX_TIMERS);
362        assert_eq!(LoadOptions::parse(r#"{ "maxTimers": 3.0 }"#, false).unwrap().max_timers, 3);
363        for bad in ["0", "1.5", "-1", "\"3\""] {
364            let text = format!(r#"{{ "maxTimers": {bad} }}"#);
365            let error = LoadOptions::parse(&text, true).unwrap_err();
366            assert_eq!(error, "options.maxTimers must be a whole number of timers, 1 or more", "{bad}");
367        }
368        assert_eq!(err("[]", true), "options must be a JSON object");
369        assert_eq!(StartOptions::parse(r#"{ "maxSteps": 5 }"#).unwrap_err(), "unknown option \"maxSteps\"");
370        assert_eq!(StartOptions::parse(r#"{ "id": 5 }"#).unwrap_err(), "options.id must be a string");
371    }
372
373    fn toggle() -> Arc<Machine<Value, Value>> {
374        let definition =
375            json!({ "id": "t", "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } });
376        Arc::new(Machine::from_json(&definition, &crate::Registry::new()).unwrap())
377    }
378
379    #[test]
380    fn a_start_takes_a_time_javascript_holds_exactly() {
381        let options = LoadOptions::default();
382        let actor = options.start(toggle(), StartOptions::default(), MAX_TIME).unwrap();
383        assert_eq!(actor.now(), MAX_TIME);
384        let Err(error) = options.start(toggle(), StartOptions::default(), MAX_TIME + 1) else {
385            panic!("the start fails")
386        };
387        assert_eq!(error.code(), Some("WORKFLOW_INVALID_INPUT"));
388        let Err(error) = options.start_json(toggle(), "", u64::MAX) else { panic!("the start fails") };
389        assert_eq!(serde_json::from_str::<Value>(&error).unwrap()["code"], "WORKFLOW_INVALID_INPUT");
390        let Err(error) = options.start_json(toggle(), r#"{ "id": 5 }"#, 0) else { panic!("the start fails") };
391        let error: Value = serde_json::from_str(&error).unwrap();
392        assert_eq!(error, json!({ "code": "WORKFLOW_INVALID_INPUT", "message": "options.id must be a string" }));
393    }
394
395    #[test]
396    fn a_snapshot_that_does_not_restore_is_an_invalid_snapshot() {
397        let options = LoadOptions::default();
398        let saved = options.start(toggle(), StartOptions::default(), 0).unwrap().persist();
399        assert!(options.restore_json(toggle(), &saved.to_string()).is_ok());
400        for bad in ["nope", "5", r#"{ "actors": {} }"#] {
401            let Err(error) = options.restore_json(toggle(), bad) else { panic!("the restore fails") };
402            let error: Value = serde_json::from_str(&error).unwrap();
403            assert_eq!(error["code"], "WORKFLOW_INVALID_SNAPSHOT", "{bad}: {error}");
404            assert!(error["message"].is_string(), "{bad}");
405        }
406        let Err(error) = options.restore(toggle(), &json!([])) else { panic!("the restore fails") };
407        assert_eq!(error.code(), Some("WORKFLOW_INVALID_SNAPSHOT"));
408    }
409
410    #[test]
411    fn load_options_that_do_not_parse_are_invalid_input() {
412        let error = LoadOptions::parse_contract(r#"{ "maxSteps": 0 }"#, true).unwrap_err();
413        assert_eq!(error, ApplyError::invalid_input("options.maxSteps must be a positive integer"));
414        assert!(LoadOptions::parse_contract("", false).is_ok());
415    }
416
417    #[test]
418    fn a_chunk_is_an_array_or_one_input() {
419        assert_eq!(parse_batch("[]").unwrap(), Vec::<Value>::new());
420        assert_eq!(parse_batch(r#"{ "type": "go" }"#).unwrap(), [json!({ "type": "go" })]);
421        for bad in ["5", "null", "nope", r#""x""#] {
422            assert_eq!(parse_batch(bad).unwrap_err().code(), Some("WORKFLOW_INVALID_INPUT"), "{bad}");
423        }
424    }
425}