#![doc = include_str!("../README.md")]
use std::any::{Any, TypeId};
use std::sync::{Arc, Mutex, PoisonError};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use xmachines_runtime::host::{apply_error_json, parse_batch, step_json, system_emitted_json, LoadOptions};
use xmachines_runtime::work::ApplyError;
use xmachines_runtime::{Actor, EventType, Machine};
pub trait TypedMachine: 'static {
type Context: Serialize + DeserializeOwned + Clone + Send + Sync + 'static;
type Event: EventType + Send + Sync + 'static;
const DEFINITION: &'static str;
const SCHEMAS: &'static str;
fn machine() -> Result<Machine<Self::Context, Self::Event>, String>;
}
pub type Compiled<T> = Result<Arc<Machine<<T as TypedMachine>::Context, <T as TypedMachine>::Event>>, String>;
static COMPILED: Mutex<Vec<(TypeId, Box<dyn Any + Send + Sync>)>> = Mutex::new(Vec::new());
pub fn compiled<T: TypedMachine>() -> Compiled<T> {
let find = |list: &[(TypeId, Box<dyn Any + Send + Sync>)]| {
list.iter().find(|(id, _)| *id == TypeId::of::<T>()).and_then(|(_, c)| c.downcast_ref::<Compiled<T>>().cloned())
};
if let Some(found) = find(&COMPILED.lock().unwrap_or_else(PoisonError::into_inner)) {
return found;
}
let machine = T::machine().map(Arc::new);
let mut list = COMPILED.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(found) = find(&list) {
return found;
}
list.push((TypeId::of::<T>(), Box::new(machine.clone())));
machine
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Info {
pub id: String,
pub version: Option<String>,
}
pub fn info<T: TypedMachine>() -> Info {
let definition: Value = serde_json::from_str(T::DEFINITION).unwrap_or(Value::Null);
let id = definition.get("id").and_then(Value::as_str).unwrap_or("(machine)").to_owned();
Info { id, version: definition.get("version").and_then(Value::as_str).map(str::to_owned) }
}
pub struct JsonMachine<T: TypedMachine> {
machine: Arc<Machine<T::Context, T::Event>>,
options: LoadOptions,
}
impl<T: TypedMachine> JsonMachine<T> {
pub fn load(options: &str) -> Result<Self, String> {
let options = LoadOptions::parse_contract(options, false).map_err(|e| apply_error_json(&e))?;
let machine = compiled::<T>().map_err(|e| apply_error_json(&ApplyError::invalid_machine(e)))?;
Ok(Self { machine, options })
}
pub fn start(&self, options: &str, now: u64) -> Result<JsonActor<T>, String> {
Ok(JsonActor { actor: self.options.start_json(self.machine.clone(), options, now)? })
}
pub fn restore(&self, snapshot: &str) -> Result<JsonActor<T>, String> {
Ok(JsonActor { actor: self.options.restore_json(self.machine.clone(), snapshot)? })
}
}
pub struct JsonActor<T: TypedMachine> {
actor: Actor<T::Context, T::Event>,
}
impl<T: TypedMachine> JsonActor<T> {
pub fn apply(&mut self, batch: &str) -> Result<String, String> {
let batch = parse_batch(batch).map_err(|e| apply_error_json(&e))?;
for input in batch.iter().filter(|i| i.get("type").is_some_and(Value::is_string)) {
if let Err(e) = T::Event::from_json(input.clone()) {
return Err(apply_error_json(&ApplyError::invalid_input(format!("not an event of this machine: {e}"))));
}
}
self.actor.apply(&batch).map(step_json).map_err(|e| apply_error_json(&e))
}
pub fn can(&self, event: &str) -> Result<bool, String> {
let event: Value = serde_json::from_str(event).map_err(|e| format!("invalid event: {e}"))?;
let event = T::Event::from_json(event).map_err(|e| format!("not an event of this machine: {e}"))?;
self.actor.can(&event).map_err(|e| e.to_string())
}
pub fn persist(&self) -> String {
self.actor.persist().to_string()
}
pub fn take_system_emitted(&mut self) -> Vec<String> {
system_emitted_json(self.actor.take_system_emitted())
}
pub fn take_logs(&mut self) -> Vec<String> {
self.actor.take_logs().into_iter().map(|args| Value::Array(args).to_string()).collect()
}
pub fn stop(&mut self) -> Result<(), String> {
self.actor.stop().map_err(|e| e.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use xmachines_runtime::Registry;
struct Anonymous;
impl TypedMachine for Anonymous {
type Context = Value;
type Event = Value;
const DEFINITION: &'static str = r#"{ "initial": "a", "states": { "a": { "invoke": { "src": "work", "onDone": { "target": "b" } } }, "b": {} } }"#;
const SCHEMAS: &'static str = "{}";
fn machine() -> Result<Machine<Value, Value>, String> {
let mut registry = Registry::new();
let work = xmachines_runtime::step::async_logic(Some("work".into()), None).map_err(|e| e.to_string())?;
registry.actor("work", Arc::new(work));
Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), ®istry).map_err(|e| e.to_string())
}
}
struct Unstartable;
impl TypedMachine for Unstartable {
type Context = Value;
type Event = Value;
const DEFINITION: &'static str =
r#"{ "id": "u", "context": { "@code": "start", "@lang": "rust" }, "initial": "a", "states": { "a": {} } }"#;
const SCHEMAS: &'static str = "{}";
fn machine() -> Result<Machine<Value, Value>, String> {
let mut registry = Registry::new();
registry.context_with("start", |args| {
args.fail("no start");
Value::Null
});
Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), ®istry).map_err(|e| e.to_string())
}
}
fn step<T: TypedMachine>(actor: &mut JsonActor<T>, batch: &str) -> Value {
serde_json::from_str(&actor.apply(batch).unwrap()).unwrap()
}
#[test]
fn a_root_context_that_throws_fails_the_start() {
let Err(error) = JsonMachine::<Unstartable>::load("").unwrap().start("", 0) else { panic!("the start fails") };
assert_eq!(
serde_json::from_str::<Value>(&error).unwrap(),
json!({ "code": "WORKFLOW_MACHINE_FAILED", "message": "no start" })
);
}
struct Failing;
impl TypedMachine for Failing {
type Context = Value;
type Event = Value;
const DEFINITION: &'static str = r#"{ "id": "f", "initial": "a", "states": { "a": { "entry": [{ "type": "@xstate.assign", "context": { "n": { "@code": "boom", "@lang": "rust" } } }] } } }"#;
const SCHEMAS: &'static str = "{}";
fn machine() -> Result<Machine<Value, Value>, String> {
let mut registry = Registry::new();
registry.expr("boom", |args| {
args.fail("boom");
Value::Null
});
Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), ®istry).map_err(|e| e.to_string())
}
}
#[test]
fn a_root_whose_initial_step_throws_fails_the_start() {
let Err(error) = JsonMachine::<Failing>::load("").unwrap().start("", 0) else { panic!("the start fails") };
assert_eq!(
serde_json::from_str::<Value>(&error).unwrap(),
json!({ "code": "WORKFLOW_MACHINE_FAILED", "message": "boom" })
);
}
struct Broken;
impl TypedMachine for Broken {
type Context = Value;
type Event = Value;
const DEFINITION: &'static str = r#"{ "id": "b", "initial": "nowhere", "states": { "a": {} } }"#;
const SCHEMAS: &'static str = "{}";
fn machine() -> Result<Machine<Value, Value>, String> {
Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), &Registry::new())
.map_err(|e| e.to_string())
}
}
struct Finishing;
impl TypedMachine for Finishing {
type Context = Value;
type Event = Value;
const DEFINITION: &'static str = r#"{ "id": "f", "initial": "a", "states": { "a": { "on": { "finish": { "target": "b" } } }, "b": { "type": "final" } } }"#;
const SCHEMAS: &'static str = "{}";
fn machine() -> Result<Machine<Value, Value>, String> {
Machine::from_json(&serde_json::from_str(Self::DEFINITION).unwrap(), &Registry::new())
.map_err(|e| e.to_string())
}
}
fn error(text: &str) -> Value {
serde_json::from_str(text).unwrap()
}
#[test]
fn a_load_that_fails_is_the_contracts_error() {
let Err(failed) = JsonMachine::<Broken>::load("") else { panic!("the load fails") };
assert_eq!(error(&failed)["code"], "WORKFLOW_INVALID_MACHINE");
let Err(failed) = JsonMachine::<Anonymous>::load(r#"{ "children": {} }"#) else { panic!("the load fails") };
assert_eq!(
error(&failed),
json!({ "code": "WORKFLOW_INVALID_INPUT", "message": "unknown option \"children\"" })
);
}
#[test]
fn a_restore_that_fails_is_an_invalid_snapshot() {
let machine = JsonMachine::<Anonymous>::load("").unwrap();
for bad in ["nope", "[]", r#"{ "actors": {} }"#] {
let Err(failed) = machine.restore(bad) else { panic!("the restore fails") };
assert_eq!(error(&failed)["code"], "WORKFLOW_INVALID_SNAPSHOT", "{bad}");
}
}
#[test]
fn an_event_to_a_run_that_is_done_is_rejected() {
let mut actor = JsonMachine::<Finishing>::load("").unwrap().start("", 0).unwrap();
assert_eq!(step(&mut actor, r#"{ "type": "finish" }"#)["root"]["status"], "done");
let rejected = error(&actor.apply(r#"{ "type": "finish" }"#).unwrap_err());
assert!(rejected["rejected"]["message"].is_string(), "{rejected}");
assert!(rejected.get("code").is_none(), "{rejected}");
}
#[test]
fn a_machine_without_an_id_has_the_default_id() {
assert_eq!(info::<Anonymous>(), Info { id: "(machine)".into(), version: None });
}
#[test]
fn invoked_work_settles_by_a_work_input() {
let machine = JsonMachine::<Anonymous>::load(r#"{ "maxSteps": 100 }"#).unwrap();
let mut actor = machine.start("", 0).unwrap();
let opening = step(&mut actor, "[]");
assert_eq!(opening["work"][0]["kind"], "invoke");
assert_eq!(opening["work"][0]["src"], "work");
let id = opening["work"][0]["id"].as_str().unwrap().to_owned();
let err = actor.apply(&json!([{ "kind": "work", "id": id, "outcome": "done" }]).to_string()).unwrap_err();
assert_eq!(serde_json::from_str::<Value>(&err).unwrap()["code"], "WORKFLOW_INVALID_WORK_RESULT");
let saved = actor.persist();
let done = step(&mut actor, &json!({ "kind": "work", "id": id, "outcome": "resolved", "data": 1 }).to_string());
assert_eq!(done["root"]["value"], "b");
assert_eq!(done["work"], json!([]));
let mut restored = machine.restore(&saved).unwrap();
assert_eq!(step(&mut restored, "[]")["root"]["value"], "a");
for bad in ["5", "nope", r#"[{ "kind": "later" }]"#] {
let err = restored.apply(bad).unwrap_err();
assert_eq!(serde_json::from_str::<Value>(&err).unwrap()["code"], "WORKFLOW_INVALID_INPUT", "{bad}");
}
}
}