#![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::{json, Value};
use xmachines_runtime::host::{parse_event, parse_json, system_emitted_json, HostOptions, OptionsFor};
use xmachines_runtime::{Actor, EventType, Machine, Status};
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) }
}
fn status_str(status: Status) -> &'static str {
match status {
Status::Active => "active",
Status::Done => "done",
Status::Error => "error",
Status::Stopped => "stopped",
}
}
pub struct JsonActor<T: TypedMachine> {
actor: Actor<T::Context, T::Event>,
}
impl<T: TypedMachine> JsonActor<T> {
pub fn start(options: &str, now: u64) -> Result<Self, String> {
let options = HostOptions::parse(options, OptionsFor::Start, false)?;
Ok(Self { actor: options.start(compiled::<T>()?, now)? })
}
pub fn restore(options: &str, snapshot: &str) -> Result<Self, String> {
let options = HostOptions::parse(options, OptionsFor::Restore, false)?;
let snapshot = parse_json("snapshot", snapshot)?;
Ok(Self { actor: options.restore(compiled::<T>()?, &snapshot)? })
}
pub fn send(&mut self, event: &str, now: u64) -> Result<(), String> {
let event =
T::Event::from_json(parse_event(event)?).map_err(|e| format!("not an event of this machine: {e}"))?;
self.actor.send(event, now).map_err(|e| e.to_string())
}
pub fn send_to(&mut self, address: &str, event: &str, now: u64) -> Result<(), String> {
let event = parse_event(event)?;
self.actor.send_to(address, event, now).map_err(|e| e.to_string())
}
pub fn advance(&mut self, now: u64) -> Result<(), String> {
self.actor.advance(now).map_err(|e| e.to_string())
}
pub fn next_deadline(&self) -> Option<u64> {
self.actor.next_deadline()
}
pub fn snapshot(&self) -> String {
let a = &self.actor;
let mut s = json!({ "status": status_str(a.status()) });
if let (Some(value), Some(context)) = (a.value(), a.context()) {
let mut context = serde_json::to_value(context).unwrap_or(Value::Null);
xmachines_runtime::js_numbers(&mut context);
s["value"] = value;
s["context"] = context;
}
if let Some(output) = a.output() {
s["output"] = output.clone();
}
if let Some(error) = a.error() {
s["error"] = error.clone();
}
s.to_string()
}
pub fn persist(&self) -> String {
self.actor.persist().to_string()
}
pub fn take_emitted(&mut self) -> Vec<String> {
self.actor.take_emitted().iter().map(Value::to_string).collect()
}
pub fn observe_system_emitted(&mut self) {
self.actor.observe_system_emitted();
}
pub fn unobserve_system_emitted(&mut self) {
self.actor.unobserve_system_emitted();
}
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 pending_effects(&self) -> Vec<String> {
self.actor.pending_effects().iter().map(|e| e.to_json().to_string()).collect()
}
pub fn resolve_effect(&mut self, id: &str, event: Option<&str>) -> Result<(), String> {
let event = event.map(parse_event).transpose()?;
self.actor.resolve_effect(id, event).map_err(|e| e.to_string())
}
pub fn stop(&mut self) -> Result<(), String> {
self.actor.stop().map_err(|e| e.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
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())
}
}
#[test]
fn a_root_context_that_throws_starts_the_actor_in_error() {
let actor = JsonActor::<Unstartable>::start("", 0).unwrap();
let snapshot: Value = serde_json::from_str(&actor.snapshot()).unwrap();
assert_eq!(
snapshot,
json!({ "status": "error", "value": "a", "context": {}, "error": { "@error": "Error", "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_start_throws_has_only_its_error() {
let actor = JsonActor::<Failing>::start("", 0).unwrap();
let snapshot: Value = serde_json::from_str(&actor.snapshot()).unwrap();
assert_eq!(snapshot, json!({ "status": "error", "error": { "@error": "Error", "message": "boom" } }));
}
#[test]
fn a_machine_without_an_id_has_the_default_id() {
assert_eq!(info::<Anonymous>(), Info { id: "(machine)".into(), version: None });
}
#[test]
fn an_effect_resolves_only_with_an_event() {
let mut actor = JsonActor::<Anonymous>::start("", 0).unwrap();
let effects = actor.pending_effects();
let id = serde_json::from_str::<Value>(&effects[0]).unwrap()["id"].as_str().unwrap().to_owned();
for bad in ["5", r#"{ "data": 1 }"#, "null"] {
let err = actor.resolve_effect(&id, Some(bad)).unwrap_err();
assert_eq!(err, "an event must be an object with a string \"type\"");
}
actor.resolve_effect(&id, Some(r#"{ "type": "xstate.async.resolve", "data": 1 }"#)).unwrap();
assert_eq!(serde_json::from_str::<Value>(&actor.snapshot()).unwrap()["value"], "b");
}
}