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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
use std::marker::PhantomData;
use std::sync::Arc;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use crate::core::Kind;
use crate::event::EventType;
use crate::interp::State;
use crate::machine::{Machine, ROOT};
use crate::system::{
ActorRef, AnySnapshot, EffectKind, ExternalEffect, FailedStart, InitOptions, Status, System, SystemError,
SystemLogic, TransitionCheck, DEFAULT_MAX_STEPS,
};
use crate::work::{
decode_address_segment, ApplyError, Failure, Input, Outcome, Root, Step, Work, DEFAULT_MAX_TIMERS, MAX_TIME,
};
/// Whether an event is a lifecycle notification only the runtime may
/// deliver (XState's `getEventBoundaryError`).
fn is_lifecycle_notification(event: &Value) -> bool {
matches!(
event.get("type").and_then(Value::as_str),
Some(
"xstate.done.actor"
| "xstate.error.actor"
| "xstate.snapshot.actor"
| "xstate.done.state"
| "xstate.error.execution"
)
)
}
/// Whether an event is one only XState itself sends, of a type that starts
/// with `xstate.`, as a lifecycle notification (`xstate.done.actor`,
/// `xstate.error.execution`, …): the workflow contract's run takes none from
/// outside, and rejects it.
fn is_runtime_event(event: &Value) -> bool {
event.get("type").and_then(Value::as_str).is_some_and(|ty| ty.starts_with("xstate."))
}
/// A root's error as the workflow contract writes it, `{ "message", "data"? }`:
/// an `Error` as XState persists one gives its message; a string is the
/// message; an object that is `{ "message", "data"? }` already stays as it
/// is; any other value is the data, with its own `message` if it has a
/// string one, or "The machine failed." if not.
fn failure_of(error: &Value) -> Failure {
if error.get("@error").is_some() {
let message = error.get("message").and_then(Value::as_str).unwrap_or_default();
return Failure::new(message);
}
if let Value::String(message) = error {
return Failure::new(message.clone());
}
if let Some(object) = error.as_object() {
if let Some(Value::String(message)) = object.get("message") {
if object.keys().all(|k| k == "message" || k == "data") {
return Failure { message: message.clone(), data: object.get("data").cloned() };
}
}
}
let message = match error.get("message").and_then(Value::as_str) {
Some(message) => message.to_owned(),
None if error.is_object() || error.is_array() => "The machine failed.".to_owned(),
// A number, a boolean or null, as JavaScript's `String` writes it.
None => error.to_string(),
};
Failure { message, data: Some(error.clone()) }
}
/// What a restore takes that a snapshot does not keep: the step bound per
/// call (as [`InitOptions::max_steps`]) and whether to observe every actor's
/// emitted events (as [`InitOptions::observe_system_emitted`]).
#[derive(Debug, Clone, Copy)]
pub struct RestoreOptions {
pub max_steps: usize,
pub observe_system_emitted: bool,
}
impl Default for RestoreOptions {
fn default() -> Self {
Self { max_steps: DEFAULT_MAX_STEPS, observe_system_emitted: false }
}
}
/// A running machine and its invoked children: an actor [`System`] whose
/// root is `machine`, with conveniences for the root.
///
/// The actor never reads a clock. The host passes the current time in
/// milliseconds; [`Actor::next_deadline`] says when timers are due.
///
/// Effects are handled as a live XState actor would: the root's emitted
/// events and logs are collected ([`Actor::take_emitted`],
/// [`Actor::take_logs`]), and every actor's emitted events once observed
/// ([`Actor::observe_system_emitted`]); custom actions with a Rust
/// implementation run immediately; async work (`@xstate.effect`) stays pending
/// until the host resolves it with [`Actor::resolve_effect`].
///
/// Errors are handled as a live XState actor handles them, where the pure
/// [`System`] fails the call: an execution error (a step that throws, an
/// action that fails) is recovered from through an active state's `onError`
/// (`xstate.error.execution`); a child that fails stops its own children and
/// reports `xstate.error.actor` to its parent, and the call goes on; the
/// root's failure fails the call, the root keeping its snapshot in the
/// `error` status.
pub struct Actor<C, E> {
machine: Arc<Machine<C, E>>,
system: System,
emitted: Vec<Value>,
/// Every actor's emitted events, while observed. Boxed: 8 bytes per actor
/// instead of a `Vec`'s 24, and most actors (one per key in the Kafka
/// engine) never observe.
#[allow(clippy::box_collection)]
system_emitted: Option<Box<Vec<(ActorRef, Value)>>>,
logs: Vec<Vec<Value>>,
/// How many timers a time input of [`Actor::apply`] fires at most in a
/// chunk of control inputs alone.
max_timers: usize,
/// Why the run can't go on, once a chunk failed with
/// `WORKFLOW_ENGINE_FAILED`: every chunk after it is refused so.
broken: Option<Box<str>>,
_event: PhantomData<fn(E)>,
}
/// What [`Actor::apply`] keeps to undo: the system as it was, a copy or,
/// of a system with a snapshot that cannot be copied, its JSON, and how
/// much the actor had collected.
struct Saved {
system: Result<System, Value>,
marks: (usize, usize, usize),
}
impl<C, E> std::fmt::Debug for Actor<C, E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Actor")
.field("machine", &self.machine.id)
.field("root", &self.system.root())
.finish_non_exhaustive()
}
}
impl<C, E> Actor<C, E>
where
C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
E: EventType + Send + Sync,
{
/// Starts an actor at time `now_ms`.
pub fn start(machine: Arc<Machine<C, E>>, now_ms: u64) -> Result<Self, SystemError> {
Self::start_with(machine, InitOptions { time: now_ms, ..Default::default() })
}
/// Starts an actor with explicit system options (input, root id,
/// registry key, execution id, time, step bound), observing every
/// actor's emitted events from the start when
/// [`InitOptions::observe_system_emitted`] is set, so what actors emit
/// while the system starts is collected too.
pub fn start_with(machine: Arc<Machine<C, E>>, options: InitOptions) -> Result<Self, SystemError> {
let observe = options.observe_system_emitted;
let logic = SystemLogic::new(machine.clone());
// Custom actions are kept from the first step, so one the host is to
// do, taken while the system starts, stays even when its actor stops
// in that very step.
let (mut system, effects) = System::initialize_with(&logic, options, true, true)?;
system.set_transient_effects(true);
// A root that fails while starting starts in `error`, as XState's.
system.take_root_failure();
let system_emitted = observe.then(Box::default);
let mut actor = Self {
machine,
system,
emitted: Vec::new(),
system_emitted,
logs: Vec::new(),
max_timers: DEFAULT_MAX_TIMERS,
broken: None,
_event: PhantomData,
};
actor.handle(effects)?;
Ok(actor)
}
/// Restores an actor from [`Actor::persist`] data. Runs no actions.
pub fn restore(machine: Arc<Machine<C, E>>, data: &Value) -> Result<Self, SystemError> {
Self::restore_with(machine, data, RestoreOptions::default())
}
/// [`Actor::restore`] with what a snapshot does not keep.
pub fn restore_with(
machine: Arc<Machine<C, E>>,
data: &Value,
options: RestoreOptions,
) -> Result<Self, SystemError> {
let logic = SystemLogic::new(machine.clone());
let mut system = System::from_json(&logic, data, options.max_steps)?;
system.set_transient_effects(true);
system.set_keep_actions(true);
system.set_live_errors(true);
let root = system.snapshot(system.root()).map(|s| s.as_any());
if !root.is_some_and(|s| s.is::<State<C, E>>() || s.is::<FailedStart>()) {
return Err(SystemError::Rejected("the snapshot's root is not this machine".into()));
}
let system_emitted = options.observe_system_emitted.then(Box::default);
Ok(Self {
machine,
system,
emitted: Vec::new(),
system_emitted,
logs: Vec::new(),
max_timers: DEFAULT_MAX_TIMERS,
broken: None,
_event: PhantomData,
})
}
/// Handles the effects of a call in order: collects emits and logs, and
/// acknowledges what needs no host (custom actions with an
/// implementation ran inside their steps). Then fails the call if the
/// root failed in it.
fn handle(&mut self, effects: Vec<ExternalEffect>) -> Result<(), SystemError> {
let root = self.system.root_address().clone();
for mut effect in effects {
let from_root = *effect.source.address == *root;
let done = match effect.kind {
EffectKind::Emit => {
if let Some(e) = effect.event.take() {
match (&mut self.system_emitted, from_root) {
(Some(all), true) => {
all.push((effect.source.clone(), e.clone()));
self.emitted.push(e);
}
(Some(all), false) => all.push((effect.source.clone(), e)),
(None, true) => self.emitted.push(e),
(None, false) => {}
}
}
true
}
_ if effect.ty == "@xstate.log" => {
if from_root {
self.logs.push(effect.args.take().unwrap_or_default());
}
true
}
_ => effect.ty == "@xstate.cancelEffect" || effect.ty == "@xstate.cleanup",
};
if done {
self.system.acknowledge(&effect.id);
}
}
self.system.take_root_failure().map_or(Ok(()), Err)
}
/// Sends `event` to the root at `now_ms` (see [`Actor::send_json`]).
pub fn send(&mut self, event: E, now_ms: u64) -> Result<(), SystemError> {
self.send_json(event.to_json(), now_ms)
}
/// Sends a JSON event to the root at `now_ms`. When time has moved
/// forward, timers due by `now_ms` fire first; a timer scheduled at the
/// current time (a zero delay) fires on the next [`Actor::advance`], as
/// with XState's `SimulatedClock`.
///
/// A lifecycle notification (`xstate.done.actor`, `xstate.error.actor`,
/// `xstate.snapshot.actor`, `xstate.done.state`,
/// `xstate.error.execution`) is not delivered: only the runtime sends
/// those, and XState's live actor takes one from the application as a
/// dead letter.
pub fn send_json(&mut self, event: Value, now_ms: u64) -> Result<(), SystemError> {
if now_ms > self.system.now() {
self.advance(now_ms)?;
}
if is_lifecycle_notification(&event) {
return Ok(());
}
let root = self.system.root_address().clone();
let effects = self.system.send(&root, event)?;
self.handle(effects)
}
/// Sends a JSON event to any actor in the system by address (the root's
/// is its id; an invoked child's is `<parent>/<invoke id>`), as
/// [`Actor::send_json`] does for the root.
pub fn send_to(&mut self, address: &str, event: Value, now_ms: u64) -> Result<(), SystemError> {
if now_ms > self.system.now() {
self.advance(now_ms)?;
}
if is_lifecycle_notification(&event) {
return Ok(());
}
let effects = self.system.send(address, event)?;
self.handle(effects)
}
/// Fires every timer due at or before `now_ms`, chronologically. Each
/// timer is its own step, as with a live XState actor: when a later
/// timer fails, the effects of the earlier ones have already run.
pub fn advance(&mut self, now_ms: u64) -> Result<(), SystemError> {
let target = now_ms.max(self.system.now());
while let Some(effects) = self.system.fire_next_timer(target)? {
self.handle(effects)?;
}
let effects = self.system.advance(target)?;
self.handle(effects)
}
/// Delivers the result of pending async work (an `@xstate.effect`), such
/// as `{ "type": "xstate.async.resolve", "data": ... }`.
pub fn resolve_effect(&mut self, effect_id: &str, event: Option<Value>) -> Result<(), SystemError> {
let effects = self.system.resolve_effect(effect_id, event)?;
self.handle(effects)
}
/// External work waiting for the host.
pub fn pending_effects(&self) -> Vec<ExternalEffect> {
self.system.external_effects().cloned().collect()
}
/// The work the actor waits for, in the order it started: invoked work
/// (`@xstate.effect`), which [`Input::Work`] settles `resolved` or
/// `rejected`, and host actions (see [`crate::HostActions`]), which it
/// settles `done`.
///
/// A host action stays listed until it is done, also when the actor that
/// took it has stopped since, even in the very step that took it, so the
/// host still does it: XState's pure system API would cancel it.
pub fn work(&self) -> Vec<Work> {
let mut work: Vec<(u64, Work)> = self
.system
.external_effects()
.filter_map(|effect| {
let order = effect.id.rsplit(':').next().and_then(|n| n.parse().ok()).unwrap_or(u64::MAX);
let actor = effect.source.address.to_string();
let item = if effect.ty == "@xstate.effect" {
let src = self.system.actor_src(&actor).unwrap_or_default();
let src = src.rfind("/actors/").map_or(src, |at| &src[at + "/actors/".len()..]);
let input = self.system.actor_logic(&actor).and_then(|(_, input)| input.cloned());
Work::Invoke { id: effect.id.clone(), actor, src: decode_address_segment(src), input }
} else if effect.kind == EffectKind::Action && !effect.ty.starts_with("@xstate.") {
let name = effect.ty.rsplit("/actions/").next().unwrap_or(&effect.ty);
// A custom action's params are its first argument.
let params = effect.args.as_ref().and_then(|a| a.first()).filter(|p| !p.is_null()).cloned();
Work::Action { id: effect.id.clone(), actor, ty: decode_address_segment(name), params }
} else {
return None;
};
Some((order, item))
})
.collect();
work.sort_by_key(|(order, _)| *order);
work.into_iter().map(|(_, w)| w).collect()
}
/// Settles work the actor waits for (see [`Actor::work`]) at its current
/// time: invoked work `resolved` or `rejected`, with `data` its output or
/// error, or a host action `done`. A result of work the actor no longer
/// waits for, as of work it cancelled, is a late result: it changes
/// nothing. An outcome of the other kind of work is
/// `WORKFLOW_INVALID_WORK_RESULT`, and changes nothing either. A failure
/// of the machine as it takes the result is a rejection of the root's
/// error, the root left in `error`; [`Actor::apply`] ends the run in
/// `error` of it instead, as it does of a result that puts the root in
/// `error` with no failure of a step.
pub fn settle(&mut self, id: &str, outcome: Outcome, data: Option<Value>) -> Result<(), ApplyError> {
match self.settle_work(id, outcome, data)? {
Ok(()) => Ok(()),
Err(error) => Err(ApplyError::rejected_with(self.failure(&error))),
}
}
/// [`Actor::settle`], with the machine's failure apart from a fault of
/// the result.
fn settle_work(
&mut self,
id: &str,
outcome: Outcome,
data: Option<Value>,
) -> Result<Result<(), SystemError>, ApplyError> {
let Some(item) = self.work().into_iter().find(|w| w.id() == id) else {
return Ok(Ok(()));
};
match (item, outcome) {
(Work::Action { .. }, Outcome::Done) => {
// Done: the host did it. Of an actor that has stopped since, too.
self.system.acknowledge(id);
Ok(Ok(()))
}
(Work::Invoke { .. }, Outcome::Resolved | Outcome::Rejected) => {
let ty = if outcome == Outcome::Resolved { "xstate.async.resolve" } else { "xstate.async.reject" };
let mut event = serde_json::Map::new();
event.insert("type".into(), ty.into());
if let Some(data) = data {
event.insert("data".into(), data);
}
Ok(self.resolve_effect(id, Some(Value::Object(event))))
}
(Work::Action { .. }, _) => Err(ApplyError::invalid_work_result("A host action is settled done.")),
(Work::Invoke { .. }, _) => {
Err(ApplyError::invalid_work_result("Invoked work is settled resolved or rejected."))
}
}
}
/// How many timers a time input of [`Actor::apply`] fires at most in a
/// chunk of control inputs alone ([`DEFAULT_MAX_TIMERS`] until
/// [`Actor::set_max_timers`]).
pub fn max_timers(&self) -> usize {
self.max_timers
}
/// Sets how many timers a time input of [`Actor::apply`] fires at most in
/// a chunk of control inputs alone, at least one, so a run far behind
/// catches up in steps, each step's `time` the last moment it reached. A
/// run's records depend on it, and a snapshot does not keep it: a host
/// sets it on each actor it starts or restores, the same for the whole
/// run, as the workflow contract's `maxTimers`.
pub fn set_max_timers(&mut self, max_timers: usize) {
self.max_timers = max_timers.max(1);
}
/// Applies one chunk of inputs, in order, as the workflow contract's
/// engine does, and gives the step: the events the root emitted in the
/// chunk (taken, as [`Actor::take_emitted`] takes them), the root, the
/// time, the next deadline and the work the actor waits for.
///
/// - An event is sent at the actor's current time. An event that fails,
/// the root failing on it, refuses the whole chunk as a rejection of
/// the root's error, `{ "message", "data"? }`, and the actor is as it
/// was before the chunk. So does an event to a run that is `done`, in
/// `error` or `stopped`, which takes none (`The run is done.`,
/// `The run is in error.`, `The run is stopped.`), and an event of a
/// type that starts with `xstate.`, which only XState itself sends.
/// - A time or work input that fails, or that puts the root in `error`
/// with no failure of a step (as invoked work rejected that no
/// `onError` handles), is a fact, which is never refused: the run ends
/// in `error`, the root's status, with the root's error, or the
/// failure's, as `{ "message", "data"? }`. What the inputs before it
/// gave stands, nothing of the failed input does, not even what it
/// emitted, and no input after it applies; the step's time is the time
/// the run had reached before the failed input. The ended run keeps no
/// timer and no invoked work, only the host actions still to do, and
/// it persists and restores in `error`.
/// - A run in `error` skips time, rejects events and still lets a host
/// action go by `done`.
/// - A time input moves the clock to `now`, a moment at a time, the
/// timers due at one moment firing together; a `now` behind the clock
/// leaves it where it is. In a chunk of control inputs alone it stops
/// before a moment once it has fired [`Actor::max_timers`] timers, its
/// time the last moment it reached; in a chunk with an event it fires
/// every timer due, so no event applies at a time that lags.
/// - A work input settles work of [`Actor::work`] (see
/// [`Actor::settle`]): a late result changes nothing, and an outcome of
/// the other kind of work refuses the chunk,
/// `WORKFLOW_INVALID_WORK_RESULT`.
///
/// An input that is no input of the contract refuses the chunk before
/// anything is applied (`WORKFLOW_INVALID_INPUT`), and an empty chunk
/// gives the step as it is. The undo is a copy of the system as it was
/// ([`System::try_clone`]), with the machine shared, taken once before
/// the chunk and once before each time or work input after the first;
/// an undo that cannot restore the system is `WORKFLOW_ENGINE_FAILED`.
/// The run can't go on after it: the actor is broken, and refuses every
/// chunk after it with `WORKFLOW_ENGINE_FAILED` too.
///
/// ```
/// use std::sync::Arc;
/// use serde_json::{json, Value};
/// use xmachines_runtime::{Actor, Machine, Registry};
///
/// let machine = Arc::new(Machine::<Value, Value>::from_json(
/// &json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } }),
/// &Registry::new(),
/// ).unwrap());
/// let mut actor = Actor::start(machine, 0).unwrap();
/// let step = actor.apply(&[json!({ "kind": "time", "now": 5 }), json!({ "type": "go" })]).unwrap();
/// assert_eq!(step.root.value, json!("b"));
/// assert_eq!(step.time, 5);
/// assert!(actor.apply(&[json!({ "type": "go" }), json!({ "kind": "time", "now": 1.5 })]).is_err());
/// ```
pub fn apply(&mut self, batch: &[Value]) -> Result<Step, ApplyError> {
if let Some(why) = &self.broken {
return Err(ApplyError::engine_failed(format!("The run can't go on: {why}")));
}
let applied = self.apply_chunk(batch);
if let Err(error) = &applied {
if error.code() == Some("WORKFLOW_ENGINE_FAILED") {
self.broken = Some(error.message().into());
}
}
applied
}
/// Whether a chunk failed with `WORKFLOW_ENGINE_FAILED`, so that
/// [`Actor::apply`] refuses every chunk after it.
pub fn is_broken(&self) -> bool {
self.broken.is_some()
}
/// [`Actor::apply`] of an actor that is not broken.
fn apply_chunk(&mut self, batch: &[Value]) -> Result<Step, ApplyError> {
let inputs = batch.iter().map(Input::from_json).collect::<Result<Vec<_>, _>>()?;
if inputs.is_empty() {
return Ok(self.step());
}
let saved = self.save();
// Every timer due in a chunk with an event, so no event lags.
let capped = inputs.iter().all(|input| !matches!(input, Input::Event(_)));
for (at, input) in inputs.into_iter().enumerate() {
let status = self.status();
// What a time or work input puts back when it fails: the first
// input's is the chunk's own.
let before = |actor: &Self| (at > 0).then(|| actor.save());
match input {
Input::Event(event) => {
let sent = match status {
Status::Done => Err(ApplyError::rejected("The run is done.")),
Status::Error => Err(ApplyError::rejected("The run is in error.")),
Status::Stopped => Err(ApplyError::rejected("The run is stopped.")),
Status::Active if is_runtime_event(&event) => {
Err(ApplyError::rejected("An event of a type that starts with xstate. is XState's own."))
}
// An event that fails a step, or that puts the root in
// error with no failed step (a child it did not handle,
// xstate.error.actor), is rejected with the root's error.
Status::Active => {
let now = self.system.now();
let sent = self.send_json(event, now);
match self.failed(status, sent.err()) {
Some(failure) => Err(ApplyError::rejected_with(failure)),
None => Ok(()),
}
}
};
if let Err(error) = sent {
self.undo(saved)?;
return Err(error);
}
}
// A run in error takes no time.
Input::Time { .. } if status == Status::Error => {}
Input::Time { now } => {
let before = before(self);
let advanced = self.advance_capped(now, capped);
if let Some(failure) = self.failed(status, advanced.err()) {
self.end_in_error(before.unwrap_or(saved), failure)?;
break;
}
}
Input::Work { id, outcome, data } => {
let before = before(self);
match self.settle_work(&id, outcome, data) {
Ok(settled) => {
if let Some(failure) = self.failed(status, settled.err()) {
self.end_in_error(before.unwrap_or(saved), failure)?;
break;
}
}
Err(error) => {
self.undo(saved)?;
return Err(error);
}
}
}
}
}
Ok(self.step())
}
/// Moves the clock towards `now`, a moment at a time, as
/// [`Actor::apply`] does: `capped`, of a chunk of control inputs alone,
/// it stops before a moment once [`Actor::max_timers`] timers fired.
fn advance_capped(&mut self, now: i64, capped: bool) -> Result<(), SystemError> {
let mut fired = 0usize;
loop {
match self.system.next_deadline() {
Some(due) if i64::try_from(due).is_ok_and(|due| due <= now) => {
if capped && fired >= self.max_timers {
return Ok(());
}
fired += self.system.timers_due_at(due);
let effects = self.system.advance(due)?;
self.handle(effects)?;
}
_ => {
if let Ok(now) = u64::try_from(now) {
if now > self.system.now() {
let effects = self.system.advance(now)?;
self.handle(effects)?;
}
}
return Ok(());
}
}
}
}
/// What [`Actor::undo`] puts back.
fn save(&self) -> Saved {
let marks = (self.emitted.len(), self.logs.len(), self.system_emitted.as_ref().map_or(0, |all| all.len()));
Saved { system: self.system.try_clone().ok_or_else(|| self.system.to_json()), marks }
}
/// Puts the system back as it was when `saved` was taken, and drops what
/// the actor collected since.
fn undo(&mut self, saved: Saved) -> Result<(), ApplyError> {
let (emitted, logs, system_emitted) = saved.marks;
self.system = match saved.system {
Ok(system) => system,
Err(before) => {
let logic = self.system.logic().clone();
let mut system = System::from_json(&logic, &before, self.system.max_steps())
.map_err(|e| ApplyError::engine_failed(format!("The run could not be put back: {e}")))?;
system.set_transient_effects(true);
system.set_keep_actions(true);
system.set_live_errors(true);
system
}
};
self.emitted.truncate(emitted);
self.logs.truncate(logs);
if let Some(all) = &mut self.system_emitted {
all.truncate(system_emitted);
}
Ok(())
}
/// The failure of a step that failed with `error`: the root's error, of
/// a root in `error`, or the error's message.
fn failure(&self, error: &SystemError) -> Failure {
match (self.status(), self.error()) {
(Status::Error, Some(root)) => failure_of(root),
_ => Failure::new(error.to_string()),
}
}
/// Whether a time or work input taken by a root of status `was` failed,
/// and of what: a step that failed with `error`, or a root it put in
/// `error` with no failure of a step, as by `xstate.error.actor` of
/// invoked work rejected that no `onError` handles.
fn failed(&self, was: Status, error: Option<SystemError>) -> Option<Failure> {
match error {
Some(error) => Some(self.failure(&error)),
None if was != Status::Error && self.status() == Status::Error => {
Some(self.error().map_or_else(|| Failure::new("The machine failed."), failure_of))
}
None => None,
}
}
/// Ends the run in `error` of a time or work input that failed with
/// `failure`: the system put back as it was before the input, then its
/// root ended with the failure, `{ "message", "data"? }`, which it
/// persists as it is.
fn end_in_error(&mut self, before: Saved, failure: Failure) -> Result<(), ApplyError> {
self.undo(before)?;
let failure = serde_json::to_value(failure).map_err(|e| ApplyError::engine_failed(e.to_string()))?;
self.system.end_in_error(failure);
Ok(())
}
/// The step of the chunk [`Actor::apply`] just applied. A run in `error`
/// has no deadline, and waits for host actions alone. A deadline past
/// [`MAX_TIME`], which no time input reaches and JavaScript does not hold
/// exactly, is left out: the timer stays, but no host can fire it.
fn step(&mut self) -> Step {
let state = self.state();
let value = state.map_or(Value::Null, |st| self.machine.state_value(&st.nodes));
let context = state.and_then(|st| serde_json::to_value(&st.context).ok()).unwrap_or(Value::Null);
let error = self.error().map(|e| serde_json::to_value(failure_of(e)).unwrap_or_default());
let status = self.status();
let root = Root { status: status.as_str().to_owned(), value, context, output: self.output().cloned(), error };
let (deadline, mut work) = (self.next_deadline(), self.work());
let deadline = if status == Status::Error {
work.retain(|w| matches!(w, Work::Action { .. }));
None
} else {
deadline.filter(|&due| due <= MAX_TIME)
};
Step { emitted: self.take_emitted(), root, time: self.now(), deadline, work }
}
/// Stops the root and its children, as XState's `actor.stop()`.
pub fn stop(&mut self) -> Result<(), SystemError> {
let root = self.system.root_address().clone();
let effects = self.system.send(&root, serde_json::json!({ "type": "xstate.stop" }))?;
self.handle(effects)
}
/// When the next timer is due, if any.
pub fn next_deadline(&self) -> Option<u64> {
self.system.next_deadline()
}
/// The root's machine snapshot; `None` when the root's start threw,
/// which leaves it only its error, as XState's live actor
/// (`{ status: 'error', error }`).
fn state(&self) -> Option<&State<C, E>> {
self.root().as_any().downcast_ref::<State<C, E>>()
}
fn root(&self) -> &dyn AnySnapshot {
self.system.snapshot(self.system.root()).expect("the root has a snapshot")
}
pub fn status(&self) -> Status {
self.root().status()
}
/// The root's context; `None` when its start threw, as XState's live
/// actor then has none.
pub fn context(&self) -> Option<&C> {
self.state().map(|st| &st.context)
}
/// The actor's output, once it is done.
pub fn output(&self) -> Option<&Value> {
self.state().and_then(|st| st.output.as_deref())
}
/// The error of an actor in the `error` status.
pub fn error(&self) -> Option<&Value> {
match self.state() {
Some(st) => st.error.as_deref(),
None => self.root().as_any().downcast_ref::<FailedStart>().map(|f| &f.error),
}
}
/// The system's virtual time.
pub fn now(&self) -> u64 {
self.system.now()
}
/// XState's nested state value, such as `{"b": "b1"}`; `None` when the
/// root's start threw, as XState's live actor then has none.
pub fn value(&self) -> Option<Value> {
self.state().map(|st| self.machine.state_value(&st.nodes))
}
/// The active states: none when the root's start threw.
fn nodes(&self) -> &[crate::core::Nid] {
self.state().map_or(&[], |st| &st.nodes)
}
/// Whether a state is active: `#id` by state id, or a `.`-separated path
/// of state keys from the root, such as `"checkout.payment"`.
pub fn matches(&self, state: &str) -> bool {
let nodes = self.nodes();
if nodes.is_empty() {
return false;
}
if let Some(id) = state.strip_prefix('#') {
return self.machine.node_by_id(id).is_some_and(|n| nodes.contains(&n));
}
let mut current = ROOT;
for key in state.split('.') {
let node = self.machine.tree.node(current);
match node.children.iter().copied().find(|&c| self.machine.data(c).key == key) {
Some(c) if nodes.contains(&c) => current = c,
_ => return false,
}
}
true
}
/// What the root would do with `event`, without taking it, as XState's
/// `snapshot.check(event)` (see [`TransitionCheck`]): accepted,
/// unhandled, rejected with the reasons of each transition that
/// rejects it, or partial. Guards and transition functions run as
/// they would when the event is sent; no action runs, no timer fires
/// and the actor is left as it is. A guard or a transition function
/// that throws fails the check.
pub fn check(&self, event: &E) -> Result<TransitionCheck, SystemError> {
self.check_json(&event.to_json())
}
/// [`Actor::check`] of a JSON event.
pub fn check_json(&self, event: &Value) -> Result<TransitionCheck, SystemError> {
self.system.check(self.system.root(), event)
}
/// Whether the root would take `event` now, as kit-workflow's `can`:
/// XState's `!isUnhandled(transition(...))`. An active root
/// selects a transition of it, any transition, also one with nothing to
/// do (`{}`, a description alone) or one that rejects the event, which
/// [`Actor::check`] calls unhandled or rejected. A guard that does not
/// pass selects nothing. A transition of JSON selects by its guard
/// alone: what it does, its context, actions and input, is not run, so
/// one that would throw as it is taken is still taken; a transition
/// function runs, as it decides. An event of a type that starts with `xstate.`,
/// which [`Actor::apply`] rejects, is never taken. Changes nothing.
pub fn can(&self, event: &E) -> Result<bool, SystemError> {
self.can_json(&event.to_json())
}
/// [`Actor::can`] of a JSON event.
pub fn can_json(&self, event: &Value) -> Result<bool, SystemError> {
if is_runtime_event(event) {
return Ok(false);
}
self.system.handles(self.system.root(), event)
}
/// Whether any active state has this tag.
pub fn has_tag(&self, tag: &str) -> bool {
self.nodes().iter().any(|&n| self.machine.data(n).tags.iter().any(|t| t == tag))
}
/// Ids of the active states, in configuration order.
pub fn configuration(&self) -> Vec<&str> {
self.nodes().iter().map(|&n| self.machine.data(n).id.as_str()).collect()
}
/// Ids of the active atomic and final states, in configuration order.
pub fn active_leaf_ids(&self) -> Vec<&str> {
self.nodes()
.iter()
.filter(|&&n| matches!(self.machine.tree.kind(n), Kind::Atomic | Kind::Final))
.map(|&n| self.machine.data(n).id.as_str())
.collect()
}
/// The root's invoked children: id and actor address.
pub fn children(&self) -> Vec<(&str, &str)> {
self.state().map(|st| st.children.iter().map(|(k, r)| (k.as_str(), &*r.address)).collect()).unwrap_or_default()
}
/// Takes the events the root emitted since the last call.
pub fn take_emitted(&mut self) -> Vec<Value> {
std::mem::take(&mut self.emitted)
}
/// Collects the events every actor in the system emits from now on, root
/// and children alike, as XState's `system.onEmitted`; read them with
/// [`Actor::take_system_emitted`]. Off by default, so emissions are not
/// copied when nobody reads them.
pub fn observe_system_emitted(&mut self) {
self.system_emitted.get_or_insert_with(Box::default);
}
/// Stops collecting what [`Actor::observe_system_emitted`] started, as
/// unsubscribing from XState's `system.onEmitted`, and drops the events
/// not taken yet.
pub fn unobserve_system_emitted(&mut self) {
self.system_emitted = None;
}
/// Takes the events every actor emitted since the last call, in order,
/// with the actor that emitted each. Empty unless observing, by
/// [`Actor::observe_system_emitted`] or
/// [`InitOptions::observe_system_emitted`].
pub fn take_system_emitted(&mut self) -> Vec<(ActorRef, Value)> {
self.system_emitted.as_deref_mut().map(std::mem::take).unwrap_or_default()
}
/// Takes the argument lists of the root's `@xstate.log` actions.
pub fn take_logs(&mut self) -> Vec<Vec<Value>> {
std::mem::take(&mut self.logs)
}
/// The whole system snapshot (XState's `SystemSnapshot` shape).
pub fn persist(&self) -> Value {
self.system.to_json()
}
/// [`Actor::persist`] as a view that serializes to the same data without
/// building it: write it straight into an encoding with serde.
pub fn persist_view(&self) -> crate::system::SystemView<'_> {
self.system.view()
}
/// A smaller snapshot that [`Actor::restore`] restores to the same actor
/// (see [`System::compact_view`]); not meant for XState's own restore.
pub fn persist_compact(&self) -> crate::system::SystemView<'_> {
self.system.compact_view()
}
pub fn machine(&self) -> &Arc<Machine<C, E>> {
&self.machine
}
/// The underlying system, for access to children.
pub fn system(&self) -> &System {
&self.system
}
/// The system's definitions.
pub fn system_logic(&self) -> &SystemLogic {
self.system.logic()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Registry;
#[test]
fn an_engine_that_failed_refuses_every_chunk_after_it() {
let definition =
serde_json::json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } });
let machine = Arc::new(Machine::<Value, Value>::from_json(&definition, &Registry::new()).unwrap());
let mut actor = Actor::start(machine, 0).unwrap();
assert!(!actor.is_broken());
// What an undo that could not put the run back leaves.
actor.broken = Some("The run could not be put back: lost".into());
for batch in [vec![], vec![serde_json::json!({ "type": "go" })]] {
let error = actor.apply(&batch).unwrap_err();
assert_eq!(error.code(), Some("WORKFLOW_ENGINE_FAILED"));
assert_eq!(error.message(), "The run can't go on: The run could not be put back: lost");
}
assert!(actor.is_broken());
}
}