1#![doc = include_str!("../README.md")]
2
3use std::any::Any;
4use std::cell::{Cell, RefCell};
5use std::collections::{HashMap, HashSet};
6use std::panic::{self, AssertUnwindSafe};
7use std::sync::Arc;
8
9use napi::bindgen_prelude::{
10 Either, FnArgs, FromNapiValue, Function, FunctionRef, Object, ToNapiValue, Undefined, Unknown,
11};
12use napi::{sys, Env, JsValue, ValueType};
13use napi_derive::napi;
14use serde_json::{json, Map, Value};
15use xmachines_runtime::host::{parse_event, parse_json, system_emitted_json, HostOptions, OptionsFor};
16use xmachines_runtime::step::async_logic;
17use xmachines_runtime::{Actor as RtActor, HostEvaluator, Logic, Machine, Registry, Status};
18
19const MAX_CHILD_DEPTH: usize = 32;
21
22fn params_arg(p: &Value) -> Either<String, Undefined> {
24 if p.is_null() {
25 Either::B(())
26 } else {
27 Either::A(p.to_string())
28 }
29}
30
31fn optional_arg(v: Option<String>) -> Either<String, Undefined> {
33 v.map_or(Either::B(()), Either::A)
34}
35
36type GuardRef = FunctionRef<FnArgs<(String, Either<String, Undefined>, String, String)>, Unknown<'static>>;
40type ActionRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
41type DelayRef = FunctionRef<FnArgs<(String, String, String)>, Unknown<'static>>;
42type ExprRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;
43type ContextExprRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
44type EvaluateRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;
45
46#[derive(Default)]
49struct Callbacks {
50 guard: Option<GuardRef>,
51 action: Option<ActionRef>,
52 delay: Option<DelayRef>,
53 expr: Option<ExprRef>,
54 context_expr: Option<ContextExprRef>,
55 evaluate: Option<EvaluateRef>,
56}
57
58fn callback<Args, Return>(object: &Object, key: &str) -> napi::Result<Option<FunctionRef<Args, Return>>>
61where
62 Args: napi::bindgen_prelude::JsValuesTupleIntoVec,
63 Return: napi::bindgen_prelude::FromNapiValue,
64{
65 let Some(value) = object.get::<Unknown>(key)? else { return Ok(None) };
66 match value.get_type()? {
67 ValueType::Undefined | ValueType::Null => Ok(None),
68 ValueType::Function => {
69 let f: Function<Args, Return> = unsafe { value.cast()? };
71 Ok(Some(f.bind(object)?.create_ref()?))
72 }
73 _ => Err(napi::Error::from_reason(format!("implementations.{key} must be a function"))),
74 }
75}
76
77impl Callbacks {
78 fn from_js(implementations: Option<Object>) -> napi::Result<Self> {
79 let Some(o) = implementations else { return Ok(Self::default()) };
80 Ok(Self {
81 guard: callback(&o, "guard")?,
82 action: callback(&o, "action")?,
83 delay: callback(&o, "delay")?,
84 expr: callback(&o, "expr")?,
85 context_expr: callback(&o, "contextExpr")?,
86 evaluate: callback(&o, "evaluate")?,
87 })
88 }
89}
90
91thread_local! {
92 static ENV: Cell<Option<sys::napi_env>> = const { Cell::new(None) };
95}
96
97fn call_js<T>(f: impl FnOnce(&Env) -> napi::Result<T>) -> Result<T, String> {
102 let Some(raw) = ENV.with(Cell::get) else {
103 return Err("an implementation was called outside a call into the actor".into());
104 };
105 let env = Env::from_raw(raw);
106 env.run_in_scope(|| Ok(f(&env).map_err(|e| thrown_message(&env, e)))).unwrap_or_else(|e| Err(e.reason))
107}
108
109fn thrown_message(env: &Env, error: napi::Error) -> String {
113 let reason = error.reason.clone();
114 let message = || -> napi::Result<String> {
115 let value = unsafe { Unknown::from_napi_value(env.raw(), ToNapiValue::to_napi_value(env.raw(), error)?)? };
117 if value.get_type()? == ValueType::Object {
118 let object: Object = unsafe { value.cast()? };
120 if let Some(message) = object.get::<Unknown>("message")? {
121 if message.get_type()? == ValueType::String {
122 return unsafe { message.cast::<String>() };
124 }
125 }
126 }
127 value.coerce_to_string()?.into_utf8()?.into_owned()
128 };
129 message().unwrap_or(reason)
130}
131
132fn json_result(what: &str, name: &str, value: Unknown) -> napi::Result<Value> {
135 if value.get_type()? != ValueType::String {
136 return Err(napi::Error::from_reason(format!("{what} \"{name}\" must return a JSON string")));
137 }
138 let text: String = unsafe { value.cast()? };
140 Ok(serde_json::from_str(&text).unwrap_or(Value::Null))
141}
142
143fn missing(kind: &str, name: &str, key: &str) -> String {
146 format!("the definition references {kind} \"{name}\" but implementations.{key} is missing")
147}
148
149type Compiled = HashMap<String, Arc<dyn Logic>>;
151
152fn compile(
155 definition: &Value,
156 children: &Map<String, Value>,
157 callbacks: &Arc<Callbacks>,
158 compiled: &mut Compiled,
159 depth: usize,
160) -> Result<Machine<Value, Value>, String> {
161 if depth > MAX_CHILD_DEPTH {
162 return Err("child machines are nested too deeply (a child invokes itself?)".into());
163 }
164 let refs = Machine::<Value, Value>::references(definition).map_err(|e| e.to_string())?;
165 let mut registry: Registry<Value, Value> = Registry::new();
166 let mut seen = HashSet::new();
167 for r in &refs.guards {
168 if seen.insert(("guard", r.name.clone())) {
169 if callbacks.guard.is_none() {
170 return Err(missing("guard", &r.name, "guard"));
171 }
172 let (name, cb) = (r.name.clone(), callbacks.clone());
173 registry.try_guard_with(r.name.clone(), move |args, p: &Value| {
174 let args = (name.clone(), params_arg(p), args.context.to_string(), args.event.to_json().to_string());
175 call_js(|env| cb.guard.as_ref().unwrap().borrow_back(env)?.call(args.into())?.coerce_to_bool())
176 });
177 }
178 }
179 for r in &refs.actions {
180 if seen.insert(("action", r.name.clone())) {
181 if callbacks.action.is_none() {
182 return Err(missing("action", &r.name, "action"));
183 }
184 let (name, cb) = (r.name.clone(), callbacks.clone());
185 registry.try_action_with(r.name.clone(), move |p: &Value| {
186 let args = (name.clone(), params_arg(p));
187 call_js(|env| cb.action.as_ref().unwrap().borrow_back(env)?.call(args.into()).map(drop))
188 });
189 }
190 }
191 for r in &refs.delays {
192 if seen.insert(("delay", r.name.clone())) {
193 if callbacks.delay.is_none() {
194 return Err(missing("delay", &r.name, "delay"));
195 }
196 let (name, cb) = (r.name.clone(), callbacks.clone());
197 registry.try_delay(r.name.clone(), move |context, event| {
198 let args = (name.clone(), context.to_string(), event.to_json().to_string());
199 call_js(|env| {
200 let result = cb.delay.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
201 let ms = match result.get_type()? {
202 ValueType::Number => unsafe { result.cast::<f64>()? },
204 _ => f64::NAN,
205 };
206 if !(ms.is_finite() && ms >= 0.0) {
207 return Err(napi::Error::from_reason(format!(
208 "delay \"{name}\" must return a non-negative number of milliseconds"
209 )));
210 }
211 Ok(ms.ceil() as u64)
213 })
214 });
215 }
216 }
217 for r in &refs.exprs {
218 if callbacks.expr.is_none() {
219 return Err(missing("expression", &r.name, "expr"));
220 }
221 let (name, cb) = (r.name.clone(), callbacks.clone());
222 registry.expr(r.name.clone(), move |args| {
223 let mut scope = json!({ "context": args.context, "event": args.event.to_json() });
224 if let Some(params) = args.params {
225 scope["params"] = params.clone();
226 }
227 let call = (name.clone(), scope.to_string());
228 let result = call_js(|env| {
229 json_result("expr", &name, cb.expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?)
230 });
231 result.unwrap_or_else(|message| {
232 args.fail(message);
233 Value::Null
234 })
235 });
236 }
237 for r in &refs.contexts {
238 if callbacks.context_expr.is_none() {
239 return Err(missing("context expression", &r.name, "contextExpr"));
240 }
241 let (name, cb) = (r.name.clone(), callbacks.clone());
242 registry.context_with(r.name.clone(), move |args| {
243 let call = (name.clone(), optional_arg(args.input.map(Value::to_string)));
244 let result = call_js(|env| {
245 let result = cb.context_expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?;
246 json_result("contextExpr", &name, result)
247 });
248 result.unwrap_or_else(|message| {
249 args.fail(message);
250 Value::Null
251 })
252 });
253 }
254 for r in &refs.languages {
255 if callbacks.evaluate.is_none() {
256 return Err(missing("code in language", &r.name, "evaluate"));
257 }
258 let cb = callbacks.clone();
259 registry.evaluator(
260 r.name.clone(),
261 HostEvaluator(move |code: &str, scope: &str| {
262 let args = (code.to_owned(), scope.to_owned());
263 let result = call_js(|env| {
264 let result = cb.evaluate.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
265 if result.get_type()? != ValueType::String {
266 return Err(napi::Error::from_reason("evaluate must return a JSON string"));
267 }
268 unsafe { result.cast::<String>() }
270 });
271 result.unwrap_or_else(|error| json!({ "error": error }).to_string())
273 }),
274 );
275 }
276 for r in &refs.actors {
277 if seen.insert(("actor", r.name.clone())) {
278 let logic: Arc<dyn Logic> = match children.get(&r.name) {
279 Some(child) => compile_child(&r.name, child, children, callbacks, compiled, depth + 1)?,
280 None => Arc::new(async_logic(Some(r.name.clone()), None).map_err(|e| e.to_string())?),
281 };
282 registry.actor(r.name.clone(), logic);
283 }
284 }
285 if depth == 0 {
286 for (src, child) in children {
289 if seen.insert(("actor", src.clone())) {
290 registry.actor(src.clone(), compile_child(src, child, children, callbacks, compiled, 1)?);
291 }
292 }
293 }
294 Machine::from_json(definition, ®istry).map_err(|e| e.to_string())
295}
296
297fn load(
298 definition: &str,
299 options: &str,
300 callbacks: &Arc<Callbacks>,
301 call: OptionsFor,
302) -> Result<(Arc<Machine<Value, Value>>, HostOptions), String> {
303 let options = HostOptions::parse(options, call, true)?;
304 let definition = parse_json("definition", definition)?;
305 let mut compiled = Compiled::new();
306 let machine = compile(&definition, &options.children, callbacks, &mut compiled, 0)?;
307 Ok((Arc::new(machine), options))
308}
309
310fn compile_child(
312 src: &str,
313 child: &Value,
314 children: &Map<String, Value>,
315 callbacks: &Arc<Callbacks>,
316 compiled: &mut Compiled,
317 depth: usize,
318) -> Result<Arc<dyn Logic>, String> {
319 if let Some(logic) = compiled.get(src) {
320 return Ok(logic.clone());
321 }
322 let machine = compile(child, children, callbacks, compiled, depth).map_err(|e| format!("child \"{src}\": {e}"))?;
323 let logic: Arc<dyn Logic> = Arc::new(machine);
324 compiled.insert(src.to_owned(), logic.clone());
325 Ok(logic)
326}
327
328fn status_str(status: Status) -> &'static str {
329 match status {
330 Status::Active => "active",
331 Status::Done => "done",
332 Status::Error => "error",
333 Status::Stopped => "stopped",
334 }
335}
336
337fn millis(now: f64) -> napi::Result<u64> {
339 if now.is_finite() && now >= 0.0 {
340 Ok(now as u64)
341 } else {
342 Err(napi::Error::from_reason("now must be a non-negative number of milliseconds"))
343 }
344}
345
346enum Failure {
348 Error(String),
351 Fatal(napi::Error),
353}
354
355fn panic_message(payload: &(dyn Any + Send)) -> String {
356 if let Some(s) = payload.downcast_ref::<&str>() {
357 (*s).to_owned()
358 } else if let Some(s) = payload.downcast_ref::<String>() {
359 s.clone()
360 } else {
361 "unknown panic".to_owned()
362 }
363}
364
365fn run<T>(env: &Env, f: impl FnOnce() -> Result<T, String>) -> Result<T, Failure> {
368 struct Restore(Option<sys::napi_env>);
369 impl Drop for Restore {
370 fn drop(&mut self) {
371 ENV.with(|e| e.set(self.0));
372 }
373 }
374 let _restore = Restore(ENV.with(|e| e.replace(Some(env.raw()))));
375 match panic::catch_unwind(AssertUnwindSafe(f)) {
376 Ok(result) => result.map_err(Failure::Error),
377 Err(payload) => {
378 Err(Failure::Fatal(napi::Error::from_reason(format!("internal error: {}", panic_message(&*payload)))))
379 }
380 }
381}
382
383fn construct(env: &Env, f: impl FnOnce() -> Result<RtActor<Value, Value>, String>) -> napi::Result<Actor> {
385 match run(env, f) {
386 Ok(actor) => Ok(Actor { state: RefCell::new(Ok(actor)) }),
387 Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
388 Err(Failure::Fatal(e)) => Err(e),
389 }
390}
391
392pub const RUNTIME_INTERFACE: &str = "xmachines:runtime@0.3.0";
396
397#[napi]
399pub fn runtime_interface() -> String {
400 RUNTIME_INTERFACE.to_string()
401}
402
403#[napi]
407pub struct Actor {
408 state: RefCell<Result<RtActor<Value, Value>, String>>,
410}
411
412impl Actor {
413 fn with<T>(&self, env: &Env, f: impl FnOnce(&mut RtActor<Value, Value>) -> Result<T, String>) -> napi::Result<T> {
414 let Ok(mut state) = self.state.try_borrow_mut() else {
415 return Err(napi::Error::from_reason("the actor is busy: an implementation called back into it"));
416 };
417 let actor = match &mut *state {
418 Ok(actor) => actor,
419 Err(why) => return Err(napi::Error::from_reason(format!("the actor is unusable: {why}"))),
420 };
421 match run(env, || f(actor)) {
422 Ok(v) => Ok(v),
423 Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
424 Err(Failure::Fatal(e)) => {
425 *state = Err(format!("an earlier call failed part way through a step ({})", e.reason));
426 Err(e)
427 }
428 }
429 }
430}
431
432#[napi]
433impl Actor {
434 #[napi(factory)]
436 pub fn start(
437 env: Env,
438 definition: String,
439 options: String,
440 now: f64,
441 implementations: Option<Object>,
442 ) -> napi::Result<Self> {
443 let now = millis(now)?;
444 let callbacks = Arc::new(Callbacks::from_js(implementations)?);
445 construct(&env, || {
446 let (machine, options) = load(&definition, &options, &callbacks, OptionsFor::Start)?;
447 options.start(machine, now)
448 })
449 }
450
451 #[napi(factory)]
455 pub fn restore(
456 env: Env,
457 definition: String,
458 options: String,
459 snapshot: String,
460 implementations: Option<Object>,
461 ) -> napi::Result<Self> {
462 let callbacks = Arc::new(Callbacks::from_js(implementations)?);
463 construct(&env, || {
464 let (machine, options) = load(&definition, &options, &callbacks, OptionsFor::Restore)?;
465 let snapshot = parse_json("snapshot", &snapshot)?;
466 options.restore(machine, &snapshot)
467 })
468 }
469
470 #[napi]
473 pub fn send(&self, env: Env, event: String, now: f64) -> napi::Result<()> {
474 let now = millis(now)?;
475 self.with(&env, |a| a.send_json(parse_event(&event)?, now).map_err(|e| e.to_string()))
476 }
477
478 #[napi]
481 pub fn send_to(&self, env: Env, address: String, event: String, now: f64) -> napi::Result<()> {
482 let now = millis(now)?;
483 self.with(&env, |a| a.send_to(&address, parse_event(&event)?, now).map_err(|e| e.to_string()))
484 }
485
486 #[napi]
488 pub fn advance(&self, env: Env, now: f64) -> napi::Result<()> {
489 let now = millis(now)?;
490 self.with(&env, |a| a.advance(now).map_err(|e| e.to_string()))
491 }
492
493 #[napi]
495 pub fn next_deadline(&self, env: Env) -> napi::Result<Option<f64>> {
496 self.with(&env, |a| Ok(a.next_deadline().map(|t| t as f64)))
497 }
498
499 #[napi]
501 pub fn snapshot(&self, env: Env) -> napi::Result<String> {
502 self.with(&env, |a| {
503 let mut s = json!({ "status": status_str(a.status()) });
504 if let (Some(value), Some(context)) = (a.value(), a.context()) {
506 s["value"] = value;
507 s["context"] = context.clone();
508 }
509 if let Some(output) = a.output() {
510 s["output"] = output.clone();
511 }
512 if let Some(error) = a.error() {
513 s["error"] = error.clone();
514 }
515 Ok(s.to_string())
516 })
517 }
518
519 #[napi]
521 pub fn persist(&self, env: Env) -> napi::Result<String> {
522 self.with(&env, |a| Ok(a.persist().to_string()))
523 }
524
525 #[napi]
527 pub fn take_emitted(&self, env: Env) -> napi::Result<Vec<String>> {
528 self.with(&env, |a| Ok(a.take_emitted().iter().map(Value::to_string).collect()))
529 }
530
531 #[napi]
534 pub fn observe_system_emitted(&self, env: Env) -> napi::Result<()> {
535 self.with(&env, |a| {
536 a.observe_system_emitted();
537 Ok(())
538 })
539 }
540
541 #[napi]
543 pub fn unobserve_system_emitted(&self, env: Env) -> napi::Result<()> {
544 self.with(&env, |a| {
545 a.unobserve_system_emitted();
546 Ok(())
547 })
548 }
549
550 #[napi]
553 pub fn take_system_emitted(&self, env: Env) -> napi::Result<Vec<String>> {
554 self.with(&env, |a| Ok(system_emitted_json(a.take_system_emitted())))
555 }
556
557 #[napi]
559 pub fn take_logs(&self, env: Env) -> napi::Result<Vec<String>> {
560 self.with(&env, |a| Ok(a.take_logs().into_iter().map(|args| Value::Array(args).to_string()).collect()))
561 }
562
563 #[napi]
565 pub fn pending_effects(&self, env: Env) -> napi::Result<Vec<String>> {
566 self.with(&env, |a| Ok(a.pending_effects().iter().map(|e| e.to_json().to_string()).collect()))
567 }
568
569 #[napi]
571 pub fn resolve_effect(&self, env: Env, id: String, event: Option<String>) -> napi::Result<()> {
572 self.with(&env, |a| {
573 let event = event.as_deref().map(parse_event).transpose()?;
574 a.resolve_effect(&id, event).map_err(|e| e.to_string())
575 })
576 }
577
578 #[napi]
580 pub fn stop(&self, env: Env) -> napi::Result<()> {
581 self.with(&env, |a| a.stop().map_err(|e| e.to_string()))
582 }
583}