#![doc = include_str!("../README.md")]
use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::panic::{self, AssertUnwindSafe};
use std::sync::Arc;
use napi::bindgen_prelude::{
Either, FnArgs, FromNapiValue, Function, FunctionRef, JsObjectValue, Object, ToNapiValue, Undefined, Unknown,
};
use napi::{sys, Env, JsValue, ValueType};
use napi_derive::napi;
use serde_json::{json, Map, Value};
use xmachines_runtime::host::{apply_error_json, apply_json, parse_json, system_emitted_json, LoadOptions};
use xmachines_runtime::step::async_logic;
use xmachines_runtime::work::ApplyError;
use xmachines_runtime::{Actor as RtActor, HostActions, HostEvaluator, Logic, Machine as RtMachine, Registry};
const MAX_CHILD_DEPTH: usize = 32;
fn params_arg(p: &Value) -> Either<String, Undefined> {
if p.is_null() {
Either::B(())
} else {
Either::A(p.to_string())
}
}
fn optional_arg(v: Option<String>) -> Either<String, Undefined> {
v.map_or(Either::B(()), Either::A)
}
type GuardRef = FunctionRef<FnArgs<(String, Either<String, Undefined>, String, String)>, Unknown<'static>>;
type ActionRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
type DelayRef = FunctionRef<FnArgs<(String, String, String)>, Unknown<'static>>;
type ExprRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;
type ContextExprRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
type EvaluateRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;
#[derive(Default)]
struct Callbacks {
guard: Option<GuardRef>,
action: Option<ActionRef>,
delay: Option<DelayRef>,
expr: Option<ExprRef>,
context_expr: Option<ContextExprRef>,
evaluate: Option<EvaluateRef>,
}
fn callback<Args, Return>(object: &Object, key: &str) -> napi::Result<Option<FunctionRef<Args, Return>>>
where
Args: napi::bindgen_prelude::JsValuesTupleIntoVec,
Return: napi::bindgen_prelude::FromNapiValue,
{
let Some(value) = object.get::<Unknown>(key)? else { return Ok(None) };
match value.get_type()? {
ValueType::Undefined | ValueType::Null => Ok(None),
ValueType::Function => {
let f: Function<Args, Return> = unsafe { value.cast()? };
Ok(Some(f.bind(object)?.create_ref()?))
}
_ => Err(napi::Error::from_reason(format!("implementations.{key} must be a function"))),
}
}
impl Callbacks {
fn from_js(implementations: Option<Object>) -> napi::Result<Self> {
let Some(o) = implementations else { return Ok(Self::default()) };
Ok(Self {
guard: callback(&o, "guard")?,
action: callback(&o, "action")?,
delay: callback(&o, "delay")?,
expr: callback(&o, "expr")?,
context_expr: callback(&o, "contextExpr")?,
evaluate: callback(&o, "evaluate")?,
})
}
}
thread_local! {
static ENV: Cell<Option<sys::napi_env>> = const { Cell::new(None) };
}
fn call_js<T>(f: impl FnOnce(&Env) -> napi::Result<T>) -> Result<T, String> {
let Some(raw) = ENV.with(Cell::get) else {
return Err("an implementation was called outside a call into the actor".into());
};
let env = Env::from_raw(raw);
env.run_in_scope(|| Ok(f(&env).map_err(|e| thrown_message(&env, e)))).unwrap_or_else(|e| Err(e.reason))
}
fn thrown_message(env: &Env, error: napi::Error) -> String {
let reason = error.reason.clone();
let message = || -> napi::Result<String> {
let value = unsafe { Unknown::from_napi_value(env.raw(), ToNapiValue::to_napi_value(env.raw(), error)?)? };
if value.get_type()? == ValueType::Object {
let object: Object = unsafe { value.cast()? };
if let Some(message) = object.get::<Unknown>("message")? {
if message.get_type()? == ValueType::String {
return unsafe { message.cast::<String>() };
}
}
}
value.coerce_to_string()?.into_utf8()?.into_owned()
};
message().unwrap_or(reason)
}
fn json_result(what: &str, name: &str, value: Unknown) -> napi::Result<Value> {
if value.get_type()? != ValueType::String {
return Err(napi::Error::from_reason(format!("{what} \"{name}\" must return a JSON string")));
}
let text: String = unsafe { value.cast()? };
Ok(serde_json::from_str(&text).unwrap_or(Value::Null))
}
fn missing(kind: &str, name: &str, key: &str) -> String {
format!("the definition references {kind} \"{name}\" but implementations.{key} is missing")
}
type Compiled = HashMap<String, Arc<dyn Logic>>;
fn compile(
definition: &Value,
children: &Map<String, Value>,
host_actions: &HostActions,
callbacks: &Arc<Callbacks>,
compiled: &mut Compiled,
depth: usize,
) -> Result<RtMachine<Value, Value>, String> {
if depth > MAX_CHILD_DEPTH {
return Err("child machines are nested too deeply (a child invokes itself?)".into());
}
let refs = RtMachine::<Value, Value>::references(definition).map_err(|e| e.to_string())?;
let mut registry: Registry<Value, Value> = Registry::new();
registry.host_actions(host_actions.clone());
let mut seen = HashSet::new();
for r in &refs.guards {
if seen.insert(("guard", r.name.clone())) {
if callbacks.guard.is_none() {
return Err(missing("guard", &r.name, "guard"));
}
let (name, cb) = (r.name.clone(), callbacks.clone());
registry.try_guard_with(r.name.clone(), move |args, p: &Value| {
let args = (name.clone(), params_arg(p), args.context.to_string(), args.event.to_json().to_string());
call_js(|env| cb.guard.as_ref().unwrap().borrow_back(env)?.call(args.into())?.coerce_to_bool())
});
}
}
for r in &refs.actions {
if host_actions != &HostActions::Unimplemented
&& !host_actions.includes(&r.name, false)
&& seen.insert(("action", r.name.clone()))
{
if callbacks.action.is_none() {
return Err(missing("action", &r.name, "action"));
}
let (name, cb) = (r.name.clone(), callbacks.clone());
registry.try_action_with(r.name.clone(), move |p: &Value| {
let args = (name.clone(), params_arg(p));
call_js(|env| cb.action.as_ref().unwrap().borrow_back(env)?.call(args.into()).map(drop))
});
}
}
for r in &refs.delays {
if seen.insert(("delay", r.name.clone())) {
if callbacks.delay.is_none() {
return Err(missing("delay", &r.name, "delay"));
}
let (name, cb) = (r.name.clone(), callbacks.clone());
registry.try_delay(r.name.clone(), move |context, event| {
let args = (name.clone(), context.to_string(), event.to_json().to_string());
call_js(|env| {
let result = cb.delay.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
let ms = match result.get_type()? {
ValueType::Number => unsafe { result.cast::<f64>()? },
_ => f64::NAN,
};
if !(ms.is_finite() && ms >= 0.0) {
return Err(napi::Error::from_reason(format!(
"delay \"{name}\" must return a non-negative number of milliseconds"
)));
}
Ok(ms.ceil() as u64)
})
});
}
}
for r in &refs.exprs {
if callbacks.expr.is_none() {
return Err(missing("expression", &r.name, "expr"));
}
let (name, cb) = (r.name.clone(), callbacks.clone());
registry.expr(r.name.clone(), move |args| {
let mut scope = json!({ "context": args.context, "event": args.event.to_json() });
if let Some(params) = args.params {
scope["params"] = params.clone();
}
let call = (name.clone(), scope.to_string());
let result = call_js(|env| {
json_result("expr", &name, cb.expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?)
});
result.unwrap_or_else(|message| {
args.fail(message);
Value::Null
})
});
}
for r in &refs.contexts {
if callbacks.context_expr.is_none() {
return Err(missing("context expression", &r.name, "contextExpr"));
}
let (name, cb) = (r.name.clone(), callbacks.clone());
registry.context_with(r.name.clone(), move |args| {
let call = (name.clone(), optional_arg(args.input.map(Value::to_string)));
let result = call_js(|env| {
let result = cb.context_expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?;
json_result("contextExpr", &name, result)
});
result.unwrap_or_else(|message| {
args.fail(message);
Value::Null
})
});
}
for r in &refs.languages {
if callbacks.evaluate.is_none() {
return Err(missing("code in language", &r.name, "evaluate"));
}
let cb = callbacks.clone();
registry.evaluator(
r.name.clone(),
HostEvaluator(move |code: &str, scope: &str| {
let args = (code.to_owned(), scope.to_owned());
let result = call_js(|env| {
let result = cb.evaluate.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
if result.get_type()? != ValueType::String {
return Err(napi::Error::from_reason("evaluate must return a JSON string"));
}
unsafe { result.cast::<String>() }
});
result.unwrap_or_else(|error| json!({ "error": error }).to_string())
}),
);
}
for r in &refs.actors {
if seen.insert(("actor", r.name.clone())) {
let logic: Arc<dyn Logic> = match children.get(&r.name) {
Some(child) => compile_child(&r.name, child, children, host_actions, callbacks, compiled, depth + 1)?,
None => Arc::new(async_logic(Some(r.name.clone()), None).map_err(|e| e.to_string())?),
};
registry.actor(r.name.clone(), logic);
}
}
if depth == 0 {
for (src, child) in children {
if seen.insert(("actor", src.clone())) {
registry.actor(src.clone(), compile_child(src, child, children, host_actions, callbacks, compiled, 1)?);
}
}
}
RtMachine::from_json(definition, ®istry).map_err(|e| e.to_string())
}
fn load(definition: &str, options: &str, callbacks: &Arc<Callbacks>) -> Result<Machine, ApplyError> {
let options = LoadOptions::parse_contract(options, true)?;
let definition = parse_json("definition", definition).map_err(ApplyError::invalid_machine)?;
let mut compiled = Compiled::new();
let machine = compile(&definition, &options.children, &options.host_actions, callbacks, &mut compiled, 0)
.map_err(ApplyError::invalid_machine)?;
Ok(Machine { machine: Arc::new(machine), options })
}
fn compile_child(
src: &str,
child: &Value,
children: &Map<String, Value>,
host_actions: &HostActions,
callbacks: &Arc<Callbacks>,
compiled: &mut Compiled,
depth: usize,
) -> Result<Arc<dyn Logic>, String> {
if let Some(logic) = compiled.get(src) {
return Ok(logic.clone());
}
let machine = compile(child, children, host_actions, callbacks, compiled, depth)
.map_err(|e| format!("child \"{src}\": {e}"))?;
let logic: Arc<dyn Logic> = Arc::new(machine);
compiled.insert(src.to_owned(), logic.clone());
Ok(logic)
}
const MAX_SAFE: f64 = 9_007_199_254_740_991.0;
fn millis(now: f64) -> Result<u64, String> {
if now.is_finite() && now >= 0.0 && now.fract() == 0.0 && now <= MAX_SAFE {
Ok(now as u64)
} else {
Err(apply_error_json(&ApplyError::invalid_input(
"now must be a whole number of milliseconds, at most 2^53 - 1",
)))
}
}
enum Failure {
Error(String),
Fatal(napi::Error),
}
fn panic_message(payload: &(dyn Any + Send)) -> String {
if let Some(s) = payload.downcast_ref::<&str>() {
(*s).to_owned()
} else if let Some(s) = payload.downcast_ref::<String>() {
s.clone()
} else {
"unknown panic".to_owned()
}
}
fn run<T>(env: &Env, f: impl FnOnce() -> Result<T, String>) -> Result<T, Failure> {
struct Restore(Option<sys::napi_env>);
impl Drop for Restore {
fn drop(&mut self) {
ENV.with(|e| e.set(self.0));
}
}
let _restore = Restore(ENV.with(|e| e.replace(Some(env.raw()))));
match panic::catch_unwind(AssertUnwindSafe(f)) {
Ok(result) => result.map_err(Failure::Error),
Err(payload) => {
Err(Failure::Fatal(napi::Error::from_reason(format!("internal error: {}", panic_message(&*payload)))))
}
}
}
fn construct<T>(env: &Env, f: impl FnOnce() -> Result<T, String>) -> napi::Result<T> {
match run(env, || Ok(f())) {
Ok(Ok(value)) => Ok(value),
Ok(Err(error)) => Err(contract_error(env, &error)),
Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
Err(Failure::Fatal(e)) => Err(e),
}
}
pub const REJECTED: &str = "WORKFLOW_REJECTED";
fn contract_error(env: &Env, text: &str) -> napi::Error {
let error: Value = serde_json::from_str(text).unwrap_or_default();
let field = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_owned();
let rejected = error.get("rejected");
let (code, message) = match rejected {
Some(rejected) => (REJECTED.to_owned(), field(rejected, "message")),
None => (field(&error, "code"), field(&error, "message")),
};
let thrown = || -> napi::Result<napi::Error> {
let mut object = env.create_error(napi::Error::from_reason(message.clone()))?;
object.set_named_property("code", code.as_str())?;
if let Some(rejected) = rejected {
let json: Object = env.get_global()?.get_named_property("JSON")?;
let parse: Function<String, Unknown> = json.get_named_property("parse")?;
object.set_named_property("rejected", parse.call(rejected.to_string())?)?;
}
Ok(napi::Error::from(object.to_unknown()))
};
thrown().unwrap_or_else(|_| napi::Error::from_reason(message.clone()))
}
pub const RUNTIME_INTERFACE: &str = "xmachines:runtime@0.4.0";
#[napi]
pub fn runtime_interface() -> String {
RUNTIME_INTERFACE.to_string()
}
#[napi]
pub struct Machine {
machine: Arc<RtMachine<Value, Value>>,
options: LoadOptions,
}
#[napi]
impl Machine {
#[napi(factory)]
pub fn load(env: Env, definition: String, options: String, implementations: Option<Object>) -> napi::Result<Self> {
let callbacks = Arc::new(Callbacks::from_js(implementations)?);
construct(&env, || load(&definition, &options, &callbacks).map_err(|e| apply_error_json(&e)))
}
#[napi]
pub fn start(&self, env: Env, options: String, now: f64) -> napi::Result<Actor> {
let now = millis(now).map_err(|error| contract_error(&env, &error))?;
let actor = construct(&env, || self.options.start_json(self.machine.clone(), &options, now))?;
Ok(Actor { state: RefCell::new(Ok(actor)) })
}
#[napi]
pub fn restore(&self, env: Env, snapshot: String) -> napi::Result<Actor> {
let actor = construct(&env, || self.options.restore_json(self.machine.clone(), &snapshot))?;
Ok(Actor { state: RefCell::new(Ok(actor)) })
}
}
#[napi]
pub struct Actor {
state: RefCell<Result<RtActor<Value, Value>, String>>,
}
impl Actor {
fn with<T>(&self, env: &Env, f: impl FnOnce(&mut RtActor<Value, Value>) -> Result<T, String>) -> napi::Result<T> {
let Ok(mut state) = self.state.try_borrow_mut() else {
return Err(napi::Error::from_reason("the actor is busy: an implementation called back into it"));
};
let actor = match &mut *state {
Ok(actor) => actor,
Err(why) => return Err(napi::Error::from_reason(format!("the actor is unusable: {why}"))),
};
match run(env, || f(actor)) {
Ok(v) => Ok(v),
Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
Err(Failure::Fatal(e)) => {
*state = Err(format!("an earlier call failed part way through a step ({})", e.reason));
Err(e)
}
}
}
}
#[napi]
impl Actor {
#[napi]
pub fn apply(&self, env: Env, batch: String) -> napi::Result<String> {
self.with(&env, |a| Ok(apply_json(a, &batch)))?.map_err(|error| contract_error(&env, &error))
}
#[napi]
pub fn can(&self, env: Env, event: String) -> napi::Result<bool> {
self.with(&env, |a| {
let event: Value = serde_json::from_str(&event).map_err(|e| format!("invalid event: {e}"))?;
if !event.get("type").is_some_and(Value::is_string) {
return Err("an event must have a string \"type\"".into());
}
a.can_json(&event).map_err(|e| e.to_string())
})
}
#[napi]
pub fn persist(&self, env: Env) -> napi::Result<String> {
self.with(&env, |a| Ok(a.persist().to_string()))
}
#[napi]
pub fn take_system_emitted(&self, env: Env) -> napi::Result<Vec<String>> {
self.with(&env, |a| Ok(system_emitted_json(a.take_system_emitted())))
}
#[napi]
pub fn take_logs(&self, env: Env) -> napi::Result<Vec<String>> {
self.with(&env, |a| Ok(a.take_logs().into_iter().map(|args| Value::Array(args).to_string()).collect()))
}
#[napi]
pub fn stop(&self, env: Env) -> napi::Result<()> {
self.with(&env, |a| a.stop().map_err(|e| e.to_string()))
}
}