xmachines-runtime 5.0.0

XState v6 semantics in Rust: a port of XState's interpreter and actor runtime; not affiliated with Stately
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! What the hosts in other languages share: the WASI components
//! (`xmachines-runtime-wasi`, `xmachines-machine-wasi`) and the Node addons (`xmachines-runtime-node`,
//! `xmachines-machine-node`) take their options and chunks and return their steps as JSON text, the same
//! way: a machine is loaded once with [`LoadOptions`], its actors start with [`StartOptions`] or
//! restore from a snapshot alone, and [`apply_json`] is [`Actor::apply`] on JSON text. A refused
//! chunk is the workflow contract's error ([`ApplyError`], [`apply_error_json`]): a rejection,
//! `{ "rejected": { "message", "data"? } }`, or a fault, `{ "code", "message" }`. A load, a start
//! or a restore that fails is a fault too: `WORKFLOW_INVALID_MACHINE` of a definition that does not
//! compile, `WORKFLOW_INVALID_INPUT` of options that do not parse or a start's time past
//! `2^53 - 1`, `WORKFLOW_MACHINE_FAILED` of a root that fails as it starts, and
//! `WORKFLOW_INVALID_SNAPSHOT` of a snapshot that does not restore.

use std::sync::Arc;

use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::{json, Map, Value};

use crate::actor::RestoreOptions;
use crate::event::EventType;
use crate::machine::Machine;
use crate::system::{ActorRef, InitOptions, Status, DEFAULT_MAX_STEPS};
use crate::work::{ApplyError, Step, DEFAULT_MAX_TIMERS, MAX_TIME};
use crate::{Actor, HostActions};

/// The root's actor id of a start that names none, the workflow contract's:
/// a work's `actor` is `root`, or a child's address under it, as `root/charge`.
pub const ROOT_ID: &str = "root";

/// Parses `text` as JSON; `what` names it in the error.
pub fn parse_json(what: &str, text: &str) -> Result<Value, String> {
    serde_json::from_str(text).map_err(|e| format!("invalid {what} JSON: {e}"))
}

/// The options a machine is loaded with (JSON, all optional), which every
/// actor started or restored from it shares, so a restore needs only the
/// snapshot:
///
/// ```text
/// { "children": { "<src>": MachineJSON }, // child machines for `invoke.src` (generic hosts)
///   "maxSteps": number,                   // bound on work per call (default DEFAULT_MAX_STEPS, 10000)
///   "maxTimers": number,                  // timers a time input fires at most in a chunk of control inputs alone (default 1000)
///   "observeSystemEmitted": bool,         // every actor's emitted events, from the start or restore
///   "hostActions": true | [string] }      // custom actions left to the host (generic hosts)
/// ```
///
/// `maxTimers` is the workflow contract's run option ([`Actor::set_max_timers`]): every actor
/// started or restored from the machine takes it, so a run and its restore fire the same timers.
#[derive(Debug, Clone)]
pub struct LoadOptions {
    pub children: Map<String, Value>,
    pub max_steps: usize,
    pub max_timers: usize,
    pub observe_system_emitted: bool,
    /// `true` is [`HostActions::Unimplemented`]: a generic host binds every
    /// custom action to the host's `action` implementation otherwise, so it
    /// binds none then, and every custom action is the host's. A list is
    /// [`HostActions::Named`]; `false` or `null` is [`HostActions::None`].
    pub host_actions: HostActions,
}

impl Default for LoadOptions {
    fn default() -> Self {
        Self {
            children: Map::new(),
            max_steps: DEFAULT_MAX_STEPS,
            max_timers: DEFAULT_MAX_TIMERS,
            observe_system_emitted: false,
            host_actions: HostActions::None,
        }
    }
}

