Expand description
§xmachines-wasi-host
Wasmtime hosts for the xmachines WASI components: the generic runtime (xmachines-runtime-wasi, world xmachines:runtime/runtime), which loads any MachineJSON and calls the host for the guards, actions, delays and expressions it references, and typed components built with xmachines-machine-wasi (world xmachines:machine/machine), one machine each with its implementations inside.
§When to use it
Use it to run the components from Rust, isolated in WebAssembly: to load machines a host does not trust, or to run machines built by other teams as components, on the same workflow contract as xmachines-runtime’s Actor::apply, with values as serde_json::Values.
Primitives, not a framework: the bindings of both worlds, Implementations of the runtime’s imports on JSON values, linker setup (Runtime::linker, Machine::linker, or add_to_linker on a linker of the host’s), loading (load, load_file), and the resources of each world, the machine compiled once (RuntimeMachine, TypedMachine: load, start, restore) and its actors (Actor, MachineActor: apply, persist, take_logs, take_system_emitted, stop), with their calls on serde_json::Values and one Error. The host keeps the Engine, the Store and its data (Host: the WASI context, the resource table and the implementations), and passes the WASI context (environment, files, clocks): the crate never reads the process’s environment. Calls are synchronous.
Implementations has a method per import (guard, action, delay, expr, context_expr, evaluate), each failing with missing implementation: <import> "<name>" unless the host writes it, so a host writes only those its machines use. An implementation’s Err(message) is an exception thrown there, which the runtime handles as XState’s live actor does, the error being { "@error": "Error", "message" } as XState persists an Error: an active state’s onError recovers from it; otherwise a guard, delay or expression fails the step, an action fails the actor that ran it inside its step, and a root whose start throws fails the start (Error::Fault with WORKFLOW_MACHINE_FAILED, and no actor). An actor that fails stops its children, and a child reports xstate.error.actor to its parent; the root’s failure on an event rejects the chunk (Error::Rejected with the root’s error as its message and data), and the actor is as it was before it; on a time or work input it ends the run in error, in a step like any other. A host action (load option hostActions) never reaches action: it is work of kind action in the step, which the host settles done. evaluate’s Err is its { "error": message }. The component instance stays usable. Implementations run while the actor is borrowed and must not call back into the same actor.
§Example
A host of the generic runtime with one guard of its own (the component is built as xmachines-runtime-wasi’s README says, or downloaded from a release):
use serde_json::{json, Value};
use xmachines_wasi_host::wasmtime::Store;
use xmachines_wasi_host::wasmtime_wasi::WasiCtx;
use xmachines_wasi_host::{Error, Host, Implementations, Runtime, RuntimeMachine};
struct Road;
impl Implementations for Road {
fn guard(&mut self, name: &str, _: Option<Value>, _: Value, event: Value) -> Result<bool, String> {
match name {
"busy" => Ok(event["cars"].as_u64() > Some(3)),
_ => Err(format!("no guard \"{name}\"")),
}
}
}
fn main() -> Result<(), Error> {
let engine = xmachines_wasi_host::engine()?;
let component = xmachines_wasi_host::load_file(&engine, "xmachines_runtime_wasi.wasm")?;
let linker = Runtime::linker(&engine)?;
// The host's WASI context: here an empty one.
let mut store = Store::new(&engine, Host::new(WasiCtx::builder().build(), Road));
let runtime = Runtime::instantiate(&mut store, &component, &linker)?;
let light = json!({
"id": "light",
"initial": "green",
"states": {
"green": { "on": { "car": { "target": "red", "guard": { "type": "busy" } } } },
"red": {}
}
});
// Compiled once; every actor of it shares the compiled machine.
let machine = RuntimeMachine::load(&mut store, &runtime, &light, &json!({}))?;
let actor = machine.start(&mut store, &json!({}), 0)?;
let step = actor.apply(&mut store, &json!([{ "kind": "time", "now": 10 }, { "type": "car", "cars": 5 }]))?;
assert_eq!(step["root"]["value"], "red");
Ok(())
}The example needs the built component, so its doctest only compiles. A typed component works the same way with Machine::linker, Machine::instantiate, TypedMachine and MachineActor, without implementations (Host<()>), and Machine::info reports its machine.
§Contract
The crate implements the host side of the WIT packages xmachines:runtime@0.4.0 and xmachines:machine@0.3.0; its wit/ files are symbolic links to the components’ own, which cargo package copies into the published crate, so the WIT is written once. Its tests build both components, drive them, and validate every value they pass and return against the packages’ JSON Schemas.
§Runs
RunsMachine (of a Runtime instance: load, open) and Run, and MachineRun (of a typed Machine instance: open), drive the components’ xmachines:workflow runs: apply gives a chunk’s records as values, a fault is Error::RunFault { code, message, seq }, can and checkpoint complete them. The bindings read the WIT of the package beside the worlds’ (wit/workflow.wit).
§Pins
Wasmtime 50 (wasmtime, wasmtime-wasi). The crate re-exports the wasmtime and wasmtime_wasi it is built on, so a host uses exactly those; its types are in the crate’s API, so a Wasmtime major is a major of this crate.
§Related crates
xmachines-runtime-wasi: the generic component.xmachines-machine-wasi: typed components, one machine each.xmachines-runtime: the same runtime in-process, without WebAssembly.
§License
MIT
Re-exports§
pub use wasmtime;pub use wasmtime_wasi;
Modules§
- bindings
- The bindings of both worlds, generated by Wasmtime’s
bindgen!from the components’ own WIT, for hosts that call them directly. Each world is bound as two: its engine, which every component of it exports, and its runs ofxmachines:workflow, which a component exports since that package, and an older one does not: a host instantiates either, and finds the runs when they are there.
Structs§
- Actor
- An actor of the generic runtime: a running machine and its invoked
children, in a
Runtimeinstance, started or restored by aRuntimeMachine. Its calls take the store the instance lives in. - Host
- The data of a store: the WASI context the host passes, the resource table
of the component’s resources, and the host’s implementations (or any
value of its own,
()for a typed component). - Info
- The machine a typed component was built for.
- Machine
- An instance of a typed machine component: its machine’s actors, with the implementations inside.
- Machine
Actor - An actor of a typed machine component, in a
Machineinstance, started or restored by aTypedMachine. Its calls take the store the instance lives in. - Machine
Run - A run of
xmachines:workflow/machine-runsin a typedMachineinstance: a run of the component’s machine, a chunk at a time. - Run
- A run of
xmachines:workflow/runsin aRuntimeinstance, opened by aRunsMachine: a chunk at a time, records out. Its calls take the store the instance lives in. - Runs
Machine - A definition loaded in a
Runtimeinstance for runs ofxmachines:workflow/runs: compiled once with its load options, as aRuntimeMachine, of whichRunsMachine::openopens runs. - Runtime
- An instance of the generic runtime component, whose actors run any
definition with the host’s
Implementations. - Runtime
Machine - A definition loaded in a
Runtimeinstance, compiled once with its load options (all optional):{ "children": { "<src>": MachineJSON }, "maxSteps", "maxTimers", "observeSystemEmitted", "hostActions": true | [name] }. Every actor started or restored from it shares both; aninvoke.srcwithout a child machine is work of kindinvoke, and a host action work of kindaction, in the step. - Typed
Machine - The component’s machine in a typed
Machineinstance, with its load options (all optional):{ "maxSteps", "maxTimers", "observeSystemEmitted" }. The component compiles the machine once per instance; every actor started or restored from this resource shares its options.
Enums§
- Error
- What a call of this crate fails with.
Traits§
- Implementations
- What the host implements for the names a definition references but does
not define: the generic runtime’s
implementationsimports, on JSON values. Every method fails withmissing implementation: <import> "<name>"unless the host writes it, so a host writes only those its machines use.