Skip to main content

Crate xmachines_eval_quickjs

Crate xmachines_eval_quickjs 

Source
Expand description

§xmachines-eval-quickjs

A JavaScript evaluator for xmachines-runtime: it runs the code nodes of a language ({ "@code": "({ context }) => context.n + 1", "@lang": "js" }, or ts with its types stripped by the extract script) in an embedded QuickJS, as XState’s own evaluators run them.

§When to use it

XState v6 serializes inline functions (guards, actions, transitions written as functions) to code nodes in the ts language. Register this evaluator when a machine authored that way should run in Rust unchanged, or when its computed values are written in JavaScript. It is opt-in, so the runtime itself keeps no JavaScript engine: code nodes in the rust language call Rust functions instead and cost what a Rust closure costs (an event that runs a guard and a context value took about 8.1 µs with JavaScript code nodes and 1.3 µs with Rust expressions; a JavaScript code node costs about 3.4 µs, mostly QuickJS’s own call and JSON work).

§How code runs

  • @code is a function, called as fn(scope, scope.enq) (Function("return (" + source + ")")()(scope, scope.enq));
  • @expr is an expression over the scope’s names (with (scope) { return (expr); }).

The scope is XState’s: context, event, input, params, self (with _parent), children, actions and actors (each name maps to itself: enq(actions.notify, params), enq.spawn(actors.worker)), and enq in actions and transitions (raise, emit, cancel, log, sendTo, spawn, stop; listen and subscribeTo throw). The root context sees input, self, actors and spawn. Actor references are { "@actor", incarnation } as XState persists them, with id as a non-enumerable property.

Values cross as JSON text, parsed in JavaScript only when the code reads them. Code runs deterministically by default: Math.random(), Date.now() and argument-less Date throw, as the runtime never reads a clock. Each thread keeps its own QuickJS runtime per evaluator (and per nesting depth, for a context spawn whose child runs code too), with a memory limit, a stack limit and an interrupt budget per call, so a runaway loop fails the step instead of the worker. An exception fails the step, as an exception from XState’s evaluator does.

§Example

use std::sync::Arc;

use serde_json::{json, Value};
use xmachines_eval_quickjs::JsEvaluator;
use xmachines_runtime::{Actor, Machine, Registry};

let mut registry: Registry<Value, Value> = Registry::new();
registry.evaluator("js", JsEvaluator::new());
let definition = json!({
    "@exprLang": "js",
    "context": { "count": 0 },
    "initial": "on",
    "states": { "on": { "on": { "inc": {
        "guard": { "@expr": "context.count < 2" },
        "context": { "count": { "@code": "({ context, event }) => context.count + event.by" } }
    } } } }
});
let machine = Machine::from_json(&definition, &registry).unwrap();
let mut actor = Actor::start(Arc::new(machine), 0).unwrap();
actor.send(json!({ "type": "inc", "by": 5 }), 0).unwrap();
assert_eq!(actor.context().unwrap()["count"], 5);

Register the same evaluator for ts too when the machine was extracted from TypeScript (registry.evaluator("ts", evaluator.clone()); clones share their engines). JsEvaluator::with_options takes JsOptions:

OptionDefaultWhat it bounds
memory_limit32 MiBthe QuickJS heap of one runtime
max_stack_size512 KiBthe stack of one call
interrupt_limit1000interrupt checks per call, each after about 10 000 bytecode instructions
deterministictruewhether Math.random(), Date.now() and new Date() throw

§Pins

QuickJS through rquickjs 0.14.

  • xmachines-runtime: the Evaluator trait this implements, and HostEvaluator for an evaluator in another runtime.
  • xmachines-kafka: its js feature registers this evaluator for js and ts in the generic binary.
  • xmachines-docs: the evaluators guide.

§License

MIT

Structs§

JsEvaluator
Evaluates JavaScript code nodes: register it for a language with xmachines_runtime::Registry::evaluator ("js", and "ts" for TypeScript sources the extract script stripped). Clones share their engines.
JsOptions
Limits and behavior of a JsEvaluator.