#![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, Object, ToNapiValue, Undefined, Unknown,
};
use napi::{sys, Env, JsValue, ValueType};
use napi_derive::napi;
use serde_json::{json, Map, Value};
use xmachines_runtime::host::{parse_event, parse_json, system_emitted_json, HostOptions, OptionsFor};
use xmachines_runtime::step::async_logic;
use xmachines_runtime::{Actor as RtActor, HostEvaluator, Logic, Machine, Registry, Status};
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>,
callbacks: &Arc<Callbacks>,
compiled: &mut Compiled,
depth: usize,
) -> Result<Machine<Value, Value>, String> {
if depth > MAX_CHILD_DEPTH {
return Err("child machines are nested too deeply (a child invokes itself?)".into());
}
let refs = Machine::<Value, Value>::references(definition).map_err(|e| e.to_string())?;
let mut registry: Registry<Value, Value> = Registry::new();
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 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, 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, callbacks, compiled, 1)?);
}
}
}
Machine::from_json(definition, ®istry).map_err(|e| e.to_string())
}
fn load(
definition: &str,
options: &str,
callbacks: &Arc<Callbacks>,
call: OptionsFor,
) -> Result<(Arc<Machine<Value, Value>>, HostOptions), String> {
let options = HostOptions::parse(options, call, true)?;
let definition = parse_json("definition", definition)?;
let mut compiled = Compiled::new();
let machine = compile(&definition, &options.children, callbacks, &mut compiled, 0)?;
Ok((Arc::new(machine), options))
}
fn compile_child(
src: &str,
child: &Value,
children: &Map<String, Value>,
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, 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)
}
fn status_str(status: Status) -> &'static str {
match status {
Status::Active => "active",
Status::Done => "done",
Status::Error => "error",
Status::Stopped => "stopped",
}
}
fn millis(now: f64) -> napi::Result<u64> {
if now.is_finite() && now >= 0.0 {
Ok(now as u64)
} else {
Err(napi::Error::from_reason("now must be a non-negative number of milliseconds"))
}
}
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(env: &Env, f: impl FnOnce() -> Result<RtActor<Value, Value>, String>) -> napi::Result<Actor> {
match run(env, f) {
Ok(actor) => Ok(Actor { state: RefCell::new(Ok(actor)) }),
Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
Err(Failure::Fatal(e)) => Err(e),
}
}
pub const RUNTIME_INTERFACE: &str = "xmachines:runtime@0.3.0";
#[napi]
pub fn runtime_interface() -> String {
RUNTIME_INTERFACE.to_string()
}
#[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(factory)]
pub fn start(
env: Env,
definition: String,
options: String,
now: f64,
implementations: Option<Object>,
) -> napi::Result<Self> {
let now = millis(now)?;
let callbacks = Arc::new(Callbacks::from_js(implementations)?);
construct(&env, || {
let (machine, options) = load(&definition, &options, &callbacks, OptionsFor::Start)?;
options.start(machine, now)
})
}
#[napi(factory)]
pub fn restore(
env: Env,
definition: String,
options: String,
snapshot: String,
implementations: Option<Object>,
) -> napi::Result<Self> {
let callbacks = Arc::new(Callbacks::from_js(implementations)?);
construct(&env, || {
let (machine, options) = load(&definition, &options, &callbacks, OptionsFor::Restore)?;
let snapshot = parse_json("snapshot", &snapshot)?;
options.restore(machine, &snapshot)
})
}
#[napi]
pub fn send(&self, env: Env, event: String, now: f64) -> napi::Result<()> {
let now = millis(now)?;
self.with(&env, |a| a.send_json(parse_event(&event)?, now).map_err(|e| e.to_string()))
}
#[napi]
pub fn send_to(&self, env: Env, address: String, event: String, now: f64) -> napi::Result<()> {
let now = millis(now)?;
self.with(&env, |a| a.send_to(&address, parse_event(&event)?, now).map_err(|e| e.to_string()))
}
#[napi]
pub fn advance(&self, env: Env, now: f64) -> napi::Result<()> {
let now = millis(now)?;
self.with(&env, |a| a.advance(now).map_err(|e| e.to_string()))
}
#[napi]
pub fn next_deadline(&self, env: Env) -> napi::Result<Option<f64>> {
self.with(&env, |a| Ok(a.next_deadline().map(|t| t as f64)))
}
#[napi]
pub fn snapshot(&self, env: Env) -> napi::Result<String> {
self.with(&env, |a| {
let mut s = json!({ "status": status_str(a.status()) });
if let (Some(value), Some(context)) = (a.value(), a.context()) {
s["value"] = value;
s["context"] = context.clone();
}
if let Some(output) = a.output() {
s["output"] = output.clone();
}
if let Some(error) = a.error() {
s["error"] = error.clone();
}
Ok(s.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_emitted(&self, env: Env) -> napi::Result<Vec<String>> {
self.with(&env, |a| Ok(a.take_emitted().iter().map(Value::to_string).collect()))
}
#[napi]
pub fn observe_system_emitted(&self, env: Env) -> napi::Result<()> {
self.with(&env, |a| {
a.observe_system_emitted();
Ok(())
})
}
#[napi]
pub fn unobserve_system_emitted(&self, env: Env) -> napi::Result<()> {
self.with(&env, |a| {
a.unobserve_system_emitted();
Ok(())
})
}
#[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 pending_effects(&self, env: Env) -> napi::Result<Vec<String>> {
self.with(&env, |a| Ok(a.pending_effects().iter().map(|e| e.to_json().to_string()).collect()))
}
#[napi]
pub fn resolve_effect(&self, env: Env, id: String, event: Option<String>) -> napi::Result<()> {
self.with(&env, |a| {
let event = event.as_deref().map(parse_event).transpose()?;
a.resolve_effect(&id, event).map_err(|e| e.to_string())
})
}
#[napi]
pub fn stop(&self, env: Env) -> napi::Result<()> {
self.with(&env, |a| a.stop().map_err(|e| e.to_string()))
}
}