xmachines-runtime 6.0.0

XState v6 semantics in Rust: a port of XState's interpreter and actor runtime; not affiliated with Stately
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! The workflow contract on [`Actor`]: host actions, work, chunks, and runs
//! that end in error. `tests/workflow_fixtures.rs` holds it to the
//! contract's shared fixtures too.

use std::sync::{Arc, Mutex};

use serde_json::{json, Value};
use xmachines_runtime::step::async_logic;
use xmachines_runtime::work::{ApplyError, Failure, Outcome, Work};
use xmachines_runtime::*;

fn load(def: Value, registry: &Registry<Value, Value>) -> Arc<Machine<Value, Value>> {
    Arc::new(Machine::from_json(&def, registry).unwrap())
}

fn hosting(names: &[&str]) -> Registry<Value, Value> {
    let mut r = Registry::new();
    r.host_actions(HostActions::Named(names.iter().map(|n| n.to_string()).collect()));
    r
}

fn auditing() -> Value {
    json!({
        "id": "order",
        "initial": "open",
        "states": {
            "open": {
                "on": { "pay": { "target": "paid", "actions": [{ "type": "audit", "params": { "what": "paid" } }] } }
            },
            "paid": { "entry": [{ "type": "audit" }] }
        }
    })
}

#[test]
fn a_host_action_waits_for_the_host_and_is_done_by_a_work_input() {
    let mut actor = Actor::start(load(auditing(), &hosting(&["audit"])), 0).unwrap();
    let step = actor.apply(&[json!({ "type": "pay" })]).unwrap();
    assert_eq!(step.root.value, json!("paid"));
    let work = serde_json::to_value(&step.work).unwrap();
    assert_eq!(
        work,
        json!([
            { "kind": "action", "id": "system:0", "actor": "order", "type": "audit", "params": { "what": "paid" } },
            { "kind": "action", "id": "system:1", "actor": "order", "type": "audit" }
        ])
    );
    // It persists and restores with the rest.
    let mut actor = Actor::restore(actor.machine().clone(), &actor.persist()).unwrap();
    assert_eq!(actor.work().len(), 2);
    let step = actor.apply(&[json!({ "kind": "work", "id": "system:0", "outcome": "done" })]).unwrap();
    assert_eq!(step.work.iter().map(Work::id).collect::<Vec<_>>(), ["system:1"]);
}

#[test]
fn a_named_host_action_runs_no_implementation_of_the_registry() {
    let ran = Arc::new(Mutex::new(0));
    let mut r = hosting(&["audit"]);
    let counter = ran.clone();
    r.action("audit", move || *counter.lock().unwrap() += 1);
    let mut actor = Actor::start(load(auditing(), &r), 0).unwrap();
    actor.apply(&[json!({ "type": "pay" })]).unwrap();
    assert_eq!(*ran.lock().unwrap(), 0);
    assert_eq!(actor.work().len(), 2);
}

#[test]
fn unimplemented_host_actions_are_those_the_registry_lacks() {
    let ran = Arc::new(Mutex::new(Vec::new()));
    let def = json!({
        "initial": "a",
        "states": { "a": { "on": { "go": { "actions": [{ "type": "audit" }, { "type": "note" }] } } } }
    });
    let mut r = Registry::new();
    let notes = ran.clone();
    r.action("note", move || notes.lock().unwrap().push("note")).host_actions(HostActions::Unimplemented);
    let mut actor = Actor::start(load(def.clone(), &r), 0).unwrap();
    let step = actor.apply(&[json!({ "type": "go" })]).unwrap();
    assert_eq!(*ran.lock().unwrap(), ["note"]);
    assert!(matches!(&step.work[..], [Work::Action { ty, .. }] if ty == "audit"));
    // Without host actions, an action with no implementation does not load.
    assert!(Machine::<Value, Value>::from_json(&def, &Registry::new()).is_err());
}

