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, JsObjectValue, 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::{apply_error_json, apply_json, parse_json, system_emitted_json, LoadOptions};
16use xmachines_runtime::step::async_logic;
17use xmachines_runtime::work::ApplyError;
18use xmachines_runtime::{Actor as RtActor, HostActions, HostEvaluator, Logic, Machine as RtMachine, Registry};
19
20const MAX_CHILD_DEPTH: usize = 32;
22
23fn params_arg(p: &Value) -> Either<String, Undefined> {
25 if p.is_null() {
26 Either::B(())
27 } else {
28 Either::A(p.to_string())
29 }
30}
31
32fn optional_arg(v: Option<String>) -> Either<String, Undefined> {
34 v.map_or(Either::B(()), Either::A)
35}
36
37type GuardRef = FunctionRef<FnArgs<(String, Either<String, Undefined>, String, String)>, Unknown<'static>>;
41type ActionRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
42type DelayRef = FunctionRef<FnArgs<(String, String, String)>, Unknown<'static>>;
43type ExprRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;
44type ContextExprRef = FunctionRef<FnArgs<(String, Either<String, Undefined>)>, Unknown<'static>>;
45type EvaluateRef = FunctionRef<FnArgs<(String, String)>, Unknown<'static>>;
46
47#[derive(Default)]
50struct Callbacks {
51 guard: Option<GuardRef>,
52 action: Option<ActionRef>,
53 delay: Option<DelayRef>,
54 expr: Option<ExprRef>,
55 context_expr: Option<ContextExprRef>,
56 evaluate: Option<EvaluateRef>,
57}
58
59fn callback<Args, Return>(object: &Object, key: &str) -> napi::Result<Option<FunctionRef<Args, Return>>>
62where
63 Args: napi::bindgen_prelude::JsValuesTupleIntoVec,
64 Return: napi::bindgen_prelude::FromNapiValue,
65{
66 let Some(value) = object.get::<Unknown>(key)? else { return Ok(None) };
67 match value.get_type()? {
68 ValueType::Undefined | ValueType::Null => Ok(None),
69 ValueType::Function => {
70 let f: Function<Args, Return> = unsafe { value.cast()? };
72 Ok(Some(f.bind(object)?.create_ref()?))
73 }
74 _ => Err(napi::Error::from_reason(format!("implementations.{key} must be a function"))),
75 }
76}
77
78impl Callbacks {
79 fn from_js(implementations: Option<Object>) -> napi::Result<Self> {
80 let Some(o) = implementations else { return Ok(Self::default()) };
81 Ok(Self {
82 guard: callback(&o, "guard")?,
83 action: callback(&o, "action")?,
84 delay: callback(&o, "delay")?,
85 expr: callback(&o, "expr")?,
86 context_expr: callback(&o, "contextExpr")?,
87 evaluate: callback(&o, "evaluate")?,
88 })
89 }
90}
91
92thread_local! {
93 static ENV: Cell<Option<sys::napi_env>> = const { Cell::new(None) };
96}
97
98fn call_js<T>(f: impl FnOnce(&Env) -> napi::Result<T>) -> Result<T, String> {
103 let Some(raw) = ENV.with(Cell::get) else {
104 return Err("an implementation was called outside a call into the actor".into());
105 };
106 let env = Env::from_raw(raw);
107 env.run_in_scope(|| Ok(f(&env).map_err(|e| thrown_message(&env, e)))).unwrap_or_else(|e| Err(e.reason))
108}
109
110fn thrown_message(env: &Env, error: napi::Error) -> String {
114 let reason = error.reason.clone();
115 let message = || -> napi::Result<String> {
116 let value = unsafe { Unknown::from_napi_value(env.raw(), ToNapiValue::to_napi_value(env.raw(), error)?)? };
118 if value.get_type()? == ValueType::Object {
119 let object: Object = unsafe { value.cast()? };
121 if let Some(message) = object.get::<Unknown>("message")? {
122 if message.get_type()? == ValueType::String {
123 return unsafe { message.cast::<String>() };
125 }
126 }
127 }
128 value.coerce_to_string()?.into_utf8()?.into_owned()
129 };
130 message().unwrap_or(reason)
131}
132
133fn json_result(what: &str, name: &str, value: Unknown) -> napi::Result<Value> {
136 if value.get_type()? != ValueType::String {
137 return Err(napi::Error::from_reason(format!("{what} \"{name}\" must return a JSON string")));
138 }
139 let text: String = unsafe { value.cast()? };
141 Ok(serde_json::from_str(&text).unwrap_or(Value::Null))
142}
143
144fn missing(kind: &str, name: &str, key: &str) -> String {
147 format!("the definition references {kind} \"{name}\" but implementations.{key} is missing")
148}
149
150type Compiled = HashMap<String, Arc<dyn Logic>>;
152
153fn compile(
157 definition: &Value,
158 children: &Map<String, Value>,
159 host_actions: &HostActions,
160 callbacks: &Arc<Callbacks>,
161 compiled: &mut Compiled,
162 depth: usize,
163) -> Result<RtMachine<Value, Value>, String> {
164 if depth > MAX_CHILD_DEPTH {
165 return Err("child machines are nested too deeply (a child invokes itself?)".into());
166 }
167 let refs = RtMachine::<Value, Value>::references(definition).map_err(|e| e.to_string())?;
168 let mut registry: Registry<Value, Value> = Registry::new();
169 registry.host_actions(host_actions.clone());
170 let mut seen = HashSet::new();
171 for r in &refs.guards {
172 if seen.insert(("guard", r.name.clone())) {
173 if callbacks.guard.is_none() {
174 return Err(missing("guard", &r.name, "guard"));
175 }
176 let (name, cb) = (r.name.clone(), callbacks.clone());
177 registry.try_guard_with(r.name.clone(), move |args, p: &Value| {
178 let args = (name.clone(), params_arg(p), args.context.to_string(), args.event.to_json().to_string());
179 call_js(|env| cb.guard.as_ref().unwrap().borrow_back(env)?.call(args.into())?.coerce_to_bool())
180 });
181 }
182 }
183 for r in &refs.actions {
184 if host_actions != &HostActions::Unimplemented
187 && !host_actions.includes(&r.name, false)
188 && seen.insert(("action", r.name.clone()))
189 {
190 if callbacks.action.is_none() {
191 return Err(missing("action", &r.name, "action"));
192 }
193 let (name, cb) = (r.name.clone(), callbacks.clone());
194 registry.try_action_with(r.name.clone(), move |p: &Value| {
195 let args = (name.clone(), params_arg(p));
196 call_js(|env| cb.action.as_ref().unwrap().borrow_back(env)?.call(args.into()).map(drop))
197 });
198 }
199 }
200 for r in &refs.delays {
201 if seen.insert(("delay", r.name.clone())) {
202 if callbacks.delay.is_none() {
203 return Err(missing("delay", &r.name, "delay"));
204 }
205 let (name, cb) = (r.name.clone(), callbacks.clone());
206 registry.try_delay(r.name.clone(), move |context, event| {
207 let args = (name.clone(), context.to_string(), event.to_json().to_string());
208 call_js(|env| {
209 let result = cb.delay.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
210 let ms = match result.get_type()? {
211 ValueType::Number => unsafe { result.cast::<f64>()? },
213 _ => f64::NAN,
214 };
215 if !(ms.is_finite() && ms >= 0.0) {
216 return Err(napi::Error::from_reason(format!(
217 "delay \"{name}\" must return a non-negative number of milliseconds"
218 )));
219 }
220 Ok(ms.ceil() as u64)
222 })
223 });
224 }
225 }
226 for r in &refs.exprs {
227 if callbacks.expr.is_none() {
228 return Err(missing("expression", &r.name, "expr"));
229 }
230 let (name, cb) = (r.name.clone(), callbacks.clone());
231 registry.expr(r.name.clone(), move |args| {
232 let mut scope = json!({ "context": args.context, "event": args.event.to_json() });
233 if let Some(params) = args.params {
234 scope["params"] = params.clone();
235 }
236 let call = (name.clone(), scope.to_string());
237 let result = call_js(|env| {
238 json_result("expr", &name, cb.expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?)
239 });
240 result.unwrap_or_else(|message| {
241 args.fail(message);
242 Value::Null
243 })
244 });
245 }
246 for r in &refs.contexts {
247 if callbacks.context_expr.is_none() {
248 return Err(missing("context expression", &r.name, "contextExpr"));
249 }
250 let (name, cb) = (r.name.clone(), callbacks.clone());
251 registry.context_with(r.name.clone(), move |args| {
252 let call = (name.clone(), optional_arg(args.input.map(Value::to_string)));
253 let result = call_js(|env| {
254 let result = cb.context_expr.as_ref().unwrap().borrow_back(env)?.call(call.into())?;
255 json_result("contextExpr", &name, result)
256 });
257 result.unwrap_or_else(|message| {
258 args.fail(message);
259 Value::Null
260 })
261 });
262 }
263 for r in &refs.languages {
264 if callbacks.evaluate.is_none() {
265 return Err(missing("code in language", &r.name, "evaluate"));
266 }
267 let cb = callbacks.clone();
268 registry.evaluator(
269 r.name.clone(),
270 HostEvaluator(move |code: &str, scope: &str| {
271 let args = (code.to_owned(), scope.to_owned());
272 let result = call_js(|env| {
273 let result = cb.evaluate.as_ref().unwrap().borrow_back(env)?.call(args.into())?;
274 if result.get_type()? != ValueType::String {
275 return Err(napi::Error::from_reason("evaluate must return a JSON string"));
276 }
277 unsafe { result.cast::<String>() }
279 });
280 result.unwrap_or_else(|error| json!({ "error": error }).to_string())
282 }),
283 );
284 }
285 for r in &refs.actors {
286 if seen.insert(("actor", r.name.clone())) {
287 let logic: Arc<dyn Logic> = match children.get(&r.name) {
288 Some(child) => compile_child(&r.name, child, children, host_actions, callbacks, compiled, depth + 1)?,
289 None => Arc::new(async_logic(Some(r.name.clone()), None).map_err(|e| e.to_string())?),
290 };
291 registry.actor(r.name.clone(), logic);
292 }
293 }
294 if depth == 0 {
295 for (src, child) in children {
298 if seen.insert(("actor", src.clone())) {
299 registry.actor(src.clone(), compile_child(src, child, children, host_actions, callbacks, compiled, 1)?);
300 }
301 }
302 }
303 RtMachine::from_json(definition, ®istry).map_err(|e| e.to_string())
304}
305
306fn load(definition: &str, options: &str, callbacks: &Arc<Callbacks>) -> Result<Machine, ApplyError> {
310 let options = LoadOptions::parse_contract(options, true)?;
311 let definition = parse_json("definition", definition).map_err(ApplyError::invalid_machine)?;
312 let mut compiled = Compiled::new();
313 let machine = compile(&definition, &options.children, &options.host_actions, callbacks, &mut compiled, 0)
314 .map_err(ApplyError::invalid_machine)?;
315 Ok(Machine { machine: Arc::new(machine), options })
316}
317
318fn compile_child(
320 src: &str,
321 child: &Value,
322 children: &Map<String, Value>,
323 host_actions: &HostActions,
324 callbacks: &Arc<Callbacks>,
325 compiled: &mut Compiled,
326 depth: usize,
327) -> Result<Arc<dyn Logic>, String> {
328 if let Some(logic) = compiled.get(src) {
329 return Ok(logic.clone());
330 }
331 let machine = compile(child, children, host_actions, callbacks, compiled, depth)
332 .map_err(|e| format!("child \"{src}\": {e}"))?;
333 let logic: Arc<dyn Logic> = Arc::new(machine);
334 compiled.insert(src.to_owned(), logic.clone());
335 Ok(logic)
336}
337
338const MAX_SAFE: f64 = 9_007_199_254_740_991.0;
340
341fn millis(now: f64) -> Result<u64, String> {
345 if now.is_finite() && now >= 0.0 && now.fract() == 0.0 && now <= MAX_SAFE {
346 Ok(now as u64)
347 } else {
348 Err(apply_error_json(&ApplyError::invalid_input(
349 "now must be a whole number of milliseconds, at most 2^53 - 1",
350 )))
351 }
352}
353
354enum Failure {
356 Error(String),
359 Fatal(napi::Error),
361}
362
363fn panic_message(payload: &(dyn Any + Send)) -> String {
364 if let Some(s) = payload.downcast_ref::<&str>() {
365 (*s).to_owned()
366 } else if let Some(s) = payload.downcast_ref::<String>() {
367 s.clone()
368 } else {
369 "unknown panic".to_owned()
370 }
371}
372
373fn run<T>(env: &Env, f: impl FnOnce() -> Result<T, String>) -> Result<T, Failure> {
376 struct Restore(Option<sys::napi_env>);
377 impl Drop for Restore {
378 fn drop(&mut self) {
379 ENV.with(|e| e.set(self.0));
380 }
381 }
382 let _restore = Restore(ENV.with(|e| e.replace(Some(env.raw()))));
383 match panic::catch_unwind(AssertUnwindSafe(f)) {
384 Ok(result) => result.map_err(Failure::Error),
385 Err(payload) => {
386 Err(Failure::Fatal(napi::Error::from_reason(format!("internal error: {}", panic_message(&*payload)))))
387 }
388 }
389}
390
391fn construct<T>(env: &Env, f: impl FnOnce() -> Result<T, String>) -> napi::Result<T> {
395 match run(env, || Ok(f())) {
396 Ok(Ok(value)) => Ok(value),
397 Ok(Err(error)) => Err(contract_error(env, &error)),
398 Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
399 Err(Failure::Fatal(e)) => Err(e),
400 }
401}
402
403pub const REJECTED: &str = "WORKFLOW_REJECTED";
405
406fn contract_error(env: &Env, text: &str) -> napi::Error {
413 let error: Value = serde_json::from_str(text).unwrap_or_default();
414 let field = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_owned();
415 let rejected = error.get("rejected");
416 let (code, message) = match rejected {
417 Some(rejected) => (REJECTED.to_owned(), field(rejected, "message")),
418 None => (field(&error, "code"), field(&error, "message")),
419 };
420 let thrown = || -> napi::Result<napi::Error> {
421 let mut object = env.create_error(napi::Error::from_reason(message.clone()))?;
422 object.set_named_property("code", code.as_str())?;
423 if let Some(rejected) = rejected {
424 let json: Object = env.get_global()?.get_named_property("JSON")?;
425 let parse: Function<String, Unknown> = json.get_named_property("parse")?;
426 object.set_named_property("rejected", parse.call(rejected.to_string())?)?;
427 }
428 Ok(napi::Error::from(object.to_unknown()))
429 };
430 thrown().unwrap_or_else(|_| napi::Error::from_reason(message.clone()))
431}
432
433pub const RUNTIME_INTERFACE: &str = "xmachines:runtime@0.4.0";
437
438#[napi]
440pub fn runtime_interface() -> String {
441 RUNTIME_INTERFACE.to_string()
442}
443
444pub const WORKFLOW_INTERFACE: &str = "xmachines:workflow@0.1.0";
448
449#[napi]
452pub fn workflow_interface() -> String {
453 WORKFLOW_INTERFACE.to_string()
454}
455
456#[napi]
461pub struct Machine {
462 machine: Arc<RtMachine<Value, Value>>,
463 options: LoadOptions,
464}
465
466#[napi]
467impl Machine {
468 #[napi(factory)]
475 pub fn load(env: Env, definition: String, options: String, implementations: Option<Object>) -> napi::Result<Self> {
476 let callbacks = Arc::new(Callbacks::from_js(implementations)?);
477 construct(&env, || load(&definition, &options, &callbacks).map_err(|e| apply_error_json(&e)))
478 }
479
480 #[napi]
486 pub fn start(&self, env: Env, options: String, now: f64) -> napi::Result<Actor> {
487 let now = millis(now).map_err(|error| contract_error(&env, &error))?;
488 let actor = construct(&env, || self.options.start_json(self.machine.clone(), &options, now))?;
489 Ok(Actor { state: RefCell::new(Ok(actor)) })
490 }
491
492 #[napi]
497 pub fn restore(&self, env: Env, snapshot: String) -> napi::Result<Actor> {
498 let actor = construct(&env, || self.options.restore_json(self.machine.clone(), &snapshot))?;
499 Ok(Actor { state: RefCell::new(Ok(actor)) })
500 }
501
502 #[napi]
512 pub fn open(&self, env: Env, options: String) -> napi::Result<Run> {
513 let opened = run(&env, || {
514 Ok(xmachines_workflow::text::open(
515 self.machine.clone(),
516 &options,
517 self.options.max_timers,
518 self.options.max_steps,
519 ))
520 });
521 match opened {
522 Ok(Ok((inner, opening))) => Ok(Run { state: RefCell::new(Ok(inner)), opening }),
523 Ok(Err(fault)) => Err(fault_error(&env, &fault)),
524 Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
525 Err(Failure::Fatal(e)) => Err(e),
526 }
527 }
528}
529
530fn fault_error(env: &Env, text: &str) -> napi::Error {
534 let fault: Value = serde_json::from_str(text).unwrap_or_default();
535 let message = fault.get("message").and_then(Value::as_str).unwrap_or_default().to_owned();
536 let thrown = || -> napi::Result<napi::Error> {
537 let mut object = env.create_error(napi::Error::from_reason(message.clone()))?;
538 object.set_named_property("code", fault.get("code").and_then(Value::as_str).unwrap_or_default())?;
539 object.set_named_property("seq", fault.get("seq").and_then(Value::as_f64).unwrap_or_default())?;
540 Ok(napi::Error::from(object.to_unknown()))
541 };
542 thrown().unwrap_or_else(|_| napi::Error::from_reason(message.clone()))
543}
544
545#[napi]
550pub struct Run {
551 state: RefCell<Result<xmachines_workflow::Run, String>>,
553 opening: Vec<String>,
554}
555
556impl Run {
557 fn with<T>(&self, env: &Env, f: impl FnOnce(&mut xmachines_workflow::Run) -> T) -> napi::Result<T> {
558 let Ok(mut state) = self.state.try_borrow_mut() else {
559 return Err(napi::Error::from_reason("the run is busy: an implementation called back into it"));
560 };
561 let inner = match &mut *state {
562 Ok(inner) => inner,
563 Err(why) => return Err(napi::Error::from_reason(format!("the run is unusable: {why}"))),
564 };
565 match run(env, || Ok(f(inner))) {
566 Ok(v) => Ok(v),
567 Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
568 Err(Failure::Fatal(e)) => {
569 *state = Err(format!("an earlier call failed part way through a step ({})", e.reason));
570 Err(e)
571 }
572 }
573 }
574}
575
576#[napi]
577impl Run {
578 #[napi(getter)]
582 pub fn opening(&self) -> Vec<String> {
583 self.opening.clone()
584 }
585
586 #[napi]
593 pub fn apply(&self, env: Env, chunk: String) -> napi::Result<Vec<String>> {
594 self.with(&env, |r| r.apply_text(&chunk))?.map_err(|fault| fault_error(&env, &fault))
595 }
596
597 #[napi]
601 pub fn can(&self, env: Env, event: String) -> napi::Result<bool> {
602 self.with(&env, |r| r.can_text(&event))
603 }
604
605 #[napi]
609 pub fn checkpoint(&self, env: Env) -> napi::Result<String> {
610 self.with(&env, |r| r.checkpoint_text())
611 }
612}
613
614#[napi]
618pub struct Actor {
619 state: RefCell<Result<RtActor<Value, Value>, String>>,
621}
622
623impl Actor {
624 fn with<T>(&self, env: &Env, f: impl FnOnce(&mut RtActor<Value, Value>) -> Result<T, String>) -> napi::Result<T> {
625 let Ok(mut state) = self.state.try_borrow_mut() else {
626 return Err(napi::Error::from_reason("the actor is busy: an implementation called back into it"));
627 };
628 let actor = match &mut *state {
629 Ok(actor) => actor,
630 Err(why) => return Err(napi::Error::from_reason(format!("the actor is unusable: {why}"))),
631 };
632 match run(env, || f(actor)) {
633 Ok(v) => Ok(v),
634 Err(Failure::Error(msg)) => Err(napi::Error::from_reason(msg)),
635 Err(Failure::Fatal(e)) => {
636 *state = Err(format!("an earlier call failed part way through a step ({})", e.reason));
637 Err(e)
638 }
639 }
640 }
641}
642
643#[napi]
644impl Actor {
645 #[napi]
656 pub fn apply(&self, env: Env, batch: String) -> napi::Result<String> {
657 self.with(&env, |a| Ok(apply_json(a, &batch)))?.map_err(|error| contract_error(&env, &error))
658 }
659
660 #[napi]
666 pub fn can(&self, env: Env, event: String) -> napi::Result<bool> {
667 self.with(&env, |a| {
668 let event: Value = serde_json::from_str(&event).map_err(|e| format!("invalid event: {e}"))?;
669 if !event.get("type").is_some_and(Value::is_string) {
670 return Err("an event must have a string \"type\"".into());
671 }
672 a.can_json(&event).map_err(|e| e.to_string())
673 })
674 }
675
676 #[napi]
679 pub fn persist(&self, env: Env) -> napi::Result<String> {
680 self.with(&env, |a| Ok(a.persist().to_string()))
681 }
682
683 #[napi]
687 pub fn take_system_emitted(&self, env: Env) -> napi::Result<Vec<String>> {
688 self.with(&env, |a| Ok(system_emitted_json(a.take_system_emitted())))
689 }
690
691 #[napi]
693 pub fn take_logs(&self, env: Env) -> napi::Result<Vec<String>> {
694 self.with(&env, |a| Ok(a.take_logs().into_iter().map(|args| Value::Array(args).to_string()).collect()))
695 }
696
697 #[napi]
699 pub fn stop(&self, env: Env) -> napi::Result<()> {
700 self.with(&env, |a| a.stop().map_err(|e| e.to_string()))
701 }
702}