Skip to main content

xmachines_runtime_wasi/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::cell::RefCell;
4use std::sync::Arc;
5
6use serde_json::{json, Map, Value};
7use xmachines_runtime::host::{apply_error_json, apply_json, parse_json, system_emitted_json, LoadOptions};
8use xmachines_runtime::step::async_logic;
9use xmachines_runtime::work::ApplyError;
10use xmachines_runtime::{Actor as RtActor, FixedState, HostActions, HostEvaluator, Logic, Machine, Registry};
11
12/// The generated bindings (used by [`export_runtime!`]).
13#[doc(hidden)]
14pub mod bindings {
15    wit_bindgen::generate!({
16        world: "runtime",
17        path: "wit",
18        pub_export_macro: true,
19        export_macro_name: "export_bindings",
20        default_bindings_module: "::xmachines_runtime_wasi::bindings",
21    });
22}
23
24use bindings::exports::xmachines::runtime::actors::{
25    Actor as ActorHandle, GuestActor, GuestMachine, Machine as MachineHandle,
26};
27use bindings::exports::xmachines::workflow::runs::{
28    GuestMachine as GuestRunsMachine, GuestRun, Machine as RunsMachineHandle, Run as RunHandle,
29};
30use bindings::xmachines::runtime::implementations as host;
31
32/// Exports the generic runtime (world `xmachines:runtime/runtime`: the
33/// `actors` interface and `xmachines:workflow/runs`, with `implementations`
34/// imported from the host) from the component being built, as `$component`.
35#[macro_export]
36macro_rules! export_runtime {
37    ($component:ident) => {
38        impl $crate::bindings::exports::xmachines::runtime::actors::Guest for $component {
39            type Machine = $crate::MachineResource;
40            type Actor = $crate::ActorResource;
41        }
42
43        impl $crate::bindings::exports::xmachines::workflow::runs::Guest for $component {
44            type Machine = $crate::RunsMachineResource;
45            type Run = $crate::RunResource;
46        }
47
48        // The component-model exports only link on wasm32; native builds
49        // just type-check the crate.
50        #[cfg(target_arch = "wasm32")]
51        $crate::bindings::export_bindings!($component with_types_in $crate::bindings);
52    };
53}
54
55/// The runtime this crate's own component exports.
56#[cfg(feature = "component")]
57struct Component;
58
59#[cfg(feature = "component")]
60export_runtime!(Component);
61
62/// Children may invoke children; a cycle of child definitions is an error.
63const MAX_CHILD_DEPTH: usize = 32;
64
65/// `params` as the host sees them: absent when the reference has none.
66fn params_json(p: &Value) -> Option<String> {
67    (!p.is_null()).then(|| p.to_string())
68}
69
70/// The child machines of the options, each compiled once (by its source).
71type Compiled = FixedMap<String, Arc<dyn Logic>>;
72
73/// The component's hash map, of the runtime's [`FixedState`] hasher, never
74/// `RandomState`, whose keys std reads of the platform (an import of
75/// `wasi:random`): the crate's
76/// `clippy.toml` disallows std's `HashMap` and `HashSet` by name.
77#[allow(clippy::disallowed_types)]
78type FixedMap<K, V> = std::collections::HashMap<K, V, FixedState>;
79
80/// The component's hash set, of the [`FixedState`] hasher (see [`FixedMap`]).
81#[allow(clippy::disallowed_types)]
82type FixedSet<T> = std::collections::HashSet<T, FixedState>;
83
84/// Compiles a definition, wiring every name it references to the host and
85/// every invoke source to a child machine or to host async work. A custom
86/// action of `host_actions` is left to the host, so it is bound to no import.
87fn compile(
88    definition: &Value,
89    children: &Map<String, Value>,
90    host_actions: &HostActions,
91    compiled: &mut Compiled,
92    depth: usize,
93) -> Result<Machine<Value, Value>, String> {
94    if depth > MAX_CHILD_DEPTH {
95        return Err("child machines are nested too deeply (a child invokes itself?)".into());
96    }
97    let refs = Machine::<Value, Value>::references(definition).map_err(|e| e.to_string())?;
98    let mut registry: Registry<Value, Value> = Registry::new();
99    registry.host_actions(host_actions.clone());
100    let mut seen = FixedSet::default();
101    for r in &refs.guards {
102        if seen.insert(("guard", r.name.clone())) {
103            let name = r.name.clone();
104            registry.try_guard_with(r.name.clone(), move |args, p: &Value| {
105                host::guard(
106                    &name,
107                    params_json(p).as_deref(),
108                    &args.context.to_string(),
109                    &args.event.to_json().to_string(),
110                )
111            });
112        }
113    }
114    for r in &refs.actions {
115        // Bound to the import unless the host does it (with `true`, none is
116        // bound, so every custom action is unimplemented and the host's).
117        if host_actions != &HostActions::Unimplemented
118            && !host_actions.includes(&r.name, false)
119            && seen.insert(("action", r.name.clone()))
120        {
121            let name = r.name.clone();
122            registry.try_action_with(r.name.clone(), move |p: &Value| host::action(&name, params_json(p).as_deref()));
123        }
124    }
125    for r in &refs.delays {
126        if seen.insert(("delay", r.name.clone())) {
127            let name = r.name.clone();
128            registry.try_delay(r.name.clone(), move |context, event| {
129                host::delay(&name, &context.to_string(), &event.to_json().to_string())
130            });
131        }
132    }
133    for r in &refs.exprs {
134        let name = r.name.clone();
135        registry.expr(r.name.clone(), move |args| {
136            let mut scope = json!({ "context": args.context, "event": args.event.to_json() });
137            if let Some(params) = args.params {
138                scope["params"] = params.clone();
139            }
140            match host::expr(&name, &scope.to_string()) {
141                Ok(text) => serde_json::from_str(&text).unwrap_or(Value::Null),
142                Err(message) => {
143                    args.fail(message);
144                    Value::Null
145                }
146            }
147        });
148    }
149    for r in &refs.contexts {
150        let name = r.name.clone();
151        registry.context_with(r.name.clone(), move |args| {
152            let input = args.input.map(Value::to_string);
153            match host::context_expr(&name, input.as_deref()) {
154                Ok(text) => serde_json::from_str(&text).unwrap_or(Value::Null),
155                Err(message) => {
156                    args.fail(message);
157                    Value::Null
158                }
159            }
160        });
161    }
162    for r in &refs.languages {
163        registry.evaluator(r.name.clone(), HostEvaluator(|code: &str, scope: &str| host::evaluate(code, scope)));
164    }
165    for r in &refs.actors {
166        if seen.insert(("actor", r.name.clone())) {
167            let logic: Arc<dyn Logic> = match children.get(&r.name) {
168                Some(child) => compile_child(&r.name, child, children, host_actions, compiled, depth + 1)?,
169                None => Arc::new(async_logic(Some(r.name.clone()), None).map_err(|e| e.to_string())?),
170            };
171            registry.actor(r.name.clone(), logic);
172        }
173    }
174    if depth == 0 {
175        // Every child machine is loaded, whether the definition invokes it
176        // or not, and the root may spawn any of them.
177        for (src, child) in children {
178            if seen.insert(("actor", src.clone())) {
179                registry.actor(src.clone(), compile_child(src, child, children, host_actions, compiled, 1)?);
180            }
181        }
182    }
183    Machine::from_json(definition, &registry).map_err(|e| e.to_string())
184}
185
186/// Loads `definition` with its load options, compiled once. Options that do
187/// not parse are `WORKFLOW_INVALID_INPUT`; a definition that is not JSON or
188/// does not compile, a child's among them, is `WORKFLOW_INVALID_MACHINE`.
189fn load(definition: &str, options: &str) -> Result<MachineResource, ApplyError> {
190    let options = LoadOptions::parse_contract(options, true)?;
191    let definition = parse_json("definition", definition).map_err(ApplyError::invalid_machine)?;
192    let mut compiled = Compiled::default();
193    let machine = compile(&definition, &options.children, &options.host_actions, &mut compiled, 0)
194        .map_err(ApplyError::invalid_machine)?;
195    Ok(MachineResource { machine: Arc::new(machine), options })
196}
197
198/// The child machine for `invoke.src` `src`, compiled the first time.
199fn compile_child(
200    src: &str,
201    child: &Value,
202    children: &Map<String, Value>,
203    host_actions: &HostActions,
204    compiled: &mut Compiled,
205    depth: usize,
206) -> Result<Arc<dyn Logic>, String> {
207    if let Some(logic) = compiled.get(src) {
208        return Ok(logic.clone());
209    }
210    let machine =
211        compile(child, children, host_actions, compiled, depth).map_err(|e| format!("child \"{src}\": {e}"))?;
212    let logic: Arc<dyn Logic> = Arc::new(machine);
213    compiled.insert(src.to_owned(), logic.clone());
214    Ok(logic)
215}
216
217/// The `machine` resource [`export_runtime!`] exports: a definition compiled
218/// once with its load options, which every actor started or restored from it
219/// shares.
220pub struct MachineResource {
221    machine: Arc<Machine<Value, Value>>,
222    options: LoadOptions,
223}
224
225impl GuestMachine for MachineResource {
226    fn load(definition: String, options: String) -> Result<MachineHandle, String> {
227        load(&definition, &options).map(MachineHandle::new).map_err(|e| apply_error_json(&e))
228    }
229
230    fn start(&self, options: String, now: u64) -> Result<ActorHandle, String> {
231        let actor = self.options.start_json(self.machine.clone(), &options, now)?;
232        Ok(ActorHandle::new(ActorResource { actor: RefCell::new(actor) }))
233    }
234
235    fn restore(&self, snapshot: String) -> Result<ActorHandle, String> {
236        let actor = self.options.restore_json(self.machine.clone(), &snapshot)?;
237        Ok(ActorHandle::new(ActorResource { actor: RefCell::new(actor) }))
238    }
239}
240
241/// The `actor` resource [`export_runtime!`] exports. Calls into the host
242/// (guards, actions, delays) happen while the actor is borrowed, so the host
243/// must not call back into the same actor from them. An error from one of
244/// them fails the step or the actor, as an exception does in XState: the
245/// root's failure on an event refuses the chunk, and on a time or work input
246/// ends the run in `error`; the actor stays usable either way.
247pub struct ActorResource {
248    actor: RefCell<RtActor<Value, Value>>,
249}
250
251impl GuestActor for ActorResource {
252    fn apply(&self, batch: String) -> Result<String, String> {
253        apply_json(&mut self.actor.borrow_mut(), &batch)
254    }
255
256    fn can(&self, event: String) -> Result<bool, String> {
257        let event: Value = serde_json::from_str(&event).map_err(|e| format!("invalid event: {e}"))?;
258        if !event.get("type").is_some_and(Value::is_string) {
259            return Err("an event must have a string \"type\"".into());
260        }
261        self.actor.borrow().can_json(&event).map_err(|e| e.to_string())
262    }
263
264    fn persist(&self) -> String {
265        self.actor.borrow().persist().to_string()
266    }
267
268    fn take_logs(&self) -> Vec<String> {
269        self.actor.borrow_mut().take_logs().into_iter().map(|args| Value::Array(args).to_string()).collect()
270    }
271
272    fn take_system_emitted(&self) -> Vec<String> {
273        system_emitted_json(self.actor.borrow_mut().take_system_emitted())
274    }
275
276    fn stop(&self) -> Result<(), String> {
277        self.actor.borrow_mut().stop().map_err(|e| e.to_string())
278    }
279}
280
281/// The `machine` resource of `xmachines:workflow/runs` that [`export_runtime!`]
282/// exports: a definition compiled once with its load options, as
283/// [`MachineResource`], of which runs open.
284pub struct RunsMachineResource {
285    machine: MachineResource,
286}
287
288/// A load error, an [`ApplyError`] fault, as the fault of the record
289/// protocol, of no chunk.
290fn fault_of_load(error: &ApplyError) -> String {
291    let code = error
292        .code()
293        .and_then(xmachines_workflow::FaultCode::parse)
294        .unwrap_or(xmachines_workflow::FaultCode::WorkflowInvalidMachine);
295    xmachines_workflow::text::fault_json(&xmachines_workflow::Fault::new(code, error.message(), 0))
296}
297
298impl GuestRunsMachine for RunsMachineResource {
299    fn load(definition: String, options: String) -> Result<RunsMachineHandle, String> {
300        let machine = load(&definition, &options).map_err(|e| fault_of_load(&e))?;
301        Ok(RunsMachineHandle::new(Self { machine }))
302    }
303
304    fn open(&self, options: String) -> Result<(RunHandle, Vec<String>), String> {
305        let MachineResource { machine, options: load } = &self.machine;
306        let (run, opening) =
307            xmachines_workflow::text::open(machine.clone(), &options, load.max_timers, load.max_steps)?;
308        Ok((RunHandle::new(RunResource { run: RefCell::new(run) }), opening))
309    }
310}
311
312/// The `run` resource of `xmachines:workflow/runs` that [`export_runtime!`]
313/// exports: [`xmachines_workflow::Run`], a chunk at a time, records out. Calls
314/// into the host happen while the run is borrowed, as of [`ActorResource`].
315pub struct RunResource {
316    run: RefCell<xmachines_workflow::Run>,
317}
318
319impl GuestRun for RunResource {
320    fn apply(&self, chunk: String) -> Result<Vec<String>, String> {
321        self.run.borrow_mut().apply_text(&chunk)
322    }
323
324    fn can(&self, event: String) -> bool {
325        self.run.borrow().can_text(&event)
326    }
327
328    fn checkpoint(&self) -> String {
329        self.run.borrow().checkpoint_text()
330    }
331}