#[test]
fn a_host_action_taken_in_the_step_its_actor_stops_is_kept() {
    // fixtures/system/action_on_stop.json: XState's pure system API cancels both actions.
    let child = json!({
        "id": "child",
        "initial": "working",
        "states": {
            "working": {
                "exit": [{ "type": "track", "params": { "why": "exit" } }],
                "on": { "finish": { "target": "finished", "actions": [{ "type": "track", "params": { "why": "finish" } }] } }
            },
            "finished": { "type": "final" }
        }
    });
    let mut r = hosting(&["track"]);
    let child = load(child, &r);
    r.actor("child", child);
    let parent = json!({
        "id": "parent",
        "initial": "idle",
        "states": {
            "idle": { "on": { "start": { "target": "running" } } },
            "running": { "invoke": { "src": "child", "id": "worker", "onDone": { "target": "idle" } } }
        }
    });
    let mut actor = Actor::start(load(parent, &r), 0).unwrap();
    actor.apply(&[json!({ "type": "start" })]).unwrap();
    actor.send_to("parent/worker", json!({ "type": "finish" }), 0).unwrap();
    assert_eq!(actor.value(), Some(json!("idle")));
    let work = serde_json::to_value(actor.work()).unwrap();
    assert_eq!(
        work,
        json!([
            { "kind": "action", "id": "system:0", "actor": "parent/worker", "type": "track", "params": { "why": "exit" } },
            { "kind": "action", "id": "system:1", "actor": "parent/worker", "type": "track", "params": { "why": "finish" } }
        ])
    );
    // Done, although its actor is gone.
    let step = actor
        .apply(&[
            json!({ "kind": "work", "id": "system:0", "outcome": "done" }),
            json!({ "kind": "work", "id": "system:1", "outcome": "done" }),
        ])
        .unwrap();
    assert!(step.work.is_empty());
}

#[test]
fn invoked_work_is_listed_by_its_src_and_input_and_settled() {
    let def = json!({
        "id": "user",
        "initial": "loading",
        "context": { "user": null },
        "states": {
            "loading": {
                "invoke": {
                    "src": "fetchUser",
                    "input": { "id": 7 },
                    "onDone": { "target": "ready" },
                    "onError": { "target": "failed" }
                }
            },
            "ready": {},
            "failed": {}
        }
    });
    let mut r = Registry::new();
    r.actor("fetchUser", Arc::new(async_logic(Some("fetchUser".into()), None).unwrap()));
    let machine = load(def, &r);
    let mut actor = Actor::start(machine.clone(), 0).unwrap();
    let work = actor.work();
    let [Work::Invoke { id, src, input, .. }] = &work[..] else { panic!("{work:?}") };
    assert_eq!((src.as_str(), input), ("fetchUser", &Some(json!({ "id": 7 }))));
    let id = id.clone();

    // The wrong outcome refuses the chunk; a result of an id the actor waits
    // for no work of is a late result, which changes nothing.
    let before = actor.persist();
    let error = actor.apply(&[json!({ "kind": "work", "id": id, "outcome": "done" })]).unwrap_err();
    assert_eq!(error.code(), Some("WORKFLOW_INVALID_WORK_RESULT"));
    let step = actor.apply(&[json!({ "kind": "work", "id": "system:99", "outcome": "resolved" })]).unwrap();
    assert_eq!((step.root.value, step.work.len()), (json!("loading"), 1));
    assert_eq!(actor.persist(), before);

    let step = actor.apply(&[json!({ "kind": "work", "id": id, "outcome": "resolved", "data": null })]).unwrap();
    assert_eq!(step.root.value, json!("ready"));
    assert!(step.work.is_empty());

    let mut actor = Actor::start(machine, 0).unwrap();
    actor.settle(&id, Outcome::Rejected, Some(json!("down"))).unwrap();
    assert_eq!(actor.value(), Some(json!("failed")));
}