impl LoadOptions {
    /// Parses load options from `text` (empty for none). `generic` says
    /// whether this host loads definitions at run time and so takes
    /// `children` and `hostActions` (a typed machine compiles its children
    /// and actions in); an option it does not take is an error.
    pub fn parse(text: &str, generic: bool) -> Result<Self, String> {
        let mut options = Self::default();
        let Some(mut o) = object(text)? else { return Ok(options) };
        if generic {
            match o.remove("children") {
                None | Some(Value::Null) => {}
                Some(Value::Object(c)) => options.children = c,
                Some(_) => return Err("options.children must map invoke sources to machine definitions".into()),
            }
            options.host_actions = match o.remove("hostActions") {
                None | Some(Value::Null | Value::Bool(false)) => HostActions::None,
                Some(Value::Bool(true)) => HostActions::Unimplemented,
                Some(Value::Array(names)) => HostActions::Named(
                    names
                        .into_iter()
                        .map(|n| match n {
                            Value::String(n) => Ok(n),
                            _ => Err("options.hostActions must be true or a list of action names".to_owned()),
                        })
                        .collect::<Result<_, _>>()?,
                ),
                Some(_) => return Err("options.hostActions must be true or a list of action names".into()),
            };
        }
        match o.remove("maxSteps") {
            None | Some(Value::Null) => {}
            // Saturated, not truncated: a usize is 32 bits on wasm32. JSON
            // does not tell `5` from `5.0`, so a whole float is an integer.
            Some(v) => {
                options.max_steps = v
                    .as_u64()
                    .or_else(|| v.as_f64().filter(|f| f.fract() == 0.0 && *f >= 0.0).map(|f| f as u64))
                    .filter(|&n| n > 0)
                    .map(|n| usize::try_from(n).unwrap_or(usize::MAX))
                    .ok_or("options.maxSteps must be a positive integer")?
            }
        }
        match o.remove("maxTimers") {
            None | Some(Value::Null) => {}
            Some(v) => {
                options.max_timers = v
                    .as_u64()
                    .or_else(|| v.as_f64().filter(|f| f.fract() == 0.0 && *f >= 1.0).map(|f| f as u64))
                    .filter(|&n| (1..=crate::work::MAX_TIME).contains(&n))
                    .map(|n| usize::try_from(n).unwrap_or(usize::MAX))
                    .ok_or("options.maxTimers must be a whole number of timers, 1 or more")?
            }
        }
        match o.remove("observeSystemEmitted") {
            None | Some(Value::Null) => {}
            Some(Value::Bool(b)) => options.observe_system_emitted = b,
            Some(_) => return Err("options.observeSystemEmitted must be a boolean".into()),
        }
        unknown(&o)?;
        Ok(options)
    }

    /// [`LoadOptions::parse`] as a host's load reports it: options that do
    /// not parse are `WORKFLOW_INVALID_INPUT`.
    pub fn parse_contract(text: &str, generic: bool) -> Result<Self, ApplyError> {
        Self::parse(text, generic).map_err(ApplyError::invalid_input)
    }

    /// Starts `machine` at `now` with these options and the start's,
    /// taking the input rather than copying it, as the workflow contract
    /// starts a run: the root's id is [`ROOT_ID`] unless the start names
    /// one, the actor takes `maxTimers`, and a start whose root fails, so the
    /// run has no state to go on from, is `WORKFLOW_MACHINE_FAILED` and no
    /// actor. A `now` past `2^53 - 1` ([`MAX_TIME`]), which JavaScript does
    /// not hold exactly, is `WORKFLOW_INVALID_INPUT`, as a time input past it
    /// is.
    pub fn start<C, E>(
        &self,
        machine: Arc<Machine<C, E>>,
        start: StartOptions,
        now: u64,
    ) -> Result<Actor<C, E>, ApplyError>
    where
        C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
        E: EventType + Send + Sync,
    {
        if now > MAX_TIME {
            return Err(ApplyError::invalid_input("A start's now is whole milliseconds, at most 2^53 - 1."));
        }
        let init = InitOptions {
            input: start.input,
            id: Some(start.id.unwrap_or_else(|| ROOT_ID.to_owned())),
            time: now,
            max_steps: self.max_steps,
            observe_system_emitted: self.observe_system_emitted,
            ..Default::default()
        };
        let mut actor = Actor::start_with(machine, init).map_err(|e| ApplyError::start_failed(e.to_string()))?;
        if actor.status() == Status::Error {
            let message = actor.error().map_or_else(|| "The machine failed as it started.".to_owned(), message_of);
            return Err(ApplyError::start_failed(message));
        }
        actor.set_max_timers(self.max_timers);
        Ok(actor)
    }

