Skip to main content

xmachines_machine/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::any::{Any, TypeId};
4use std::sync::{Arc, Mutex, PoisonError};
5
6use serde::de::DeserializeOwned;
7use serde::Serialize;
8use serde_json::Value;
9use xmachines_runtime::host::{apply_error_json, parse_batch, step_json, system_emitted_json, LoadOptions};
10use xmachines_runtime::system::DEFAULT_MAX_STEPS;
11use xmachines_runtime::work::ApplyError;
12use xmachines_runtime::work::DEFAULT_MAX_TIMERS;
13use xmachines_runtime::{Actor, EventType, Machine};
14pub use xmachines_workflow::Run;
15
16/// The machine a guest is built for: its types, its definition and schemas as
17/// codegen emits them, and how to compile it with its implementations.
18pub trait TypedMachine: 'static {
19    /// The machine's context (codegen's `Context`).
20    type Context: Serialize + DeserializeOwned + Clone + Send + Sync + 'static;
21    /// The machine's events (codegen's `Event`); the guests deserialize every
22    /// event sent to the root into it.
23    type Event: EventType + Send + Sync + 'static;
24    /// The `MachineJSON` definition (codegen's `DEFINITION`).
25    const DEFINITION: &'static str;
26    /// The bundle's JSON Schemas (codegen's `SCHEMAS`).
27    const SCHEMAS: &'static str;
28    /// Compiles the machine with its implementations (codegen's `machine`).
29    /// Called once per guest instance, by [`compiled`].
30    fn machine() -> Result<Machine<Self::Context, Self::Event>, String>;
31}
32
33/// A compiled machine, or why it did not compile.
34pub type Compiled<T> = Result<Arc<Machine<<T as TypedMachine>::Context, <T as TypedMachine>::Event>>, String>;
35
36/// The compiled machines of this guest instance, by the type of their
37/// [`TypedMachine`]. A guest exports one machine or a few, so a list is
38/// enough.
39static COMPILED: Mutex<Vec<(TypeId, Box<dyn Any + Send + Sync>)>> = Mutex::new(Vec::new());
40
41/// The machine of `T`, compiled by the first call and shared by every actor
42/// of the guest instance after it (a failure is kept too: the definition and
43/// the implementations are compiled in, so it would fail again).
44pub fn compiled<T: TypedMachine>() -> Compiled<T> {
45    let find = |list: &[(TypeId, Box<dyn Any + Send + Sync>)]| {
46        list.iter().find(|(id, _)| *id == TypeId::of::<T>()).and_then(|(_, c)| c.downcast_ref::<Compiled<T>>().cloned())
47    };
48    if let Some(found) = find(&COMPILED.lock().unwrap_or_else(PoisonError::into_inner)) {
49        return found;
50    }
51    // Compiled without the lock, so that a machine may compile another
52    // component's; when two threads race, the first one kept wins.
53    let machine = T::machine().map(Arc::new);
54    let mut list = COMPILED.lock().unwrap_or_else(PoisonError::into_inner);
55    if let Some(found) = find(&list) {
56        return found;
57    }
58    list.push((TypeId::of::<T>(), Box::new(machine.clone())));
59    machine
60}
61
62/// The machine a guest was built for, as the typed world's `info` reports it.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct Info {
65    /// The machine's `id`, or `(machine)` when the definition has none: the
66    /// id the runtime gives such a machine and its root actor (XState v5's
67    /// default; XState v6's machine has the empty id).
68    pub id: String,
69    /// The definition's `version`, if any.
70    pub version: Option<String>,
71}
72
73/// The id and version of `T`'s machine, from its definition.
74pub fn info<T: TypedMachine>() -> Info {
75    let definition: Value = serde_json::from_str(T::DEFINITION).unwrap_or(Value::Null);
76    let id = definition.get("id").and_then(Value::as_str).unwrap_or("(machine)").to_owned();
77    Info { id, version: definition.get("version").and_then(Value::as_str).map(str::to_owned) }
78}
79
80/// The [`compiled`] machine of a [`TypedMachine`] with its load options, as
81/// the typed world's `machine` resource holds it: every actor started or
82/// restored from it shares both.
83pub struct JsonMachine<T: TypedMachine> {
84    machine: Arc<Machine<T::Context, T::Event>>,
85    options: LoadOptions,
86}
87
88impl<T: TypedMachine> JsonMachine<T> {
89    /// The [`compiled`] machine with load options (JSON, all optional):
90    /// `{ "maxSteps": number, "maxTimers": number, "observeSystemEmitted": bool }`. A typed machine
91    /// compiles its children and actions in, so it takes no `children` or
92    /// `hostActions`. An error is the contract's `{ "code", "message" }`:
93    /// options that do not parse are `WORKFLOW_INVALID_INPUT`, and a machine
94    /// that does not compile `WORKFLOW_INVALID_MACHINE`.
95    pub fn load(options: &str) -> Result<Self, String> {
96        let options = LoadOptions::parse_contract(options, false).map_err(|e| apply_error_json(&e))?;
97        let machine = compiled::<T>().map_err(|e| apply_error_json(&ApplyError::invalid_machine(e)))?;
98        Ok(Self { machine, options })
99    }
100
101    /// Starts an actor at `now`, with `{ "input"?, "id"? }`, its root's id
102    /// `root` unless it names one. An error is the contract's
103    /// `{ "code", "message" }` ([`LoadOptions::start_json`]): a start whose
104    /// root fails is `WORKFLOW_MACHINE_FAILED`, and no actor.
105    pub fn start(&self, options: &str, now: u64) -> Result<JsonActor<T>, String> {
106        Ok(JsonActor { actor: self.options.start_json(self.machine.clone(), options, now)? })
107    }
108
109    /// Restores an actor from [`JsonActor::persist`] output: its `input` and
110    /// `id` are in the snapshot, the rest is the machine's. Runs no actions.
111    /// An error is the contract's `{ "code", "message" }`
112    /// ([`LoadOptions::restore_json`]): a snapshot that does not restore is
113    /// `WORKFLOW_INVALID_SNAPSHOT`.
114    pub fn restore(&self, snapshot: &str) -> Result<JsonActor<T>, String> {
115        Ok(JsonActor { actor: self.options.restore_json(self.machine.clone(), snapshot)? })
116    }
117}
118
119/// An actor of a [`TypedMachine`] behind the typed world's actor API: chunks,
120/// steps and results go in and out as JSON text, and errors are messages, or
121/// the contract's error of a refused chunk: a rejection,
122/// `{ "rejected": { "message", "data"? } }`, or a fault, `{ "code", "message" }`.
123/// Each guest wraps it in its own actor type.
124pub struct JsonActor<T: TypedMachine> {
125    actor: Actor<T::Context, T::Event>,
126}
127
128impl<T: TypedMachine> JsonActor<T> {
129    /// Applies a chunk of inputs as [`Actor::apply`]: a JSON
130    /// array of inputs, or one input object, in; the step's JSON out, or the
131    /// error's: a rejection, `{ "rejected": { "message", "data"? } }`, of an
132    /// event the root failed on or one to a run that is over, after which the
133    /// run goes on as it was, or a fault, `{ "code", "message" }`. An event input that is not an event
134    /// of the machine (it does not deserialize into its `Event` type) is a
135    /// `WORKFLOW_INVALID_INPUT`. An empty chunk gives the current step.
136    pub fn apply(&mut self, batch: &str) -> Result<String, String> {
137        let batch = parse_batch(batch).map_err(|e| apply_error_json(&e))?;
138        for input in batch.iter().filter(|i| i.get("type").is_some_and(Value::is_string)) {
139            if let Err(e) = T::Event::from_json(input.clone()) {
140                return Err(apply_error_json(&ApplyError::invalid_input(format!("not an event of this machine: {e}"))));
141            }
142        }
143        self.actor.apply(&batch).map(step_json).map_err(|e| apply_error_json(&e))
144    }
145
146    /// Whether the root would take `event` (JSON text) now, as
147    /// [`Actor::can`]. An event that is not an event of the machine is an
148    /// error, as is a guard or a transition function that threw.
149    pub fn can(&self, event: &str) -> Result<bool, String> {
150        let event: Value = serde_json::from_str(event).map_err(|e| format!("invalid event: {e}"))?;
151        let event = T::Event::from_json(event).map_err(|e| format!("not an event of this machine: {e}"))?;
152        self.actor.can(&event).map_err(|e| e.to_string())
153    }
154
155    /// The whole system (XState's `SystemSnapshot` shape), for
156    /// [`JsonMachine::restore`].
157    pub fn persist(&self) -> String {
158        self.actor.persist().to_string()
159    }
160
161    /// Events every actor emitted since the last call, oldest first, as
162    /// `{ "actor": { "@actor", "incarnation" }, "event": ... }`; always empty
163    /// unless the machine was loaded with `observeSystemEmitted`.
164    pub fn take_system_emitted(&mut self) -> Vec<String> {
165        system_emitted_json(self.actor.take_system_emitted())
166    }
167
168    /// Argument lists of the root's `@xstate.log` actions since the last call.
169    pub fn take_logs(&mut self) -> Vec<String> {
170        self.actor.take_logs().into_iter().map(|args| Value::Array(args).to_string()).collect()
171    }
172
173    /// Stops the root and its children.
174    pub fn stop(&mut self) -> Result<(), String> {
175        self.actor.stop().map_err(|e| e.to_string())
176    }
177}
178
179/// A run of a [`TypedMachine`]'s machine, of its context and event types.
180pub type TypedRun<T> = Run<<T as TypedMachine>::Context, <T as TypedMachine>::Event>;
181
182/// A run of `T`'s [`compiled`] machine, as the typed world's
183/// `machine-runs` opens one: run options of JSON text in
184/// (`workflow-options.schema.json`), the run and its opening records out,
185/// each JSON text. The run takes the events of `T`'s `Event` type alone. An
186/// error is the record protocol's fault as JSON text,
187/// `{ "code", "message", "seq" }`: a machine that does not compile is
188/// `WORKFLOW_INVALID_MACHINE`.
189pub fn open_run<T: TypedMachine>(options: &str) -> Result<(TypedRun<T>, Vec<String>), String> {
190    let machine = compiled::<T>().map_err(|e| {
191        xmachines_workflow::text::fault_json(&xmachines_workflow::Fault::new(
192            xmachines_workflow::FaultCode::WorkflowInvalidMachine,
193            e,
194            0,
195        ))
196    })?;
197    xmachines_workflow::text::open(machine, options, DEFAULT_MAX_TIMERS, DEFAULT_MAX_STEPS)
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203    use serde_json::json;
204    use xmachines_runtime::Registry;
205
206    /// A machine without an `id`, with an async invoke whose work stays pending.
207    struct Anonymous;
208
209    impl TypedMachine for Anonymous {
210        type Context = Value;
211        type Event = Value;
212        const DEFINITION: &'static str = r#"{ "initial": "a", "states": { "a": { "invoke": { "src": "work", "onDone": { "target": "b" } } }, "b": {} } }"#;
213        const SCHEMAS: &'static str = "{}";
214        fn machine() -> Result<Machine<Value, Value>, String> {
215            let mut registry = Registry::new();
216            let work = xmachines_runtime::step::async_logic(Some("work".into()), None).map_err(|e| e.to_string())?;
217            registry.actor("work", Arc::new(work));
218            Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), &registry).map_err(|e| e.to_string())
219        }
220    }
221
222    /// A machine whose root context throws.
223    struct Unstartable;
224
225    impl TypedMachine for Unstartable {
226        type Context = Value;
227        type Event = Value;
228        const DEFINITION: &'static str =
229            r#"{ "id": "u", "context": { "@code": "start", "@lang": "rust" }, "initial": "a", "states": { "a": {} } }"#;
230        const SCHEMAS: &'static str = "{}";
231        fn machine() -> Result<Machine<Value, Value>, String> {
232            let mut registry = Registry::new();
233            registry.context_with("start", |args| {
234                args.fail("no start");
235                Value::Null
236            });
237            Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), &registry).map_err(|e| e.to_string())
238        }
239    }
240
241    fn step<T: TypedMachine>(actor: &mut JsonActor<T>, batch: &str) -> Value {
242        serde_json::from_str(&actor.apply(batch).unwrap()).unwrap()
243    }
244
245    #[test]
246    fn a_root_context_that_throws_fails_the_start() {
247        let Err(error) = JsonMachine::<Unstartable>::load("").unwrap().start("", 0) else { panic!("the start fails") };
248        assert_eq!(
249            serde_json::from_str::<Value>(&error).unwrap(),
250            json!({ "code": "WORKFLOW_MACHINE_FAILED", "message": "no start" })
251        );
252    }
253
254    /// A machine whose initial step throws.
255    struct Failing;
256
257    impl TypedMachine for Failing {
258        type Context = Value;
259        type Event = Value;
260        const DEFINITION: &'static str = r#"{ "id": "f", "initial": "a", "states": { "a": { "entry": [{ "type": "@xstate.assign", "context": { "n": { "@code": "boom", "@lang": "rust" } } }] } } }"#;
261        const SCHEMAS: &'static str = "{}";
262        fn machine() -> Result<Machine<Value, Value>, String> {
263            let mut registry = Registry::new();
264            registry.expr("boom", |args| {
265                args.fail("boom");
266                Value::Null
267            });
268            Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), &registry).map_err(|e| e.to_string())
269        }
270    }
271
272    #[test]
273    fn a_root_whose_initial_step_throws_fails_the_start() {
274        let Err(error) = JsonMachine::<Failing>::load("").unwrap().start("", 0) else { panic!("the start fails") };
275        assert_eq!(
276            serde_json::from_str::<Value>(&error).unwrap(),
277            json!({ "code": "WORKFLOW_MACHINE_FAILED", "message": "boom" })
278        );
279    }
280
281    /// A machine whose definition does not compile.
282    struct Broken;
283
284    impl TypedMachine for Broken {
285        type Context = Value;
286        type Event = Value;
287        const DEFINITION: &'static str = r#"{ "id": "b", "initial": "nowhere", "states": { "a": {} } }"#;
288        const SCHEMAS: &'static str = "{}";
289        fn machine() -> Result<Machine<Value, Value>, String> {
290            Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), &Registry::new())
291                .map_err(|e| e.to_string())
292        }
293    }
294
295    /// A machine that is done once it takes `finish`.
296    struct Finishing;
297
298    impl TypedMachine for Finishing {
299        type Context = Value;
300        type Event = Value;
301        const DEFINITION: &'static str = r#"{ "id": "f", "initial": "a", "states": { "a": { "on": { "finish": { "target": "b" } } }, "b": { "type": "final" } } }"#;
302        const SCHEMAS: &'static str = "{}";
303        fn machine() -> Result<Machine<Value, Value>, String> {
304            Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), &Registry::new())
305                .map_err(|e| e.to_string())
306        }
307    }
308
309    fn error(text: &str) -> Value {
310        serde_json::from_str(text).unwrap()
311    }
312
313    #[test]
314    fn a_load_that_fails_is_the_contracts_error() {
315        let Err(failed) = JsonMachine::<Broken>::load("") else { panic!("the load fails") };
316        assert_eq!(error(&failed)["code"], "WORKFLOW_INVALID_MACHINE");
317        let Err(failed) = JsonMachine::<Anonymous>::load(r#"{ "children": {} }"#) else { panic!("the load fails") };
318        assert_eq!(
319            error(&failed),
320            json!({ "code": "WORKFLOW_INVALID_INPUT", "message": "unknown option \"children\"" })
321        );
322    }
323
324    #[test]
325    fn a_restore_that_fails_is_an_invalid_snapshot() {
326        let machine = JsonMachine::<Anonymous>::load("").unwrap();
327        for bad in ["nope", "[]", r#"{ "actors": {} }"#] {
328            let Err(failed) = machine.restore(bad) else { panic!("the restore fails") };
329            assert_eq!(error(&failed)["code"], "WORKFLOW_INVALID_SNAPSHOT", "{bad}");
330        }
331    }
332
333    #[test]
334    fn an_event_to_a_run_that_is_done_is_rejected() {
335        let mut actor = JsonMachine::<Finishing>::load("").unwrap().start("", 0).unwrap();
336        assert_eq!(step(&mut actor, r#"{ "type": "finish" }"#)["root"]["status"], "done");
337        let rejected = error(&actor.apply(r#"{ "type": "finish" }"#).unwrap_err());
338        assert!(rejected["rejected"]["message"].is_string(), "{rejected}");
339        assert!(rejected.get("code").is_none(), "{rejected}");
340    }
341
342    #[test]
343    fn a_machine_without_an_id_has_the_default_id() {
344        assert_eq!(info::<Anonymous>(), Info { id: "(machine)".into(), version: None });
345    }
346
347    #[test]
348    fn invoked_work_settles_by_a_work_input() {
349        let machine = JsonMachine::<Anonymous>::load(r#"{ "maxSteps": 100 }"#).unwrap();
350        let mut actor = machine.start("", 0).unwrap();
351        let opening = step(&mut actor, "[]");
352        assert_eq!(opening["work"][0]["kind"], "invoke");
353        assert_eq!(opening["work"][0]["src"], "work");
354        let id = opening["work"][0]["id"].as_str().unwrap().to_owned();
355        let err = actor.apply(&json!([{ "kind": "work", "id": id, "outcome": "done" }]).to_string()).unwrap_err();
356        assert_eq!(serde_json::from_str::<Value>(&err).unwrap()["code"], "WORKFLOW_INVALID_WORK_RESULT");
357        let saved = actor.persist();
358        let done = step(&mut actor, &json!({ "kind": "work", "id": id, "outcome": "resolved", "data": 1 }).to_string());
359        assert_eq!(done["root"]["value"], "b");
360        assert_eq!(done["work"], json!([]));
361        // A restore needs only the snapshot; the machine holds the rest.
362        let mut restored = machine.restore(&saved).unwrap();
363        assert_eq!(step(&mut restored, "[]")["root"]["value"], "a");
364        for bad in ["5", "nope", r#"[{ "kind": "later" }]"#] {
365            let err = restored.apply(bad).unwrap_err();
366            assert_eq!(serde_json::from_str::<Value>(&err).unwrap()["code"], "WORKFLOW_INVALID_INPUT", "{bad}");
367        }
368    }
369}