fn emitting() -> Value {
    json!({
        "id": "m",
        "initial": "a",
        "context": { "n": 0 },
        "states": {
            "a": {
                "entry": [{ "type": "@xstate.emit", "event": { "type": "inA" } }],
                "on": {
                    "go": { "target": "b", "context": { "n": 1 } },
                    "boom": { "actions": [{ "type": "boom" }] }
                },
                "after": { "100": { "target": "c" } }
            },
            "b": {
                "entry": [{ "type": "@xstate.emit", "event": { "type": "inB" } }],
                "on": { "back": { "target": "a" }, "boom": { "actions": [{ "type": "boom" }] } }
            },
            "c": {}
        }
    })
}

fn booming() -> Registry<Value, Value> {
    let mut r = Registry::new();
    r.try_action_with("boom", |_: &Value| Err("boom".into()));
    r
}

#[test]
fn an_event_that_fails_refuses_the_whole_chunk() {
    let mut actor = Actor::start(load(emitting(), &booming()), 0).unwrap();
    assert_eq!(actor.take_emitted(), [json!({ "type": "inA" })]);
    let before = actor.persist();
    // The time moves and the event steps, then the failing event refuses the chunk: nothing of it stays.
    let error = actor
        .apply(&[json!({ "kind": "time", "now": 50 }), json!({ "type": "go" }), json!({ "type": "boom" })])
        .unwrap_err();
    assert_eq!(error, ApplyError::rejected("boom"));
    assert_eq!(actor.persist(), before);
    assert!(actor.take_emitted().is_empty());
    assert_eq!((actor.now(), actor.status()), (0, Status::Active));

    let step = actor.apply(&[json!({ "kind": "time", "now": 50 }), json!({ "type": "go" })]).unwrap();
    assert_eq!(step.root.value, json!("b"));
    assert_eq!(step.root.context, json!({ "n": 1 }));
    assert_eq!(step.emitted, [json!({ "type": "inB" })]);
    assert_eq!((step.time, step.deadline), (50, None));

    let step = actor.apply(&[json!({ "type": "back" })]).unwrap();
    assert_eq!((step.time, step.deadline), (50, Some(150)));
    let step = actor.apply(&[json!({ "kind": "time", "now": 150 })]).unwrap();
    assert_eq!(step.root.value, json!("c"));
}

/// A machine whose timer at 25 runs into an endless loop of eventless
/// transitions, as the contract's `failed-timer` fixture.
fn failing_timer() -> Value {
    json!({
        "id": "armed",
        "initial": "idle",
        "options": { "maxIterations": 100 },
        "states": {
            "idle": { "on": { "arm": { "target": "armed", "actions": [{ "type": "audit" }] } } },
            "armed": {
                "after": { "25": { "target": "a" } },
                "on": { "ping": { "actions": [{ "type": "@xstate.emit", "event": { "type": "pong" } }] } }
            },
            "a": { "always": { "target": "b" } },
            "b": { "always": { "target": "a" } }
        }
    })
}

