use std::sync::{Arc, Mutex};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use xmachines_runtime::*;
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
struct Ctx {
count: i64,
#[serde(default)]
mode: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
enum Event {
#[serde(rename = "inc")]
Inc { by: i64 },
#[serde(rename = "reset")]
Reset,
#[serde(rename = "finish")]
Finish,
}
impl EventType for Event {
fn event_type(&self) -> &str {
match self {
Event::Inc { .. } => "inc",
Event::Reset => "reset",
Event::Finish => "finish",
}
}
}
#[derive(Deserialize)]
struct Limit {
max: i64,
}
fn counter_registry(notes: Arc<Mutex<Vec<String>>>) -> Registry<Ctx, Event> {
let mut r: Registry<Ctx, Event> = Registry::new();
r.guard_with("below", |args, p: &Limit| args.context.count < p.max)
.guard_with("byAtLeast", |args, p: &Limit| matches!(args.event, Ev::User(Event::Inc { by }) if *by >= p.max))
.action_with("note", move |text: &String| notes.lock().unwrap().push(text.clone()))
.delay("backoff", |ctx, _| (ctx.count as u64) * 100);
r
}
fn counter_machine(notes: Arc<Mutex<Vec<String>>>) -> Arc<Machine<Ctx, Event>> {
let def = json!({
"id": "counter",
"initial": "counting",
"context": { "count": 0, "mode": "slow" },
"states": {
"counting": {
"entry": [{ "type": "note", "params": "counting" }],
"on": {
"inc": [
{ "guard": { "type": "byAtLeast", "params": { "max": 10 } }, "target": "full" },
{ "guard": { "type": "below", "params": { "max": 3 } }, "context": { "count": 3 } },
{ "context": { "mode": "fast" }, "actions": [{ "type": "note", "params": "fast" }] }
],
"finish": { "target": "cooldown" }
}
},
"full": {
"tags": ["full"],
"on": { "reset": { "target": "counting", "actions": [{ "type": "@xstate.assign", "context": { "count": 0 } }] } }
},
"cooldown": { "after": { "backoff": { "target": "done" } } },
"done": { "type": "final", "output": { "ok": true } }
}
});
Arc::new(Machine::from_json(&def, &counter_registry(notes)).unwrap())
}
#[test]
fn typed_context_guards_with_params_and_effects() {
let notes = Arc::new(Mutex::new(Vec::new()));
let mut actor = Actor::start(counter_machine(notes.clone()), 0).unwrap();
assert_eq!(*notes.lock().unwrap(), vec!["counting"]);
actor.send(Event::Inc { by: 1 }, 0).unwrap();
assert_eq!(actor.context().unwrap(), &Ctx { count: 3, mode: "slow".into() });
actor.send(Event::Inc { by: 1 }, 0).unwrap();
assert_eq!(actor.context().unwrap(), &Ctx { count: 3, mode: "fast".into() });
assert_eq!(*notes.lock().unwrap(), vec!["counting", "fast"]);
actor.send(Event::Inc { by: 10 }, 0).unwrap();
assert_eq!(actor.value().unwrap(), json!("full"));
assert!(actor.has_tag("full"));
actor.send(Event::Finish, 0).unwrap();
assert_eq!(actor.value().unwrap(), json!("full"), "finish is not handled in full");
actor.send(Event::Reset, 0).unwrap();
assert_eq!(actor.context().unwrap().count, 0);
assert_eq!(*notes.lock().unwrap(), vec!["counting", "fast", "counting"]);
}
#[test]
fn named_delay_from_registry_reads_context() {
let mut actor = Actor::start(counter_machine(Default::default()), 0).unwrap();
actor.send(Event::Inc { by: 1 }, 0).unwrap();
actor.send(Event::Finish, 50).unwrap();
assert_eq!(actor.next_deadline(), Some(350));
actor.advance(349).unwrap();
assert_eq!(actor.status(), Status::Active);
actor.advance(350).unwrap();
assert_eq!(actor.status(), Status::Done);
assert_eq!(actor.output(), Some(&json!({ "ok": true })));
assert_eq!(actor.next_deadline(), None);
actor.send(Event::Reset, 400).unwrap();
assert_eq!(actor.value().unwrap(), json!("done"));
}
fn machine(def: Value) -> Arc<Machine<Value, Value>> {
machine_in(def, &Registry::new())
}
fn machine_in(def: Value, r: &Registry<Value, Value>) -> Arc<Machine<Value, Value>> {
Arc::new(Machine::from_json(&def, r).unwrap())
}
fn send(actor: &mut Actor<Value, Value>, ty: &str) {
let now = actor.now();
actor.send(json!({ "type": ty }), now).unwrap()
}
fn system_emitted(actor: &mut Actor<Value, Value>) -> Vec<(String, Value)> {
actor.take_system_emitted().into_iter().map(|(source, event)| (source.address.to_string(), event)).collect()
}
#[test]
fn traffic_light() {
let m = machine(json!({
"id": "light",
"initial": "green",
"states": {
"green": { "on": { "timer": { "target": "yellow" } } },
"yellow": { "on": { "timer": { "target": "red" } } },
"red": { "on": { "timer": { "target": "green" } } }
}
}));
let mut a = Actor::start(m, 0).unwrap();
for expected in ["yellow", "red", "green", "yellow"] {
send(&mut a, "timer");
assert_eq!(a.value().unwrap(), json!(expected));
}
assert!(a.matches("yellow"));
assert!(a.matches("#light.yellow"));
assert!(!a.matches("red"));
}
#[test]
fn on_done_is_accepted_and_matches_its_own_state() {
let m = machine(json!({
"id": "m",
"initial": "outer",
"states": {
"outer": {
"initial": "inner",
"states": {
"inner": {
"initial": "x",
"states": { "x": { "on": { "go": { "target": "y" } } }, "y": { "type": "final" } },
"onDone": { "target": "innerDone" }
},
"innerDone": { "on": { "go": { "target": "end" } } },
"end": { "type": "final", "output": 42 }
},
"onDone": { "target": "finished" }
},
"finished": { "type": "final" }
}
}));
let mut a = Actor::start(m, 0).unwrap();
send(&mut a, "go");
assert_eq!(a.value().unwrap(), json!({ "outer": "innerDone" }));
send(&mut a, "go");
assert_eq!(a.value().unwrap(), json!("finished"));
assert_eq!(a.status(), Status::Done);
assert_eq!(a.output(), None);
}
#[test]
fn deep_history_restores_atomic_descendants() {
let m = machine(json!({
"initial": "app",
"states": {
"app": {
"initial": "a",
"states": {
"a": { "initial": "a1", "states": { "a1": { "on": { "next": { "target": "a2" } } }, "a2": {} } },
"hist": { "type": "history", "history": "deep", "target": "a" }
},
"on": { "leave": { "target": "away" } }
},
"away": { "on": { "back": { "target": "app.hist" } } }
}
}));
let mut a = Actor::start(m.clone(), 0).unwrap();
send(&mut a, "back");
send(&mut a, "next");
send(&mut a, "leave");
assert_eq!(a.value().unwrap(), json!("away"));
let saved = a.persist();
send(&mut a, "back");
assert_eq!(a.value().unwrap(), json!({ "app": { "a": "a2" } }));
let restored: Value = serde_json::from_str(&saved.to_string()).unwrap();
let mut b = Actor::restore(m, &restored).unwrap();
send(&mut b, "back");
assert_eq!(b.value().unwrap(), json!({ "app": { "a": "a2" } }));
}
#[test]
fn runaway_eventless_loop_is_an_error() {
for (max, expected) in
[(50, json!(["c", "b", "c", "b", "c"])), (51, json!(["b", "c", "b", "c", "b"])), (3, json!(["b", "c", "b"]))]
{
let m = machine(json!({
"options": { "maxIterations": max },
"initial": "a",
"states": {
"a": { "on": { "go": { "target": "b" } } },
"b": { "always": { "target": "c" } },
"c": { "always": { "target": "b" } }
}
}));
let mut a = Actor::start(m, 0).unwrap();
let err = a.send(json!({ "type": "go" }), 0).unwrap_err();
match &err {
SystemError::InfiniteLoop { max_iterations, states, .. } => {
assert_eq!(*max_iterations, max);
assert_eq!(Value::Array(states.clone()), expected, "max {max}");
}
other => panic!("{other}"),
}
assert_eq!(a.status(), Status::Error);
}
}
#[test]
fn a_macrostep_is_unbounded_without_max_iterations() {
let counting = |options: Value| {
let mut def = json!({
"initial": "idle",
"context": { "n": 0 },
"states": {
"idle": { "on": { "start": { "target": "count" } } },
"count": {
"always": [
{ "guard": { "type": "done" }, "target": "end" },
{ "target": "count", "reenter": true, "context": { "n": { "@code": "inc", "@lang": "rust" } } }
]
},
"end": {}
}
});
if !options.is_null() {
def["options"] = options;
}
let mut r: Registry<Value, Value> = Registry::new();
r.guard("done", |a| a.context["n"] == json!(1400));
r.expr("inc", |a| json!(a.context["n"].as_u64().unwrap() + 1));
machine_in(def, &r)
};
let mut a = Actor::start(counting(Value::Null), 0).unwrap();
a.send(json!({ "type": "start" }), 0).unwrap();
assert_eq!((a.status(), a.context().unwrap()["n"].clone()), (Status::Active, json!(1400)));
let mut a = Actor::start(counting(json!({ "maxIterations": 5000 })), 0).unwrap();
a.send(json!({ "type": "start" }), 0).unwrap();
assert_eq!(a.context().unwrap()["n"], json!(1400));
let mut a = Actor::start(counting(json!({ "maxIterations": 1000 })), 0).unwrap();
let err = a.send(json!({ "type": "start" }), 0).unwrap_err();
assert_eq!(
err.to_string(),
"XState error E16 (\"(machine)\", \"start\", 1000). See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e16"
);
assert_eq!(a.status(), Status::Error);
}
#[test]
fn v5_lifecycle_event_types_are_rejected_as_on_keys() {
let def = |key: &str| json!({ "initial": "a", "states": { "a": { "on": { key: { "target": "b" } } }, "b": {} } });
for key in [
"xstate.done.actor.job",
"xstate.error.actor.job",
"xstate.done.state.form",
"xstate.after.1000.loading",
"xstate.snapshot.job",
"xstate.done.actor.job.*",
] {
let Err(err) = Machine::<Value, Value>::from_json(&def(key), &Registry::new()) else { panic!("{key}") };
assert_eq!(err.path, format!("$.states.a.on.{key}"));
assert!(err.message.contains("never fires"), "{err}");
}
let err = Machine::<Value, Value>::from_json(&def("xstate.done.actor.job"), &Registry::new()).err().unwrap();
assert!(err.message.ends_with("key on 'xstate.done.actor' with `matches: { actorId: 'job' }`"), "{err}");
for key in [
"xstate.done.actor",
"xstate.done.actor.*",
"xstate.error.*",
"xstate.snapshot.actor",
"xstate.snapshot.actor.*",
"xstate.after",
"done.actor.job",
] {
assert!(Machine::<Value, Value>::from_json(&def(key), &Registry::new()).is_ok(), "{key}");
}
}
#[test]
fn machine_options_are_checked() {
for (options, path) in [
(json!({ "maxIterations": -1 }), "$.options.maxIterations"),
(json!({ "maxIterations": 2.5 }), "$.options.maxIterations"),
(json!({ "maxIterations": "10" }), "$.options.maxIterations"),
(json!({ "maxSteps": 10 }), "$.options.maxSteps"),
(json!(10), "$.options"),
] {
let def = json!({ "options": options, "initial": "a", "states": { "a": {} } });
let Err(err) = Machine::<Value, Value>::from_json(&def, &Registry::new()) else { panic!("{options}") };
assert_eq!(err.path, path, "{options}");
}
}
#[test]
fn a_failed_macrostep_rolls_back_an_untyped_context() {
for initial in [json!({ "n": 0, "tags": ["a"], "z": "keep" }), json!({ "n": 1.0, "z": "keep" })] {
let m = machine(json!({
"options": { "maxIterations": 20 },
"initial": "a",
"context": initial,
"states": {
"a": { "on": { "go": { "target": "b", "context": { "n": 5, "added": true } } } },
"b": { "always": { "target": "c", "context": { "tags": [], "more": 1 } } },
"c": { "always": { "target": "b" } }
}
}));
let mut a = Actor::start(m, 0).unwrap();
let before = a.context().unwrap().to_string();
assert!(a.send(json!({ "type": "go" }), 0).is_err());
assert_eq!(a.status(), Status::Error);
assert_eq!(a.context().unwrap().to_string(), before);
}
}
#[test]
fn failing_guards_delays_and_actions_fail_the_actor() {
let ran = Arc::new(Mutex::new(Vec::new()));
let mut r: Registry<Value, Value> = Registry::new();
r.try_guard_with("broken", |_, _: &Value| Err("guard broke".into()));
r.try_delay("broken", |_, _| Err("delay broke".into()));
let seen = ran.clone();
r.try_action_with("note", move |p: &Value| {
seen.lock().unwrap().push(p.clone());
match p.as_str() {
Some("fail") => Err("action broke".into()),
_ => Ok(()),
}
});
let m = machine_in(
json!({
"initial": "a",
"context": { "n": 0 },
"states": {
"a": { "on": {
"guard": { "target": "b", "guard": { "type": "broken" } },
"delay": { "target": "waiting" },
"act": {
"target": "b",
"context": { "n": 1 },
"actions": [
{ "type": "note", "params": "first" },
{ "type": "note", "params": "fail" },
{ "type": "@xstate.emit", "event": { "type": "after" } },
{ "type": "note", "params": "last" }
]
}
} },
"waiting": { "after": { "broken": { "target": "b" } } },
"b": {}
}
}),
&r,
);
for (event, message) in [("guard", "guard broke"), ("delay", "delay broke")] {
let mut a = Actor::start(m.clone(), 0).unwrap();
assert_eq!(a.send(json!({ "type": event }), 0).unwrap_err().to_string(), message);
let error = json!({ "@error": "Error", "message": message });
assert_eq!((a.status(), a.value().unwrap(), a.error()), (Status::Error, json!("a"), Some(&error)));
}
let mut a = Actor::start(m, 0).unwrap();
assert_eq!(a.send(json!({ "type": "act" }), 0).unwrap_err().to_string(), "action broke");
assert_eq!((a.status(), a.value().unwrap(), a.context().unwrap()), (Status::Error, json!("b"), &json!({ "n": 1 })));
assert_eq!(a.error(), Some(&json!({ "@error": "Error", "message": "action broke" })));
assert_eq!(*ran.lock().unwrap(), [json!("first"), json!("fail")]);
assert!(a.take_emitted().is_empty());
let saved = a.persist();
assert_eq!(saved["actors"]["(machine)"]["snapshot"]["status"], json!("error"), "{saved}");
assert!(a.send(json!({ "type": "act" }), 1).is_ok());
assert_eq!(*ran.lock().unwrap(), [json!("first"), json!("fail")]);
}
#[test]
fn a_failed_child_stops_its_children_and_reports_to_its_parent() {
let mut r: Registry<Value, Value> = Registry::new();
r.try_guard_with("broken", |_, _: &Value| Err("guard broke".into()));
let grandchild = json!({ "id": "grandchild", "initial": "on", "states": { "on": {} } });
r.actor("grandchild", machine(grandchild));
let child = json!({
"id": "child",
"initial": "on",
"states": { "on": {
"invoke": { "id": "g", "src": "grandchild" },
"on": { "break": { "target": "on", "guard": { "type": "broken" } } }
} }
});
r.actor("child", machine_in(child, &r));
let parent = json!({
"id": "p",
"initial": "a",
"states": {
"a": { "invoke": { "id": "c", "src": "child", "onError": { "target": "b", "context": { "@code": "caught", "@lang": "rust" } } } },
"b": {}
}
});
r.expr("caught", |a| json!({ "error": a.event.field("error"), "from": a.event.field("actorId") }));
let m = machine_in(parent, &r);
let mut actor = Actor::start(m.clone(), 0).unwrap();
actor.send_to("p/c", json!({ "type": "break" }), 0).unwrap();
assert_eq!(actor.value().unwrap(), json!("b"));
let error = json!({ "@error": "Error", "message": "guard broke" });
assert_eq!(actor.context().unwrap(), &json!({ "error": error, "from": "c" }));
let status = |a: &Actor<Value, Value>, address: &str| a.persist()["actors"][address]["snapshot"]["status"].clone();
assert_eq!(status(&actor, "p/c"), json!("error"));
assert_eq!(status(&actor, "p/c/g"), json!("stopped"));
let logic = SystemLogic::new(m);
let (mut system, _) = System::initialize(&logic, InitOptions::default()).unwrap();
let err = system.send("p/c", json!({ "type": "break" })).unwrap_err();
assert_eq!(err.to_string(), "guard broke");
assert_eq!(system.to_json()["actors"]["p/c/g"]["snapshot"]["status"], json!("active"));
}
#[test]
fn a_root_whose_start_throws_keeps_only_its_error() {
let mut r: Registry<Value, Value> = Registry::new();
r.expr("boom", |a| {
a.fail("boom");
Value::Null
});
let definition = json!({
"id": "m",
"initial": "a",
"states": { "a": { "entry": [{ "type": "@xstate.assign", "context": { "n": { "@code": "boom", "@lang": "rust" } } }] } }
});
let m = machine_in(definition, &r);
let mut actor = Actor::start(m.clone(), 0).unwrap();
let error = json!({ "@error": "Error", "message": "boom" });
assert_eq!(
(actor.status(), actor.value(), actor.context(), actor.error()),
(Status::Error, None, None, Some(&error))
);
assert!(!actor.matches("a") && actor.configuration().is_empty() && actor.children().is_empty());
let saved = actor.persist();
assert_eq!(saved["actors"]["m"]["snapshot"], json!({ "status": "error", "error": error }));
assert_eq!(Actor::restore(m, &saved).unwrap().persist(), saved);
assert!(actor.send(json!({ "type": "go" }), 0).is_ok());
assert_eq!(actor.persist()["actors"]["m"], saved["actors"]["m"]);
}
#[test]
fn a_failed_root_stops_its_children() {
let mut r: Registry<Value, Value> = Registry::new();
r.try_guard_with("broken", |_, _: &Value| Err("guard broke".into()));
r.actor("kid", machine(json!({ "id": "kid", "initial": "on", "states": { "on": {} } })));
let parent = json!({
"id": "p",
"initial": "a",
"states": { "a": { "invoke": { "id": "k", "src": "kid" }, "on": { "go": { "target": "b", "guard": { "type": "broken" } } } }, "b": {} }
});
let mut actor = Actor::start(machine_in(parent, &r), 0).unwrap();
assert_eq!(actor.send(json!({ "type": "go" }), 0).unwrap_err().to_string(), "guard broke");
assert_eq!((actor.status(), actor.value().unwrap()), (Status::Error, json!("a")));
assert_eq!(actor.persist()["actors"]["p/k"]["snapshot"]["status"], json!("stopped"));
}
#[test]
fn a_failed_root_stops_its_spawned_children() {
let mut r: Registry<Value, Value> = Registry::new();
r.actor("kid", machine(json!({ "id": "kid", "initial": "on", "states": { "on": {} } })));
r.expr("spawn", |a| {
a.enq().expect("an action has enq").spawn("kid", SpawnOptions { id: Some("s".into()), ..Default::default() });
Value::Null
});
r.expr("boom", |a| {
a.fail("boom");
Value::Null
});
r.try_action_with("broken", |_: &Value| Err("action broke".into()));
let code = |name: &str| json!({ "@code": name, "@lang": "rust" });
let parent = json!({
"id": "p",
"initial": "a",
"states": { "a": {
"entry": [code("spawn")],
"on": { "step": { "context": { "n": code("boom") } }, "act": { "actions": [{ "type": "broken" }] } }
} }
});
let m = machine_in(parent, &r);
for (event, message) in [("step", "boom"), ("act", "action broke")] {
let mut actor = Actor::start(m.clone(), 0).unwrap();
assert_eq!(actor.persist()["actors"]["p/s"]["snapshot"]["status"], json!("active"));
assert_eq!(actor.send(json!({ "type": event }), 0).unwrap_err().to_string(), message);
assert_eq!(actor.status(), Status::Error);
assert_eq!(actor.persist()["actors"]["p/s"]["snapshot"]["status"], json!("stopped"), "{event}");
}
}
#[test]
fn enq_spawn_creates_its_child_at_once() {
let mut r: Registry<Value, Value> = Registry::new();
r.actor("kid", machine(json!({ "id": "kid", "initial": "on", "states": { "on": {} } })));
let named = || SpawnOptions { id: Some("s".into()), ..Default::default() };
r.expr("respawn", move |a| {
let enq = a.enq().expect("an action has enq");
enq.stop("s");
enq.spawn("kid", named());
Value::Null
});
r.expr("spawnAway", move |a| {
a.enq().expect("a transition function has enq").spawn("kid", named());
json!({ "target": "b" })
});
r.expr("spawnKid", |a| {
let id = a.enq().expect("an action has enq").spawn("kid", SpawnOptions::default());
json!({ "context": { "last": id } })
});
r.expr("spawnKidAway", |a| {
let id = a.enq().expect("a transition function has enq").spawn("kid", SpawnOptions::default());
json!({ "target": "b", "context": { "first": id } })
});
let code = |name: &str| json!({ "@code": name, "@lang": "rust" });
let parent = json!({
"id": "p",
"initial": "a",
"states": {
"a": {
"invoke": { "id": "s", "src": "kid" },
"exit": [code("spawnKid")],
"on": { "respawn": { "actions": [code("respawn")] }, "away": code("spawnAway"), "order": code("spawnKidAway") }
},
"b": {}
}
});
let m = machine_in(parent, &r);
let e67 = "XState error E67 (\"s\", \"p\"). See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e67";
for (event, message) in [("respawn", "Actor address 'p/s' is already occupied."), ("away", e67)] {
let mut actor = Actor::start(m.clone(), 0).unwrap();
assert_eq!(actor.send(json!({ "type": event }), 0).unwrap_err().to_string(), message, "{event}");
}
let mut actor = Actor::start(m, 0).unwrap();
actor.send(json!({ "type": "order" }), 0).unwrap();
assert_eq!(actor.context().unwrap(), &json!({ "first": "kid:0", "last": "kid:1" }));
let saved = actor.persist();
assert_eq!(saved["actors"]["p/kid:0"]["incarnation"], json!("2"));
assert_eq!(saved["actors"]["p/kid:1"]["incarnation"], json!("3"));
}
#[test]
fn a_host_error_comes_after_its_enq_calls() {
let calls = Arc::new(Mutex::new(0));
let counted = calls.clone();
let mut r: Registry<Value, Value> = Registry::new();
r.actor("kid", machine(json!({ "id": "kid", "initial": "on", "states": { "on": {} } })));
r.evaluator(
"host",
HostEvaluator(move |code: &str, _scope: &str| {
let code: Value = serde_json::from_str(code).unwrap();
let spawn = |id: &str| json!(["spawn", "kid", { "id": id }]);
let answer = match code["source"].as_str().unwrap() {
"spawnThenThrow" => json!({ "enq": [spawn("s")], "error": "boom" }),
"restartThenThrow" => json!({ "enq": [["stop", "s"], spawn("s")], "error": "boom" }),
"emitThenThrow" => json!({ "enq": [["emit", { "type": "x" }]], "error": "boom" }),
"throwsOnce" => {
let mut n = counted.lock().unwrap();
*n += 1;
match *n {
1 => json!({ "enq": [spawn("t")], "error": "boom" }),
_ => json!({ "enq": [spawn("t")], "value": { "target": "b" } }),
}
}
other => panic!("no answer for {other}"),
};
answer.to_string()
}),
);
let code = |name: &str| json!({ "@code": name, "@lang": "host" });
let parent = json!({
"id": "p",
"initial": "a",
"states": {
"a": {
"invoke": { "id": "s", "src": "kid" },
"on": {
"act": { "actions": [code("spawnThenThrow")] },
"select": code("spawnThenThrow"),
"restart": { "actions": [code("restartThenThrow")] },
"emit": { "actions": [code("emitThenThrow")] },
"once": code("throwsOnce")
}
},
"b": {}
}
});
let m = machine_in(parent, &r);
let e67 = "XState error E67 (\"s\", \"p\"). See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e67";
for (event, message) in
[("act", e67), ("select", e67), ("restart", "Actor address 'p/s' is already occupied."), ("emit", "boom")]
{
let mut actor = Actor::start(m.clone(), 0).unwrap();
assert_eq!(actor.send(json!({ "type": event }), 0).unwrap_err().to_string(), message, "{event}");
}
let mut actor = Actor::start(m, 0).unwrap();
actor.send(json!({ "type": "once" }), 0).unwrap();
assert_eq!(*calls.lock().unwrap(), 2);
assert_eq!(actor.value().unwrap(), json!("b"));
assert_eq!(actor.persist()["actors"]["p/t"]["snapshot"]["status"], json!("active"));
}
#[test]
fn a_child_whose_start_throws_keeps_only_its_error() {
let mut r: Registry<Value, Value> = Registry::new();
r.expr("boom", |a| {
a.fail("boom");
Value::Null
});
let kid = json!({
"id": "kid",
"initial": "on",
"states": { "on": { "entry": [{ "type": "@xstate.assign", "context": { "n": { "@code": "boom", "@lang": "rust" } } }] } }
});
r.actor("kid", machine_in(kid, &r));
let parent = json!({
"id": "p",
"initial": "a",
"states": { "a": { "invoke": { "id": "k", "src": "kid", "onError": { "target": "b" } } }, "b": {} }
});
let m = machine_in(parent, &r);
let actor = Actor::start(m.clone(), 0).unwrap();
assert_eq!(actor.value().unwrap(), json!("b"));
let saved = actor.persist();
let error = json!({ "@error": "Error", "message": "boom" });
assert_eq!(saved["actors"]["p/k"]["snapshot"], json!({ "status": "error", "error": error }));
let restored = Actor::restore(m, &saved).unwrap();
assert_eq!(restored.persist(), saved);
}
#[test]
fn an_unhandled_child_error_stops_the_parents_other_children() {
let mut r: Registry<Value, Value> = Registry::new();
r.try_guard_with("broken", |_, _: &Value| Err("guard broke".into()));
let kid = json!({ "id": "kid", "initial": "on", "states": { "on": { "on": { "break": { "target": "on", "guard": { "type": "broken" } } } } } });
r.actor("kid", machine_in(kid, &r));
let parent = json!({
"id": "p",
"initial": "a",
"states": { "a": { "invoke": [{ "id": "k1", "src": "kid" }, { "id": "k2", "src": "kid" }] } }
});
let mut actor = Actor::start(machine_in(parent, &r), 0).unwrap();
actor.send_to("p/k1", json!({ "type": "break" }), 0).unwrap();
assert_eq!(actor.status(), Status::Error);
assert_eq!(actor.error(), Some(&json!({ "@error": "Error", "message": "guard broke" })));
assert_eq!(actor.persist()["actors"]["p/k2"]["snapshot"]["status"], json!("stopped"));
}
#[test]
fn a_child_recovers_from_its_action_through_on_error() {
let mut r: Registry<Value, Value> = Registry::new();
r.try_action_with("broken", |_: &Value| Err("action broke".into()));
let child = json!({
"id": "child",
"initial": "on",
"onError": { "target": ".recovered" },
"states": {
"on": { "on": { "act": { "target": "acted", "actions": [{ "type": "broken" }] } } },
"acted": {},
"recovered": {}
}
});
r.actor("child", machine_in(child, &r));
let parent = json!({
"id": "p",
"initial": "a",
"states": { "a": { "invoke": { "id": "c", "src": "child", "onError": { "target": "b" } } }, "b": {} }
});
let mut actor = Actor::start(machine_in(parent, &r), 0).unwrap();
actor.send_to("p/c", json!({ "type": "act" }), 0).unwrap();
assert_eq!(actor.value().unwrap(), json!("a"));
let saved = actor.persist();
assert_eq!(saved["actors"]["p/c"]["snapshot"]["value"], json!("recovered"), "{saved}");
assert_eq!(saved["actors"]["p/c"]["snapshot"]["status"], json!("active"));
}
#[test]
fn raised_event_loop_is_an_error() {
let m = machine(json!({
"options": { "maxIterations": 1000 },
"initial": "a",
"states": {
"a": { "on": { "ping": { "actions": [{ "type": "@xstate.raise", "event": { "type": "ping" } }] } } }
}
}));
let mut a = Actor::start(m, 0).unwrap();
assert!(matches!(a.send(json!({ "type": "ping" }), 0), Err(SystemError::InfiniteLoop { .. })));
}
#[test]
fn targetless_eventless_transition_without_effect_does_not_loop() {
let m = machine(json!({
"initial": "a",
"states": { "a": { "always": { "actions": [{ "type": "@xstate.emit", "event": { "type": "tick" } }] } } }
}));
let mut a = Actor::start(m, 0).unwrap();
assert_eq!(a.take_emitted(), vec![json!({ "type": "tick" })]);
send(&mut a, "anything");
assert_eq!(a.take_emitted(), vec![json!({ "type": "tick" })]);
}
#[test]
fn persist_and_restore_pending_timers() {
let def = json!({
"id": "t",
"version": "1",
"initial": "a",
"context": { "n": 1 },
"states": {
"a": {
"entry": [
{ "type": "@xstate.raise", "event": { "type": "named" }, "delay": 300, "id": "named" },
{ "type": "@xstate.raise", "event": { "type": "anon", "x": 1 }, "delay": 200 }
],
"after": { "500": { "target": "b" } },
"on": {
"named": { "actions": [{ "type": "@xstate.emit", "event": { "type": "gotNamed" } }] },
"anon": { "actions": [{ "type": "@xstate.assign", "context": { "n": 2 } }] }
}
},
"b": {}
}
});
let m = machine(def);
let a = Actor::start(m.clone(), 1000).unwrap();
let snapshot: Value = serde_json::from_str(&a.persist().to_string()).unwrap();
assert_eq!(snapshot["timers"].as_array().unwrap().len(), 3);
assert_eq!(snapshot["actors"]["t"]["snapshot"]["nodeIds"], json!(["t", "t.a"]));
let mut b = Actor::restore(m, &snapshot).unwrap();
assert_eq!(b.now(), 1000);
assert_eq!(b.next_deadline(), Some(1200));
b.advance(1300).unwrap();
assert_eq!(b.context().unwrap(), &json!({ "n": 2 }));
assert_eq!(b.take_emitted(), vec![json!({ "type": "gotNamed" })]);
b.advance(1500).unwrap();
assert_eq!(b.value().unwrap(), json!("b"));
assert_eq!(b.next_deadline(), None);
}
#[test]
fn a_delayed_send_to_the_actor_itself_persists_as_self() {
let mut r: Registry<Value, Value> = Registry::new();
r.expr("later", |a| {
let me = a.self_ref().to_json();
a.enq().unwrap().send_to_ref_delayed(&me, json!({ "type": "ping" }), 100, Some("p"));
Value::Null
});
let m = machine_in(
json!({
"id": "s",
"context": { "pings": 0 },
"entry": [{ "@code": "later", "@lang": "rust" }],
"on": { "ping": { "context": { "pings": 1 } } }
}),
&r,
);
let a = Actor::start(m.clone(), 0).unwrap();
let snapshot = a.persist();
assert_eq!(
snapshot["actors"]["s"]["snapshot"]["timers"],
json!([{ "id": "p", "delay": 100, "type": "@xstate.sendTo", "event": { "type": "ping" }, "target": "self" }])
);
let mut b = Actor::restore(m.clone(), &snapshot).unwrap();
assert_eq!(b.persist(), snapshot);
b.advance(100).unwrap();
assert_eq!(b.context().unwrap(), &json!({ "pings": 1 }));
for (ty, target) in [
("@xstate.raise", json!({ "@actor": "s", "incarnation": "0" })),
("@xstate.sendTo", json!("parent")),
("@xstate.sendTo", json!({ "type": "parent" })),
("@xstate.delay", json!("self")),
] {
let mut bad = snapshot.clone();
let timer = &mut bad["actors"]["s"]["snapshot"]["timers"][0];
timer["type"] = json!(ty);
timer["target"] = target;
assert!(Actor::restore(m.clone(), &bad).is_err(), "{ty}");
}
}
#[test]
fn restore_rejects_unknown_and_duplicate_states() {
let m = machine(json!({ "id": "x", "initial": "a", "states": { "a": {}, "b": {} } }));
let a = Actor::start(m.clone(), 0).unwrap();
let with_nodes = |nodes: Value| {
let mut snap = a.persist();
snap["actors"]["x"]["snapshot"]["nodeIds"] = nodes;
snap
};
let err = Actor::restore(m.clone(), &with_nodes(json!(["x", "x.gone"]))).unwrap_err();
assert!(err.to_string().contains("x.gone"), "{err}");
let err = Actor::restore(m.clone(), &with_nodes(json!(["x", "x.a", "x.a"]))).unwrap_err();
assert!(err.to_string().contains("appears twice"), "{err}");
let restored = Actor::restore(m.clone(), &with_nodes(json!(["x", "x.a", "x.b"]))).unwrap();
assert_eq!(restored.configuration(), vec!["x", "x.a", "x.b"]);
let other = machine(json!({ "id": "y", "initial": "a", "states": { "a": {} } }));
assert!(Actor::restore(other, &a.persist()).is_err());
}
#[test]
fn delayed_raise_with_same_id_replaces_the_pending_timer() {
let m = machine(json!({
"initial": "a",
"states": {
"a": {
"on": {
"arm": { "actions": [{ "type": "@xstate.raise", "event": { "type": "fire" }, "delay": 100, "id": "t" }] },
"fire": { "target": "b" }
}
},
"b": {}
}
}));
let mut a = Actor::start(m, 0).unwrap();
a.send(json!({ "type": "arm" }), 0).unwrap();
a.send(json!({ "type": "arm" }), 50).unwrap();
assert_eq!(a.next_deadline(), Some(150));
a.advance(149).unwrap();
assert_eq!(a.value().unwrap(), json!("a"));
a.advance(150).unwrap();
assert_eq!(a.value().unwrap(), json!("b"));
}
#[test]
fn internal_events_cannot_be_sent_from_outside() {
let m = machine(json!({
"initial": "a",
"internalEvents": ["secret.*"],
"states": { "a": { "on": { "secret.open": { "target": "b" } } }, "b": {} }
}));
let mut a = Actor::start(m, 0).unwrap();
let err = a.send(json!({ "type": "secret.open" }), 0).unwrap_err();
assert!(err.to_string().contains("Internal event"), "{err}");
assert_eq!(a.value().unwrap(), json!("a"));
}
#[test]
fn stop_cancels_timers_without_exit_actions() {
let m = machine(json!({
"initial": "a",
"states": {
"a": {
"exit": [{ "type": "@xstate.emit", "event": { "type": "exited" } }],
"after": { "100": { "target": "b" } }
},
"b": {}
}
}));
let mut a = Actor::start(m, 0).unwrap();
a.stop().unwrap();
assert_eq!(a.status(), Status::Stopped);
assert_eq!(a.next_deadline(), None);
assert!(a.take_emitted().is_empty());
send(&mut a, "anything");
assert_eq!(a.status(), Status::Stopped);
}
#[test]
fn final_root_child_runs_exit_actions_and_clears_timers() {
let m = machine(json!({
"initial": "a",
"exit": [{ "type": "@xstate.emit", "event": { "type": "rootExit" } }],
"states": {
"a": {
"entry": [{ "type": "@xstate.raise", "event": { "type": "late" }, "delay": 1000 }],
"on": { "end": { "target": "z" } }
},
"z": { "type": "final", "exit": [{ "type": "@xstate.emit", "event": { "type": "zExit" } }] }
}
}));
let mut a = Actor::start(m, 0).unwrap();
assert_eq!(a.next_deadline(), Some(1000));
send(&mut a, "end");
assert_eq!(a.status(), Status::Done);
assert_eq!(a.take_emitted(), vec![json!({ "type": "zExit" }), json!({ "type": "rootExit" })]);
assert_eq!(a.next_deadline(), None);
}
#[test]
fn logs_are_collected() {
let m = machine(json!({
"initial": "a",
"states": { "a": { "entry": [{ "type": "@xstate.log", "args": ["hello", 1] }] } }
}));
let mut a = Actor::start(m, 0).unwrap();
assert_eq!(a.take_logs(), vec![vec![json!("hello"), json!(1)]]);
}
#[test]
fn guard_args_expose_the_configuration() {
let mut r: Registry<Value, Value> = Registry::new();
r.guard("inB", |args| args.in_state("#p.r2.b"));
let def = json!({
"id": "p",
"type": "parallel",
"states": {
"r1": { "initial": "x", "states": { "x": { "on": { "go": { "target": "y", "guard": { "type": "inB" } } } }, "y": {} } },
"r2": { "initial": "a", "states": { "a": { "on": { "flip": { "target": "b" } } }, "b": {} } }
}
});
let mut a = Actor::start(Arc::new(Machine::from_json(&def, &r).unwrap()), 0).unwrap();
send(&mut a, "go");
assert_eq!(a.value().unwrap(), json!({ "r1": "x", "r2": "a" }));
send(&mut a, "flip");
send(&mut a, "go");
assert_eq!(a.value().unwrap(), json!({ "r1": "y", "r2": "b" }));
}
fn load_err(def: Value) -> LoadError {
match Machine::<Value, Value>::from_json(&def, &Registry::new()) {
Ok(_) => panic!("expected a load error"),
Err(e) => e,
}
}
#[test]
fn rejects_code_with_its_path() {
let e = load_err(json!({
"initial": "a",
"states": { "a": { "on": { "go": { "@code": "() => ({ target: 'b' })", "@lang": "ts" } } }, "b": {} }
}));
assert_eq!(e.kind, LoadErrorKind::Code);
assert_eq!(e.path, "$.states.a.on.go");
}
#[test]
fn rejects_unsupported_features() {
let e = load_err(json!({ "initial": "a", "states": { "a": { "invoke": { "src": "worker" } } } }));
assert_eq!((e.kind, e.path.as_str()), (LoadErrorKind::MissingImplementation, "$.states.a.invoke.src"));
let e = load_err(json!({ "initial": "a", "states": { "a": { "type": "choice" } } }));
assert_eq!(
(e.kind, e.message.as_str()),
(LoadErrorKind::Invalid, "Choice state at $.states.a must declare choice.")
);
let e = load_err(json!({ "initial": "a", "states": { "a": { "timeout": 100 } } }));
assert!(e.message.contains("onTimeout"), "{e}");
}
#[test]
fn rejects_invalid_definitions() {
let e = load_err(json!({ "initial": "a", "states": { "a": { "on": { "go": "b" } }, "b": {} } }));
assert!(e.message.contains("instead of a string"), "{e}");
let e = load_err(json!({ "initial": "a", "states": { "a": { "bogus": 1 } } }));
assert_eq!((e.kind, e.path.as_str()), (LoadErrorKind::UnknownKey, "$.states.a"));
let e = load_err(json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "nope" } } } } }));
assert_eq!((e.kind, e.path.as_str()), (LoadErrorKind::InvalidTarget, "$.states.a.on.go.target"));
let e = load_err(json!({ "initial": "a", "states": { "a": { "id": "dup" }, "b": { "id": "dup" } } }));
assert_eq!(e.kind, LoadErrorKind::DuplicateId);
let e = load_err(json!({ "states": { "a": {} } }));
assert!(e.message.contains("no initial state"), "{e}");
let e = load_err(
json!({ "initial": "a", "states": { "a": { "states": { "h": { "type": "history" } }, "initial": "h" } } }),
);
assert!(e.message.contains("history state must declare"), "{e}");
let e = load_err(json!({
"type": "parallel",
"states": { "a": { "on": { "go": { "target": ["c", "c.x"] } } }, "b": {}, "c": { "initial": "x", "states": { "x": {} } } }
}));
assert_eq!(e.kind, LoadErrorKind::InvalidTarget, "{e}");
}
#[test]
fn rejects_missing_implementations() {
let e = load_err(json!({ "initial": "a", "states": { "a": { "on": { "go": { "guard": { "type": "nope" } } } } } }));
assert_eq!((e.kind, e.path.as_str()), (LoadErrorKind::MissingImplementation, "$.states.a.on.go.guard"));
let e = load_err(json!({ "initial": "a", "states": { "a": { "entry": [{ "type": "nope" }] } } }));
assert_eq!((e.kind, e.path.as_str()), (LoadErrorKind::MissingImplementation, "$.states.a.entry[0]"));
let e = load_err(json!({ "initial": "a", "states": { "a": { "after": { "soon": { "target": "a" } } } } }));
assert_eq!(e.kind, LoadErrorKind::MissingImplementation);
let e = load_err(json!({
"initial": "a",
"actions": { "loop": { "type": "loop" } },
"states": { "a": { "entry": [{ "type": "loop" }] } }
}));
assert!(e.message.contains("circular action reference"), "{e}");
}
#[test]
fn rejects_bad_params_at_load_time() {
let mut r: Registry<Value, Value> = Registry::new();
r.guard_with("below", |_, _p: &u32| true);
let def = json!({ "initial": "a", "states": { "a": { "on": { "go": { "guard": { "type": "below", "params": "ten" } } } } } });
let e = Machine::from_json(&def, &r).err().unwrap();
assert_eq!((e.kind, e.path.as_str()), (LoadErrorKind::InvalidParams, "$.states.a.on.go.guard.params"));
}
#[test]
fn expressions_compute_typed_context_events_guards_and_delays() {
let mut r: Registry<Ctx, Event> = Registry::new();
r.expr("countPlusBy", |a| match a.event {
Ev::User(Event::Inc { by }) => json!(a.context.count + by),
_ => json!(a.context.count),
})
.expr("double", |a| json!({ "context": { "count": a.context.count * 2 } }))
.expr("report", |a| json!({ "type": "count", "count": a.context.count, "mode": a.context.mode }))
.expr("large", |a| json!(a.context.count >= 10))
.expr("wait", |a| json!(format!("{}ms", a.context.count * 10)))
.context(
"fromInput",
|input| json!({ "count": input.and_then(|i| i["count"].as_i64()).unwrap_or(1), "mode": "input" }),
);
let code = |name: &str| json!({ "@code": name, "@lang": "rust" });
let def = json!({
"id": "typed",
"context": code("fromInput"),
"initial": "counting",
"states": {
"counting": {
"on": {
"inc": [
{ "guard": code("large"), "target": "big" },
{ "context": { "count": code("countPlusBy") }, "actions": [code("double"), { "type": "@xstate.emit", "event": code("report") }] }
]
}
},
"big": { "after": { "pause": { "target": "counting", "context": { "mode": "rested" } } } }
},
"delays": { "pause": { "duration": code("wait") } }
});
let machine = Arc::new(Machine::from_json(&def, &r).unwrap());
let mut actor =
Actor::start_with(machine, InitOptions { input: Some(json!({ "count": 2 })), ..Default::default() }).unwrap();
assert_eq!(actor.context().unwrap(), &Ctx { count: 2, mode: "input".into() });
actor.send(Event::Inc { by: 3 }, 0).unwrap();
assert_eq!(actor.context().unwrap().count, 10);
assert_eq!(actor.take_emitted(), vec![json!({ "type": "count", "count": 10, "mode": "input" })]);
actor.send(Event::Inc { by: 1 }, 0).unwrap();
assert!(actor.matches("big"));
assert_eq!(actor.next_deadline(), Some(100));
actor.advance(100).unwrap();
assert_eq!(actor.context().unwrap(), &Ctx { count: 10, mode: "rested".into() });
}
#[test]
fn expressions_with_strings_for_patches_spread_like_javascript() {
let mut r: Registry<Value, Value> = Registry::new();
r.expr("text", |_| json!("ab")).expr("raw", |_| json!("not an event"));
let def = json!({
"context": { "count": 1 }, "initial": "a",
"states": { "a": { "on": {
"spread": { "actions": [{ "type": "@xstate.assign", "context": { "@code": "text", "@lang": "rust" } }] },
"bad": { "actions": [{ "type": "@xstate.raise", "event": { "@code": "raw", "@lang": "rust" } }] }
} } }
});
let mut actor = Actor::start(Arc::new(Machine::from_json(&def, &r).unwrap()), 0).unwrap();
actor.send(json!({ "type": "spread" }), 0).unwrap();
assert_eq!(actor.context().unwrap(), &json!({ "count": 1, "0": "a", "1": "b" }));
assert!(actor.send(json!({ "type": "bad" }), 0).is_err());
assert_eq!(actor.status(), Status::Error);
}
#[test]
fn expression_load_errors_and_references() {
let code = |name: &str| json!({ "@code": name, "@lang": "rust" });
let e = load_err(json!({ "context": { "n": { "@expr": "1 + 1", "@lang": "js" } } }));
assert_eq!((e.kind, e.path.as_str()), (LoadErrorKind::Code, "$.context.n"));
let e = load_err(json!({ "context": { "n": { "@code": "one" } } }));
assert_eq!(e.kind, LoadErrorKind::Code);
let e = load_err(json!({ "@exprLang": "rust", "context": { "n": { "@code": "one" } } }));
assert_eq!((e.kind, e.path.as_str()), (LoadErrorKind::MissingImplementation, "$.context.n"));
let e = load_err(json!({ "initial": "a", "states": { "a": { "on": { "go": code("pick") } } } }));
assert_eq!((e.kind, e.path.as_str()), (LoadErrorKind::MissingImplementation, "$.states.a.on.go"));
let mut r: Registry<Value, Value> = Registry::new();
r.expr("one", |_| json!(1)).context("start", |_| json!({}));
let e = Machine::from_json(&json!({ "context": code("one") }), &r).err().unwrap();
assert!(e.message.contains("Registry::context"), "{e}");
let def = json!({ "initial": "a", "states": { "a": { "entry": [code("start")] } } });
assert!(Machine::from_json(&def, &r).err().unwrap().message.contains("only the root `context`"));
let refs = Machine::<Value, Value>::references(&json!({
"context": { "n": code("init") },
"initial": "a",
"states": { "a": { "on": { "go": { "guard": code("ok"), "context": { "n": code("next") }, "actions": [code("next")] } } } }
}))
.unwrap();
let names = |r: &[Reference]| r.iter().map(|r| (r.name.clone(), r.path.clone())).collect::<Vec<_>>();
assert_eq!(names(&refs.contexts), vec![("init".into(), "$.context.n".into())]);
assert_eq!(
names(&refs.exprs),
vec![("ok".into(), "$.states.a.on.go.guard".into()), ("next".into(), "$.states.a.on.go.context.n".into())]
);
}
#[test]
fn transition_functions_run_typed_with_enq() {
let mut r: Registry<Ctx, Event> = Registry::new();
let seen = Arc::new(Mutex::new(Vec::new()));
let notes = seen.clone();
r.action_with("note", move |text: &String| notes.lock().unwrap().push(text.clone()))
.expr("step", |a| match a.event {
Ev::User(Event::Inc { by }) if *by > 0 => {
let enq = a.enq().expect("a transition function has enq");
enq.emit(json!({ "type": "stepped", "by": by }));
enq.action("note", json!(format!("by {by}")));
json!({ "target": if a.context.count + by >= 10 { "big" } else { "small" }, "context": { "count": a.context.count + by } })
}
_ => Value::Null,
});
let def = json!({
"id": "fn",
"context": { "count": 0, "mode": "" },
"initial": "small",
"states": {
"small": { "on": { "inc": [{ "@code": "step", "@lang": "rust" }, { "target": "zero" }] } },
"big": {},
"zero": {}
}
});
let machine = Arc::new(Machine::from_json(&def, &r).unwrap());
let mut actor = Actor::start(machine.clone(), 0).unwrap();
actor.send(Event::Inc { by: 4 }, 0).unwrap();
assert!(actor.matches("small"));
actor.send(Event::Inc { by: 7 }, 0).unwrap();
assert!(actor.matches("big"));
assert_eq!(actor.context().unwrap().count, 11);
assert_eq!(
actor.take_emitted(),
vec![json!({ "type": "stepped", "by": 4 }), json!({ "type": "stepped", "by": 7 })]
);
assert_eq!(*seen.lock().unwrap(), ["by 4", "by 7"]);
let mut actor = Actor::start(machine, 0).unwrap();
actor.send(Event::Inc { by: 0 }, 0).unwrap();
assert!(actor.matches("zero"));
}
#[test]
fn context_expressions_spawn_children_or_start_the_actor_in_error() {
let kid = json!({ "id": "kid", "initial": "on", "states": { "on": {} } });
let mut r: Registry<Value, Value> = Registry::new();
r.context_with(
"two",
|a| json!({ "a": a.spawn("kid", SpawnOptions::default()), "b": a.spawn("kid", SpawnOptions::default()) }),
)
.context_with("unknown", |a| json!({ "a": a.spawn("nope", SpawnOptions::default()) }))
.context_with("twice", |a| {
let id = || SpawnOptions { id: Some("x".into()), ..Default::default() };
json!({ "a": a.spawn("kid", id()), "b": a.spawn("kid", id()) })
});
r.actor("kid", machine(kid));
let start = |context: &str| {
let def = json!({ "id": "p", "context": { "@code": context, "@lang": "rust" }, "initial": "a", "states": { "a": {} } });
Actor::start(machine_in(def, &r), 0)
};
let actor = start("two").unwrap();
assert_eq!(
actor.context().unwrap(),
&json!({ "a": { "@actor": "p/kid:0", "incarnation": "1" }, "b": { "@actor": "p/kid:1", "incarnation": "2" } })
);
for (context, message) in [
(
"unknown",
"XState error E66 (\"nope\"). See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e66",
),
(
"twice",
"XState error E67 (\"x\", \"p\"). See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e67",
),
] {
let actor = start(context).unwrap();
let error = json!({ "@error": "Error", "message": message });
assert_eq!(
(actor.status(), actor.error(), actor.context().unwrap()),
(Status::Error, Some(&error), &json!({}))
);
assert!(actor.children().is_empty());
}
}
#[test]
fn system_emitted_events_come_from_every_actor_once_observed() {
let kid = json!({
"id": "kid",
"initial": "on",
"states": { "on": { "on": { "ping": { "actions": [{ "type": "@xstate.emit", "event": { "type": "pong" } }] } } } }
});
let mut r: Registry<Value, Value> = Registry::new();
r.actor("kid", machine(kid));
let def = json!({
"id": "p",
"initial": "a",
"states": {
"a": {
"invoke": { "id": "k", "src": "kid" },
"on": { "go": { "actions": [{ "type": "@xstate.emit", "event": { "type": "went" } }] } }
}
}
});
let mut actor = Actor::start(machine_in(def, &r), 0).unwrap();
actor.send_to("p/k", json!({ "type": "ping" }), 0).unwrap();
assert!(actor.take_system_emitted().is_empty());
actor.observe_system_emitted();
actor.send_to("p/k", json!({ "type": "ping" }), 0).unwrap();
send(&mut actor, "go");
let emitted = system_emitted(&mut actor);
assert_eq!(emitted, [("p/k".to_string(), json!({ "type": "pong" })), ("p".to_string(), json!({ "type": "went" }))]);
assert!(actor.take_system_emitted().is_empty());
assert_eq!(actor.take_emitted(), [json!({ "type": "went" })]);
actor.unobserve_system_emitted();
actor.send_to("p/k", json!({ "type": "ping" }), 0).unwrap();
send(&mut actor, "go");
assert!(actor.take_system_emitted().is_empty());
assert_eq!(actor.take_emitted(), [json!({ "type": "went" })]);
}
#[test]
fn system_emitted_events_include_the_start_when_observed_from_it() {
let kid = json!({
"id": "kid",
"initial": "on",
"states": { "on": { "entry": [{ "type": "@xstate.emit", "event": { "type": "born" } }] } }
});
let mut r: Registry<Value, Value> = Registry::new();
r.actor("kid", machine(kid));
let def = json!({ "id": "p", "initial": "a", "states": { "a": { "invoke": { "id": "k", "src": "kid" } } } });
let m = machine_in(def, &r);
let mut actor = Actor::start(m.clone(), 0).unwrap();
actor.observe_system_emitted();
assert!(actor.take_system_emitted().is_empty());
let mut actor = Actor::start_with(m, InitOptions { observe_system_emitted: true, ..Default::default() }).unwrap();
assert_eq!(system_emitted(&mut actor), [("p/k".to_string(), json!({ "type": "born" }))]);
}
#[test]
fn restore_with_keeps_a_step_bound() {
let kid = json!({ "id": "kid", "initial": "on", "states": { "on": {} } });
let mut r: Registry<Value, Value> = Registry::new();
r.actor("kid", machine(kid));
let invoke: Vec<Value> = (1..=5).map(|i| json!({ "id": format!("k{i}"), "src": "kid" })).collect();
let def = json!({ "id": "p", "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": { "invoke": invoke } } });
let m = machine_in(def, &r);
let saved = Actor::start(m.clone(), 0).unwrap().persist();
let go = json!({ "type": "go" });
assert!(matches!(
Actor::restore_with(m.clone(), &saved, RestoreOptions { max_steps: 3, ..Default::default() })
.unwrap()
.send(go.clone(), 0),
Err(SystemError::MaxSteps)
));
assert!(Actor::restore(m, &saved).unwrap().send(go, 0).is_ok());
}
#[test]
fn restore_with_observes_system_emitted_when_asked() {
let kid = json!({
"id": "kid",
"initial": "on",
"states": {
"on": {
"entry": [{ "type": "@xstate.emit", "event": { "type": "born" } }],
"on": { "ping": { "actions": [{ "type": "@xstate.emit", "event": { "type": "pong" } }] } }
}
}
});
let mut r: Registry<Value, Value> = Registry::new();
r.actor("kid", machine(kid));
let def = json!({
"id": "p",
"initial": "a",
"states": {
"a": { "on": { "go": { "target": "b", "actions": [{ "type": "@xstate.emit", "event": { "type": "went" } }] } } },
"b": { "invoke": { "id": "k", "src": "kid" } }
}
});
let m = machine_in(def, &r);
let saved = Actor::start(m.clone(), 0).unwrap().persist();
for observe in [true, false] {
let options = RestoreOptions { observe_system_emitted: observe, ..Default::default() };
let mut actor = Actor::restore_with(m.clone(), &saved, options).unwrap();
actor.send(json!({ "type": "go" }), 0).unwrap();
let emitted = system_emitted(&mut actor);
let expected = [("p".to_string(), json!({ "type": "went" })), ("p/k".to_string(), json!({ "type": "born" }))];
assert_eq!(emitted, if observe { &expected[..] } else { &[] });
assert_eq!(actor.take_emitted(), [json!({ "type": "went" })]);
}
let mut running = Actor::start(m.clone(), 0).unwrap();
running.send(json!({ "type": "go" }), 0).unwrap();
let saved = running.persist();
let options = RestoreOptions { observe_system_emitted: true, ..Default::default() };
let mut actor = Actor::restore_with(m, &saved, options).unwrap();
actor.send_to("p/k", json!({ "type": "ping" }), 0).unwrap();
assert_eq!(system_emitted(&mut actor), [("p/k".to_string(), json!({ "type": "pong" }))]);
}