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
16pub trait TypedMachine: 'static {
19 type Context: Serialize + DeserializeOwned + Clone + Send + Sync + 'static;
21 type Event: EventType + Send + Sync + 'static;
24 const DEFINITION: &'static str;
26 const SCHEMAS: &'static str;
28 fn machine() -> Result<Machine<Self::Context, Self::Event>, String>;
31}
32
33pub type Compiled<T> = Result<Arc<Machine<<T as TypedMachine>::Context, <T as TypedMachine>::Event>>, String>;
35
36static COMPILED: Mutex<Vec<(TypeId, Box<dyn Any + Send + Sync>)>> = Mutex::new(Vec::new());
40
41pub 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 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#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct Info {
65 pub id: String,
69 pub version: Option<String>,
71}
72
73pub 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
80pub struct JsonMachine<T: TypedMachine> {
84 machine: Arc<Machine<T::Context, T::Event>>,
85 options: LoadOptions,
86}
87
88impl<T: TypedMachine> JsonMachine<T> {
89 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 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 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
119pub struct JsonActor<T: TypedMachine> {
125 actor: Actor<T::Context, T::Event>,
126}
127
128impl<T: TypedMachine> JsonActor<T> {
129 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 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 pub fn persist(&self) -> String {
158 self.actor.persist().to_string()
159 }
160
161 pub fn take_system_emitted(&mut self) -> Vec<String> {
165 system_emitted_json(self.actor.take_system_emitted())
166 }
167
168 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 pub fn stop(&mut self) -> Result<(), String> {
175 self.actor.stop().map_err(|e| e.to_string())
176 }
177}
178
179pub type TypedRun<T> = Run<<T as TypedMachine>::Context, <T as TypedMachine>::Event>;
181
182pub 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 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(), ®istry).map_err(|e| e.to_string())
219 }
220 }
221
222 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(), ®istry).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 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(), ®istry).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 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 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 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}