#[test]
fn a_time_input_that_fails_ends_the_run_in_error_and_keeps_what_came_before() {
    let machine = load(failing_timer(), &hosting(&["audit"]));
    let mut actor = Actor::start(machine.clone(), 0).unwrap();
    actor.apply(&[json!({ "type": "arm" })]).unwrap();
    let step = actor
        .apply(&[
            json!({ "kind": "time", "now": 10 }),
            json!({ "type": "ping" }),
            json!({ "kind": "time", "now": 30 }),
            json!({ "type": "ping" }),
        ])
        .unwrap();
    // The inputs before the failed one stand, nothing after it applies, and
    // the time is the one reached before it.
    assert_eq!(step.emitted, [json!({ "type": "pong" })]);
    assert_eq!((step.root.status.as_str(), &step.root.value), ("error", &json!("armed")));
    assert!(step.root.error.as_ref().is_some_and(|e| e["message"].is_string()), "{:?}", step.root.error);
    assert_eq!((step.time, step.deadline), (10, None));
    // The host action stays, to do.
    assert!(matches!(&step.work[..], [Work::Action { ty, .. }] if ty == "audit"));
    let id = step.work[0].id().to_owned();

    // It persists and restores in error, and the ended run skips time,
    // rejects an event, and still lets a host action go.
    let mut actor = Actor::restore(machine, &actor.persist()).unwrap();
    assert_eq!(actor.status(), Status::Error);
    let step = actor.apply(&[json!({ "kind": "time", "now": 500 })]).unwrap();
    assert_eq!((step.time, step.root.status.as_str()), (10, "error"));
    let before = actor.persist();
    let error = actor.apply(&[json!({ "kind": "work", "id": id, "outcome": "done" }), json!({ "type": "ping" })]);
    assert_eq!(error.unwrap_err(), ApplyError::rejected("The run is in error."));
    assert_eq!(actor.persist(), before);
    let error = actor.apply(&[json!({ "kind": "work", "id": id, "outcome": "resolved" })]).unwrap_err();
    assert_eq!(error.code(), Some("WORKFLOW_INVALID_WORK_RESULT"));
    let step = actor.apply(&[json!({ "kind": "work", "id": id, "outcome": "done" })]).unwrap();
    assert!(step.work.is_empty());
}

#[test]
fn a_work_input_that_fails_ends_the_run_in_error() {
    let def = json!({
        "id": "loader",
        "initial": "loading",
        "states": {
            "loading": { "invoke": { "src": "fetch", "onDone": { "target": "done", "actions": [{ "type": "boom" }] } } },
            "done": {}
        }
    });
    let mut r = booming();
    r.actor("fetch", Arc::new(async_logic(Some("fetch".into()), None).unwrap()));
    let mut actor = Actor::start(load(def, &r), 0).unwrap();
    let id = actor.work()[0].id().to_owned();
    let step = actor
        .apply(&[
            json!({ "kind": "time", "now": 5 }),
            json!({ "kind": "work", "id": id, "outcome": "resolved" }),
            json!({ "kind": "time", "now": 9 }),
        ])
        .unwrap();
    assert_eq!((step.root.status.as_str(), &step.root.value, step.time), ("error", &json!("loading"), 5));
    // The invoked work is dropped, and a result of it is late now.
    assert!(step.work.is_empty());
    assert!(actor.apply(&[json!({ "kind": "work", "id": id, "outcome": "resolved" })]).is_ok());
}

#[test]
fn an_event_to_a_run_that_is_done_is_rejected() {
    let def =
        json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": { "type": "final" } } });
    let mut actor = Actor::start(load(def, &Registry::new()), 0).unwrap();
    assert_eq!(actor.apply(&[json!({ "type": "go" })]).unwrap().root.status, "done");
    let error = actor.apply(&[json!({ "kind": "time", "now": 5 }), json!({ "type": "go" })]).unwrap_err();
    assert_eq!(error, ApplyError::rejected("The run is done."));
    assert_eq!(actor.now(), 0);
    // Time still moves.
    assert_eq!(actor.apply(&[json!({ "kind": "time", "now": 5 })]).unwrap().time, 5);
}

#[test]
fn a_time_input_of_control_inputs_alone_fires_at_most_max_timers() {
    let def = json!({
        "id": "beat",
        "initial": "on",
        "states": {
            "on": {
                "after": {
                    "10": { "target": "on", "reenter": true, "actions": [{ "type": "@xstate.emit", "event": { "type": "tick" } }] }
                },
                "on": { "ping": {} }
            }
        }
    });
    let machine = load(def, &Registry::new());
    let mut actor = Actor::start(machine.clone(), 0).unwrap();
    assert_eq!(actor.max_timers(), work::DEFAULT_MAX_TIMERS);
    actor.set_max_timers(3);
    // Three moments, then the time is the last one reached.
    let step = actor.apply(&[json!({ "kind": "time", "now": 100 })]).unwrap();
    assert_eq!((step.emitted.len(), step.time, step.deadline), (3, 30, Some(40)));
    // A chunk with an event fires every timer due.
    let step = actor.apply(&[json!({ "kind": "time", "now": 100 }), json!({ "type": "ping" })]).unwrap();
    assert_eq!((step.emitted.len(), step.time), (7, 100));
    // A now behind the clock, a negative one too, leaves it where it is.
    for now in [json!(50), json!(-5)] {
        assert_eq!(actor.apply(&[json!({ "kind": "time", "now": now })]).unwrap().time, 100);
    }
    // A restored actor takes the bound its host sets again.
    let mut actor = Actor::restore(machine, &actor.persist()).unwrap();
    actor.set_max_timers(1);
    assert_eq!(actor.apply(&[json!({ "kind": "time", "now": 1000 })]).unwrap().time, 110);
}

