- Rust 96%
- TypeScript 4%
- Shell <1%
plusthree #
A fast, typed Rust port of XState v6 statecharts.
- Typed. Context, events, effects, children and their outputs are your
own Rust types.
machine!checks every state reference at compile time and generates typed state handles. no_stdcore. The kernel needs onlyalloc, takes no locks, does no I/O and allocates nothing per event in steady state. The same machine runs under tokio, on embedded targets, in WASM, or in a test with simulated time.- XState v6 semantics, checked against XState. A differential harness
replays more than 400 traces recorded from XState
6.0.0-beta.3through plusthree on every change. Where plusthree deliberately differs, usually where XState leaks a JavaScript artifact or has a bug, DEVIATIONS.md says what, why, and which test checks it. - XState ecosystem. Load MachineJSON exported from XState or Stately Studio, export any machine back to MachineJSON so Stately's tools can draw it, and read and write XState's persisted snapshot format.
Quick start #
[dependencies]
plusthree = "0.1"
use plusthree::prelude::*;
#[derive(Context, Clone, Default)]
struct Ctx { count: u32 }
#[derive(Event, Clone)]
enum Ev { Inc, Lock, Unlock }
#[derive(Debug)]
enum Fx { Show(u32) }
plusthree::machine! {
Counter { context: Ctx, events: Ev, effects: Fx }
id: "counter",
initial: unlocked,
states: {
unlocked: {
on: {
Ev::Inc => |a, enq| {
enq.action(Fx::Show(a.context.count + 1));
Transition::stay().patch(|p| p.count(a.context.count + 1))
},
Ev::Lock => locked,
},
after: { 30s => locked },
},
locked: { on: { Ev::Unlock => unlocked } },
}
}
fn main() {
let m = Counter::machine();
let mut fx = Effects::new();
let mut snap = m.initial((), &mut fx).unwrap();
m.step(&mut snap, Ev::Inc, &mut fx);
for effect in fx.drain() {
match effect {
Effect::Action(Fx::Show(n)) => println!("count is {n}"),
Effect::Schedule(timer) => { /* start a timer; on expiry: m.fire(&mut snap, &timer.key, ..) */ }
Effect::Cancel(key) => { /* stop that timer */ }
_ => {}
}
}
assert!(snap.matches(counter::states::UNLOCKED));
}
Core concepts #
- Machine. The definition, built and validated once and immutable.
Counter::machine()returns a&'static Machine<Counter>. - Snapshot. One running instance: active states, context, history, pending timers, children, status. Plain data with no reference to the machine, so you can clone it, keep many, and persist them.
- Step.
machine.step(&mut snapshot, event, &mut effects)runs one event to completion in place and returnsHandled,UnhandledorErrored. - Effects as data. Actions never run inside the machine. A step fills a
reusable buffer with
Effects (replacing the last step's), in XState's order: your action enum, timers to schedule and cancel, children to spawn, start and stop, messages to other actors. Your code executes them: HTTP, IMAP, the UI, anything. - Context patches. A transition returns the fields it changes
(
.patch(|p| p.count(n))), the typed form of XState'sassign. - The host fires timers.
after,timeoutand delayed events come out asEffect::Schedule { key, delay }. When the delay has passed, the host callsmachine.fire(&mut snapshot, &key, &mut effects). The kernel has no clock, so tests run timers instantly and persisted timers survive restarts.host::Drivenkeeps the timers for a host that steps a machine itself: it calls the host'sSchedulerto start and stop them.
docs/guide.md explains these for XState users, with the patterns real apps need (async I/O, debouncing, back-off, per-entity actors).
Features #
| States | atomic, compound, parallel, final, shallow and deep history, choice (builder and JSON) |
| Transitions | targets, guards, transition functions, reenter, wildcards ("*", "user.*"), eventless, state input |
| Time | after (fixed or named delay functions), state and invoke timeout, delayed raise and send, cancel |
| Errors | Err from user code aborts the macrostep; on_error recovers from the snapshot before the event |
| Actors | invoke and spawn with typed on_done/on_error/on_snapshot, send_to, registry_key, dead letters |
plusthree::system |
a pure actor system: one FIFO queue, system time, async and callback actors, persistence |
plusthree::json (feature json) |
MachineJSON import with a registry of named actions, guards, delays and actors; MachineJSON export; XState persisted snapshots |
plusthree::runtime (feature runtime) |
a tokio driver: mailbox, real or simulated clock, futures for async actors |
plusthree::inspect (feature inspect) |
watch machines live in the Stately Inspector, stepped by your host or in a system: actors, events, diagrams with active states and the transitions taken |
| Inspection | an Observer hook per microstep, microsteps(), next_transitions(), XState inspection events in the system |
Performance budgets and measurements are in design §10 and BASELINES.md: a flat transition costs about 600 instructions, a 2-region parallel transition about 1,100, with no allocation.
Examples #
Each example asserts what it shows. Run one with
cargo run -p plusthree --example <name>, or all with just examples.
| Example | Shows |
|---|---|
counter |
machine!, patches, effects, Unhandled |
traffic_light |
after timers driven by a host loop |
parallel_history |
parallel regions; an overlay that returns through deep history |
guards_and_patches |
guards, candidate lists, eventless transitions, multi-field patches |
errors |
Err from handlers, on_error recovery, the error status |
mail_search |
async I/O through effects, a debounce from context, capped back-off |
json_persist |
XState JSON with a Registry, persist and restore with timers (feature json) |
actor_system |
one actor per account, invoked async jobs, plusthree::system |
tokio_runtime |
the same actors on tokio (feature runtime) |
inspect |
the same actors in the Stately Inspector (features inspect, runtime) |
inspect_host |
machines a host steps itself, with host::Driven, in the Stately Inspector (feature inspect) |
Crates #
Depend on plusthree; the others are its parts.
| Crate | |
|---|---|
plusthree |
the facade: re-exports, prelude, features |
plusthree-ir |
no_std. The statechart IR: builder, validation, flattening |
plusthree-core |
no_std. The kernel: snapshots, step, effects, the typed builder |
plusthree-derive |
#[derive(Context, Event, Children)] and machine! |
plusthree-system |
no_std. The pure actor-system reducer |
plusthree-json |
MachineJSON and persisted snapshots |
plusthree-runtime |
the tokio runtime |
plusthree-inspect |
the Stately Inspector bridge |
Status #
0.1.0 implements XState v6 (6.0.0-beta.3) through milestone M4 of
the design: the kernel, timers and errors,
typed and JSON definitions, persistence, actors and the tokio runtime.
XState v6 is itself in beta, so expect breaking changes before 1.0. Not yet
supported: JavaScript embedded in JSON (@code, @expr), durable
(journaled) async logic, observable actors, and an embassy adapter.
plusthree follows XState, not SCXML; SCXML semantics are not planned.
Contributing #
docs/design.md is the design and is canonical; AGENTS.md has the layout
and commands. just check runs everything required before a push.
License #
MIT.