xmachines_machine_node/
lib.rs1#![doc = include_str!("../README.md")]
2
3use std::any::Any;
4use std::panic::{self, AssertUnwindSafe};
5
6use xmachines_machine::{JsonActor, TypedMachine};
7
8pub const MACHINE_INTERFACE: &str = "xmachines:machine@0.2.0";
11
12#[doc(hidden)]
15pub mod __private {
16 pub use ::napi;
17 pub use napi_derive::napi;
18 pub use xmachines_machine;
19}
20
21#[macro_export]
24macro_rules! export_machine {
25 ($component:ty) => {
26 #[doc(hidden)]
27 mod __xmachines_machine_node {
28 #[allow(unused_imports)]
29 use super::*;
30 use $crate::__private::napi;
34
35 type __Component = $component;
36
37 #[$crate::__private::napi]
39 pub fn machine_interface() -> ::std::string::String {
40 $crate::MACHINE_INTERFACE.into()
41 }
42
43 #[$crate::__private::napi(namespace = "info")]
45 pub fn id() -> ::std::string::String {
46 $crate::__private::xmachines_machine::info::<__Component>().id
47 }
48
49 #[$crate::__private::napi(namespace = "info")]
51 pub fn version() -> ::core::option::Option<::std::string::String> {
52 $crate::__private::xmachines_machine::info::<__Component>().version
53 }
54
55 #[$crate::__private::napi(namespace = "info")]
57 pub fn definition() -> ::std::string::String {
58 <__Component as $crate::__private::xmachines_machine::TypedMachine>::DEFINITION.into()
59 }
60
61 #[$crate::__private::napi(namespace = "info")]
64 pub fn schemas() -> ::std::string::String {
65 <__Component as $crate::__private::xmachines_machine::TypedMachine>::SCHEMAS.into()
66 }
67
68 #[$crate::__private::napi]
70 pub struct Actor {
71 inner: $crate::NodeActor<__Component>,
72 }
73
74 #[$crate::__private::napi]
75 impl Actor {
76 #[napi(factory)]
78 pub fn start(options: ::std::string::String, now: f64) -> napi::Result<Self> {
79 $crate::NodeActor::start(&options, now).map(|inner| Self { inner })
80 }
81
82 #[napi(factory)]
84 pub fn restore(options: ::std::string::String, snapshot: ::std::string::String) -> napi::Result<Self> {
85 $crate::NodeActor::restore(&options, &snapshot).map(|inner| Self { inner })
86 }
87
88 #[napi]
90 pub fn send(&mut self, event: ::std::string::String, now: f64) -> napi::Result<()> {
91 self.inner.send(&event, now)
92 }
93
94 #[napi]
96 pub fn send_to(
97 &mut self,
98 address: ::std::string::String,
99 event: ::std::string::String,
100 now: f64,
101 ) -> napi::Result<()> {
102 self.inner.send_to(&address, &event, now)
103 }
104
105 #[napi]
107 pub fn advance(&mut self, now: f64) -> napi::Result<()> {
108 self.inner.advance(now)
109 }
110
111 #[napi]
113 pub fn next_deadline(&self) -> napi::Result<::core::option::Option<f64>> {
114 self.inner.next_deadline()
115 }
116
117 #[napi]
119 pub fn snapshot(&self) -> napi::Result<::std::string::String> {
120 self.inner.snapshot()
121 }
122
123 #[napi]
125 pub fn persist(&self) -> napi::Result<::std::string::String> {
126 self.inner.persist()
127 }
128
129 #[napi]
131 pub fn take_emitted(&mut self) -> napi::Result<::std::vec::Vec<::std::string::String>> {
132 self.inner.take_emitted()
133 }
134
135 #[napi]
137 pub fn observe_system_emitted(&mut self) -> napi::Result<()> {
138 self.inner.observe_system_emitted()
139 }
140
141 #[napi]
143 pub fn unobserve_system_emitted(&mut self) -> napi::Result<()> {
144 self.inner.unobserve_system_emitted()
145 }
146
147 #[napi]
149 pub fn take_system_emitted(&mut self) -> napi::Result<::std::vec::Vec<::std::string::String>> {
150 self.inner.take_system_emitted()
151 }
152
153 #[napi]
155 pub fn take_logs(&mut self) -> napi::Result<::std::vec::Vec<::std::string::String>> {
156 self.inner.take_logs()
157 }
158
159 #[napi]
161 pub fn pending_effects(&self) -> napi::Result<::std::vec::Vec<::std::string::String>> {
162 self.inner.pending_effects()
163 }
164
165 #[napi]
167 pub fn resolve_effect(
168 &mut self,
169 id: ::std::string::String,
170 event: ::core::option::Option<::std::string::String>,
171 ) -> napi::Result<()> {
172 self.inner.resolve_effect(&id, event.as_deref())
173 }
174
175 #[napi]
177 pub fn stop(&mut self) -> napi::Result<()> {
178 self.inner.stop()
179 }
180 }
181 }
182 };
183}
184
185fn millis(now: f64) -> napi::Result<u64> {
187 if now.is_finite() && now >= 0.0 {
188 Ok(now as u64)
189 } else {
190 Err(napi::Error::from_reason("now must be a non-negative number of milliseconds"))
191 }
192}
193
194fn panic_message(payload: &(dyn Any + Send)) -> String {
195 if let Some(s) = payload.downcast_ref::<&str>() {
196 (*s).to_owned()
197 } else if let Some(s) = payload.downcast_ref::<String>() {
198 s.clone()
199 } else {
200 "unknown panic".to_owned()
201 }
202}
203
204fn guarded<R>(f: impl FnOnce() -> Result<R, String>) -> Result<R, (napi::Error, Option<String>)> {
207 match panic::catch_unwind(AssertUnwindSafe(f)) {
208 Ok(result) => result.map_err(|msg| (napi::Error::from_reason(msg), None)),
209 Err(payload) => {
210 let msg = format!("an implementation panicked: {}", panic_message(&*payload));
211 Err((napi::Error::from_reason(msg.clone()), Some(msg)))
212 }
213 }
214}
215
216pub struct NodeActor<T: TypedMachine> {
219 state: Result<JsonActor<T>, String>,
221}
222
223impl<T: TypedMachine> NodeActor<T> {
224 pub fn start(options: &str, now: f64) -> napi::Result<Self> {
226 let now = millis(now)?;
227 let actor = guarded(|| JsonActor::start(options, now)).map_err(|(e, _)| e)?;
228 Ok(Self { state: Ok(actor) })
229 }
230
231 pub fn restore(options: &str, snapshot: &str) -> napi::Result<Self> {
234 let actor = guarded(|| JsonActor::restore(options, snapshot)).map_err(|(e, _)| e)?;
235 Ok(Self { state: Ok(actor) })
236 }
237
238 fn actor(&self) -> napi::Result<&JsonActor<T>> {
239 self.state.as_ref().map_err(|why| napi::Error::from_reason(format!("the actor is unusable: {why}")))
240 }
241
242 fn with<R>(&mut self, f: impl FnOnce(&mut JsonActor<T>) -> Result<R, String>) -> napi::Result<R> {
245 let actor = match &mut self.state {
246 Ok(actor) => actor,
247 Err(why) => return Err(napi::Error::from_reason(format!("the actor is unusable: {why}"))),
248 };
249 guarded(|| f(actor)).map_err(|(e, panicked)| {
250 if let Some(msg) = panicked {
251 self.state = Err(format!("an earlier call failed part way through a step ({msg})"));
252 }
253 e
254 })
255 }
256
257 pub fn send(&mut self, event: &str, now: f64) -> napi::Result<()> {
259 let now = millis(now)?;
260 self.with(|a| a.send(event, now))
261 }
262
263 pub fn send_to(&mut self, address: &str, event: &str, now: f64) -> napi::Result<()> {
265 let now = millis(now)?;
266 self.with(|a| a.send_to(address, event, now))
267 }
268
269 pub fn advance(&mut self, now: f64) -> napi::Result<()> {
271 let now = millis(now)?;
272 self.with(|a| a.advance(now))
273 }
274
275 pub fn next_deadline(&self) -> napi::Result<Option<f64>> {
277 Ok(self.actor()?.next_deadline().map(|t| t as f64))
278 }
279
280 pub fn snapshot(&self) -> napi::Result<String> {
282 Ok(self.actor()?.snapshot())
283 }
284
285 pub fn persist(&self) -> napi::Result<String> {
287 Ok(self.actor()?.persist())
288 }
289
290 pub fn take_emitted(&mut self) -> napi::Result<Vec<String>> {
292 self.with(|a| Ok(a.take_emitted()))
293 }
294
295 pub fn observe_system_emitted(&mut self) -> napi::Result<()> {
297 self.with(|a| {
298 a.observe_system_emitted();
299 Ok(())
300 })
301 }
302
303 pub fn unobserve_system_emitted(&mut self) -> napi::Result<()> {
305 self.with(|a| {
306 a.unobserve_system_emitted();
307 Ok(())
308 })
309 }
310
311 pub fn take_system_emitted(&mut self) -> napi::Result<Vec<String>> {
313 self.with(|a| Ok(a.take_system_emitted()))
314 }
315
316 pub fn take_logs(&mut self) -> napi::Result<Vec<String>> {
318 self.with(|a| Ok(a.take_logs()))
319 }
320
321 pub fn pending_effects(&self) -> napi::Result<Vec<String>> {
323 Ok(self.actor()?.pending_effects())
324 }
325
326 pub fn resolve_effect(&mut self, id: &str, event: Option<&str>) -> napi::Result<()> {
328 self.with(|a| a.resolve_effect(id, event))
329 }
330
331 pub fn stop(&mut self) -> napi::Result<()> {
333 self.with(|a| a.stop())
334 }
335}