#[test]
fn inputs_are_checked_before_anything_is_applied() {
    let def = json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } });
    let mut actor = Actor::start(load(def, &Registry::new()), 0).unwrap();
    for bad in [
        json!({ "kind": "time", "now": 10.5 }),
        json!({ "kind": "time", "now": 9007199254740992u64 }),
        json!({ "kind": "time", "now": -9007199254740992i64 }),
        json!({ "kind": "time", "now": "1" }),
        json!({ "kind": "time", "now": 1, "type": "go" }),
        json!({ "kind": "work", "id": "system:0", "outcome": "done", "type": "go" }),
        json!({ "kind": "work", "id": "system:0", "outcome": "finished" }),
        json!({ "kind": "work", "id": 0, "outcome": "done" }),
        // A result of done carries no data, not even null.
        json!({ "kind": "work", "id": "system:0", "outcome": "done", "data": 1 }),
        json!({ "kind": "work", "id": "system:0", "outcome": "done", "data": null }),
        json!({ "kind": "nope" }),
        json!({ "now": 1 }),
        json!({ "type": 1 }),
        json!("go"),
    ] {
        let error = actor.apply(&[json!({ "type": "go" }), bad.clone()]).unwrap_err();
        assert_eq!(error.code(), Some("WORKFLOW_INVALID_INPUT"), "{bad}");
    }
    assert_eq!(actor.value(), Some(json!("a")));
    // A whole number written with a zero fraction is a whole number, and a
    // control input may carry keys it does not read.
    assert_eq!(actor.apply(&[json!({ "kind": "time", "now": 5.0, "note": 1 })]).unwrap().time, 5);
    assert_eq!(actor.apply(&[json!({ "kind": "time", "now": -9007199254740991i64 })]).unwrap().time, 5);
    // A kind other than time or work beside a type is the event's own field.
    let step = actor.apply(&[json!({ "type": "go", "kind": "book" })]).unwrap();
    assert_eq!(step.root.value, json!("b"));
}

#[test]
fn a_failed_root_refuses_the_chunk_and_keeps_its_state() {
    let def = json!({
        "initial": "a",
        "states": { "a": { "on": { "go": { "target": "b", "actions": [{ "type": "boom" }] } } }, "b": {} }
    });
    let mut actor = Actor::start(load(def, &booming()), 0).unwrap();
    let error = actor.apply(&[json!({ "type": "go" })]).unwrap_err();
    assert!(error.rejection().is_some_and(|r| r.message == "boom"), "{error}");
    assert_eq!((actor.status(), actor.value()), (Status::Active, Some(json!("a"))));
}

#[test]
fn a_host_action_taken_as_the_root_starts_and_stops_is_kept() {
    // The root takes it on its way to its final state, in its start step.
    let def = json!({
        "id": "once",
        "initial": "a",
        "states": { "a": { "always": { "target": "b", "actions": [{ "type": "audit" }] } }, "b": { "type": "final" } }
    });
    let actor = Actor::start(load(def, &hosting(&["audit"])), 0).unwrap();
    assert_eq!(actor.status(), Status::Done);
    assert!(matches!(&actor.work()[..], [Work::Action { ty, actor, .. }] if ty == "audit" && actor == "once"));
}