    /// [`LoadOptions::start`] of start options as JSON text (see
    /// [`StartOptions::parse`]); the error is [`apply_error_json`] text,
    /// options that do not parse `WORKFLOW_INVALID_INPUT`.
    pub fn start_json<C, E>(&self, machine: Arc<Machine<C, E>>, options: &str, now: u64) -> Result<Actor<C, E>, String>
    where
        C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
        E: EventType + Send + Sync,
    {
        let start = StartOptions::parse(options).map_err(|e| apply_error_json(&ApplyError::invalid_input(e)))?;
        self.start(machine, start, now).map_err(|e| apply_error_json(&e))
    }

    /// Restores `machine` from `snapshot` with these options. A snapshot
    /// that does not restore is `WORKFLOW_INVALID_SNAPSHOT`, and no actor.
    pub fn restore<C, E>(&self, machine: Arc<Machine<C, E>>, snapshot: &Value) -> Result<Actor<C, E>, ApplyError>
    where
        C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
        E: EventType + Send + Sync,
    {
        let options = RestoreOptions { max_steps: self.max_steps, observe_system_emitted: self.observe_system_emitted };
        let mut actor =
            Actor::restore_with(machine, snapshot, options).map_err(|e| ApplyError::invalid_snapshot(e.to_string()))?;
        actor.set_max_timers(self.max_timers);
        Ok(actor)
    }

    /// [`LoadOptions::restore`] of a snapshot as JSON text; the error is
    /// [`apply_error_json`] text, `WORKFLOW_INVALID_SNAPSHOT` also of text
    /// that is not JSON.
    pub fn restore_json<C, E>(&self, machine: Arc<Machine<C, E>>, snapshot: &str) -> Result<Actor<C, E>, String>
    where
        C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
        E: EventType + Send + Sync,
    {
        let snapshot =
            parse_json("snapshot", snapshot).map_err(|e| apply_error_json(&ApplyError::invalid_snapshot(e)))?;
        self.restore(machine, &snapshot).map_err(|e| apply_error_json(&e))
    }
}

/// The message of a root's error: an `Error`'s, as XState persists one, or
/// the error itself as JSON.
fn message_of(error: &Value) -> String {
    match error {
        Value::String(message) => message.clone(),
        _ => error.get("message").and_then(Value::as_str).map_or_else(|| error.to_string(), str::to_owned),
    }
}

/// The options of a start (JSON, all optional): what differs from one actor
/// of a machine to the next, and what a snapshot holds, so a restore takes
/// none.
///
/// ```text
/// { "input": any,  // the root's input
///   "id": string } // the root's actor id (default `root`, ROOT_ID)
/// ```
#[derive(Debug, Clone, Default)]
pub struct StartOptions {
    pub input: Option<Value>,
    pub id: Option<String>,
}

impl StartOptions {
    /// Parses start options from `text` (empty for none). A `null` `input` is
    /// an input; a `null` `id` is no id.
    pub fn parse(text: &str) -> Result<Self, String> {
        let mut options = Self::default();
        let Some(mut o) = object(text)? else { return Ok(options) };
        options.input = o.remove("input");
        match o.remove("id") {
            None | Some(Value::Null) => {}
            Some(Value::String(s)) => options.id = Some(s),
            Some(_) => return Err("options.id must be a string".into()),
        }
        unknown(&o)?;
        Ok(options)
    }
}

/// The JSON object of options in `text`, or `None` for an empty or blank
/// string.
fn object(text: &str) -> Result<Option<Map<String, Value>>, String> {
    if text.trim().is_empty() {
        return Ok(None);
    }
    match parse_json("options", text)? {
        Value::Object(o) => Ok(Some(o)),
        _ => Err("options must be a JSON object".into()),
    }
}

/// Fails on the first key the options parse left.
fn unknown(o: &Map<String, Value>) -> Result<(), String> {
    match o.keys().next() {
        Some(k) => Err(format!("unknown option \"{k}\"")),
        None => Ok(()),
    }
}

