Skip to main content

xmachines_eval_quickjs/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::cell::{Cell, RefCell};
4use std::collections::HashSet;
5use std::rc::Rc;
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::sync::Arc;
8
9use rquickjs::{CatchResultExt, CaughtError, Context, Ctx, Exception, Function, Persistent, Runtime};
10use serde::Serialize;
11use serde_json::Value;
12use xmachines_runtime::{Code, CodeKind, ContextArgs, Enq, Evaluator, EventType, ExprArgs, Scope, Slot, SpawnOptions};
13
14/// Limits and behavior of a [`JsEvaluator`].
15#[derive(Debug, Clone)]
16pub struct JsOptions {
17    /// Bytes the QuickJS heap of one runtime may use (default 32 MiB).
18    pub memory_limit: usize,
19    /// Bytes of stack a call may use (default 512 KiB).
20    pub max_stack_size: usize,
21    /// QuickJS interrupt checks a call may take, each after about 10 000
22    /// bytecode instructions (default 1000): past it the call fails.
23    pub interrupt_limit: u64,
24    /// Whether `Math.random()`, `Date.now()` and `new Date()` throw
25    /// (default true), so code nodes cannot read randomness or a clock.
26    pub deterministic: bool,
27}
28
29impl Default for JsOptions {
30    fn default() -> Self {
31        Self { memory_limit: 32 << 20, max_stack_size: 512 << 10, interrupt_limit: 1000, deterministic: true }
32    }
33}
34
35/// Evaluates JavaScript code nodes: register it for a language with
36/// [`xmachines_runtime::Registry::evaluator`] (`"js"`, and `"ts"` for TypeScript
37/// sources the extract script stripped). Clones share their engines.
38#[derive(Clone)]
39pub struct JsEvaluator {
40    inner: Arc<Inner>,
41}
42
43struct Inner {
44    id: u64,
45    options: JsOptions,
46}
47
48impl Drop for Inner {
49    fn drop(&mut self) {
50        // This thread's engines go now; other threads' go when they exit.
51        let _ = ENGINES.try_with(|engines| engines.borrow_mut().retain(|(id, _, _)| *id != self.id));
52    }
53}
54
55static NEXT_EVALUATOR: AtomicU64 = AtomicU64::new(0);
56
57impl Default for JsEvaluator {
58    fn default() -> Self {
59        Self::new()
60    }
61}
62
63impl JsEvaluator {
64    pub fn new() -> Self {
65        Self::with_options(JsOptions::default())
66    }
67
68    pub fn with_options(options: JsOptions) -> Self {
69        Self { inner: Arc::new(Inner { id: NEXT_EVALUATOR.fetch_add(1, Ordering::Relaxed), options }) }
70    }
71
72    /// Runs `f` with this thread's engine for the current nesting depth.
73    fn with_engine<R>(&self, f: impl FnOnce(&Engine) -> R) -> Result<R, String> {
74        let depth = DEPTH.with(Cell::get);
75        let id = self.inner.id;
76        let found = ENGINES.with(|e| e.borrow().iter().find(|(i, d, _)| *i == id && *d == depth).map(|e| e.2.clone()));
77        let engine = match found {
78            Some(engine) => engine,
79            None => {
80                let engine = Rc::new(Engine::new(&self.inner.options)?);
81                ENGINES.with(|e| e.borrow_mut().push((id, depth, engine.clone())));
82                engine
83            }
84        };
85        DEPTH.with(|d| d.set(depth + 1));
86        let _depth = Restore(&DEPTH, depth);
87        Ok(f(&engine))
88    }
89}
90
91/// Restores a thread-local cell when dropped.
92struct Restore<T: Copy + 'static>(&'static std::thread::LocalKey<Cell<T>>, T);
93
94impl<T: Copy + 'static> Drop for Restore<T> {
95    fn drop(&mut self) {
96        let value = self.1;
97        let _ = self.0.try_with(|c| c.set(value));
98    }
99}
100
101thread_local! {
102    /// Engines by evaluator id and nesting depth.
103    static ENGINES: RefCell<Vec<(u64, usize, Rc<Engine>)>> = const { RefCell::new(Vec::new()) };
104    /// Evaluations running on this thread.
105    static DEPTH: Cell<usize> = const { Cell::new(0) };
106    /// The call `enq` and `spawn` act for (see [`Live`]).
107    static LIVE: Cell<*const Live<'static>> = const { Cell::new(std::ptr::null()) };
108}
109
110/// What JavaScript's `enq`, `spawn` and the actor references reach during
111/// one call.
112struct Live<'a> {
113    enq: Option<&'a Enq<'a>>,
114    context: Option<&'a ContextArgs<'a>>,
115    /// `{ self, parent?, children? }`, built when the code reads them.
116    refs: Option<&'a dyn Fn() -> Value>,
117}
118
119/// Makes `live` what `enq` and `spawn` act for while `f` runs.
120fn with_live<R>(live: &Live<'_>, f: impl FnOnce() -> R) -> R {
121    // Only the lifetime is erased; the pointer is cleared (restored to the
122    // enclosing call's) before `live` goes out of scope, panics included.
123    let ptr: *const Live<'static> = std::ptr::from_ref(live).cast();
124    let previous = LIVE.with(|l| l.replace(ptr));
125    let _restore = Restore(&LIVE, previous);
126    f()
127}
128
129/// Calls `f` with the live call, if there is one.
130fn live<R>(f: impl FnOnce(&Live<'_>) -> R) -> Option<R> {
131    let ptr = LIVE.with(Cell::get);
132    if ptr.is_null() {
133        return None;
134    }
135    // SAFETY: `ptr` is set only by `with_live`, from a reference that
136    // outlives the call (the restore guard clears it before the reference
137    // ends), and JavaScript runs on this thread only during that call. The
138    // reference handed to `f` cannot escape it.
139    Some(f(unsafe { &*ptr }))
140}
141
142struct Engine {
143    /// `__xstate.compile`, `run` and `runContext` (dropped before the
144    /// runtime: fields drop in order).
145    functions: [Persistent<Function<'static>>; 3],
146    compiled: RefCell<HashSet<u64>>,
147    calls: Rc<Cell<u64>>,
148    limit: u64,
149    context: Context,
150    _runtime: Runtime,
151}
152
153/// Defines `__xstate` (`compile`, `run`, `runContext`), given the Rust
154/// bridge as `__xstate_bridge`.
155const PRELUDE: &str = include_str!("prelude.js");
156
157/// Makes randomness and the clock throw.
158const DETERMINISM: &str = r#"(() => {
159  const fail = (what) => () => { throw new Error(`${what} is not available: code nodes run deterministically`); };
160  Math.random = fail('Math.random()');
161  const RealDate = Date;
162  function DeterministicDate(...args) {
163    if (args.length === 0) fail('new Date()')();
164    return new.target ? new RealDate(...args) : RealDate(...args);
165  }
166  DeterministicDate.prototype = RealDate.prototype;
167  DeterministicDate.UTC = RealDate.UTC;
168  DeterministicDate.parse = RealDate.parse;
169  DeterministicDate.now = fail('Date.now()');
170  globalThis.Date = DeterministicDate;
171})();"#;
172
173impl Engine {
174    fn new(options: &JsOptions) -> Result<Self, String> {
175        let runtime = Runtime::new().map_err(|e| e.to_string())?;
176        runtime.set_memory_limit(options.memory_limit);
177        runtime.set_max_stack_size(options.max_stack_size);
178        let calls = Rc::new(Cell::new(0));
179        let counter = calls.clone();
180        let limit = options.interrupt_limit;
181        runtime.set_interrupt_handler(Some(Box::new(move || {
182            counter.set(counter.get() + 1);
183            counter.get() > limit
184        })));
185        let context = Context::full(&runtime).map_err(|e| e.to_string())?;
186        let functions = context.with(|ctx| -> Result<_, String> {
187            let bridge = Function::new(ctx.clone(), bridge).map_err(|e| e.to_string())?;
188            ctx.globals().set("__xstate_bridge", bridge).map_err(|e| e.to_string())?;
189            ctx.eval::<(), _>(PRELUDE).catch(&ctx).map_err(|e| format!("prelude: {e}"))?;
190            if options.deterministic {
191                ctx.eval::<(), _>(DETERMINISM).catch(&ctx).map_err(|e| format!("prelude: {e}"))?;
192            }
193            let xstate: rquickjs::Object = ctx.globals().get("__xstate").map_err(|e| e.to_string())?;
194            let get = |name: &str| -> Result<Persistent<Function<'static>>, String> {
195                let f: Function = xstate.get(name).map_err(|e| e.to_string())?;
196                Ok(Persistent::save(&ctx, f))
197            };
198            Ok([get("compile")?, get("run")?, get("runContext")?])
199        })?;
200        Ok(Self { functions, compiled: RefCell::new(HashSet::new()), calls, limit, context, _runtime: runtime })
201    }
202
203    /// Runs a code node with its scope (each value as JSON text) and
204    /// returns its result.
205    fn run(&self, code: &Code, scope: &ScopeText) -> Result<Value, String> {
206        self.calls.set(0);
207        self.context.with(|ctx| {
208            let function = |i: usize| self.functions[i].clone().restore(&ctx).map_err(|e| e.to_string());
209            let kind = code.kind.as_str();
210            let id = code.id as f64;
211            if !self.compiled.borrow().contains(&code.id) {
212                function(0)?
213                    .call::<_, ()>((id, kind, code.source.as_str()))
214                    .catch(&ctx)
215                    .map_err(|e| self.message(&ctx, e))?;
216                self.compiled.borrow_mut().insert(code.id);
217            }
218            let code_mode = i32::from(code.kind == CodeKind::Code);
219            let out: Option<String> = match scope {
220                ScopeText::Expr { enq, context, event, input, params } => {
221                    // A transition's scope has `reject` (XState's transition arguments).
222                    let mode = code_mode | if *enq { 2 } else { 0 } | if code.slot == Slot::Transition { 4 } else { 0 };
223                    function(1)?.call((id, mode, context.as_str(), event.as_str(), input.as_deref(), params.as_deref()))
224                }
225                ScopeText::Context { input, self_ref } => {
226                    function(2)?.call((id, code_mode, input.as_deref(), self_ref.as_deref()))
227                }
228            }
229            .catch(&ctx)
230            .map_err(|e| self.message(&ctx, e))?;
231            match out {
232                None => Ok(Value::Null),
233                Some(text) => serde_json::from_str(&text).map_err(|e| format!("the result is not JSON: {e}")),
234            }
235        })
236    }
237
238    fn message(&self, _ctx: &Ctx<'_>, error: CaughtError<'_>) -> String {
239        if self.calls.get() > self.limit {
240            return "the code ran too long (its interrupt budget ran out)".into();
241        }
242        match error {
243            CaughtError::Exception(e) => e.message().unwrap_or_else(|| e.to_string()),
244            CaughtError::Value(v) => v.as_string().and_then(|s| s.to_string().ok()).unwrap_or_else(|| format!("{v:?}")),
245            CaughtError::Error(e) => e.to_string(),
246        }
247    }
248}
249
250/// A code node's scope, each value as JSON text.
251enum ScopeText {
252    Expr { enq: bool, context: String, event: String, input: Option<String>, params: Option<String> },
253    Context { input: Option<String>, self_ref: Option<String> },
254}
255
256/// The JavaScript side's calls into Rust: `(op, JSON args)` to JSON text.
257fn bridge<'js>(ctx: Ctx<'js>, op: String, args: String) -> rquickjs::Result<Option<String>> {
258    let args: Vec<Value> = serde_json::from_str(&args).unwrap_or_default();
259    let result = live(|live| apply(live, &op, args))
260        .unwrap_or_else(|| Err(format!("enq.{op} can only be used while the code node that received it runs")));
261    match result {
262        Ok(v) => Ok(v.map(|v| v.to_string())),
263        Err(message) => Err(Exception::throw_message(&ctx, &message)),
264    }
265}
266
267fn apply(live: &Live<'_>, op: &str, args: Vec<Value>) -> Result<Option<Value>, String> {
268    if op == "refs" {
269        return Ok(live.refs.map(|refs| refs()));
270    }
271    if op == "spawnContext" {
272        let cx = live.context.ok_or("spawn is only available in the root context")?;
273        let src = args.first().and_then(Value::as_str).ok_or("spawn: the source must be a string (actors.<name>)")?;
274        let options = args.get(1).map(SpawnOptions::from_json).unwrap_or_default();
275        return Ok(Some(cx.spawn(src, options)));
276    }
277    live.enq.ok_or_else(|| format!("enq.{op} is not available here"))?.call(op, &args)
278}
279
280impl<C: Serialize, E: EventType> Evaluator<C, E> for JsEvaluator {
281    fn eval(&self, code: &Code, scope: Scope<'_, '_, C, E>) -> Result<Value, String> {
282        match scope {
283            Scope::Expr(a) => {
284                let text = expr_scope(a)?;
285                let refs = || refs(a);
286                let live = Live { enq: a.enq(), context: None, refs: Some(&refs) };
287                self.with_engine(|engine| with_live(&live, || engine.run(code, &text)))?
288            }
289            Scope::Context(a) => {
290                let text = ScopeText::Context {
291                    input: a.input.map(Value::to_string),
292                    self_ref: a.self_ref().map(|r| r.to_json().to_string()),
293                };
294                let live = Live { enq: None, context: Some(a), refs: None };
295                self.with_engine(|engine| with_live(&live, || engine.run(code, &text)))?
296            }
297        }
298    }
299}
300
301/// `self` (with its parent) and the children, as JavaScript reads them.
302fn refs<C, E>(a: &ExprArgs<'_, C, E>) -> Value {
303    let mut refs = serde_json::Map::new();
304    refs.insert("self".into(), a.self_ref().to_json());
305    if let Some(parent) = a.parent_ref() {
306        refs.insert("parent".into(), parent.to_json());
307    }
308    let children = a.children();
309    if !children.is_empty() {
310        let children = children.iter().map(|(id, r)| (id.clone(), r.to_json())).collect();
311        refs.insert("children".into(), Value::Object(children));
312    }
313    Value::Object(refs)
314}
315
316fn expr_scope<C: Serialize, E: EventType>(a: &ExprArgs<'_, C, E>) -> Result<ScopeText, String> {
317    Ok(ScopeText::Expr {
318        enq: a.enq().is_some(),
319        context: serde_json::to_string(a.context).map_err(|e| format!("the context does not serialize: {e}"))?,
320        event: a.event.to_json().to_string(),
321        input: a.input.map(Value::to_string),
322        params: a.params.map(Value::to_string),
323    })
324}
325
326#[cfg(test)]
327mod tests;