#[test]
fn a_host_action_a_child_takes_as_it_starts_and_stops_is_kept() {
    let child = json!({
        "id": "child",
        "initial": "a",
        "states": { "a": { "entry": [{ "type": "track" }], "always": { "target": "b" } }, "b": { "type": "final" } }
    });
    let mut r = hosting(&["track"]);
    let child = load(child, &r);
    r.actor("child", child);
    let parent = json!({
        "id": "parent",
        "initial": "running",
        "states": { "running": { "invoke": { "src": "child", "id": "worker", "onDone": { "target": "over" } } }, "over": {} }
    });
    let mut actor = Actor::start(load(parent, &r), 0).unwrap();
    assert_eq!(actor.value(), Some(json!("over")));
    let work = actor.work();
    assert!(matches!(&work[..], [Work::Action { ty, actor, .. }] if ty == "track" && actor == "parent/worker"));
    let step = actor.apply(&[json!({ "kind": "work", "id": work[0].id(), "outcome": "done" })]).unwrap();
    assert!(step.work.is_empty());
}

#[test]
fn a_child_stopped_by_its_parent_runs_no_exit_action() {
    // fixtures/system/action_on_stop.json, its last step: XState runs no
    // exit action of a child its parent stops, so no host action is taken.
    let child = json!({
        "id": "child",
        "initial": "working",
        "states": { "working": { "exit": [{ "type": "track", "params": { "why": "exit" } }] } }
    });
    let mut r = hosting(&["track"]);
    let child = load(child, &r);
    r.actor("child", child);
    let parent = json!({
        "id": "parent",
        "initial": "idle",
        "states": {
            "idle": { "on": { "start": { "target": "running" } } },
            "running": { "invoke": { "src": "child", "id": "worker" }, "on": { "cancel": { "target": "idle" } } }
        }
    });
    let mut actor = Actor::start(load(parent, &r), 0).unwrap();
    actor.apply(&[json!({ "type": "start" })]).unwrap();
    let step = actor.apply(&[json!({ "type": "cancel" })]).unwrap();
    assert_eq!(step.root.value, json!("idle"));
    assert!(step.work.is_empty());
}

#[test]
fn can_is_whether_a_transition_is_selected() {
    let def = json!({
        "initial": "a",
        "states": {
            "a": { "on": {
                "go": { "target": "b" },
                "stay": {},
                "maybe": { "target": "b", "guard": { "type": "no" } }
            } },
            "b": { "type": "final" }
        }
    });
    let mut r = Registry::new();
    r.guard("no", |_| false);
    let mut actor = Actor::start(load(def, &r), 0).unwrap();
    assert!(actor.can_json(&json!({ "type": "go" })).unwrap());
    // An empty transition is selected, though check calls it unhandled.
    assert!(actor.can_json(&json!({ "type": "stay" })).unwrap());
    assert_eq!(actor.check_json(&json!({ "type": "stay" })).unwrap(), TransitionCheck::Unhandled);
    assert!(!actor.can_json(&json!({ "type": "maybe" })).unwrap());
    assert!(!actor.can_json(&json!({ "type": "unknown" })).unwrap());
    actor.apply(&[json!({ "type": "go" })]).unwrap();
    assert!(!actor.can_json(&json!({ "type": "go" })).unwrap());
}