/// Parses a chunk of [`Actor::apply`] from `text`: a JSON array of inputs, or
/// one input object as a chunk of one. Anything else, or text that is not
/// JSON, is a [`WORKFLOW_INVALID_INPUT`](ApplyError::invalid_input).
pub fn parse_batch(text: &str) -> Result<Vec<Value>, ApplyError> {
    match serde_json::from_str(text) {
        Ok(Value::Array(inputs)) => Ok(inputs),
        Ok(input @ Value::Object(_)) => Ok(vec![input]),
        Ok(_) => Err(ApplyError::invalid_input("A chunk is an array of inputs, or one input object.")),
        Err(e) => Err(ApplyError::invalid_input(format!("A chunk is JSON: {e}."))),
    }
}

/// A [`Step`] as JSON text, its root's context and output with numbers
/// written as JavaScript writes them.
pub fn step_json(mut step: Step) -> String {
    crate::js_numbers(&mut step.root.context);
    if let Some(output) = &mut step.root.output {
        crate::js_numbers(output);
    }
    serde_json::to_string(&step).unwrap_or_default()
}

/// An [`ApplyError`] as JSON text: a rejection,
/// `{ "rejected": { "message", "data"? } }`, or a fault, `{ "code", "message" }`.
pub fn apply_error_json(error: &ApplyError) -> String {
    serde_json::to_string(error).unwrap_or_default()
}

/// [`Actor::apply`] on JSON text: the chunk in (see [`parse_batch`]), the
/// step out ([`step_json`]), or the error ([`apply_error_json`]).
pub fn apply_json<C, E>(actor: &mut Actor<C, E>, batch: &str) -> Result<String, String>
where
    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
    E: EventType + Send + Sync,
{
    let batch = parse_batch(batch).map_err(|e| apply_error_json(&e))?;
    actor.apply(&batch).map(step_json).map_err(|e| apply_error_json(&e))
}

