plusthree for XState users #
plusthree runs XState v6 statecharts in Rust. If you know XState, you already
know the semantics: states, transitions, guards, after, invoke, history,
onDone, onError. Those work the way XState v6 defines them, and a
conformance harness checks that against XState itself.
What changes is the shape of the API. Rust has types, no garbage collector and no event loop of its own, so plusthree makes four choices that XState does not:
- Patches instead of
assign. Context changes are values a transition returns, not mutations. - Effects as data. Actions don't run inside the machine. A step returns a list of effects, and your code executes them.
- The host fires timers. The kernel has no clock. It tells you when to start and cancel timers, and you tell it when one is due.
- Typed events. Events are a Rust enum, matched by pattern.
This guide walks through each, then the patterns an application needs, and
ends with the places where plusthree deliberately differs from XState. The
runnable examples in crates/plusthree/examples
show everything here in full; each one asserts what it demonstrates.
Vocabulary #
| XState | plusthree |
|---|---|
setup({ types }).createMachine({...}) |
plusthree::machine! { Name { context: C, events: E, .. } ... } |
machineFromJSON(json) |
Machine::<Json>::from_json(&json, ®istry) (feature json) |
| machine | Machine<T>, built once: Name::machine() |
createActor(machine).start() |
machine.initial(input, &mut fx) returns a Snapshot |
actor.send(event) |
machine.step(&mut snapshot, event, &mut fx) |
getNextSnapshot / transition |
machine.transition(&snapshot, event) |
snapshot.matches('a.b') |
snapshot.matches(name::states::a::B), a typed handle |
snapshot.can(event) |
machine.can(&snapshot, &event) |
snapshot.value |
snapshot.value(machine.def()) |
assign({ count: ... }) |
Transition::stay().patch(|p| p.count(...)) |
raise, sendTo, emit, log, cancel |
enq.raise, enq.send_to, enq.emit, enq.log, enq.cancel |
custom action ({ context }) => ... |
enq.action(Fx::Something), executed by the host |
guard: ({ context, event }) => ... |
guard: |a| ... with a.context, a.event |
after: { 1000: 'b' } |
after: { 1s => b } |
delays: { wait: ({ context }) => ... } |
delays: { wait: |a| Duration::... } |
isUnhandled |
Outcome::Unhandled |
createActor with children, system |
plusthree::system::System, or plusthree::runtime on tokio |
Typed events #
Events are an enum with #[derive(Event)]. A variant's name is its event
name, as XState sees it in JSON, inspection and wildcards:
#[derive(Event, Clone, Debug)]
enum Ev {
Inc, // "Inc"
Add { n: u32 }, // "Add"
#[event(rename = "user.login")]
Login { name: String }, // "user.login", matched by "user.*"
}
#[event(rename_all = "SCREAMING_SNAKE_CASE")] renames every variant.
In machine!, a key in on is a pattern. Its bindings are references into
the event, in scope in the transition's guard and handlers. A pattern that
doesn't cover the whole variant also guards the transition:
on: {
Ev::Add { n } => |a, _| Transition::stay().patch(|p| p.count(a.context.count + n)),
Ev::Set(0) => idle, // only Set(0)
Ev::Set(n) => |_, _| Transition::stay().patch(|p| p.count(*n)),
Ev::Inc | Ev::Reset => counting,
"user.*" => |a, enq| { /* any user.* event; a.event is the envelope */ },
}
Events must be Clone: the kernel clones them for can, delayed raises and
inspection. Put large or non-Clone payloads, such as a fetched message
body, behind an Arc:
enum Ev { Fetched { seq: u32, body: Arc<[u8]> }, ... }
Handlers see built-in events (xstate.after, xstate.done.actor,
xstate.error.execution, ...) through a.event, an Envelope: Envelope::Event(ev)
is a user event, and the other variants are the built-ins. a.event.event()
returns the user event when there is one.
Patches instead of assign #
XState computes assign during the microstep, against the context from
before it, and merges the results after the exit actions, in document order.
plusthree does the same with a value: a transition returns a patch, the
fields it changes. #[derive(Context)] on
#[derive(Context, Clone, Default)]
struct Ctx { count: u32, query: String }
generates CtxPatch { count: Option<u32>, query: Option<String> } with a
setter per field. You use it in three places:
// A transition function: stay and patch.
Ev::Inc => |a, _| Transition::stay().patch(|p| p.count(a.context.count + 1)),
// A transition to another state, with a patch.
Ev::Reset => |_, _| Transition::to(counter::states::IDLE).patch(|p| p.count(0)),
// An action (entry, exit, or a transition object's `actions`) returns
// `Option<CtxPatch>`. Inside `machine!` handlers, `Patch` names it.
entry: |a, _| Some(Patch::default().count(0).query(String::new())),
A shared action written outside machine! names the machine:
Patch<Counter> (in the prelude), as in
fn reset(a: &Args<Counter>, enq: &mut Enq<Counter>) -> Option<Patch<Counter>>,
built with Patch::<Counter>::default(). Use it in the machine as
entry: self::reset.
Patches are data, which is what makes rollback after an error cheap (the kernel applies the inverse patch) and lets tests compare them.
What belongs in context. Every patch moves values into the context, and
cloning a snapshot clones the context. Keep in context the small facts the
chart decides on: counters, ids, the current query, flags, a sequence
number. Keep big or shared data outside, in your own structs next to the
snapshot (a mailbox's messages, a cache, a connection), or share it with an
Arc. The chart can hold an id or an Arc and the host looks up the rest.
Effects as data #
In XState an action is a function that runs inside actor.send. In
plusthree, the handler enqueues an effect and returns:
#[derive(Debug)]
enum Fx { FetchFolder { account: String }, Notify(String) }
entry: |a, enq| enq.action(Fx::FetchFolder { account: a.context.account.clone() }),
step writes everything the macrostep wants done into an Effects buffer,
in XState's order: exit actions, then transition actions, then entry
actions, then the starts of new children. Each initial, step and fire
clears the buffer first, so effects you ignore don't pile up. Your host
drains it:
m.step(&mut snap, event, &mut fx);
for effect in fx.drain() {
match effect {
Effect::Action(Fx::FetchFolder { account }) => imap.fetch(account),
Effect::Action(Fx::Notify(text)) => ui.toast(text),
// Timers: see "The host fires timers" below.
Effect::Schedule(timer) => timers.start(timer.key, timer.delay),
Effect::Cancel(key) => timers.cancel(&key),
_ => {}
}
}
Other effects are Emit (enq.emit), Log (enq.log), Spawn, Start,
Stop and SendTo (children and messages, carried out by an actor system),
and DeadLetter (a send to a target that doesn't exist).
Reuse one Effects buffer for a machine instance: it also holds the
kernel's scratch space, so a steady-state step allocates nothing.
Besides enq.action, handlers can enq.raise(ev) (an internal event,
processed in the same macrostep), enq.raise_after(ev, delay, Some(id)) and
enq.cancel(id), enq.emit(..), enq.log(..), enq.send_to(target, ev),
enq.spawn(child, options) and enq.stop(id).
Async I/O #
The pattern for any request: the chart enqueues the request as an effect, the host runs it however it likes, and the answer comes back as an event.
searching: {
entry: |a, enq| {
let seq = a.context.seq + 1;
enq.action(Fx::Search { seq, query: a.context.query.clone() });
Some(Patch::default().seq(seq))
},
on: {
// Only the answer to the request in flight counts.
Ev::Results { seq, hits } => { target: idle, guard: |a| *seq == a.context.seq, .. },
Ev::Failed { seq } => { target: retrying, guard: |a| *seq == a.context.seq, .. },
},
},
The sequence number makes a late answer to an older request harmless. The
host can run the request on a thread, a tokio task, or a test double; the
chart doesn't know. The mail_search
example does this end to end.
invoke is the other way, and it is XState's: a state invokes a child, and
on_done/on_error handle its typed output or error. A child is an
actor, so it needs something to run it: plusthree::system
or the tokio runtime. If you run machines yourself inside your app's own
state, use effects and events. If you want XState's actor model (children
that outlive a request, per-entity actors, sendTo between them), use
invoke and spawn with the system.
The host fires timers #
The kernel has no clock. When a state with after is entered (or a handler
calls enq.raise_after), the step returns Effect::Schedule(timer) with a
timer.key and a timer.delay, and records the timer in the snapshot. When
the state is exited first, the step returns Effect::Cancel(key). When the
delay has passed, you call:
m.fire(&mut snap, &key, &mut fx);
The host keeps its own timer handle for each pending timer: a tokio
AbortHandle, a GUI toolkit's timeout id, or a deadline.
plusthree::host::Driven<T, H> does the bookkeeping. It holds the machine,
the snapshot, the effects buffer and the pending timers with your handle
H for each. step runs an event, fire a due timer and stop stops the
machine on teardown; each takes your host::Scheduler<H>, which starts a
timer (schedule(delay, token) -> H, whose callback hands token to
fire) and stops one (cancel(H)). The timer effects never reach you:
they become calls to your scheduler. Your other effects stay in
effects(), in order, until the next call.
Starting and stopping usually need the same context, such as a GUI
toolkit's or a transaction's, so implement Scheduler on it, or on a thin
wrapper around a borrow of it, and pass &mut ctx:
use plusthree::host::{Driven, Scheduler, TimerToken};
impl Scheduler<TimeoutId> for Ui {
fn schedule(&mut self, delay: Duration, token: TimerToken) -> TimeoutId {
self.timeout(delay, move |app| app.mail_timer(token)) // calls back with `token`
}
fn cancel(&mut self, id: TimeoutId) {
self.cancel_timeout(id);
}
}
// Driven<'static, Mail, TimeoutId>
let mut mail = Driven::start(Mail::machine(), input, &mut ui)?;
mail.step(event, &mut ui);
for effect in mail.effects_mut().drain() { /* your actions, as above */ }
// When the host's timer callback runs with `token`:
mail.fire(token, &mut ui);
// On teardown: stops the machine and every timer still running.
mail.stop(&mut ui);
When the two need nothing in common, host::schedule_with(schedule, cancel) makes a scheduler of two closures, typed from its signature. With
tokio, schedule spawns a task that sleeps and sends the token on a
channel, and returns its AbortHandle; cancel aborts it:
let timers = || schedule_with(
|delay, token| { let tx = tx.clone(); tokio::spawn(async move { sleep(delay).await; let _ = tx.send(token); }).abort_handle() },
|handle| handle.abort(),
);
mail.step(event, timers());
With a simulated clock the handle is the deadline,
schedule_with(move |delay, _| now + delay, |_| {}): timers() lists each
pending timer's token and handle, so the clock fires the earliest due one.
Two stock schedulers cover the rest. host::NoTimers is for a machine
that starts no timer, or for Driven::start before your scheduler exists
when the initial states have none; it panics if a timer starts. For tests,
host::Recorder records each timer started and stopped, with handles
counting up from 1, lists the ones running, and delivers one with
recorder.fire(&mut driven, token) (or recorder.fired(token) after
calling driven.fire yourself). recorder.take() returns the starts and
stops since the last call, in order, to check what one step did.
The netting covers what one macrostep can produce. A state re-entered with
reenter: true yields Cancel(k) then Schedule(k): the old handle is
stopped and a new timer started with the full delay. A state entered and
left again in the same macrostep, as by always, yields Schedule(k) then
Cancel(k): nothing is started.
Each start carries a fresh TimerToken, and your timer callback reports
the token, not the key. On an event loop, a timer's callback can already be
queued when a step cancels or re-arms its key. That callback carries the
old token, so fire returns None, runs nothing and leaves the effects
empty, and the new timer is not fired early.
Driven is built on plusthree::host::Timers<H>, the map from each
pending timer to your handle, which you can use directly if you keep the
snapshot yourself: after each step or fire, timers.apply(&mut fx, &mut ops) takes the timer effects out of the buffer and nets them into
TimerOp::Arm { delay, token, .. } and TimerOp::Disarm(handle); give
each new handle to timers.armed(token, handle), and when a callback runs
pass its token to timers.fired(token), which returns the key for
m.fire or None for a stale callback. A host that starts its timers
later than it steps, say after a transaction commits, calls armed when
the handle exists, in any order: when a step has cancelled or re-armed the
key in the meantime, armed returns the handle for you to stop.
Scheduling a key that is already pending replaces it. In tests, a simulated
clock makes timers instant and deterministic; the
traffic_light example has
a complete host loop with Driven, using each deadline as the handle.
Delays can be fixed (after: { 500ms => b }, with ms, s, min, h) or
named functions of the snapshot, evaluated when the timer is scheduled:
delays: {
debounce: |a| a.context.debounce, // from context
backoff: |a| Duration::from_millis(250 << a.context.failures.min(4)),
},
states: {
typing: { after: { debounce => searching } },
retrying: { after: { backoff => searching } },
}
Debounce. Re-arm a timer on every keystroke by re-entering its state.
reenter: true exits and enters the state even when it is already active,
which cancels the old timer and schedules a new one:
on: {
Ev::Key { query } => {
target: .typing,
reenter: true,
actions: |_, _| Some(Patch::default().query(query.clone())),
},
},
Back-off. Count failures in context and let a delay function read the count, as above; a guard on the failure count decides when to give up.
Persisting timers. Because the snapshot lists its pending timers,
persisting a machine persists its timers. plusthree-json asks for each
timer's deadline on your clock when persisting and returns each timer's
remaining delay when restoring, so a restored timer fires when it would
have (DEVIATIONS.md D19). Use the same clock for both, such as time since
the Unix epoch. Wrap the restored snapshot in Driven::new(machine, snapshot) and call restore(restored.timers, scheduler), which
starts each timer with its remaining delay (and stops whatever was pending
before). When your handle is a deadline, |k| driven.timers().handle(k).copied()
is the deadline function persisting asks for.
Guards and transition functions #
A guard is a function of the snapshot and event; guard: self::is_valid
names a function. A guard closure sees the bindings of its on pattern
(Ev::Swipe { distance } => { target: armed, guard: |a| *distance > 40 }).
A named function gets a.event, the Envelope; a.event.event() returns
the typed event when it is one:
fn far_enough(a: &Args<Pager>) -> bool {
matches!(a.event.event(), Some(Ev::Swipe { distance }) if *distance > 40)
}
A list of candidates is tried in order, and the first enabled one wins, as with XState's guarded transition arrays:
Ev::Send => [
{ target: sending, guard: self::is_valid },
{ actions: |_, enq| enq.action(Fx::Warn("add a recipient")) },
],
A transition function decides everything at run time. It returns a
Transition, Option<Transition>, (), or any of those in a Result.
() counts as None. Returning None or () without enqueuing anything
declines the event, and the search continues with the parent state, as in
XState; if it enqueued something, it takes a targetless transition. To take
the event without enqueuing anything, or to change the context, return
Transition::stay() (with .patch(..) for the context). It runs exactly once per
selection (DEVIATIONS.md D2), so side effects through enq are safe.
Handling an event only in some substates #
Declining is how a statechart says "only here". A reader re-asks for its
thread on every redraw, but should start settling only when it is idle.
Put that handler on idle and let it decline everything else; the parent
handles what is left, here a switch to another thread:
open: {
initial: idle,
on: {
// Reached only when no active child took the event.
Ev::Show { thread, .. } => |a, _| (a.context.thread != *thread)
.then(|| Transition::to(reader::states::open::IDLE).reenter(true)),
},
states: {
idle: {
on: {
Ev::Show { thread, want } => |a, _| (a.context.thread == *thread && *want)
.then(|| Transition::to(reader::states::open::SETTLING)),
},
},
settling: { after: { 250ms => fetching } },
fetching: {},
},
},
While settling or fetching, a repeated Show for the same thread is
unhandled, so the settle timer is not restarted. When a decision needs the
whole picture in one place, a function can also ask which states are active
with a.matches(reader::states::open::IDLE), as Snapshot::matches does
for a snapshot.
Errors #
A handler fails by returning Err. The machine's error type is the
header's error: key:
plusthree::machine! {
Mailbox { context: Ctx, events: Ev, effects: Fx, error: MailError }
...
Ev::Received(raw) => |a, enq| {
let msg = parse(raw)?;
Ok(Transition::stay().patch(|p| p.received(a.context.received + 1)))
},
As in XState, an error aborts the whole macrostep: its patches and effects
are discarded. If an active state declares on_error, the macrostep reruns
from the snapshot before the event with xstate.error.execution
(Envelope::ErrorExecution), and on_error handles it. Otherwise the step
returns Outcome::Errored, snapshot.status() is Status::Error, and
snapshot.error() holds the error. An errored machine cancels its timers
and stops its children.
A handler that always fails needs its return type spelled out, because Rust
cannot tell which Result it returns:
Ev::Corrupt => |_, _| -> Result<(), MailError> { Err(MailError::Storage) },
Panics are not caught (DEVIATIONS.md D3). See the
errors example.
Parallel states and history #
These work as in XState. A history state returns to what an overlay was opened over:
window: {
initial: main,
on: { Ev::Settings => settings },
states: {
main: { type: parallel, states: { view: { .. }, sync: { .. } } },
back: { type: history, history: deep, target: main },
},
},
settings: { on: { Ev::Close => window.back } },
Actors #
Children are declared as an enum with #[derive(Children)], one variant
per kind of child, whose fields are its input. The derive generates enums
for the children's typed outputs, so on_done matches on them:
#[derive(Children, Clone, Debug)]
#[children(message = Msg)] // what this machine sends to other actors
enum Jobs {
#[child(output = u32)]
Fetch(String),
}
syncing: {
invoke: {
src: |a| Jobs::Fetch(a.context.account.clone()),
id: "fetch",
on_done: { JobsOutput::Fetch(n) => { target: idle, actions: .. } },
on_error: idle,
timeout: { 30s => idle },
},
},
Spawn from a handler with
enq.spawn(Kids::Account(name), SpawnOptions::new().id(name)), and address
children with enq.send_to(Target::Child(id), ev) or the parent
with Target::Parent.
The kernel only describes children (Effect::Spawn, Start, Stop,
SendTo). plusthree::system::System runs a whole tree: machines, async
jobs (AsyncActor, XState's fromPromise) and callbacks, with one FIFO
message queue and timers in system time. Like the kernel, it is a pure
reducer: the host sends events, advances time, settles async jobs and
drains Notices. plusthree::runtime (feature runtime) drives one on
tokio with real time and real futures.
An actor system speaks one set of value types, its Universe. A JSON
machine needs no glue: plusthree::json::json_actor(machine, input, spawn)
runs it as an actor of JsonUniverse, where every value is a
serde_json::Value as in XState, and spawn creates the logic of each
child it invokes or spawns:
use plusthree::json::{json_actor, JsonUniverse};
let root = json_actor(Arc::new(machine), None, |child| match child.src.as_str() {
"fetch" => Box::new(AsyncActor::new(plan_for(child), async_snapshot)),
src => panic!("no actor named {src}"),
});
let mut sys = System::new("mail", root, Duration::ZERO)?;
A typed machine joins a system through a Bridge that converts its
events, outputs and effects, and creates the actors of the children it
spawns. For 0.1 you write that bridge yourself; the
actor_system and
tokio_runtime examples
share one in support/accounts.rs,
with one actor per mail account.
Watching machines in the Stately Inspector #
With feature inspect, machines show up live in the
Stately Inspector, as an XState app
inspected with @statelyai/sdk's createInspector does: the actors, the
events they process, and each machine's diagram with its active states and
the transitions just taken highlighted.
Inspector::serve(addr) starts a local inspection relay on a background
thread; open inspector.url() in Chrome. The viewer is Stately's hosted
page; it connects back to the relay on your machine, so no account is
needed and inspection data stays local. The URL carries a random room id
that the relay checks. Chrome may ask whether sky.stately.ai may reach
your local network: allow it.
Machines your host steps #
A host that owns its snapshots shows each machine with
inspector.actor(id, machine, &snap), and steps it through the
ActorHandle it returns. Report::step and Report::fire step the machine
and report the macrostep in one call: the event's name, the snapshot, the
transitions taken (highlighted in the diagram) and the actions.
use plusthree::inspect::{Inspector, Report};
let inspector = Inspector::serve("127.0.0.1:4242")?;
println!("{}", inspector.url());
// An account has no machine of its own: a group, with its machines in it.
let account = inspector.group("work");
let mut sync = account.child("sync", Sync::machine(), &snap);
let mut draft = account.child("draft", Compose::machine(), &draft_snap);
sync.step(m, &mut snap, event, &mut fx); // shows the event's name
sync.fire(m, &mut snap, &key, &mut fx); // shows `xstate.timer`
Where inspection is optional, keep an Option<ActorHandle>: the same
step and fire calls work on it, and with None they are the machine's
plain step and fire. Option<O> is also an Observer, so
m.step_with(.., &mut self.actor) covers both cases for a host that
steps the machine itself and calls handle.stepped(event, &snap) after.
A machine run by host::Driven takes the handle as its observer instead,
and reports every step, fire and stop itself:
use plusthree::host::Driven;
// Start with the observer type it keeps, so the kernel is compiled once
// for this machine; the handle needs the snapshot, so it starts as `None`.
let mut sync: Driven<_, _, Option<ActorHandle>> = Driven::start_with(Sync::machine(), (), &mut ui, None)?;
*sync.observer_mut() = inspector.as_ref().map(|i| i.actor("sync", Sync::machine(), sync.snapshot()));
sync.step(event, &mut ui); // shows the event's name
if let Some(a) = sync.observer() { a.move_to(&account); }
sync.stop(&mut ui); // shows `xstate.stop`
By default the viewer gets only what cannot leak: event names, the state,
built-in actions (timers, raises, sends, children, logs, emits) by their v6
types, and the machine's own effects as effect. Of the context it gets
only the fields you mark #[context(show)]:
#[derive(Context, Clone, Default)]
pub struct SyncCtx {
#[context(show)]
unread: u32, // a count, as is
#[context(show)]
retry_in: Duration, // in milliseconds
#[context(show)]
phase: Phase, // a #[derive(VariantName)] enum, by variant
#[context(show_with = Option::is_some)]
token: Option<String>, // whether there is one, not the token
subjects: Vec<String>, // not marked: never shown
}
Flags, numbers, durations, text, Options of those and
#[derive(VariantName)] enums can be shown; marking a field of another
type is a compile error that suggests show_with. To name the machine's
own effects by their variants, never their data, derive VariantName for
the effect enum and call name_effects with the machine, which ties the
naming to the machine's effect type at compile time:
#[derive(Debug, VariantName)]
pub enum SyncFx { Notify { subject: String } } // shows as `Notify`
let mut sync = account.child("sync", Sync::machine(), &snap).name_effects(Sync::machine());
For anything else, build the JSON yourself. show_context replaces the
marked fields, and show_effects makes each effect a name or a
{"type", "params"} object; it panics if its closure takes another type
than the machine's effects:
let mut sync = account
.child("sync", Sync::machine(), &snap)
.show_context(&snap, |c: &SyncCtx| json!({ "unread": c.unread }))
.show_effects(|e: &SyncFx| match e {
SyncFx::Notify { .. } => json!({ "type": "notify", "params": { "n": 1 } }),
});
// One event with a payload: a string is the event type, an object the
// whole event.
sync.step_showing(m, &mut snap, event, &mut fx, |e| json!({ "type": e.name(), "folder": "inbox" }));
For a Driven machine, which steps without a per-call closure, set the
event's JSON once per actor with show_events(|e: &SyncEv| ..); like
show_effects, it panics if its closure takes another type than the
machine's events.
id is the label the viewer shows. child nests actors under an actor or a
group, and the viewer groups siblings running the same machine
(account, 2 actors). Dropping a handle or group shows it as stopped, and
registering its id again in the same place then replaces it, as when a
draft starts again; while it runs, both show.
Register a machine when it starts, even before you know where it belongs,
and move it there later with move_to: into a group, under another handle,
or back to the top level with the inspector itself. It keeps its history
and children; open viewers redraw it under its new parent.
// The session signs in before its account exists.
let session = inspector.actor("jmap", Jmap::machine(), &snap);
// ... later, once the account is known:
session.move_to(&account);
``` The
[`inspect_host`](../crates/plusthree/examples/inspect_host.rs) example runs
two accounts this way, with `host::Driven`.
### Actor systems
For a `System`, pass the inspector every notice and register the machines
under the names their actors are created with:
```rust,ignore
inspector
.machine("mail", Mail::machine()) // the root, by its actor id
.machine("Account", Account::machine()); // children, by their `src`
let ins = inspector.clone();
let (handle, driver) = Driver::new(clock, make_system, move |n| {
ins.notice(&n);
// ... the host's own handling ...
});
A host that drains a System itself calls inspector.notice(&n) in its
drain loop. machine exports the machine's MachineJSON for the diagram;
pass a JSON-loaded machine as the JsonMachine itself, which keeps its
action parameters.
The universe says how its values look as JSON by implementing Inspect:
events as {"type": ..} objects, and snapshots as v6's
{"status", "value", "context"?}. JsonUniverse already implements it. A
typed bridge can publish JSON snapshots with
plusthree::json::snapshot_json(machine, snapshot); see the
inspect example, which runs the
mail actors this way.
JSON and persistence #
With feature json, Machine::<Json>::from_json(&value, ®istry) loads
MachineJSON as XState's machineToJSON and Stately Studio produce it.
JSON cannot hold code, so the actions, guards, delays and actors it names
are bound from a Registry; a missing name is a load error at its JSON
path. registry.effect("name") turns an action into an
Effect::Action(CustomAction) for the host. Built-in actions
(@xstate.assign, @xstate.raise, ...) run natively. Embedded code
(@code, @expr) is rejected.
The other way, machine.to_json() (trait plusthree::json::ToJson)
exports any machine, typed or loaded from JSON, as MachineJSON that
XState's machineFromJSON, Stately Studio, the visualizer and the Stately
Inspector accept: serde_json::to_string(&Light::machine().to_json()).
Functions become names, so a diagram shows guard: is_unlocked. A
machine! handler written as a path (guard: self::is_unlocked) and a
function passed to the builder by name keep their function's name; a
closure is named after where it sits, such as door.closed.on.Lock[0].actions.
A transition function shows up as a transition without a target whose one
action is its name, since only running it decides where it goes. Design §7
lists the rest.
machine.persist(&snapshot, deadline) writes XState's persisted snapshot
format, and machine.restore(&persisted, now) reads it back. See
json_persist.
Where plusthree differs from XState #
plusthree follows XState v6 except where XState leaks a JavaScript artifact or has a bug. DEVIATIONS.md lists every difference with its reason and the test that checks it. The ones you are most likely to notice:
- An infinite eventless loop is cut off after 10,000 microsteps and raises an execution error (D1).
- A transition function runs exactly once per selection (D2).
- Document order is the written order, also for integer-like JSON keys (D6), and parallel regions always take events in document order (D15).
- Final states schedule no timers (D5), and an unrecovered error cancels every pending timer and stops every child (D16).
- Actors exchange messages through one FIFO queue, each macrostep running
to completion first, as in XState's
systemTransition(D18). - Restored timers keep their deadlines under any clock (D19).
- An error in the initial macrostep is never recovered (D20).
Gotchas #
machine!defines types and a module, so invoke it at module level, not inside a function.- On the root, a transition targets children with a leading dot
(
on: { Ev::Fault => .broken }); the macro says so if you forget. - Every state reference is checked at compile time: an unknown target,
initialor delay name is a compile error on the offending token. - Built-in event names (
"xstate.done.actor.fetch") are keys inonfor one child's events;out @ "xstate.done.actor.fetch"binds its typed output.