/// Two regions with timers: one invokes a child whose own timer fails it,
/// which fails the root by `xstate.error.actor`, no `onError` handling it:
/// the root is in `error` with no failure of a step of its own.
fn racing() -> Arc<Machine<Value, Value>> {
    let mut r = booming();
    let kid = json!({
        "id": "kid",
        "initial": "wait",
        "states": { "wait": { "after": { "10": { "target": "done", "actions": [{ "type": "boom" }] } } }, "done": {} }
    });
    let kid = load(kid, &r);
    r.actor("kid", kid);
    let def = json!({
        "id": "race",
        "type": "parallel",
        "states": {
            "x": { "initial": "wait", "states": { "wait": { "invoke": { "src": "kid", "id": "kid" } } } },
            "y": {
                "initial": "wait",
                "states": {
                    "wait": {
                        "after": { "5": { "target": "ticked", "actions": [{ "type": "@xstate.emit", "event": { "type": "tick" } }] } }
                    },
                    "ticked": {
                        "after": { "5": { "target": "late", "actions": [{ "type": "@xstate.emit", "event": { "type": "late" } }] } }
                    },
                    "late": {}
                }
            }
        }
    });
    load(def, &r)
}

#[test]
fn a_time_input_that_puts_the_root_in_error_with_no_failure_ends_the_run() {
    let mut actor = Actor::start(racing(), 0).unwrap();
    let step = actor
        .apply(&[
            json!({ "kind": "time", "now": 5 }),
            json!({ "kind": "time", "now": 20 }),
            json!({ "kind": "time", "now": 30 }),
        ])
        .unwrap();
    // The first input stands; nothing of the second does, not what it
    // emitted at the moment the child failed, and the third is not applied.
    assert_eq!(step.emitted, [json!({ "type": "tick" })]);
    assert_eq!((step.root.status.as_str(), step.time, step.deadline), ("error", 5, None));
    assert_eq!(step.root.value, json!({ "x": "wait", "y": "ticked" }));
    assert_eq!(step.root.error, Some(json!({ "message": "boom" })));
    // The run persists in error and restores so.
    let restored = Actor::restore(actor.machine().clone(), &actor.persist()).unwrap();
    assert_eq!(restored.error(), Some(&json!({ "message": "boom" })));
    assert_eq!((restored.status(), restored.next_deadline()), (Status::Error, None));
}

#[test]
fn invoked_work_rejected_that_no_on_error_handles_ends_the_run() {
    let def = json!({
        "id": "pay",
        "initial": "idle",
        "states": {
            "idle": { "on": { "pay": { "target": "paying" } } },
            "paying": {
                "invoke": { "src": "charge", "id": "charge", "onDone": { "target": "paid" } },
                "on": { "ping": { "actions": [{ "type": "@xstate.emit", "event": { "type": "pong" } }] } }
            },
            "paid": { "type": "final" }
        }
    });
    let mut registry = Registry::new();
    registry.actor("charge", Arc::new(async_logic(Some("charge".into()), None).unwrap()));
    let mut actor = Actor::start(load(def, &registry), 0).unwrap();
    let id = actor.apply(&[json!({ "type": "pay" })]).unwrap().work[0].id().to_owned();
    // The event after the work result is not applied: it is no rejection either.
    let step = actor
        .apply(&[
            json!({ "kind": "work", "id": id, "outcome": "rejected", "data": { "code": "declined" } }),
            json!({ "type": "ping" }),
        ])
        .unwrap();
    assert!(step.emitted.is_empty());
    assert_eq!(step.root.status, "error");
    assert_eq!(step.root.error, Some(json!({ "message": "The machine failed.", "data": { "code": "declined" } })));
    assert!(step.work.is_empty());
    assert_eq!(actor.apply(&[json!({ "type": "ping" })]).unwrap_err(), ApplyError::rejected("The run is in error."));
}

#[test]
fn an_event_to_a_stopped_run_is_rejected() {
    let def = json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } });
    let mut actor = Actor::start(load(def, &Registry::new()), 0).unwrap();
    actor.stop().unwrap();
    assert_eq!(actor.apply(&[json!({ "type": "go" })]).unwrap_err(), ApplyError::rejected("The run is stopped."));
    assert_eq!(actor.status(), Status::Stopped);
}

