#![doc = include_str!("../README.md")]
use std::cell::RefCell;
use std::sync::Arc;
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, FixedState, HostActions, HostEvaluator, Logic, Machine, Registry};
#[doc(hidden)]
pub mod bindings {
wit_bindgen::generate!({
world: "runtime",
path: "wit",
pub_export_macro: true,
export_macro_name: "export_bindings",
default_bindings_module: "::xmachines_runtime_wasi::bindings",
});
}
use bindings::exports::xmachines::runtime::actors::{
Actor as ActorHandle, GuestActor, GuestMachine, Machine as MachineHandle,
};
use bindings::exports::xmachines::workflow::runs::{
GuestMachine as GuestRunsMachine, GuestRun, Machine as RunsMachineHandle, Run as RunHandle,
};
use bindings::xmachines::runtime::implementations as host;
#[macro_export]
macro_rules! export_runtime {
($component:ident) => {
impl $crate::bindings::exports::xmachines::runtime::actors::Guest for $component {
type Machine = $crate::MachineResource;
type Actor = $crate::ActorResource;
}
impl $crate::bindings::exports::xmachines::workflow::runs::Guest for $component {
type Machine = $crate::RunsMachineResource;
type Run = $crate::RunResource;
}
#[cfg(target_arch = "wasm32")]
$crate::bindings::export_bindings!($component with_types_in $crate::bindings);
};
}
#[cfg(feature = "component")]
struct Component;
#[cfg(feature = "component")]
export_runtime!(Component);
const MAX_CHILD_DEPTH: usize = 32;
fn params_json(p: &Value) -> Option<String> {
(!p.is_null()).then(|| p.to_string())
}
type Compiled = FixedMap<String, Arc<dyn Logic>>;
#[allow(clippy::disallowed_types)]
type FixedMap<K, V> = std::collections::HashMap<K, V, FixedState>;
#[allow(clippy::disallowed_types)]
type FixedSet<T> = std::collections::HashSet<T, FixedState>;
fn compile(
definition: &Value,
children: &Map<String, Value>,
host_actions: &HostActions,
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();
registry.host_actions(host_actions.clone());
let mut seen = FixedSet::default();
for r in &refs.guards {
if seen.insert(("guard", r.name.clone())) {
let name = r.name.clone();
registry.try_guard_with(r.name.clone(), move |args, p: &Value| {
host::guard(
&name,
params_json(p).as_deref(),
&args.context.to_string(),
&args.event.to_json().to_string(),
)
});
}
}
for r in &refs.actions {
if host_actions != &HostActions::Unimplemented
&& !host_actions.includes(&r.name, false)
&& seen.insert(("action", r.name.clone()))
{
let name = r.name.clone();
registry.try_action_with(r.name.clone(), move |p: &Value| host::action(&name, params_json(p).as_deref()));
}
}
for r in &refs.delays {
if seen.insert(("delay", r.name.clone())) {
let name = r.name.clone();
registry.try_delay(r.name.clone(), move |context, event| {
host::delay(&name, &context.to_string(), &event.to_json().to_string())
});
}
}
for r in &refs.exprs {
let name = r.name.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();
}
match host::expr(&name, &scope.to_string()) {
Ok(text) => serde_json::from_str(&text).unwrap_or(Value::Null),
Err(message) => {
args.fail(message);
Value::Null
}
}
});
}
for r in &refs.contexts {
let name = r.name.clone();
registry.context_with(r.name.clone(), move |args| {
let input = args.input.map(Value::to_string);
match host::context_expr(&name, input.as_deref()) {
Ok(text) => serde_json::from_str(&text).unwrap_or(Value::Null),
Err(message) => {
args.fail(message);
Value::Null
}
}
});
}
for r in &refs.languages {
registry.evaluator(r.name.clone(), HostEvaluator(|code: &str, scope: &str| host::evaluate(code, scope)));
}
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, 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, compiled, 1)?);
}
}
}
Machine::from_json(definition, ®istry).map_err(|e| e.to_string())
}
fn load(definition: &str, options: &str) -> Result<MachineResource, ApplyError> {
let options = LoadOptions::parse_contract(options, true)?;
let definition = parse_json("definition", definition).map_err(ApplyError::invalid_machine)?;
let mut compiled = Compiled::default();
let machine = compile(&definition, &options.children, &options.host_actions, &mut compiled, 0)
.map_err(ApplyError::invalid_machine)?;
Ok(MachineResource { machine: Arc::new(machine), options })
}
fn compile_child(
src: &str,
child: &Value,
children: &Map<String, Value>,
host_actions: &HostActions,
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, 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)
}
pub struct MachineResource {
machine: Arc<Machine<Value, Value>>,
options: LoadOptions,
}
impl GuestMachine for MachineResource {
fn load(definition: String, options: String) -> Result<MachineHandle, String> {
load(&definition, &options).map(MachineHandle::new).map_err(|e| apply_error_json(&e))
}
fn start(&self, options: String, now: u64) -> Result<ActorHandle, String> {
let actor = self.options.start_json(self.machine.clone(), &options, now)?;
Ok(ActorHandle::new(ActorResource { actor: RefCell::new(actor) }))
}
fn restore(&self, snapshot: String) -> Result<ActorHandle, String> {
let actor = self.options.restore_json(self.machine.clone(), &snapshot)?;
Ok(ActorHandle::new(ActorResource { actor: RefCell::new(actor) }))
}
}
pub struct ActorResource {
actor: RefCell<RtActor<Value, Value>>,
}
impl GuestActor for ActorResource {
fn apply(&self, batch: String) -> Result<String, String> {
apply_json(&mut self.actor.borrow_mut(), &batch)
}
fn can(&self, event: String) -> Result<bool, String> {
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());
}
self.actor.borrow().can_json(&event).map_err(|e| e.to_string())
}
fn persist(&self) -> String {
self.actor.borrow().persist().to_string()
}
fn take_logs(&self) -> Vec<String> {
self.actor.borrow_mut().take_logs().into_iter().map(|args| Value::Array(args).to_string()).collect()
}
fn take_system_emitted(&self) -> Vec<String> {
system_emitted_json(self.actor.borrow_mut().take_system_emitted())
}
fn stop(&self) -> Result<(), String> {
self.actor.borrow_mut().stop().map_err(|e| e.to_string())
}
}
pub struct RunsMachineResource {
machine: MachineResource,
}
fn fault_of_load(error: &ApplyError) -> String {
let code = error
.code()
.and_then(xmachines_workflow::FaultCode::parse)
.unwrap_or(xmachines_workflow::FaultCode::WorkflowInvalidMachine);
xmachines_workflow::text::fault_json(&xmachines_workflow::Fault::new(code, error.message(), 0))
}
impl GuestRunsMachine for RunsMachineResource {
fn load(definition: String, options: String) -> Result<RunsMachineHandle, String> {
let machine = load(&definition, &options).map_err(|e| fault_of_load(&e))?;
Ok(RunsMachineHandle::new(Self { machine }))
}
fn open(&self, options: String) -> Result<(RunHandle, Vec<String>), String> {
let MachineResource { machine, options: load } = &self.machine;
let (run, opening) =
xmachines_workflow::text::open(machine.clone(), &options, load.max_timers, load.max_steps)?;
Ok((RunHandle::new(RunResource { run: RefCell::new(run) }), opening))
}
}
pub struct RunResource {
run: RefCell<xmachines_workflow::Run>,
}
impl GuestRun for RunResource {
fn apply(&self, chunk: String) -> Result<Vec<String>, String> {
self.run.borrow_mut().apply_text(&chunk)
}
fn can(&self, event: String) -> bool {
self.run.borrow().can_text(&event)
}
fn checkpoint(&self) -> String {
self.run.borrow().checkpoint_text()
}
}