Skip to main content

xmachines_wasi_host/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::fmt;
4use std::marker::PhantomData;
5use std::path::Path;
6
7use serde_json::Value;
8use wasmtime::component::{Component, HasData, Linker, ResourceAny, ResourceTable};
9use wasmtime::{AsContextMut, Engine};
10use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
11
12pub use wasmtime;
13pub use wasmtime_wasi;
14
15/// The bindings of both worlds, generated by Wasmtime's `bindgen!` from the
16/// components' own WIT, for hosts that call them directly. Each world is
17/// bound as two: its engine, which every component of it exports, and its
18/// runs of `xmachines:workflow`, which a component exports since that
19/// package, and an older one does not: a host instantiates either, and finds
20/// the runs when they are there.
21pub mod bindings {
22    /// World `xmachines:runtime/runtime`, the generic runtime, without the
23    /// runs: its imports and `actors`. Its imports are trappable, for what
24    /// only a broken component causes (a value it passes that is not JSON);
25    /// an implementation's error is the import's `result` error.
26    pub mod runtime {
27        wasmtime::component::bindgen!({
28            path: ["wit/workflow.wit", "wit/runtime.wit"],
29            inline: "package xmachines:hosts;
30                world runtime {
31                    import xmachines:runtime/implementations@0.4.0;
32                    export xmachines:runtime/actors@0.4.0;
33                }",
34            world: "xmachines:hosts/runtime",
35            imports: { default: trappable },
36        });
37    }
38
39    /// The runs of `xmachines:workflow/runs` of the generic runtime, of a
40    /// component that exports them.
41    pub mod runtime_runs {
42        wasmtime::component::bindgen!({
43            path: ["wit/workflow.wit", "wit/runtime.wit"],
44            inline: "package xmachines:hosts;
45                world runtime-runs {
46                    export xmachines:workflow/runs@0.1.0;
47                }",
48            world: "xmachines:hosts/runtime-runs",
49        });
50    }
51
52    /// World `xmachines:machine/machine`, a typed component of one machine,
53    /// without the runs: `info` and `actors`.
54    pub mod machine {
55        wasmtime::component::bindgen!({
56            path: ["wit/workflow.wit", "wit/machine.wit"],
57            inline: "package xmachines:hosts;
58                world machine {
59                    export xmachines:machine/info@0.3.0;
60                    export xmachines:machine/actors@0.3.0;
61                }",
62            world: "xmachines:hosts/machine",
63        });
64    }
65
66    /// The runs of `xmachines:workflow/machine-runs` of a typed component
67    /// that exports them.
68    pub mod machine_runs {
69        wasmtime::component::bindgen!({
70            path: ["wit/workflow.wit", "wit/machine.wit"],
71            inline: "package xmachines:hosts;
72                world machine-runs {
73                    export xmachines:workflow/machine-runs@0.1.0;
74                }",
75            world: "xmachines:hosts/machine-runs",
76        });
77    }
78}
79
80use bindings::runtime::xmachines::runtime::implementations;
81
82/// What a call of this crate fails with.
83#[derive(Debug)]
84#[non_exhaustive]
85pub enum Error {
86    /// Wasmtime failed: compiling or linking a component, instantiating it,
87    /// or a trap while it ran.
88    Wasmtime(wasmtime::Error),
89    /// The component refused a call of no contract's error, with its
90    /// message: a `can` of no event, or one whose guard threw, or a `stop`
91    /// that failed.
92    Component(String),
93    /// The run rejected a chunk of `apply`, the contract's
94    /// `{ "rejected": { "message", "data"? } }`: an event the root failed on,
95    /// or one to a run that is `done`, in `error` or stopped, or of a type
96    /// that starts with `xstate.`. The actor is as it was before the chunk,
97    /// and the run goes on.
98    Rejected { message: String, data: Option<Value> },
99    /// A fault, the contract's `{ "code", "message" }`. Of `apply`, the actor
100    /// is as it was before the chunk: `WORKFLOW_INVALID_INPUT`,
101    /// `WORKFLOW_INVALID_WORK_RESULT` or `WORKFLOW_ENGINE_FAILED`. Of a load,
102    /// a start or a restore, there is no machine or actor:
103    /// `WORKFLOW_INVALID_MACHINE`, `WORKFLOW_INVALID_INPUT`,
104    /// `WORKFLOW_MACHINE_FAILED` or `WORKFLOW_INVALID_SNAPSHOT`.
105    Fault { code: String, message: String },
106    /// A fault of a run of `xmachines:workflow`, the record protocol's
107    /// `{ "code", "message", "seq" }`: of `open`, there is no run; of
108    /// `apply`, it is the chunk's terminal outcome, and the run goes on
109    /// after `WORKFLOW_INVALID_INPUT` and `WORKFLOW_INVALID_WORK_RESULT`.
110    RunFault { code: String, message: String, seq: u64 },
111    /// A value that crossed the boundary is not JSON.
112    Json(serde_json::Error),
113}
114
115impl fmt::Display for Error {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        match self {
118            Error::Wasmtime(e) => fmt::Display::fmt(e, f),
119            Error::Component(message) => f.write_str(message),
120            Error::Rejected { message, .. } => write!(f, "rejected: {message}"),
121            Error::Fault { code, message } => write!(f, "{code}: {message}"),
122            Error::RunFault { code, message, seq } => write!(f, "{code} (chunk {seq}): {message}"),
123            Error::Json(e) => fmt::Display::fmt(e, f),
124        }
125    }
126}
127
128impl std::error::Error for Error {
129    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
130        // The wrapped errors are transparent: their sources are ours.
131        match self {
132            Error::Wasmtime(e) => e.source(),
133            Error::Json(e) => e.source(),
134            Error::Component(_) | Error::Rejected { .. } | Error::Fault { .. } | Error::RunFault { .. } => None,
135        }
136    }
137}
138
139impl From<wasmtime::Error> for Error {
140    /// A value the component passed that is not JSON, which trapped the
141    /// call, comes back as it was; anything else is Wasmtime's.
142    fn from(e: wasmtime::Error) -> Self {
143        match e.downcast::<Error>() {
144            Ok(e) => e,
145            Err(e) => Error::Wasmtime(e),
146        }
147    }
148}
149
150impl From<serde_json::Error> for Error {
151    fn from(e: serde_json::Error) -> Self {
152        Error::Json(e)
153    }
154}
155
156/// An engine with Wasmtime's default configuration, which runs the
157/// components. A host that configures its own (fuel, epochs, pooling, a
158/// cache) passes that one instead.
159pub fn engine() -> Result<Engine, Error> {
160    Ok(Engine::new(&wasmtime::Config::new())?)
161}
162
163/// Compiles a component, generic or typed, from its bytes.
164pub fn load(engine: &Engine, bytes: &[u8]) -> Result<Component, Error> {
165    Ok(Component::from_binary(engine, bytes)?)
166}
167
168/// Compiles a component, generic or typed, from a file.
169pub fn load_file(engine: &Engine, path: impl AsRef<Path>) -> Result<Component, Error> {
170    Ok(Component::from_file(engine, path)?)
171}
172
173/// What the host implements for the names a definition references but does
174/// not define: the generic runtime's `implementations` imports, on JSON
175/// values. Every method fails with `missing implementation: <import>
176/// "<name>"` unless the host writes it, so a host writes only those its
177/// machines use.
178///
179/// An `Err` is the message of an exception thrown there, which the runtime
180/// handles as XState's live actor does, the error being `{ "@error":
181/// "Error", "message" }` as XState persists an `Error`: an active state's
182/// `onError` recovers from it (`xstate.error.execution`); otherwise a guard,
183/// delay or expression fails the step (the actor keeps its snapshot from
184/// before the step), an action fails the actor that ran it inside its step,
185/// and a root whose start throws fails the start, [`Error::Fault`] with
186/// `WORKFLOW_MACHINE_FAILED`. An actor that fails stops its children, and a
187/// child reports `xstate.error.actor` to its parent; the root's failure on an
188/// event rejects the chunk, [`Error::Rejected`] with the root's error as
189/// `{ message, data }`, and leaves the actor as it was before it, and on a
190/// time or work input ends the run in `error`. The component instance stays
191/// usable. An `Err` of `evaluate` is its `{ "error": message }`.
192/// Calls happen while the actor is borrowed; an implementation must not call
193/// back into the same actor.
194pub trait Implementations {
195    /// A custom guard (`{ "type": name, "params"?: ... }`), with the context
196    /// and event it is evaluated with. `params` is `None` when the reference
197    /// has none.
198    fn guard(&mut self, name: &str, params: Option<Value>, context: Value, event: Value) -> Result<bool, String> {
199        let _ = (params, context, event);
200        Err(missing("guard", name))
201    }
202
203    /// A custom action, with only its params. It runs inside the step that
204    /// takes it, in order with the step's other actions, before the actor
205    /// takes another input. A host action (load option `hostActions`) never
206    /// reaches it: it is work of kind `action` in the step instead.
207    fn action(&mut self, name: &str, params: Option<Value>) -> Result<(), String> {
208        let _ = params;
209        Err(missing("action", name))
210    }
211
212    /// A named delay in milliseconds, computed when the timer is scheduled.
213    fn delay(&mut self, name: &str, context: Value, event: Value) -> Result<u64, String> {
214        let _ = (context, event);
215        Err(missing("delay", name))
216    }
217
218    /// An expression (XState's code node in the `rust` language) wherever
219    /// XState evaluates one, with the scope `{ "context", "event", "params"? }`.
220    fn expr(&mut self, name: &str, scope: Value) -> Result<Value, String> {
221        let _ = scope;
222        Err(missing("expr", name))
223    }
224
225    /// An expression in the root `context`, computed from the actor's input
226    /// (`None` without one) when it starts.
227    fn context_expr(&mut self, name: &str, input: Option<Value>) -> Result<Value, String> {
228        let _ = input;
229        Err(missing("context-expr", name))
230    }
231
232    /// A code node in a language other than `rust` (`code` is `{ "id",
233    /// "lang", "source", "kind", "slot", "path" }`) with XState's scope. It
234    /// returns `{ "value"?, "enq"?, "error"? }`, as the WIT's `evaluate`
235    /// describes; an `Err` is returned to the component as `{ "error" }`.
236    fn evaluate(&mut self, code: Value, scope: Value) -> Result<Value, String> {
237        let _ = scope;
238        Err(missing("evaluate", code.get("lang").and_then(Value::as_str).unwrap_or_default()))
239    }
240}
241
242/// The message of an implementation the host does not write: the import's
243/// name and the name the machine references (for `evaluate`, the code
244/// node's language).
245fn missing(import: &str, name: &str) -> String {
246    format!("missing implementation: {import} \"{name}\"")
247}
248
249/// No implementations: a host whose machines reference none.
250impl Implementations for () {}
251
252/// The data of a store: the WASI context the host passes, the resource table
253/// of the component's resources, and the host's implementations (or any
254/// value of its own, `()` for a typed component).
255pub struct Host<I> {
256    /// The WASI context: environment, files, clocks and standard streams.
257    pub wasi: WasiCtx,
258    /// The component's resources, actors among them.
259    pub table: ResourceTable,
260    /// The host's implementations of the runtime's imports.
261    pub implementations: I,
262}
263
264impl<I> Host<I> {
265    /// A store's data with the host's WASI context and implementations.
266    pub fn new(wasi: WasiCtx, implementations: I) -> Self {
267        Host { wasi, table: ResourceTable::new(), implementations }
268    }
269}
270
271impl<I: Send> WasiView for Host<I> {
272    fn ctx(&mut self) -> WasiCtxView<'_> {
273        WasiCtxView { ctx: &mut self.wasi, table: &mut self.table }
274    }
275}
276
277impl<I: Implementations> Implementations for Host<I> {
278    fn guard(&mut self, name: &str, params: Option<Value>, context: Value, event: Value) -> Result<bool, String> {
279        self.implementations.guard(name, params, context, event)
280    }
281
282    fn action(&mut self, name: &str, params: Option<Value>) -> Result<(), String> {
283        self.implementations.action(name, params)
284    }
285
286    fn delay(&mut self, name: &str, context: Value, event: Value) -> Result<u64, String> {
287        self.implementations.delay(name, context, event)
288    }
289
290    fn expr(&mut self, name: &str, scope: Value) -> Result<Value, String> {
291        self.implementations.expr(name, scope)
292    }
293
294    fn context_expr(&mut self, name: &str, input: Option<Value>) -> Result<Value, String> {
295        self.implementations.context_expr(name, input)
296    }
297
298    fn evaluate(&mut self, code: Value, scope: Value) -> Result<Value, String> {
299        self.implementations.evaluate(code, scope)
300    }
301}
302
303/// The store's data seen as the bindings' `implementations` host.
304struct Imports<'a, T: ?Sized>(&'a mut T);
305
306/// [`Imports`] as the linker's [`HasData`].
307struct HasImports<T: ?Sized>(PhantomData<T>);
308
309impl<T: ?Sized + 'static> HasData for HasImports<T> {
310    type Data<'a> = Imports<'a, T>;
311}
312
313/// A JSON value the component passed, or a trap.
314fn parse_import(text: &str) -> wasmtime::Result<Value> {
315    serde_json::from_str(text).map_err(|e| wasmtime::Error::new(Error::Json(e)))
316}
317
318impl<T: Implementations + ?Sized> implementations::Host for Imports<'_, T> {
319    fn guard(
320        &mut self,
321        name: String,
322        params: Option<String>,
323        context: String,
324        event: String,
325    ) -> wasmtime::Result<Result<bool, String>> {
326        let params = params.as_deref().map(parse_import).transpose()?;
327        Ok(self.0.guard(&name, params, parse_import(&context)?, parse_import(&event)?))
328    }
329
330    fn action(&mut self, name: String, params: Option<String>) -> wasmtime::Result<Result<(), String>> {
331        let params = params.as_deref().map(parse_import).transpose()?;
332        Ok(self.0.action(&name, params))
333    }
334
335    fn delay(&mut self, name: String, context: String, event: String) -> wasmtime::Result<Result<u64, String>> {
336        Ok(self.0.delay(&name, parse_import(&context)?, parse_import(&event)?))
337    }
338
339    fn expr(&mut self, name: String, scope: String) -> wasmtime::Result<Result<String, String>> {
340        Ok(self.0.expr(&name, parse_import(&scope)?).map(|v| v.to_string()))
341    }
342
343    fn context_expr(&mut self, name: String, input: Option<String>) -> wasmtime::Result<Result<String, String>> {
344        let input = input.as_deref().map(parse_import).transpose()?;
345        Ok(self.0.context_expr(&name, input).map(|v| v.to_string()))
346    }
347
348    fn evaluate(&mut self, code: String, scope: String) -> wasmtime::Result<String> {
349        let result = self.0.evaluate(parse_import(&code)?, parse_import(&scope)?);
350        Ok(result.unwrap_or_else(|error| serde_json::json!({ "error": error })).to_string())
351    }
352}
353
354/// A JSON value the component returned.
355fn parse(text: &str) -> Result<Value, Error> {
356    Ok(serde_json::from_str(text)?)
357}
358
359/// JSON values the component returned.
360fn parse_all(texts: Vec<String>) -> Result<Vec<Value>, Error> {
361    texts.iter().map(|t| parse(t)).collect()
362}
363
364/// An instance of the generic runtime component, whose actors run any
365/// definition with the host's [`Implementations`].
366pub struct Runtime {
367    bindings: bindings::runtime::Runtime,
368    /// The runs of a component that exports them.
369    runs: Option<bindings::runtime_runs::RuntimeRuns>,
370}
371
372impl Runtime {
373    /// A linker with WASI 0.2 and the host's implementations, to which the
374    /// host can add imports of its own (`linker.instance("my:pkg/api")`) for
375    /// a component that exports the runtime next to its own world.
376    pub fn linker<T: WasiView + Implementations + 'static>(engine: &Engine) -> Result<Linker<T>, Error> {
377        let mut linker = Linker::new(engine);
378        Self::add_to_linker(&mut linker)?;
379        Ok(linker)
380    }
381
382    /// Adds WASI 0.2 and the host's implementations to a linker of the
383    /// host's own. A linker that has WASI already needs
384    /// [`Linker::allow_shadowing`].
385    pub fn add_to_linker<T: WasiView + Implementations + 'static>(linker: &mut Linker<T>) -> Result<(), Error> {
386        wasmtime_wasi::p2::add_to_linker_sync(linker)?;
387        implementations::add_to_linker::<T, HasImports<T>>(linker, |data| Imports(data))?;
388        Ok(())
389    }
390
391    /// Instantiates a generic runtime component in a store.
392    pub fn instantiate<T: 'static>(
393        store: impl AsContextMut<Data = T>,
394        component: &Component,
395        linker: &Linker<T>,
396    ) -> Result<Self, Error> {
397        let mut store = store;
398        let instance = linker.instantiate(&mut store, component)?;
399        let bindings = bindings::runtime::Runtime::new(&mut store, &instance)?;
400        // An older component exports no runs: the engine alone, then. One that exports runs this
401        // host cannot read is an error.
402        let runs = match exports_workflow(component, store.as_context_mut().engine()) {
403            true => Some(bindings::runtime_runs::RuntimeRuns::new(&mut store, &instance).map_err(unreadable_runs)?),
404            false => None,
405        };
406        Ok(Runtime { bindings, runs })
407    }
408
409    /// Whether the component exports runs of `xmachines:workflow/runs`: one
410    /// built before that package does not, and runs the engine alone.
411    pub fn has_runs(&self) -> bool {
412        self.runs.is_some()
413    }
414
415    /// The instance's generated bindings.
416    pub fn bindings(&self) -> &bindings::runtime::Runtime {
417        &self.bindings
418    }
419}
420
421/// An instance of a typed machine component: its machine's actors, with the
422/// implementations inside.
423pub struct Machine {
424    bindings: bindings::machine::Machine,
425    /// The runs of a component that exports them.
426    runs: Option<bindings::machine_runs::MachineRuns>,
427}
428
429/// The machine a typed component was built for.
430#[derive(Debug, Clone, PartialEq)]
431pub struct Info {
432    /// The machine's `id`.
433    pub id: String,
434    /// The definition's `version`, if any.
435    pub version: Option<String>,
436    /// The `MachineJSON` definition.
437    pub definition: Value,
438    /// The JSON Schemas of its context, events, emitted events, input and
439    /// output.
440    pub schemas: Value,
441}
442
443impl Machine {
444    /// A linker with WASI 0.2, the only imports of a typed component, to
445    /// which the host can add imports of its own.
446    pub fn linker<T: WasiView + 'static>(engine: &Engine) -> Result<Linker<T>, Error> {
447        let mut linker = Linker::new(engine);
448        Self::add_to_linker(&mut linker)?;
449        Ok(linker)
450    }
451
452    /// Adds WASI 0.2 to a linker of the host's own.
453    pub fn add_to_linker<T: WasiView + 'static>(linker: &mut Linker<T>) -> Result<(), Error> {
454        Ok(wasmtime_wasi::p2::add_to_linker_sync(linker)?)
455    }
456
457    /// Instantiates a typed machine component in a store.
458    pub fn instantiate<T: 'static>(
459        store: impl AsContextMut<Data = T>,
460        component: &Component,
461        linker: &Linker<T>,
462    ) -> Result<Self, Error> {
463        let mut store = store;
464        let instance = linker.instantiate(&mut store, component)?;
465        let bindings = bindings::machine::Machine::new(&mut store, &instance)?;
466        // An older component exports no runs: the engine alone, then. One that exports runs this
467        // host cannot read is an error.
468        let runs = match exports_workflow(component, store.as_context_mut().engine()) {
469            true => Some(bindings::machine_runs::MachineRuns::new(&mut store, &instance).map_err(unreadable_runs)?),
470            false => None,
471        };
472        Ok(Machine { bindings, runs })
473    }
474
475    /// The machine the component was built for.
476    pub fn info(&self, mut store: impl AsContextMut) -> Result<Info, Error> {
477        let info = self.bindings.xmachines_machine_info();
478        Ok(Info {
479            id: info.call_id(&mut store)?,
480            version: info.call_version(&mut store)?,
481            definition: parse(&info.call_definition(&mut store)?)?,
482            schemas: parse(&info.call_schemas(&mut store)?)?,
483        })
484    }
485
486    /// Whether the component exports runs of `xmachines:workflow/machine-runs`:
487    /// one built before that package does not.
488    pub fn has_runs(&self) -> bool {
489        self.runs.is_some()
490    }
491
492    /// The instance's generated bindings.
493    pub fn bindings(&self) -> &bindings::machine::Machine {
494        &self.bindings
495    }
496}
497
498/// The contract's error the component returned: a rejection,
499/// `{ "rejected": { "message", "data"? } }`, is [`Error::Rejected`], and a
500/// fault, `{ "code", "message" }`, [`Error::Fault`]. Text of neither shape is
501/// [`Error::Component`].
502fn contract_error(text: String) -> Error {
503    let Ok(Value::Object(mut e)) = serde_json::from_str::<Value>(&text) else { return Error::Component(text) };
504    let message = |v: &serde_json::Map<String, Value>| v.get("message").and_then(Value::as_str).map(str::to_owned);
505    match (e.remove("rejected"), e.get("code").and_then(Value::as_str)) {
506        (Some(Value::Object(mut rejected)), None) => match message(&rejected) {
507            Some(message) => Error::Rejected { message, data: rejected.remove("data") },
508            None => Error::Component(text),
509        },
510        (None, Some(code)) => match message(&e) {
511            Some(message) => Error::Fault { code: code.to_owned(), message },
512            None => Error::Component(text),
513        },
514        _ => Error::Component(text),
515    }
516}
517
518/// A definition loaded in a [`Runtime`] instance, compiled once with its load
519/// options (all optional): `{ "children": { "<src>": MachineJSON },
520/// "maxSteps", "maxTimers", "observeSystemEmitted", "hostActions": true | [name] }`.
521/// Every actor started or restored from it shares both; an `invoke.src`
522/// without a child machine is work of kind `invoke`, and a host action work
523/// of kind `action`, in the step.
524pub struct RuntimeMachine {
525    actors: bindings::runtime::exports::xmachines::runtime::actors::Guest,
526    resource: ResourceAny,
527}
528
529impl RuntimeMachine {
530    /// Loads `definition` (`MachineJSON`) with its load options. A load that
531    /// fails is [`Error::Fault`]: `WORKFLOW_INVALID_MACHINE` of a definition
532    /// that does not compile, `WORKFLOW_INVALID_INPUT` of options that do not
533    /// parse.
534    pub fn load(
535        mut store: impl AsContextMut,
536        runtime: &Runtime,
537        definition: &Value,
538        options: &Value,
539    ) -> Result<Self, Error> {
540        let actors = runtime.bindings.xmachines_runtime_actors().clone();
541        let (definition, options) = (definition.to_string(), options.to_string());
542        let resource = actors.machine().call_load(&mut store, &definition, &options)?.map_err(contract_error)?;
543        Ok(RuntimeMachine { actors, resource })
544    }
545
546    /// Starts an actor at `now`, with `{ "input"?, "id"? }`, its root's id
547    /// `root` unless it names one. A start that fails is [`Error::Fault`] of
548    /// the contract's code, and no actor: `WORKFLOW_MACHINE_FAILED` of a root
549    /// that failed as it started, `WORKFLOW_INVALID_INPUT` of options that do
550    /// not parse or a `now` past `2^53 - 1`.
551    pub fn start(&self, mut store: impl AsContextMut, options: &Value, now: u64) -> Result<Actor, Error> {
552        let options = options.to_string();
553        let resource =
554            self.actors.machine().call_start(&mut store, self.resource, &options, now)?.map_err(contract_error)?;
555        Ok(Actor { actors: self.actors.clone(), resource })
556    }
557
558    /// Restores an actor from [`Actor::persist`] output. Runs no actions. A
559    /// snapshot that does not restore is [`Error::Fault`] of
560    /// `WORKFLOW_INVALID_SNAPSHOT`.
561    pub fn restore(&self, mut store: impl AsContextMut, snapshot: &Value) -> Result<Actor, Error> {
562        let snapshot = snapshot.to_string();
563        let resource =
564            self.actors.machine().call_restore(&mut store, self.resource, &snapshot)?.map_err(contract_error)?;
565        Ok(Actor { actors: self.actors.clone(), resource })
566    }
567
568    /// Drops the machine's resource in the component. Its actors live on.
569    pub fn release(self, mut store: impl AsContextMut) -> Result<(), Error> {
570        Ok(self.resource.resource_drop(&mut store)?)
571    }
572}
573
574/// An actor of the generic runtime: a running machine and its invoked
575/// children, in a [`Runtime`] instance, started or restored by a
576/// [`RuntimeMachine`]. Its calls take the store the instance lives in.
577pub struct Actor {
578    actors: bindings::runtime::exports::xmachines::runtime::actors::Guest,
579    resource: ResourceAny,
580}
581
582/// The component's machine in a typed [`Machine`] instance, with its load
583/// options (all optional): `{ "maxSteps", "maxTimers", "observeSystemEmitted" }`. The
584/// component compiles the machine once per instance; every actor started or
585/// restored from this resource shares its options.
586pub struct TypedMachine {
587    actors: bindings::machine::exports::xmachines::machine::actors::Guest,
588    resource: ResourceAny,
589}
590
591impl TypedMachine {
592    /// The component's machine with these load options. A load that fails is
593    /// [`Error::Fault`]: `WORKFLOW_INVALID_INPUT` of options that do not
594    /// parse, `WORKFLOW_INVALID_MACHINE` of a machine that does not compile.
595    pub fn load(mut store: impl AsContextMut, machine: &Machine, options: &Value) -> Result<Self, Error> {
596        let actors = machine.bindings.xmachines_machine_actors().clone();
597        let resource = actors.machine().call_load(&mut store, &options.to_string())?.map_err(contract_error)?;
598        Ok(TypedMachine { actors, resource })
599    }
600
601    /// Starts an actor at `now`, with `{ "input"?, "id"? }`, as
602    /// [`RuntimeMachine::start`]: a start that fails is [`Error::Fault`].
603    pub fn start(&self, mut store: impl AsContextMut, options: &Value, now: u64) -> Result<MachineActor, Error> {
604        let options = options.to_string();
605        let resource =
606            self.actors.machine().call_start(&mut store, self.resource, &options, now)?.map_err(contract_error)?;
607        Ok(MachineActor { actors: self.actors.clone(), resource })
608    }
609
610    /// Restores an actor from [`MachineActor::persist`] output. Runs no
611    /// actions. A snapshot that does not restore is [`Error::Fault`] of
612    /// `WORKFLOW_INVALID_SNAPSHOT`.
613    pub fn restore(&self, mut store: impl AsContextMut, snapshot: &Value) -> Result<MachineActor, Error> {
614        let snapshot = snapshot.to_string();
615        let resource =
616            self.actors.machine().call_restore(&mut store, self.resource, &snapshot)?.map_err(contract_error)?;
617        Ok(MachineActor { actors: self.actors.clone(), resource })
618    }
619
620    /// Drops the machine's resource in the component. Its actors live on.
621    pub fn release(self, mut store: impl AsContextMut) -> Result<(), Error> {
622        Ok(self.resource.resource_drop(&mut store)?)
623    }
624}
625
626/// An actor of a typed machine component, in a [`Machine`] instance, started
627/// or restored by a [`TypedMachine`]. Its calls take the store the instance
628/// lives in.
629pub struct MachineActor {
630    actors: bindings::machine::exports::xmachines::machine::actors::Guest,
631    resource: ResourceAny,
632}
633
634/// The calls both worlds' `actor` resources share.
635macro_rules! actor_calls {
636    ($actor:ident) => {
637        impl $actor {
638            /// Applies a chunk of inputs: an array of the contract's inputs
639            /// (`{ "kind": "time", "now" }`; `{ "kind": "work", "id",
640            /// "outcome", "data"? }`; anything else with a `type` is an event),
641            /// or one input. Returns the step: `{ "emitted", "root", "time",
642            /// "deadline"?, "work" }`. An empty chunk, `[]`, gives the current
643            /// step. A refused chunk leaves the actor as it was: an event that
644            /// fails, or one to a run that is over, is [`Error::Rejected`],
645            /// after which the run goes on; an input that is no input or a
646            /// result of the other kind of work is [`Error::Fault`]. A time or
647            /// work input that fails ends the run in `error`, a step like any
648            /// other.
649            pub fn apply(&self, mut store: impl AsContextMut, batch: &Value) -> Result<Value, Error> {
650                let step = self
651                    .actors
652                    .actor()
653                    .call_apply(&mut store, self.resource, &batch.to_string())?
654                    .map_err(contract_error)?;
655                parse(&step)
656            }
657
658            /// Whether the root would select a transition for `event` now, as
659            /// kit-workflow's `can`: XState's `!isUnhandled(transition(...))`,
660            /// any transition, an empty one among them. Changes nothing.
661            pub fn can(&self, mut store: impl AsContextMut, event: &Value) -> Result<bool, Error> {
662                self.actors.actor().call_can(&mut store, self.resource, &event.to_string())?.map_err(Error::Component)
663            }
664
665            /// The whole system (XState's `SystemSnapshot`), for `restore`.
666            pub fn persist(&self, mut store: impl AsContextMut) -> Result<Value, Error> {
667                parse(&self.actors.actor().call_persist(&mut store, self.resource)?)
668            }
669
670            /// Events every actor emitted since the last call, oldest first,
671            /// as `{ "actor": { "@actor", "incarnation" }, "event" }`; always
672            /// empty unless the machine was loaded with
673            /// `observeSystemEmitted`.
674            pub fn take_system_emitted(&self, mut store: impl AsContextMut) -> Result<Vec<Value>, Error> {
675                parse_all(self.actors.actor().call_take_system_emitted(&mut store, self.resource)?)
676            }
677
678            /// Argument lists (arrays) of the root's `@xstate.log` actions
679            /// since the last call.
680            pub fn take_logs(&self, mut store: impl AsContextMut) -> Result<Vec<Value>, Error> {
681                parse_all(self.actors.actor().call_take_logs(&mut store, self.resource)?)
682            }
683
684            /// Stops the root and its children.
685            pub fn stop(&self, mut store: impl AsContextMut) -> Result<(), Error> {
686                self.actors.actor().call_stop(&mut store, self.resource)?.map_err(Error::Component)
687            }
688
689            /// Drops the actor's resource in the component. An actor not
690            /// released lives as long as its store.
691            pub fn release(self, mut store: impl AsContextMut) -> Result<(), Error> {
692                Ok(self.resource.resource_drop(&mut store)?)
693            }
694        }
695    };
696}
697
698actor_calls!(Actor);
699actor_calls!(MachineActor);
700
701/// Whether `component` exports an interface of `xmachines:workflow`, of any
702/// version: one built before that package exports none.
703fn exports_workflow(component: &Component, engine: &Engine) -> bool {
704    component.component_type().exports(engine).any(|(name, _)| name.starts_with("xmachines:workflow/"))
705}
706
707/// The error of a component that exports runs of `xmachines:workflow` of
708/// another version or shape than this host reads.
709fn unreadable_runs(error: wasmtime::Error) -> Error {
710    Error::Component(format!(
711        "the component exports runs of xmachines:workflow that this host, of xmachines:workflow@0.1.0, cannot read: {error}"
712    ))
713}
714
715/// The error of runs asked of a component that exports none, one built
716/// before `xmachines:workflow`.
717fn no_runs() -> Error {
718    Error::Component("the component exports no runs of xmachines:workflow: it was built before them".into())
719}
720
721/// A fault of `xmachines:workflow` the component returned,
722/// `{ "code", "message", "seq" }`, as [`Error::RunFault`]; text of no such
723/// shape is [`Error::Component`].
724fn run_fault(text: String) -> Error {
725    let Ok(Value::Object(e)) = serde_json::from_str::<Value>(&text) else { return Error::Component(text) };
726    match (e.get("code").and_then(Value::as_str), e.get("message").and_then(Value::as_str), e.get("seq")) {
727        (Some(code), Some(message), Some(seq)) if seq.is_u64() => {
728            Error::RunFault { code: code.to_owned(), message: message.to_owned(), seq: seq.as_u64().unwrap_or(0) }
729        }
730        _ => Error::Component(text),
731    }
732}
733
734/// A definition loaded in a [`Runtime`] instance for runs of
735/// `xmachines:workflow/runs`: compiled once with its load options, as a
736/// [`RuntimeMachine`], of which [`RunsMachine::open`] opens runs.
737pub struct RunsMachine {
738    runs: bindings::runtime_runs::exports::xmachines::workflow::runs::Guest,
739    resource: ResourceAny,
740}
741
742impl RunsMachine {
743    /// Loads `definition` (`MachineJSON`) with its load options. A load that
744    /// fails is [`Error::RunFault`]: `WORKFLOW_INVALID_MACHINE` of a
745    /// definition that does not compile, `WORKFLOW_INVALID_INPUT` of options
746    /// that do not parse.
747    pub fn load(
748        mut store: impl AsContextMut,
749        runtime: &Runtime,
750        definition: &Value,
751        options: &Value,
752    ) -> Result<Self, Error> {
753        let runs = runtime.runs.as_ref().ok_or_else(no_runs)?.xmachines_workflow_runs().clone();
754        let (definition, options) = (definition.to_string(), options.to_string());
755        let resource = runs.machine().call_load(&mut store, &definition, &options)?.map_err(run_fault)?;
756        Ok(RunsMachine { runs, resource })
757    }
758
759    /// Opens a run with run options (`{ "actor"?, "time"?, "input"?,
760    /// "checkpoint"?, "maxTimers"?, "maxSteps"?, "from"? }`): the run, and its
761    /// opening records. An open that fails is [`Error::RunFault`].
762    pub fn open(&self, mut store: impl AsContextMut, options: &Value) -> Result<(Run, Vec<Value>), Error> {
763        let (resource, opening) =
764            self.runs.machine().call_open(&mut store, self.resource, &options.to_string())?.map_err(run_fault)?;
765        Ok((Run { runs: self.runs.clone(), resource }, parse_all(opening)?))
766    }
767
768    /// Drops the machine's resource in the component. Its runs live on.
769    pub fn release(self, mut store: impl AsContextMut) -> Result<(), Error> {
770        Ok(self.resource.resource_drop(&mut store)?)
771    }
772}
773
774/// A run of `xmachines:workflow/runs` in a [`Runtime`] instance, opened by a
775/// [`RunsMachine`]: a chunk at a time, records out. Its calls take the store
776/// the instance lives in.
777pub struct Run {
778    runs: bindings::runtime_runs::exports::xmachines::workflow::runs::Guest,
779    resource: ResourceAny,
780}
781
782/// A run of `xmachines:workflow/machine-runs` in a typed [`Machine`]
783/// instance: a run of the component's machine, a chunk at a time.
784pub struct MachineRun {
785    runs: bindings::machine_runs::exports::xmachines::workflow::machine_runs::Guest,
786    resource: ResourceAny,
787}
788
789impl MachineRun {
790    /// Opens a run of the component's machine with run options, as
791    /// [`RunsMachine::open`]: the run, and its opening records.
792    pub fn open(mut store: impl AsContextMut, machine: &Machine, options: &Value) -> Result<(Self, Vec<Value>), Error> {
793        let runs = machine.runs.as_ref().ok_or_else(no_runs)?.xmachines_workflow_machine_runs().clone();
794        let (resource, opening) = runs.run().call_open(&mut store, &options.to_string())?.map_err(run_fault)?;
795        Ok((MachineRun { runs, resource }, parse_all(opening)?))
796    }
797}
798
799/// The calls both worlds' `run` resources share.
800macro_rules! run_calls {
801    ($run:ident) => {
802        impl $run {
803            /// Applies one chunk, an input or a batch of them, under the run's
804            /// next `seq`: its records, the events the machine emitted then
805            /// its snapshot, or one rejection. A fault, the chunk's terminal
806            /// outcome, is [`Error::RunFault`].
807            pub fn apply(&self, mut store: impl AsContextMut, chunk: &Value) -> Result<Vec<Value>, Error> {
808                let records =
809                    self.runs.run().call_apply(&mut store, self.resource, &chunk.to_string())?.map_err(run_fault)?;
810                parse_all(records)
811            }
812
813            /// Whether the root would take `event` now. Changes nothing.
814            pub fn can(&self, mut store: impl AsContextMut, event: &Value) -> Result<bool, Error> {
815                Ok(self.runs.run().call_can(&mut store, self.resource, &event.to_string())?)
816            }
817
818            /// The run as a checkpoint now, `{ "seq", "snapshot" }`, with the
819            /// engine's state: what a run reopens of, as `from`.
820            pub fn checkpoint(&self, mut store: impl AsContextMut) -> Result<Value, Error> {
821                parse(&self.runs.run().call_checkpoint(&mut store, self.resource)?)
822            }
823
824            /// Drops the run's resource in the component.
825            pub fn release(self, mut store: impl AsContextMut) -> Result<(), Error> {
826                Ok(self.resource.resource_drop(&mut store)?)
827            }
828        }
829    };
830}
831
832run_calls!(Run);
833run_calls!(MachineRun);
834
835#[cfg(test)]
836mod tests {
837    use super::*;
838
839    #[test]
840    fn a_component_exports_workflow_by_any_interface_of_the_package() {
841        let engine = Engine::default();
842        let of = |export: &str| {
843            let text = format!(r#"(component (instance $i) (export "{export}" (instance $i)))"#);
844            exports_workflow(&Component::new(&engine, text).unwrap(), &engine)
845        };
846        assert!(of("xmachines:workflow/runs@0.1.0"));
847        assert!(of("xmachines:workflow/runs@0.2.0"));
848        assert!(!of("xmachines:runtime/engine@0.1.0"));
849    }
850}