#[test]
fn an_event_of_xstates_own_type_is_rejected_and_never_taken() {
    let def = json!({
        "initial": "a",
        "states": { "a": { "on": { "xstate.done.actor": { "target": "b" }, "go": { "target": "b" } } }, "b": {} }
    });
    let mut actor = Actor::start(load(def, &Registry::new()), 0).unwrap();
    for ty in ["xstate.done.actor", "xstate.error.execution", "xstate.stop"] {
        assert!(!actor.can_json(&json!({ "type": ty })).unwrap(), "{ty}");
        let error = actor.apply(&[json!({ "type": "go" }), json!({ "type": ty })]).unwrap_err();
        assert!(error.rejection().is_some(), "{ty}: {error}");
        assert_eq!(actor.value(), Some(json!("a")));
    }
}

#[test]
fn a_rejection_and_a_fault_are_told_apart_as_json() {
    let rejected = ApplyError::rejected_with(Failure { message: "no".into(), data: Some(json!({ "code": 1 })) });
    assert_eq!(
        serde_json::to_value(&rejected).unwrap(),
        json!({ "rejected": { "message": "no", "data": { "code": 1 } } })
    );
    assert_eq!(serde_json::to_value(ApplyError::rejected("no")).unwrap(), json!({ "rejected": { "message": "no" } }));
    let fault = ApplyError::invalid_input("bad");
    assert_eq!(serde_json::to_value(&fault).unwrap(), json!({ "code": "WORKFLOW_INVALID_INPUT", "message": "bad" }));
    for error in [rejected, fault] {
        let json = serde_json::to_value(&error).unwrap();
        assert_eq!(serde_json::from_value::<ApplyError>(json).unwrap(), error);
    }
}

/// A parent that invokes `kid` in `running`, and emits `pong` on `ping`.
fn parent_of_kid() -> Value {
    json!({ "id": "p", "initial": "idle", "states": {
        "idle": { "on": {
            "go": { "target": "running" },
            "ping": { "actions": [{ "type": "@xstate.emit", "event": { "type": "pong" } }] }
        } },
        "running": { "invoke": { "src": "kid", "id": "k" } }
    } })
}

/// Applies `[ping, go]` to a parent whose child fails as it starts, which
/// puts the root in error with no failed step of its own: the chunk is
/// rejected with the child's error, and the run goes on from `idle`.
fn an_event_that_fails_the_root_through_its_child(registry: Registry<Value, Value>) {
    let mut actor = Actor::start(load(parent_of_kid(), &registry), 0).unwrap();
    let error = actor.apply(&[json!({ "type": "ping" }), json!({ "type": "go" })]).unwrap_err();
    let rejected = error.rejection().expect("a rejection, not a fault");
    assert_eq!(rejected.message, "boom");
    assert_eq!((actor.status(), actor.value()), (Status::Active, Some(json!("idle"))));
    let step = actor.apply(&[]).unwrap();
    assert!(step.emitted.is_empty(), "{:?}", step.emitted);
    // The run goes on.
    assert_eq!(actor.apply(&[json!({ "type": "ping" })]).unwrap().emitted, [json!({ "type": "pong" })]);
}

#[test]
fn an_event_whose_registry_child_fails_is_rejected() {
    let mut r: Registry<Value, Value> = Registry::new();
    r.try_action_with("boom", |_: &Value| Err("boom".into()));
    let kid = load(json!({ "id": "kid", "initial": "a", "states": { "a": { "entry": [{ "type": "boom" }] } } }), &r);
    r.actor("kid", kid);
    an_event_that_fails_the_root_through_its_child(r);
}

#[test]
fn an_event_whose_child_of_json_fails_is_rejected() {
    let mut r: Registry<Value, Value> = Registry::new();
    r.expr("boom", |args| {
        args.fail("boom");
        Value::Null
    });
    let kid = load(
        json!({ "id": "kid", "initial": "a", "context": { "n": 0 }, "states": { "a": {
            "entry": [{ "type": "@xstate.assign", "context": { "n": { "@code": "boom", "@lang": "rust" } } }]
        } } }),
        &r,
    );
    r.actor("kid", kid);
    an_event_that_fails_the_root_through_its_child(r);
}