xmachines-runtime-wasi 6.0.0

WASI 0.2 component that runs XState v6 machine definitions, with guards and actions from the host
Documentation
#![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};

/// The generated bindings (used by [`export_runtime!`]).
#[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;

/// Exports the generic runtime (world `xmachines:runtime/runtime`: the
/// `actors` interface and `xmachines:workflow/runs`, with `implementations`
/// imported from the host) from the component being built, as `$component`.
#[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;
        }

        // The component-model exports only link on wasm32; native builds
        // just type-check the crate.
        #[cfg(target_arch = "wasm32")]
        $crate::bindings::export_bindings!($component with_types_in $crate::bindings);
    };
}

/// The runtime this crate's own component exports.
#[cfg(feature = "component")]
struct Component;

#[cfg(feature = "component")]
export_runtime!(Component);

/// Children may invoke children; a cycle of child definitions is an error.
const MAX_CHILD_DEPTH: usize = 32;

/// `params` as the host sees them: absent when the reference has none.
fn params_json(p: &Value) -> Option<String> {
    (!p.is_null()).then(|| p.to_string())
}

/// The child machines of the options, each compiled once (by its source).
type Compiled = FixedMap<String, Arc<dyn Logic>>;

/// The component's hash map, of the runtime's [`FixedState`] hasher, never
/// `RandomState`, whose keys std reads of the platform (an import of
/// `wasi:random`): the crate's
/// `clippy.toml` disallows std's `HashMap` and `HashSet` by name.
#[allow(clippy::disallowed_types)]
type FixedMap<K, V> = std::collections::HashMap<K, V, FixedState>;

/// The component's hash set, of the [`FixedState`] hasher (see [`FixedMap`]).
#[allow(clippy::disallowed_types)]
type FixedSet<T> = std::collections::HashSet<T, FixedState>;

/// Compiles a definition, wiring every name it references to the host and
/// every invoke source to a child machine or to host async work. A custom
/// action of `host_actions` is left to the host, so it is bound to no import.
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 {
        // Bound to the import unless the host does it (with `true`, none is
        // bound, so every custom action is unimplemented and the host's).
        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 {
        // Every child machine is loaded, whether the definition invokes it
        // or not, and the root may spawn any of them.
        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, &registry).map_err(|e| e.to_string())
}

/// Loads `definition` with its load options, compiled once. Options that do
/// not parse are `WORKFLOW_INVALID_INPUT`; a definition that is not JSON or
/// does not compile, a child's among them, is `WORKFLOW_INVALID_MACHINE`.
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 })
}

/// The child machine for `invoke.src` `src`, compiled the first time.
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)
}

/// The `machine` resource [`export_runtime!`] exports: a definition compiled
/// once with its load options, which every actor started or restored from it
/// shares.
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) }))
    }
}

/// The `actor` resource [`export_runtime!`] exports. Calls into the host
/// (guards, actions, delays) happen while the actor is borrowed, so the host
/// must not call back into the same actor from them. An error from one of
/// them fails the step or the actor, as an exception does in XState: the
/// root's failure on an event refuses the chunk, and on a time or work input
/// ends the run in `error`; the actor stays usable either way.
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())
    }
}

/// The `machine` resource of `xmachines:workflow/runs` that [`export_runtime!`]
/// exports: a definition compiled once with its load options, as
/// [`MachineResource`], of which runs open.
pub struct RunsMachineResource {
    machine: MachineResource,
}

/// A load error, an [`ApplyError`] fault, as the fault of the record
/// protocol, of no chunk.
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))
    }
}

/// The `run` resource of `xmachines:workflow/runs` that [`export_runtime!`]
/// exports: [`xmachines_workflow::Run`], a chunk at a time, records out. Calls
/// into the host happen while the run is borrowed, as of [`ActorResource`].
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()
    }
}