/// [`crate::Actor::take_system_emitted`] as JSON text, one
/// `{ "actor": { "@actor", "incarnation" }, "event": ... }` per event.
pub fn system_emitted_json(emitted: Vec<(ActorRef, Value)>) -> Vec<String> {
    emitted.into_iter().map(|(actor, event)| json!({ "actor": actor.to_json(), "event": event }).to_string()).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn load_and_start_options() {
        let o = LoadOptions::parse(r#"{ "maxSteps": 5, "observeSystemEmitted": true }"#, false).unwrap();
        assert_eq!((o.max_steps, o.observe_system_emitted), (5, true));
        assert_eq!(LoadOptions::parse("", true).unwrap().max_steps, DEFAULT_MAX_STEPS);
        let o = LoadOptions::parse(r#"{ "maxSteps": 4294967299 }"#, true).unwrap();
        assert!(o.max_steps >= 4_294_967_295);
        assert_eq!(LoadOptions::parse(r#"{ "maxSteps": 5.0 }"#, true).unwrap().max_steps, 5);
        assert!(LoadOptions::parse(r#"{ "maxSteps": 1e300 }"#, true).unwrap().max_steps >= 4_294_967_295);
        assert_eq!(
            LoadOptions::parse(r#"{ "hostActions": true }"#, true).unwrap().host_actions,
            HostActions::Unimplemented
        );
        assert_eq!(
            LoadOptions::parse(r#"{ "hostActions": ["a"] }"#, true).unwrap().host_actions,
            HostActions::Named(vec!["a".into()])
        );
        assert_eq!(LoadOptions::parse(r#"{ "hostActions": false }"#, true).unwrap().host_actions, HostActions::None);
        let o = StartOptions::parse(r#"{ "input": 1, "id": "x" }"#).unwrap();
        assert_eq!((o.input, o.id.as_deref()), (Some(json!(1)), Some("x")));
        assert_eq!(StartOptions::parse(r#"{ "id": null }"#).unwrap().id, None);

        let err = |text, generic| LoadOptions::parse(text, generic).unwrap_err();
        assert_eq!(err(r#"{ "children": {} }"#, false), "unknown option \"children\"");
        assert_eq!(err(r#"{ "hostActions": true }"#, false), "unknown option \"hostActions\"");
        assert_eq!(
            err(r#"{ "hostActions": [1] }"#, true),
            "options.hostActions must be true or a list of action names"
        );
        assert_eq!(err(r#"{ "input": 1 }"#, true), "unknown option \"input\"");
        assert_eq!(err(r#"{ "maxSteps": 0 }"#, false), "options.maxSteps must be a positive integer");
        assert_eq!(err(r#"{ "observeSystemEmitted": 1 }"#, true), "options.observeSystemEmitted must be a boolean");
        assert_eq!(LoadOptions::parse("", true).unwrap().max_timers, DEFAULT_MAX_TIMERS);
        assert_eq!(LoadOptions::parse(r#"{ "maxTimers": 3.0 }"#, false).unwrap().max_timers, 3);
        for bad in ["0", "1.5", "-1", "\"3\""] {
            let text = format!(r#"{{ "maxTimers": {bad} }}"#);
            let error = LoadOptions::parse(&text, true).unwrap_err();
            assert_eq!(error, "options.maxTimers must be a whole number of timers, 1 or more", "{bad}");
        }
        assert_eq!(err("[]", true), "options must be a JSON object");
        assert_eq!(StartOptions::parse(r#"{ "maxSteps": 5 }"#).unwrap_err(), "unknown option \"maxSteps\"");
        assert_eq!(StartOptions::parse(r#"{ "id": 5 }"#).unwrap_err(), "options.id must be a string");
    }

    fn toggle() -> Arc<Machine<Value, Value>> {
        let definition =
            json!({ "id": "t", "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } });
        Arc::new(Machine::from_json(&definition, &crate::Registry::new()).unwrap())
    }

    #[test]
    fn a_start_takes_a_time_javascript_holds_exactly() {
        let options = LoadOptions::default();
        let actor = options.start(toggle(), StartOptions::default(), MAX_TIME).unwrap();
        assert_eq!(actor.now(), MAX_TIME);
        let Err(error) = options.start(toggle(), StartOptions::default(), MAX_TIME + 1) else {
            panic!("the start fails")
        };
        assert_eq!(error.code(), Some("WORKFLOW_INVALID_INPUT"));
        let Err(error) = options.start_json(toggle(), "", u64::MAX) else { panic!("the start fails") };
        assert_eq!(serde_json::from_str::<Value>(&error).unwrap()["code"], "WORKFLOW_INVALID_INPUT");
        let Err(error) = options.start_json(toggle(), r#"{ "id": 5 }"#, 0) else { panic!("the start fails") };
        let error: Value = serde_json::from_str(&error).unwrap();
        assert_eq!(error, json!({ "code": "WORKFLOW_INVALID_INPUT", "message": "options.id must be a string" }));
    }

    #[test]
    fn a_snapshot_that_does_not_restore_is_an_invalid_snapshot() {
        let options = LoadOptions::default();
        let saved = options.start(toggle(), StartOptions::default(), 0).unwrap().persist();
        assert!(options.restore_json(toggle(), &saved.to_string()).is_ok());
        for bad in ["nope", "5", r#"{ "actors": {} }"#] {
            let Err(error) = options.restore_json(toggle(), bad) else { panic!("the restore fails") };
            let error: Value = serde_json::from_str(&error).unwrap();
            assert_eq!(error["code"], "WORKFLOW_INVALID_SNAPSHOT", "{bad}: {error}");
            assert!(error["message"].is_string(), "{bad}");
        }
        let Err(error) = options.restore(toggle(), &json!([])) else { panic!("the restore fails") };
        assert_eq!(error.code(), Some("WORKFLOW_INVALID_SNAPSHOT"));
    }

    #[test]
    fn load_options_that_do_not_parse_are_invalid_input() {
        let error = LoadOptions::parse_contract(r#"{ "maxSteps": 0 }"#, true).unwrap_err();
        assert_eq!(error, ApplyError::invalid_input("options.maxSteps must be a positive integer"));
        assert!(LoadOptions::parse_contract("", false).is_ok());
    }

    #[test]
    fn a_chunk_is_an_array_or_one_input() {
        assert_eq!(parse_batch("[]").unwrap(), Vec::<Value>::new());
        assert_eq!(parse_batch(r#"{ "type": "go" }"#).unwrap(), [json!({ "type": "go" })]);
        for bad in ["5", "null", "nope", r#""x""#] {
            assert_eq!(parse_batch(bad).unwrap_err().code(), Some("WORKFLOW_INVALID_INPUT"), "{bad}");
        }
    }
}