Skip to main content

xmachines_machine_wasi/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::cell::RefCell;
4
5use xmachines_machine::{JsonActor, JsonMachine, TypedMachine};
6
7/// The generated bindings (used by [`export_machine!`]).
8#[doc(hidden)]
9pub mod bindings {
10    wit_bindgen::generate!({
11        world: "machine",
12        path: "wit",
13        pub_export_macro: true,
14        export_macro_name: "export_bindings",
15        default_bindings_module: "::xmachines_machine_wasi::bindings",
16    });
17}
18
19/// What [`export_machine!`] expands to refers to.
20#[doc(hidden)]
21pub mod __private {
22    pub use xmachines_machine;
23}
24
25use bindings::exports::xmachines::machine::actors::{
26    Actor as ActorHandle, GuestActor, GuestMachine, Machine as MachineHandle,
27};
28use bindings::exports::xmachines::workflow::machine_runs::{GuestRun, Run as RunHandle};
29
30/// Exports `info`, `actors` and `xmachines:workflow/machine-runs` for a
31/// [`TypedMachine`].
32#[macro_export]
33macro_rules! export_machine {
34    ($component:ty) => {
35        // wit-bindgen's export macro takes a name, not a path: the alias gives one.
36        #[doc(hidden)]
37        type __XmachinesWasiMachine = $component;
38
39        impl $crate::bindings::exports::xmachines::machine::actors::Guest for __XmachinesWasiMachine {
40            type Machine = $crate::MachineResource<__XmachinesWasiMachine>;
41            type Actor = $crate::ActorResource<__XmachinesWasiMachine>;
42        }
43
44        impl $crate::bindings::exports::xmachines::workflow::machine_runs::Guest for __XmachinesWasiMachine {
45            type Run = $crate::RunResource<__XmachinesWasiMachine>;
46        }
47
48        impl $crate::bindings::exports::xmachines::machine::info::Guest for __XmachinesWasiMachine {
49            fn id() -> ::std::string::String {
50                $crate::__private::xmachines_machine::info::<__XmachinesWasiMachine>().id
51            }
52            fn version() -> ::core::option::Option<::std::string::String> {
53                $crate::__private::xmachines_machine::info::<__XmachinesWasiMachine>().version
54            }
55            fn definition() -> ::std::string::String {
56                <__XmachinesWasiMachine as $crate::__private::xmachines_machine::TypedMachine>::DEFINITION.into()
57            }
58            fn schemas() -> ::std::string::String {
59                <__XmachinesWasiMachine as $crate::__private::xmachines_machine::TypedMachine>::SCHEMAS.into()
60            }
61        }
62
63        // The component-model exports only link on wasm32; native builds
64        // just type-check the crate.
65        #[cfg(target_arch = "wasm32")]
66        $crate::bindings::export_bindings!(__XmachinesWasiMachine with_types_in $crate::bindings);
67    };
68}
69
70/// The `machine` resource of a [`TypedMachine`]: a [`JsonMachine`], the
71/// machine compiled once per component instance with the load options of
72/// this resource.
73pub struct MachineResource<T: TypedMachine> {
74    machine: JsonMachine<T>,
75}
76
77impl<T: TypedMachine> GuestMachine for MachineResource<T> {
78    fn load(options: String) -> Result<MachineHandle, String> {
79        JsonMachine::load(&options).map(|machine| MachineHandle::new(Self { machine }))
80    }
81
82    fn start(&self, options: String, now: u64) -> Result<ActorHandle, String> {
83        self.machine.start(&options, now).map(ActorResource::handle)
84    }
85
86    fn restore(&self, snapshot: String) -> Result<ActorHandle, String> {
87        self.machine.restore(&snapshot).map(ActorResource::handle)
88    }
89}
90
91/// The `actor` resource of a [`TypedMachine`]: a [`JsonActor`] behind the
92/// resource's calls. A component instance is single-threaded, and its
93/// implementations are Rust that cannot call back into it, so the cell is
94/// never borrowed twice.
95pub struct ActorResource<T: TypedMachine> {
96    actor: RefCell<JsonActor<T>>,
97}
98
99impl<T: TypedMachine> ActorResource<T> {
100    fn handle(actor: JsonActor<T>) -> ActorHandle {
101        ActorHandle::new(Self { actor: RefCell::new(actor) })
102    }
103}
104
105impl<T: TypedMachine> GuestActor for ActorResource<T> {
106    fn apply(&self, batch: String) -> Result<String, String> {
107        self.actor.borrow_mut().apply(&batch)
108    }
109
110    fn can(&self, event: String) -> Result<bool, String> {
111        self.actor.borrow().can(&event)
112    }
113
114    fn persist(&self) -> String {
115        self.actor.borrow().persist()
116    }
117
118    fn take_logs(&self) -> Vec<String> {
119        self.actor.borrow_mut().take_logs()
120    }
121
122    fn take_system_emitted(&self) -> Vec<String> {
123        self.actor.borrow_mut().take_system_emitted()
124    }
125
126    fn stop(&self) -> Result<(), String> {
127        self.actor.borrow_mut().stop()
128    }
129}
130
131/// The `run` resource of `xmachines:workflow/machine-runs` for a
132/// [`TypedMachine`]: a run of its machine, compiled once per component
133/// instance, a chunk at a time, records out.
134pub struct RunResource<T: TypedMachine> {
135    run: RefCell<xmachines_machine::Run<T::Context, T::Event>>,
136}
137
138impl<T: TypedMachine> GuestRun for RunResource<T> {
139    fn open(options: String) -> Result<(RunHandle, Vec<String>), String> {
140        let (run, opening) = xmachines_machine::open_run::<T>(&options)?;
141        Ok((RunHandle::new(Self { run: RefCell::new(run) }), opening))
142    }
143
144    fn apply(&self, chunk: String) -> Result<Vec<String>, String> {
145        self.run.borrow_mut().apply_text(&chunk)
146    }
147
148    fn can(&self, event: String) -> bool {
149        self.run.borrow().can_text(&event)
150    }
151
152    fn checkpoint(&self) -> String {
153        self.run.borrow().checkpoint_text()
154    }
155}