1use std::any::Any;
18use std::cmp::Reverse;
19use std::collections::{BinaryHeap, VecDeque};
20use std::fmt;
21use std::sync::Arc;
22
23use indexmap::IndexMap;
24use serde::ser::{SerializeMap, SerializeSeq};
25use serde::{Serialize, Serializer};
26use serde_json::{json, Map, Value};
27
28use crate::error::{xstate_error, CodeValue::Raw, CodeValue::Str};
29use crate::{FixedMap, FixedSet};
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
33#[serde(rename_all = "lowercase")]
34pub enum Status {
35 Active,
36 Done,
37 Error,
38 Stopped,
39}
40
41impl Status {
42 pub fn as_str(self) -> &'static str {
43 match self {
44 Status::Active => "active",
45 Status::Done => "done",
46 Status::Error => "error",
47 Status::Stopped => "stopped",
48 }
49 }
50
51 fn parse(s: &str) -> Option<Self> {
52 Some(match s {
53 "active" => Status::Active,
54 "done" => Status::Done,
55 "error" => Status::Error,
56 "stopped" => Status::Stopped,
57 _ => return None,
58 })
59 }
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Hash)]
65pub struct ActorRef {
66 pub address: Arc<str>,
67 pub incarnation: u64,
68}
69
70impl ActorRef {
71 pub fn to_json(&self) -> Value {
72 json!({ "@actor": &*self.address, "incarnation": self.incarnation.to_string() })
73 }
74
75 pub fn from_json(value: &Value) -> Option<Self> {
76 let address = value.get("@actor")?.as_str()?;
77 let incarnation = value.get("incarnation")?.as_str()?.parse().ok()?;
78 Some(Self { address: address.into(), incarnation })
79 }
80}
81
82#[derive(Debug, Clone, PartialEq)]
86pub enum SystemError {
87 Rejected(String),
90 InfiniteLoop { actor_id: String, event_type: String, max_iterations: usize, states: Vec<Value> },
94 MaxSteps,
96 Failed(String),
98}
99
100impl SystemError {
101 pub fn to_value(&self) -> Value {
105 let name = match self {
106 SystemError::InfiniteLoop { .. } => "InfiniteTransitionError",
107 _ => "Error",
108 };
109 json!({ "@error": name, "message": self.to_string() })
110 }
111
112 pub fn is_execution_error(&self) -> bool {
116 matches!(self, SystemError::Failed(_) | SystemError::InfiniteLoop { .. })
117 }
118}
119
120impl fmt::Display for SystemError {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 match self {
123 SystemError::Rejected(m) | SystemError::Failed(m) => f.write_str(m),
124 SystemError::InfiniteLoop { actor_id, event_type, max_iterations, .. } => {
126 f.write_str(&xstate_error(16, &[Str(actor_id), Str(event_type), Raw(&max_iterations.to_string())]))
127 }
128 SystemError::MaxSteps => {
129 f.write_str("System transition exceeded maxSteps; the input snapshot is unchanged.")
130 }
131 }
132 }
133}
134
135impl std::error::Error for SystemError {}
136
137fn rejected<T>(message: impl Into<String>) -> Result<T, SystemError> {
138 Err(SystemError::Rejected(message.into()))
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum EffectKind {
144 Builtin,
145 Emit,
146 Action,
147}
148
149impl EffectKind {
150 fn as_str(self) -> &'static str {
151 match self {
152 EffectKind::Builtin => "builtin",
153 EffectKind::Emit => "emit",
154 EffectKind::Action => "action",
155 }
156 }
157}
158
159pub type EffectExec = Arc<dyn Fn() -> Result<(), String> + Send + Sync>;
162
163#[derive(Clone)]
165pub enum EffectType {
166 Fixed(String),
168 Action(String),
171}
172
173#[derive(Clone)]
176pub struct ExternalSpec {
177 pub kind: EffectKind,
178 pub ty: EffectType,
179 pub params: Option<Value>,
181 pub args: Vec<Value>,
182 pub event: Option<Value>,
183 pub reason: Option<String>,
184 pub exec: Option<EffectExec>,
185}
186
187#[derive(Clone)]
189pub enum Effect {
190 Spawn(ActorRef),
192 Start(ActorRef),
194 Stop(ActorRef),
196 Cancel(TimerKey),
198 DelayedRaise { key: TimerKey, delay: u64, occurrence: u64 },
201 SendTo { target: ActorRef, event: Value },
203 Terminate,
205 External(ExternalSpec),
207}
208
209pub struct Transition {
211 pub snapshot: Box<dyn AnySnapshot>,
212 pub effects: Vec<Effect>,
213}
214
215pub trait AnySnapshot: Send + 'static {
217 fn status(&self) -> Status;
218 fn output(&self) -> Option<Value>;
219 fn error(&self) -> Option<Value>;
220 fn fail(&mut self, error: Value);
223 fn timer_pending(&self, _key: &TimerKey) -> bool {
226 false
227 }
228 fn as_any(&self) -> &dyn Any;
229 fn as_any_mut(&mut self) -> &mut dyn Any;
230 fn clone_box(&self) -> Option<Box<dyn AnySnapshot>> {
233 None
234 }
235}
236
237#[derive(Debug, Clone)]
242pub struct FailedStart {
243 pub error: Value,
244}
245
246impl FailedStart {
247 fn data(&self) -> Value {
248 json!({ "status": "error", "error": self.error })
249 }
250
251 fn from_data(data: &Value) -> Option<Self> {
253 let o = data.as_object()?;
254 let bare = o.get("status") == Some(&Value::from("error")) && o.keys().all(|k| k == "status" || k == "error");
255 bare.then(|| Self { error: o.get("error").cloned().unwrap_or(Value::Null) })
256 }
257}
258
259impl AnySnapshot for FailedStart {
260 fn status(&self) -> Status {
261 Status::Error
262 }
263 fn output(&self) -> Option<Value> {
264 None
265 }
266 fn error(&self) -> Option<Value> {
267 Some(self.error.clone())
268 }
269 fn fail(&mut self, error: Value) {
270 self.error = error;
271 }
272 fn as_any(&self) -> &dyn Any {
273 self
274 }
275 fn as_any_mut(&mut self) -> &mut dyn Any {
276 self
277 }
278 fn clone_box(&self) -> Option<Box<dyn AnySnapshot>> {
279 Some(Box::new(self.clone()))
280 }
281}
282
283#[derive(Debug, Clone, PartialEq)]
287pub struct TransitionRejection {
288 pub source: String,
289 pub reasons: Vec<Value>,
290}
291
292impl Serialize for TransitionRejection {
293 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
294 let mut m = s.serialize_map(Some(2))?;
295 m.serialize_entry("source", &self.source)?;
296 m.serialize_entry("reasons", &self.reasons)?;
297 m.end()
298 }
299}
300
301#[derive(Debug, Clone, PartialEq)]
310pub enum TransitionCheck {
311 Accepted,
312 Unhandled,
313 Rejected(Vec<TransitionRejection>),
315 Partial(Vec<TransitionRejection>),
318}
319
320impl TransitionCheck {
321 pub fn status(&self) -> &'static str {
323 match self {
324 Self::Accepted => "accepted",
325 Self::Unhandled => "unhandled",
326 Self::Rejected(_) => "rejected",
327 Self::Partial(_) => "partial",
328 }
329 }
330
331 pub fn rejections(&self) -> &[TransitionRejection] {
333 match self {
334 Self::Rejected(r) | Self::Partial(r) => r,
335 Self::Accepted | Self::Unhandled => &[],
336 }
337 }
338
339 pub fn to_json(&self) -> Value {
341 serde_json::to_value(self).expect("a check serializes")
342 }
343}
344
345impl Serialize for TransitionCheck {
346 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
347 let rejections = self.rejections();
348 let mut m = s.serialize_map(Some(if rejections.is_empty() { 1 } else { 2 }))?;
349 m.serialize_entry("status", self.status())?;
350 if !rejections.is_empty() {
351 m.serialize_entry("rejections", rejections)?;
352 }
353 m.end()
354 }
355}
356
357pub trait Logic: Send + Sync + 'static {
359 fn version(&self) -> Option<&str> {
361 None
362 }
363 fn logic_id(&self) -> Option<String> {
365 None
366 }
367 fn snapshot_data(&self, snapshot: &dyn AnySnapshot) -> Value;
369 fn snapshot_serialize<'a>(
374 &'a self,
375 snapshot: &'a dyn AnySnapshot,
376 _compact: bool,
377 ) -> Box<dyn erased_serde::Serialize + 'a> {
378 Box::new(self.snapshot_data(snapshot))
379 }
380 fn initial_transition(&self, input: Option<&Value>, cx: &mut dyn Context) -> Result<Transition, SystemError>;
382 fn transition(
385 &self,
386 snapshot: &mut Box<dyn AnySnapshot>,
387 event: Value,
388 cx: &mut dyn Context,
389 ) -> Result<Vec<Effect>, SystemError>;
390 fn timer_transition(
394 &self,
395 snapshot: &mut Box<dyn AnySnapshot>,
396 key: TimerKey,
397 occurrence: Option<u64>,
398 cx: &mut dyn Context,
399 ) -> Result<Vec<Effect>, SystemError> {
400 self.transition(snapshot, TimerEvent::Key(key, occurrence).to_value(), cx)
401 }
402 fn restore(&self, data: &Value) -> Result<Box<dyn AnySnapshot>, SystemError>;
404 fn is_internal_event_type(&self, _event_type: &str) -> bool {
406 false
407 }
408 fn actor_sources(&self) -> Vec<(String, Arc<dyn Logic>)> {
410 Vec::new()
411 }
412 fn async_timeout(&self) -> Option<(Value, u64)> {
414 None
415 }
416 fn execution_error_event(&self, _snapshot: &dyn AnySnapshot, _error: &Value) -> Option<Value> {
422 None
423 }
424 fn check(
430 &self,
431 _snapshot: &dyn AnySnapshot,
432 _event: &Value,
433 _cx: &mut dyn Context,
434 ) -> Result<TransitionCheck, SystemError> {
435 Err(SystemError::Rejected("Only a machine's snapshot can check an event.".into()))
436 }
437 fn handles(&self, _snapshot: &dyn AnySnapshot, _event: &Value, _cx: &mut dyn Context) -> Result<bool, SystemError> {
443 Err(SystemError::Rejected("Only a machine's snapshot can check an event.".into()))
444 }
445}
446
447#[derive(Debug, Clone, Default)]
449pub struct AllocateOptions {
450 pub id: String,
451 pub input: Option<Value>,
452 pub parent: Option<ActorRef>,
453 pub registry_key: Option<String>,
454 pub sync_snapshot: Option<bool>,
455 pub defer_initialization: bool,
461}
462
463pub trait Context {
465 fn self_ref(&self) -> ActorRef;
467 fn parent_ref(&self) -> Option<ActorRef>;
469 fn self_id(&self) -> String;
471 fn now(&self) -> u64;
473 fn allocate(&mut self, logic: &Arc<dyn Logic>, options: AllocateOptions) -> Result<ActorRef, SystemError>;
476 fn initialize(&mut self, actor: &ActorRef, input: Option<Value>) -> Result<(), SystemError>;
480 fn status_of(&self, actor: &ActorRef) -> Status;
482 fn unregister(&mut self, actor: &ActorRef);
484 fn live_errors(&self) -> bool {
488 false
489 }
490}
491
492pub fn encode_address_segment(id: &str) -> String {
494 if id.contains('/') || id.contains('%') {
495 id.replace('%', "%25").replace('/', "%2F")
496 } else {
497 id.to_owned()
498 }
499}
500
501#[derive(Debug, Clone)]
503pub struct Message {
504 pub source: Option<ActorRef>,
505 pub target: ActorRef,
506 pub event: QueuedEvent,
507 pub sequence: u64,
508 pub timer_occurrence: Option<u64>,
509}
510
511#[derive(Debug, Clone, PartialEq)]
514pub enum QueuedEvent {
515 Value(Value),
516 Timer(TimerKey, Option<u64>),
518}
519
520impl QueuedEvent {
521 pub fn event_type(&self) -> &str {
522 match self {
523 Self::Value(v) => v.get("type").and_then(Value::as_str).unwrap_or(""),
524 Self::Timer(..) => TIMER,
525 }
526 }
527
528 pub fn to_value(&self) -> Value {
530 match self {
531 Self::Value(v) => v.clone(),
532 Self::Timer(key, occurrence) => TimerEvent::Key(key.clone(), *occurrence).to_value(),
533 }
534 }
535}
536
537#[derive(Debug, Clone, PartialEq)]
539pub struct SystemTimer {
540 pub source: ActorRef,
541 pub occurrence: u64,
542 pub scheduled_at: u64,
543 pub due_at: u64,
544 pub sequence: u64,
545 pub event: TimerEvent,
546}
547
548#[derive(Debug, Clone, PartialEq)]
552pub enum AfterDelay {
553 Number(serde_json::Number),
554 Name(String),
555}
556
557impl AfterDelay {
558 pub fn from_value(v: Value) -> Option<Self> {
560 match v {
561 Value::Number(n) => Some(Self::Number(n)),
562 Value::String(s) => Some(Self::Name(s)),
563 _ => None,
564 }
565 }
566
567 pub fn to_value(&self) -> Value {
568 match self {
569 Self::Number(n) => Value::Number(n.clone()),
570 Self::Name(s) => Value::String(s.clone()),
571 }
572 }
573
574 pub fn is(&self, v: &Value) -> bool {
576 match (self, v) {
577 (Self::Number(a), Value::Number(b)) => a == b,
578 (Self::Name(a), Value::String(b)) => a == b,
579 _ => false,
580 }
581 }
582
583 fn push(&self, out: &mut String) {
584 match self {
585 Self::Number(n) => {
586 use std::fmt::Write;
587 let _ = write!(out, "{n}");
588 }
589 Self::Name(s) => push_json_str(out, s),
590 }
591 }
592}
593
594impl Serialize for AfterDelay {
595 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
596 match self {
597 Self::Number(n) => n.serialize(s),
598 Self::Name(name) => name.serialize(s),
599 }
600 }
601}
602
603#[derive(Debug, Clone, PartialEq)]
607pub enum TimerKey {
608 Id(String),
610 Seq(u64),
612 After { delay: AfterDelay, state_id: String },
614 StateTimeout { state_id: String },
616 Event(Box<Value>),
618}
619
620impl TimerKey {
621 pub fn of_timer_event(event: &Value) -> Option<Self> {
624 if let Some(id) = event.get("id").and_then(Value::as_str) {
625 return Some(Self::Id(id.to_owned()));
626 }
627 if let Some(seq) = event.get("seq").filter(|v| v.is_number()) {
628 return seq.as_u64().map(Self::Seq);
629 }
630 match event.get("event") {
631 Some(e @ Value::Object(o)) if o.get("type").is_some_and(Value::is_string) => Some(Self::of_event(e)),
632 _ => None,
633 }
634 }
635
636 fn of_event(event: &Value) -> Self {
639 let has = |names: &[&str]| {
640 event.as_object().is_some_and(|o| o.len() == names.len() && names.iter().all(|n| o.contains_key(*n)))
641 };
642 let state_id = event.get("stateId").and_then(Value::as_str);
643 let delay = || event.get("delay").cloned().and_then(AfterDelay::from_value);
644 match (event.get("type").and_then(Value::as_str), state_id) {
645 (Some("xstate.after"), Some(id)) if has(&["type", "delay", "stateId"]) && delay().is_some() => {
646 Self::After { delay: delay().expect("checked"), state_id: id.to_owned() }
647 }
648 (Some("xstate.timeout.state"), Some(id)) if has(&["type", "stateId"]) => {
649 Self::StateTimeout { state_id: id.to_owned() }
650 }
651 _ => Self::Event(Box::new(event.clone())),
652 }
653 }
654
655 fn push(&self, out: &mut String) {
658 match self {
659 Self::Id(id) => {
660 out.push_str("id,");
661 push_json_str(out, id);
662 }
663 Self::Seq(n) => {
664 out.push_str("seq,");
665 out.push_str(itoa(*n, &mut [0; 20]));
666 }
667 Self::After { delay, state_id } => {
668 out.push_str("event,{\"type\":\"xstate.after\",\"delay\":");
669 delay.push(out);
670 out.push_str(",\"stateId\":");
671 push_json_str(out, state_id);
672 out.push('}');
673 }
674 Self::StateTimeout { state_id } => {
675 out.push_str("event,{\"type\":\"xstate.timeout.state\",\"stateId\":");
676 push_json_str(out, state_id);
677 out.push('}');
678 }
679 Self::Event(event) => {
680 out.push_str("event,");
681 push_event_identity(out, event);
682 }
683 }
684 }
685}
686
687#[derive(Debug, Clone, PartialEq)]
692pub enum TimerEvent {
693 Key(TimerKey, Option<u64>),
696 Other(Box<Value>),
698}
699
700const TIMER: &str = "xstate.timer";
701
702impl TimerEvent {
703 pub fn from_value(event: Value) -> Self {
706 match Self::typed(&event) {
707 Some((key, occurrence)) => Self::Key(key, occurrence),
708 None => Self::Other(Box::new(event)),
709 }
710 }
711
712 fn typed(event: &Value) -> Option<(TimerKey, Option<u64>)> {
713 let m = event.as_object()?;
714 let occurrence = match m.len() {
715 2 => None,
716 3 => {
717 let (k, v) = m.iter().nth(2)?;
718 if k != "occurrence" || !v.is_u64() {
719 return None;
720 }
721 v.as_u64()
722 }
723 _ => return None,
724 };
725 let mut entries = m.iter();
726 let (k, v) = entries.next()?;
727 if k != "type" || v.as_str() != Some(TIMER) {
728 return None;
729 }
730 let (k, v) = entries.next()?;
731 let in_order =
732 |o: &Map<String, Value>, names: &[&str]| o.len() == names.len() && o.keys().zip(names).all(|(k, n)| k == n);
733 let key = match k.as_str() {
734 "id" => v.as_str().map(|id| TimerKey::Id(id.to_owned())),
735 "seq" => v.as_u64().filter(|_| v.is_u64()).map(TimerKey::Seq),
736 "event" => {
737 let o = v.as_object()?;
738 o.get("type")?.as_str()?;
739 match TimerKey::of_event(v) {
740 TimerKey::After { .. } if !in_order(o, &["type", "delay", "stateId"]) => None,
743 TimerKey::StateTimeout { .. } if !in_order(o, &["type", "stateId"]) => None,
744 key => Some(key),
745 }
746 }
747 _ => None,
748 };
749 key.map(|key| (key, occurrence))
750 }
751
752 pub fn to_value(&self) -> Value {
754 match self {
755 Self::Other(v) => (**v).clone(),
756 Self::Key(..) => serde_json::to_value(self).expect("timer events serialize"),
757 }
758 }
759
760 fn machine_key(&self) -> Option<TimerKey> {
762 match self {
763 Self::Key(key, _) => Some(key.clone()),
764 Self::Other(v) if v.get("type").and_then(Value::as_str) == Some(TIMER) => TimerKey::of_timer_event(v),
765 Self::Other(_) => None,
766 }
767 }
768
769 fn is_machine_timer(&self) -> bool {
770 match self {
771 Self::Other(v) => v.get("type").and_then(Value::as_str) == Some(TIMER),
772 Self::Key(..) => true,
773 }
774 }
775
776 fn push_key(&self, out: &mut String) {
779 match self {
780 Self::Key(key, _) => key.push(out),
781 Self::Other(event) => {
782 let ty = event.get("type").and_then(Value::as_str);
783 if ty == Some(TIMER) {
784 if let Some(key) = TimerKey::of_timer_event(event) {
785 return key.push(out);
786 }
787 if let Some(seq) = event.get("seq").filter(|v| v.is_number()) {
788 out.push_str("seq,");
790 return push_json(out, seq);
791 }
792 }
793 push_json_str(out, ty.unwrap_or(""));
794 }
795 }
796 }
797}
798
799impl Serialize for TimerEvent {
800 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
801 struct Identity<'a>(&'static str, Option<&'a AfterDelay>, &'a str);
802 impl Serialize for Identity<'_> {
803 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
804 let mut m = s.serialize_map(Some(2 + usize::from(self.1.is_some())))?;
805 m.serialize_entry("type", self.0)?;
806 if let Some(delay) = self.1 {
807 m.serialize_entry("delay", delay)?;
808 }
809 m.serialize_entry("stateId", self.2)?;
810 m.end()
811 }
812 }
813 let (key, occurrence) = match self {
814 Self::Other(v) => return v.serialize(s),
815 Self::Key(key, occurrence) => (key, occurrence),
816 };
817 let mut m = s.serialize_map(Some(2 + usize::from(occurrence.is_some())))?;
818 m.serialize_entry("type", TIMER)?;
819 match key {
820 TimerKey::Id(id) => m.serialize_entry("id", id)?,
821 TimerKey::Seq(n) => m.serialize_entry("seq", n)?,
822 TimerKey::After { delay, state_id } => {
823 m.serialize_entry("event", &Identity("xstate.after", Some(delay), state_id))?
824 }
825 TimerKey::StateTimeout { state_id } => {
826 m.serialize_entry("event", &Identity("xstate.timeout.state", None, state_id))?
827 }
828 TimerKey::Event(event) => m.serialize_entry("event", &**event)?,
829 }
830 if let Some(occurrence) = occurrence {
831 m.serialize_entry("occurrence", occurrence)?;
832 }
833 m.end()
834 }
835}
836
837#[derive(Clone)]
839pub struct ExternalEffect {
840 pub id: String,
843 pub source: ActorRef,
844 pub ty: String,
845 pub kind: EffectKind,
846 pub params: Option<Value>,
847 pub args: Option<Vec<Value>>,
848 pub event: Option<Value>,
849 pub reason: Option<String>,
850 pub exec: Option<EffectExec>,
852}
853
854impl fmt::Debug for ExternalEffect {
855 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
856 f.write_str(&self.to_json().to_string())
857 }
858}
859
860impl ExternalEffect {
861 pub fn to_json(&self) -> Value {
863 let mut m = Map::new();
864 m.insert("id".into(), Value::String(self.id.clone()));
865 m.insert("source".into(), self.source.to_json());
866 m.insert("type".into(), Value::String(self.ty.clone()));
867 m.insert("kind".into(), Value::String(self.kind.as_str().into()));
868 if let Some(p) = &self.params {
869 m.insert("params".into(), p.clone());
870 }
871 if let Some(a) = &self.args {
872 m.insert("args".into(), Value::Array(a.clone()));
873 }
874 if let Some(e) = &self.event {
875 m.insert("event".into(), e.clone());
876 }
877 if let Some(r) = &self.reason {
878 m.insert("reason".into(), Value::String(r.clone()));
879 }
880 Value::Object(m)
881 }
882
883 fn from_json(value: &Value) -> Option<Self> {
884 Some(Self {
885 id: value.get("id")?.as_str()?.to_owned(),
886 source: ActorRef::from_json(value.get("source")?)?,
887 ty: value.get("type")?.as_str()?.to_owned(),
888 kind: match value.get("kind")?.as_str()? {
889 "builtin" => EffectKind::Builtin,
890 "emit" => EffectKind::Emit,
891 "action" => EffectKind::Action,
892 _ => return None,
893 },
894 params: value.get("params").cloned(),
895 args: value.get("args").and_then(Value::as_array).cloned(),
896 event: value.get("event").cloned(),
897 reason: value.get("reason").and_then(Value::as_str).map(str::to_owned),
898 exec: None,
899 })
900 }
901
902 pub fn run(&self) -> Result<bool, String> {
905 match &self.exec {
906 Some(exec) => exec().map(|()| true),
907 None => Ok(false),
908 }
909 }
910}
911
912struct ActorEntry {
913 id: String,
914 address: Arc<str>,
915 incarnation: u64,
916 src: std::borrow::Cow<'static, str>,
918 logic: Arc<dyn Logic>,
920 logic_version: Option<Box<str>>,
921 parent: Option<ActorRef>,
922 registry_key: Option<Box<str>>,
923 sync_snapshot: Option<bool>,
924 started: bool,
925 input: Option<Box<Value>>,
927 snapshot: Option<Box<dyn AnySnapshot>>,
929 status: Status,
930}
931
932impl ActorEntry {
933 fn try_clone(&self) -> Option<Self> {
935 let snapshot = match &self.snapshot {
936 Some(snapshot) => Some(snapshot.clone_box()?),
937 None => None,
938 };
939 Some(Self {
940 id: self.id.clone(),
941 address: self.address.clone(),
942 incarnation: self.incarnation,
943 src: self.src.clone(),
944 logic: self.logic.clone(),
945 logic_version: self.logic_version.clone(),
946 parent: self.parent.clone(),
947 registry_key: self.registry_key.clone(),
948 sync_snapshot: self.sync_snapshot,
949 started: self.started,
950 input: self.input.clone(),
951 snapshot,
952 status: self.status,
953 })
954 }
955
956 fn reference(&self) -> ActorRef {
957 ActorRef { address: self.address.clone(), incarnation: self.incarnation }
958 }
959
960 fn snapshot_data(&self, logic: Option<&Arc<dyn Logic>>) -> Value {
961 if let Some(failed) = self.snapshot.as_deref().and_then(|s| s.as_any().downcast_ref::<FailedStart>()) {
962 return failed.data();
963 }
964 match (&self.snapshot, logic) {
965 (Some(s), Some(l)) => l.snapshot_data(&**s),
966 _ => json!({ "status": self.status.as_str() }),
967 }
968 }
969}
970
971#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
972struct Counters {
973 actor: u64,
974 timer: u64,
975 sequence: u64,
976 effect: u64,
977}
978
979#[derive(Clone)]
982pub struct SystemLogic {
983 pub root: Arc<dyn Logic>,
984 pub actors: Vec<(String, Arc<dyn Logic>)>,
985}
986
987impl SystemLogic {
988 pub fn new(root: Arc<dyn Logic>) -> Self {
989 Self { root, actors: Vec::new() }
990 }
991}
992
993fn same_logic(a: &Arc<dyn Logic>, b: &Arc<dyn Logic>) -> bool {
994 std::ptr::eq(Arc::as_ptr(a) as *const (), Arc::as_ptr(b) as *const ())
995}
996
997type Definitions = Vec<(String, Arc<dyn Logic>)>;
1000
1001fn definitions(logic: &SystemLogic) -> Definitions {
1002 fn add(
1003 out: &mut Vec<(String, Arc<dyn Logic>)>,
1004 visited: &mut Vec<Arc<dyn Logic>>,
1005 key: String,
1006 logic: Arc<dyn Logic>,
1007 ) {
1008 match out.iter_mut().find(|(k, _)| *k == key) {
1009 Some(entry) => entry.1 = logic.clone(),
1010 None => out.push((key.clone(), logic.clone())),
1011 }
1012 if visited.iter().any(|v| same_logic(v, &logic)) {
1013 return;
1014 }
1015 visited.push(logic.clone());
1016 for (name, child) in logic.actor_sources() {
1017 add(out, visited, format!("{key}/actors/{}", encode_address_segment(&name)), child);
1018 }
1019 }
1020 let mut out = Vec::new();
1021 let mut visited = Vec::new();
1022 add(&mut out, &mut visited, "root".into(), logic.root.clone());
1023 for (key, l) in &logic.actors {
1024 add(&mut out, &mut visited, format!("actors/{}", encode_address_segment(key)), l.clone());
1025 }
1026 out
1027}
1028
1029pub(crate) fn has_builtin_timer_identity(event_type: &str) -> bool {
1033 matches!(event_type, "xstate.after" | "xstate.timeout.state" | "xstate.timeout.actor")
1034}
1035
1036fn push_json(out: &mut String, v: &Value) {
1038 use std::fmt::Write;
1039 match v {
1040 Value::String(s) => push_json_str(out, s),
1041 other => {
1042 let _ = write!(out, "{other}");
1043 }
1044 }
1045}
1046
1047fn push_json_str(out: &mut String, s: &str) {
1049 const HEX: &[u8; 16] = b"0123456789abcdef";
1050 out.reserve(s.len() + 2);
1051 out.push('"');
1052 let mut start = 0;
1053 for (i, b) in s.bytes().enumerate() {
1054 let escape = match b {
1055 b'"' => "\\\"",
1056 b'\\' => "\\\\",
1057 b'\n' => "\\n",
1058 b'\r' => "\\r",
1059 b'\t' => "\\t",
1060 0x08 => "\\b",
1061 0x0c => "\\f",
1062 0..=0x1f => "",
1063 _ => continue,
1064 };
1065 out.push_str(&s[start..i]);
1066 if escape.is_empty() {
1067 out.push_str("\\u00");
1068 out.push(HEX[usize::from(b >> 4)] as char);
1069 out.push(HEX[usize::from(b & 0xf)] as char);
1070 } else {
1071 out.push_str(escape);
1072 }
1073 start = i + 1;
1074 }
1075 out.push_str(&s[start..]);
1076 out.push('"');
1077}
1078
1079fn itoa(mut n: u64, buf: &mut [u8; 20]) -> &str {
1081 let mut i = buf.len();
1082 loop {
1083 i -= 1;
1084 buf[i] = b'0' + (n % 10) as u8;
1085 n /= 10;
1086 if n == 0 {
1087 break;
1088 }
1089 }
1090 std::str::from_utf8(&buf[i..]).expect("digits")
1091}
1092
1093fn push_event_identity(out: &mut String, event: &Value) {
1096 let fields: &[&str] = match event.get("type").and_then(Value::as_str) {
1097 Some("xstate.after") => &["delay", "stateId"],
1098 Some("xstate.timeout.state") => &["stateId"],
1099 Some("xstate.timeout.actor") => &["actorId"],
1100 _ => return push_json(out, event),
1101 };
1102 out.push_str("{\"type\":");
1103 push_json(out, &event["type"]);
1104 for f in fields {
1105 if let Some(v) = event.get(*f) {
1106 out.push_str(",\"");
1107 out.push_str(f);
1108 out.push_str("\":");
1109 push_json(out, v);
1110 }
1111 }
1112 out.push('}');
1113}
1114
1115fn system_timer_key(source: &ActorRef, event: &TimerEvent) -> String {
1117 let mut out = system_key_prefix(source);
1118 event.push_key(&mut out);
1119 out.shrink_to_fit();
1120 out
1121}
1122
1123fn system_timer_key_for(source: &ActorRef, key: &TimerKey) -> String {
1125 let mut out = system_key_prefix(source);
1126 key.push(&mut out);
1127 out
1128}
1129
1130fn system_key_prefix(source: &ActorRef) -> String {
1131 let mut out = String::with_capacity(64);
1132 push_json_str(&mut out, &source.address);
1133 out.push(',');
1134 out.push_str(itoa(source.incarnation, &mut [0; 20]));
1135 out.push(',');
1136 out
1137}
1138
1139pub const DEFAULT_MAX_STEPS: usize = 10_000;
1141
1142#[derive(Debug, Clone)]
1144pub struct InitOptions {
1145 pub input: Option<Value>,
1146 pub id: Option<String>,
1148 pub registry_key: Option<String>,
1149 pub execution_id: String,
1151 pub time: u64,
1152 pub max_steps: usize,
1155 pub observe_system_emitted: bool,
1159}
1160
1161impl Default for InitOptions {
1162 fn default() -> Self {
1163 Self {
1164 input: None,
1165 id: None,
1166 registry_key: None,
1167 execution_id: "system".into(),
1168 time: 0,
1169 max_steps: DEFAULT_MAX_STEPS,
1170 observe_system_emitted: false,
1171 }
1172 }
1173}
1174
1175fn definition_key(key: String) -> std::borrow::Cow<'static, str> {
1176 if key == "root" {
1177 std::borrow::Cow::Borrowed("root")
1178 } else {
1179 std::borrow::Cow::Owned(key)
1180 }
1181}
1182
1183fn execution_id(id: String) -> std::borrow::Cow<'static, str> {
1184 if id == "system" {
1185 std::borrow::Cow::Borrowed("system")
1186 } else {
1187 std::borrow::Cow::Owned(id)
1188 }
1189}
1190
1191#[derive(Default)]
1197struct ActorMap(Vec<ActorEntry>);
1198
1199impl ActorMap {
1200 fn get(&self, address: &str) -> Option<&ActorEntry> {
1201 #[cfg(feature = "op-counts")]
1202 self.scanned(address);
1203 self.0.iter().find(|a| *a.address == *address)
1204 }
1205
1206 fn get_mut(&mut self, address: &str) -> Option<&mut ActorEntry> {
1207 #[cfg(feature = "op-counts")]
1208 self.scanned(address);
1209 self.0.iter_mut().find(|a| *a.address == *address)
1210 }
1211
1212 fn get_key_value(&self, address: &str) -> Option<(&Arc<str>, &ActorEntry)> {
1213 self.get(address).map(|a| (&a.address, a))
1214 }
1215
1216 fn insert(&mut self, entry: ActorEntry) {
1218 match self.0.iter().position(|a| a.address == entry.address) {
1219 Some(i) => self.0[i] = entry,
1220 None => {
1221 self.0.reserve_exact(1);
1222 self.0.push(entry);
1223 }
1224 }
1225 }
1226
1227 #[cfg(feature = "op-counts")]
1229 fn scanned(&self, address: &str) {
1230 if crate::ops::enabled() {
1231 let n = self.0.iter().position(|a| *a.address == *address).map_or(self.0.len(), |i| i + 1);
1232 crate::ops::count_n(crate::ops::Op::ActorScan, n as u64);
1233 }
1234 }
1235
1236 fn len(&self) -> usize {
1237 self.0.len()
1238 }
1239
1240 fn iter(&self) -> impl Iterator<Item = (&Arc<str>, &ActorEntry)> {
1241 self.0.iter().map(|a| (&a.address, a))
1242 }
1243}
1244
1245pub type FixedState = std::hash::BuildHasherDefault<std::collections::hash_map::DefaultHasher>;
1258
1259pub struct System {
1261 logic: SystemLogic,
1265 defs: Option<Arc<Definitions>>,
1266 execution_id: std::borrow::Cow<'static, str>,
1268 root: Arc<str>,
1270 now: u64,
1271 actors: ActorMap,
1272 registry: IndexMap<String, ActorRef, FixedState>,
1273 messages: VecDeque<Message>,
1274 timers: IndexMap<String, SystemTimer, FixedState>,
1275 deadlines: BinaryHeap<Reverse<(u64, u64, u64)>>,
1276 external_effects: IndexMap<String, ExternalEffect, FixedState>,
1277 transient_effects: bool,
1282 keep_actions: bool,
1288 live_errors: bool,
1295 root_failure: Option<Box<SystemError>>,
1298 counters: Counters,
1299 max_steps: usize,
1300 scratch: Option<Box<Scratch>>,
1302 remaining: usize,
1303}
1304
1305#[derive(Default)]
1308struct Scratch {
1309 out: Vec<ExternalEffect>,
1310 initial_effects: FixedMap<ActorRef, Vec<Effect>>,
1311 stopping: FixedSet<ActorRef>,
1312 recovering: Vec<ActorRef>,
1315}
1316
1317impl System {
1318 pub fn initialize(logic: &SystemLogic, options: InitOptions) -> Result<(Self, Vec<ExternalEffect>), SystemError> {
1321 Self::initialize_with(logic, options, false, false)
1322 }
1323
1324 pub(crate) fn initialize_with(
1330 logic: &SystemLogic,
1331 options: InitOptions,
1332 live_errors: bool,
1333 keep_actions: bool,
1334 ) -> Result<(Self, Vec<ExternalEffect>), SystemError> {
1335 crate::ops::count(crate::ops::Op::SystemCall);
1336 let mut sys = Self {
1337 logic: logic.clone(),
1338 defs: None,
1339 execution_id: execution_id(options.execution_id.clone()),
1340 root: Arc::from(""),
1341 now: options.time,
1342 actors: ActorMap::default(),
1343 registry: IndexMap::default(),
1344 messages: VecDeque::new(),
1345 timers: IndexMap::default(),
1346 deadlines: BinaryHeap::new(),
1347 external_effects: IndexMap::default(),
1348 transient_effects: false,
1349 keep_actions,
1350 live_errors,
1351 root_failure: None,
1352 counters: Counters::default(),
1353 max_steps: options.max_steps.max(1),
1354 scratch: None,
1355 remaining: 0,
1356 };
1357 sys.begin();
1358 let id = options.id.or_else(|| logic.root.logic_id()).unwrap_or_else(|| "root".into());
1359 let root_logic = logic.root.clone();
1360 let root = sys.allocate(
1361 &root_logic,
1362 AllocateOptions { id, input: options.input, registry_key: options.registry_key, ..Default::default() },
1363 )?;
1364 sys.root = root.address.clone();
1365 sys.start(&root)?;
1366 sys.settle()?;
1367 let effects = sys_end(&mut sys);
1368 Ok((sys, effects))
1369 }
1370
1371 fn begin(&mut self) {
1372 if self.messages.capacity() == 0 {
1373 self.messages = take_message_queue();
1374 }
1375 self.remaining = self.max_steps;
1376 let scratch = self.scratch();
1377 scratch.out.clear();
1378 scratch.initial_effects.clear();
1379 scratch.stopping.clear();
1380 scratch.recovering.clear();
1381 }
1382
1383 fn scratch(&mut self) -> &mut Scratch {
1384 self.scratch.get_or_insert_with(take_scratch)
1385 }
1386
1387 fn step(&mut self) -> Result<(), SystemError> {
1388 if self.remaining == 0 {
1389 return Err(SystemError::MaxSteps);
1390 }
1391 self.remaining -= 1;
1392 Ok(())
1393 }
1394
1395 pub fn root(&self) -> &str {
1397 &self.root
1398 }
1399
1400 pub fn root_address(&self) -> &Arc<str> {
1402 &self.root
1403 }
1404
1405 pub fn now(&self) -> u64 {
1407 self.now
1408 }
1409
1410 pub fn next_deadline(&self) -> Option<u64> {
1412 self.deadlines.peek().map(|Reverse((due, _, _))| *due)
1414 }
1415
1416 pub(crate) fn timers_due_at(&self, at: u64) -> usize {
1419 self.timers.values().filter(|t| t.due_at == at).count()
1420 }
1421
1422 pub(crate) fn end_in_error(&mut self, error: Value) {
1428 if let Some(snapshot) = self.actors.get_mut(&self.root).and_then(|a| a.snapshot.as_mut()) {
1429 snapshot.fail(error);
1430 }
1431 if let Some(root) = self.actors.get_mut(&self.root) {
1432 root.status = Status::Error;
1433 }
1434 self.timers.clear();
1435 self.deadlines.clear();
1436 self.external_effects.retain(|_, e| e.kind == EffectKind::Action && !e.ty.starts_with("@xstate."));
1437 }
1438
1439 pub fn try_clone(&self) -> Option<Self> {
1444 let actors = self.actors.0.iter().map(ActorEntry::try_clone).collect::<Option<Vec<_>>>()?;
1445 Some(Self {
1446 logic: self.logic.clone(),
1447 defs: self.defs.clone(),
1448 execution_id: self.execution_id.clone(),
1449 root: self.root.clone(),
1450 now: self.now,
1451 actors: ActorMap(actors),
1452 registry: self.registry.clone(),
1453 messages: self.messages.clone(),
1454 timers: self.timers.clone(),
1455 deadlines: self.deadlines.clone(),
1456 external_effects: self.external_effects.clone(),
1457 transient_effects: self.transient_effects,
1458 keep_actions: self.keep_actions,
1459 live_errors: self.live_errors,
1460 root_failure: None,
1461 counters: self.counters,
1462 max_steps: self.max_steps,
1463 scratch: None,
1464 remaining: 0,
1465 })
1466 }
1467
1468 fn forget_deadline(&mut self, timer: &SystemTimer) {
1471 let entry = (timer.due_at, timer.sequence, timer.occurrence);
1472 self.deadlines.retain(|Reverse(e)| *e != entry);
1473 }
1474
1475 pub fn external_effects(&self) -> impl Iterator<Item = &ExternalEffect> {
1477 self.external_effects.values()
1478 }
1479
1480 pub fn actor_ref(&self, address: &str) -> Option<ActorRef> {
1482 self.actors.get(address).map(ActorEntry::reference)
1483 }
1484
1485 pub fn registry(&self) -> impl Iterator<Item = (&str, &ActorRef)> {
1487 self.registry.iter().map(|(k, v)| (k.as_str(), v))
1488 }
1489
1490 pub fn logic(&self) -> &SystemLogic {
1492 &self.logic
1493 }
1494
1495 pub fn actor_src(&self, address: &str) -> Option<&str> {
1498 self.actors.get(address).map(|a| &*a.src)
1499 }
1500
1501 pub fn actor_logic(&self, address: &str) -> Option<(Option<String>, Option<&Value>)> {
1504 let actor = self.actors.get(address)?;
1505 Some((actor.logic.logic_id(), actor.input.as_deref()))
1506 }
1507
1508 pub fn snapshot(&self, address: &str) -> Option<&dyn AnySnapshot> {
1510 self.actors.get(address)?.snapshot.as_deref()
1511 }
1512
1513 pub fn check(&self, address: &str, event: &Value) -> Result<TransitionCheck, SystemError> {
1518 let Some(actor) = self.actors.get(address) else {
1519 return rejected(format!("Unknown actor address '{address}'."));
1520 };
1521 let Some(snapshot) = actor.snapshot.as_deref() else {
1522 return Ok(TransitionCheck::Unhandled);
1523 };
1524 let mut cx = CheckCx { sys: self, self_ref: actor.reference() };
1525 actor.logic.check(snapshot, event, &mut cx)
1526 }
1527
1528 pub fn handles(&self, address: &str, event: &Value) -> Result<bool, SystemError> {
1531 let Some(actor) = self.actors.get(address) else {
1532 return rejected(format!("Unknown actor address '{address}'."));
1533 };
1534 let Some(snapshot) = actor.snapshot.as_deref() else {
1535 return Ok(false);
1536 };
1537 let mut cx = CheckCx { sys: self, self_ref: actor.reference() };
1538 actor.logic.handles(snapshot, event, &mut cx)
1539 }
1540
1541 fn recover_or_fail(&mut self, r: &ActorRef, error: SystemError) -> Result<(), SystemError> {
1553 let recovering = self.scratch().recovering.contains(r);
1554 let Some(entry) = self.current(r).filter(|a| a.status == Status::Active) else {
1555 return Ok(());
1556 };
1557 let logic = entry.logic.clone();
1558 let value = error.to_value();
1559 let event = if recovering {
1560 None
1561 } else {
1562 entry.snapshot.as_deref().and_then(|s| logic.execution_error_event(s, &value))
1563 };
1564 if let Some(event) = event {
1565 self.scratch().recovering.push(r.clone());
1566 let recovered = self.transition_now(r, &logic, event);
1567 self.scratch().recovering.pop();
1568 match recovered {
1569 Ok(()) => return Ok(()),
1570 Err(e) if !e.is_execution_error() => return Err(e),
1571 Err(_) => {}
1573 }
1574 }
1575 let Some(entry) = self.actors.get_mut(&r.address).filter(|a| a.incarnation == r.incarnation) else {
1576 return Ok(());
1577 };
1578 if entry.status != Status::Active {
1579 return Ok(());
1580 }
1581 entry.status = Status::Error;
1582 if let Some(snapshot) = entry.snapshot.as_mut() {
1583 snapshot.fail(value);
1584 }
1585 let root = entry.parent.is_none();
1586 self.error_actor(r)?;
1587 if root {
1588 self.root_failure.get_or_insert(Box::new(error));
1589 }
1590 Ok(())
1591 }
1592
1593 fn transition_now(&mut self, r: &ActorRef, logic: &Arc<dyn Logic>, event: Value) -> Result<(), SystemError> {
1596 let entry = self.actors.get_mut(&r.address).expect("current");
1597 let previous_status = entry.status;
1598 let mut snapshot = entry.snapshot.take().expect("snapshot present outside its transition");
1599 let result = {
1600 let mut cx = Cx { sys: self, self_ref: r.clone() };
1601 logic.transition(&mut snapshot, event, &mut cx)
1602 };
1603 let status = snapshot.status();
1604 self.store(r, snapshot);
1605 let effects = finalize(previous_status, false, status, result?);
1606 self.effects_for(r, effects)
1607 }
1608
1609 fn error_actor(&mut self, r: &ActorRef) -> Result<(), SystemError> {
1613 let children: Vec<ActorRef> = self
1614 .actors
1615 .iter()
1616 .map(|(_, a)| a)
1617 .filter(|a| a.parent.as_ref() == Some(r) && a.status == Status::Active)
1618 .map(ActorEntry::reference)
1619 .collect();
1620 for child in children {
1621 self.stop(&child)?;
1622 }
1623 self.terminate(r);
1624 Ok(())
1625 }
1626
1627 fn current(&self, r: &ActorRef) -> Option<&ActorEntry> {
1628 self.actors.get(&r.address).filter(|a| a.incarnation == r.incarnation)
1629 }
1630
1631 fn allocate(&mut self, logic: &Arc<dyn Logic>, options: AllocateOptions) -> Result<ActorRef, SystemError> {
1632 self.step()?;
1633 let src = if same_logic(logic, &self.logic.root) {
1635 "root".to_owned()
1636 } else {
1637 let defs = self.defs.get_or_insert_with(|| Arc::new(definitions(&self.logic)));
1638 let Some((src, _)) = defs.iter().find(|(_, l)| same_logic(l, logic)) else {
1639 return Err(SystemError::Failed("Register dynamically spawned logic in systemLogic.actors.".into()));
1640 };
1641 src.clone()
1642 };
1643 let segment = encode_address_segment(&options.id);
1644 let address: Arc<str> = match &options.parent {
1645 Some(p) => format!("{}/{}", p.address, segment).into(),
1646 None => segment.into(),
1647 };
1648 if let Some(occupied) = self.actors.get(&address) {
1649 if occupied.status == Status::Active {
1650 let previous = occupied.reference();
1651 if !self.scratch.as_ref().is_some_and(|s| s.stopping.contains(&previous)) {
1652 return Err(SystemError::Failed(format!("Actor address '{address}' is already occupied.")));
1653 }
1654 self.stop(&previous)?;
1655 }
1656 }
1657 let incarnation = self.counters.actor;
1658 self.counters.actor += 1;
1659 let r = ActorRef { address: address.clone(), incarnation };
1660 let entry = ActorEntry {
1661 id: options.id.clone(),
1662 address: address.clone(),
1663 incarnation,
1664 src: definition_key(src),
1665 logic: logic.clone(),
1666 logic_version: logic.version().map(Box::from),
1667 parent: options.parent.clone(),
1668 registry_key: options.registry_key.as_deref().map(Box::from),
1669 sync_snapshot: options.sync_snapshot,
1670 started: false,
1671 input: options.input.clone().map(Box::new),
1672 snapshot: None,
1673 status: Status::Active,
1674 };
1675 self.actors.insert(entry);
1677 if let Some(key) = &options.registry_key {
1678 if self.registry.contains_key(key) {
1679 return Err(SystemError::Failed(format!("Registry key '{key}' is already occupied.")));
1680 }
1681 self.registry.insert(key.clone(), r.clone());
1682 }
1683 if !options.defer_initialization {
1684 self.initialize_actor(&r, options.input)?;
1685 }
1686 Ok(r)
1687 }
1688
1689 fn initialize_actor(&mut self, r: &ActorRef, input: Option<Value>) -> Result<(), SystemError> {
1692 let Some(entry) = self.actors.get_mut(&r.address).filter(|a| a.incarnation == r.incarnation) else {
1693 return Err(SystemError::Failed(format!("Actor '{}' is not allocated.", r.address)));
1694 };
1695 entry.input = input.clone().map(Box::new);
1696 let logic = entry.logic.clone();
1697 let result = {
1698 let mut cx = Cx { sys: self, self_ref: r.clone() };
1699 logic.initial_transition(input.as_ref(), &mut cx)
1700 };
1701 let result = match result {
1702 Ok(result) => result,
1703 Err(e) if self.live_errors && e.is_execution_error() => {
1707 Transition { snapshot: Box::new(FailedStart { error: e.to_value() }), effects: Vec::new() }
1708 }
1709 Err(e) => return Err(e),
1710 };
1711 let effects = finalize(Status::Active, true, result.snapshot.status(), result.effects);
1712 self.store(r, result.snapshot);
1713 self.scratch().initial_effects.insert(r.clone(), effects);
1714 Ok(())
1715 }
1716
1717 fn store(&mut self, r: &ActorRef, snapshot: Box<dyn AnySnapshot>) {
1718 if let Some(entry) = self.actors.get_mut(&r.address).filter(|a| a.incarnation == r.incarnation) {
1719 entry.status = snapshot.status();
1720 entry.snapshot = Some(snapshot);
1721 }
1722 }
1723
1724 fn external(&mut self, r: &ActorRef, spec: ExternalSpec) -> Result<(), String> {
1728 let ty = match spec.ty {
1729 EffectType::Fixed(t) => t,
1730 EffectType::Action(name) => {
1731 let src = self.current(r).map(|a| a.src.clone()).unwrap_or_default();
1732 format!("{src}/actions/{}", encode_address_segment(&name))
1733 }
1734 };
1735 let transient = self.transient_effects
1736 && (spec.kind == EffectKind::Emit
1737 || spec.exec.is_some()
1738 || matches!(ty.as_str(), "@xstate.log" | "@xstate.cancelEffect" | "@xstate.cleanup"));
1739 let id = if transient { String::new() } else { format!("{}:{}", self.execution_id, self.counters.effect) };
1742 self.counters.effect += 1;
1743 if self.live_errors {
1744 if let Some(exec) = &spec.exec {
1745 return exec();
1746 }
1747 }
1748 let mut params = spec.params;
1749 if spec.kind == EffectKind::Emit && params.is_none() && !transient {
1750 let mut p = spec.event.as_ref().and_then(Value::as_object).cloned().unwrap_or_default();
1752 p.remove("type");
1753 params = Some(Value::Object(p));
1754 }
1755 let effect = ExternalEffect {
1756 id: id.clone(),
1757 source: r.clone(),
1758 ty,
1759 kind: spec.kind,
1760 params,
1761 args: Some(spec.args),
1762 event: spec.event,
1763 reason: spec.reason,
1764 exec: spec.exec,
1765 };
1766 if transient {
1767 self.scratch().out.push(effect);
1768 } else {
1769 crate::ops::count(crate::ops::Op::EffectStored);
1770 self.scratch().out.push(effect.clone());
1771 self.external_effects.insert(id, effect);
1772 }
1773 Ok(())
1774 }
1775
1776 pub fn max_steps(&self) -> usize {
1778 self.max_steps
1779 }
1780
1781 pub(crate) fn set_keep_actions(&mut self, on: bool) {
1783 self.keep_actions = on;
1784 }
1785
1786 pub(crate) fn set_transient_effects(&mut self, on: bool) {
1788 self.transient_effects = on;
1789 }
1790
1791 pub(crate) fn set_live_errors(&mut self, on: bool) {
1793 self.live_errors = on;
1794 }
1795
1796 pub(crate) fn take_root_failure(&mut self) -> Option<SystemError> {
1799 self.root_failure.take().map(|e| *e)
1800 }
1801
1802 fn enqueue(&mut self, source: Option<ActorRef>, target: ActorRef, event: Value, timer_occurrence: Option<u64>) {
1803 crate::ops::count(crate::ops::Op::Message);
1804 self.enqueue_event(source, target, QueuedEvent::Value(event), timer_occurrence);
1805 }
1806
1807 fn enqueue_event(
1808 &mut self,
1809 source: Option<ActorRef>,
1810 target: ActorRef,
1811 event: QueuedEvent,
1812 timer_occurrence: Option<u64>,
1813 ) {
1814 let sequence = self.counters.sequence;
1815 self.counters.sequence += 1;
1816 self.messages.push_back(Message { source, target, event, sequence, timer_occurrence });
1817 }
1818
1819 fn cancel(&mut self, r: &ActorRef, key: Option<&TimerKey>) {
1820 let cancelled = key.map(|k| system_timer_key_for(r, k));
1821 let mut removed = Vec::new();
1822 self.timers.retain(|timer_key, timer| {
1823 let keep = !(timer.source == *r && cancelled.as_ref().is_none_or(|c| c == timer_key));
1824 if !keep {
1825 removed.push((timer.due_at, timer.sequence, timer.occurrence));
1826 }
1827 keep
1828 });
1829 if !removed.is_empty() {
1830 self.deadlines.retain(|Reverse(e)| !removed.contains(e));
1831 }
1832 }
1833
1834 fn effects_for(&mut self, r: &ActorRef, effects: Vec<Effect>) -> Result<(), SystemError> {
1835 for effect in effects {
1836 match effect {
1837 Effect::Spawn(_) => {}
1838 Effect::Start(child) => self.start(&child)?,
1839 Effect::Stop(child) => self.stop(&child)?,
1840 Effect::Cancel(key) => self.cancel(r, Some(&key)),
1841 Effect::DelayedRaise { key, delay, occurrence } => {
1842 let pending =
1843 self.current(r).and_then(|a| a.snapshot.as_ref()).is_some_and(|s| s.timer_pending(&key));
1844 if pending {
1845 self.schedule(r, delay, TimerEvent::Key(key, Some(occurrence)))?;
1846 }
1847 }
1848 Effect::SendTo { target, event } => self.enqueue(Some(r.clone()), target, event, None),
1849 Effect::Terminate if self.live_errors && self.current(r).is_some_and(|a| a.status == Status::Error) => {
1853 self.error_actor(r)?
1854 }
1855 Effect::Terminate => self.terminate(r),
1856 Effect::External(spec) => {
1857 if let Err(message) = self.external(r, spec) {
1858 let error = SystemError::Failed(message);
1860 if self.scratch().recovering.last() == Some(r) {
1861 return Err(error);
1862 }
1863 return self.recover_or_fail(r, error);
1864 }
1865 }
1866 }
1867 }
1868 Ok(())
1869 }
1870
1871 fn schedule(&mut self, r: &ActorRef, delay: u64, event: TimerEvent) -> Result<(), SystemError> {
1872 let due_at = self.now.checked_add(delay).ok_or_else(|| {
1873 SystemError::Failed("System timer deadlines must be finite and delays nonnegative.".into())
1874 })?;
1875 let timer = SystemTimer {
1876 source: r.clone(),
1877 occurrence: self.counters.timer,
1878 scheduled_at: self.now,
1879 due_at,
1880 sequence: self.counters.sequence,
1881 event,
1882 };
1883 self.counters.timer += 1;
1884 self.counters.sequence += 1;
1885 let key = system_timer_key(r, &timer.event);
1886 if let Some(replaced) = self.timers.shift_remove(&key) {
1887 self.forget_deadline(&replaced);
1888 }
1889 if self.deadlines.len() == self.deadlines.capacity() {
1890 self.deadlines.reserve_exact(1);
1891 }
1892 self.deadlines.push(Reverse((timer.due_at, timer.sequence, timer.occurrence)));
1893 if self.timers.len() == self.timers.capacity() {
1894 self.timers.reserve_exact(1);
1895 }
1896 self.timers.insert(key, timer);
1897 Ok(())
1898 }
1899
1900 fn start(&mut self, r: &ActorRef) -> Result<(), SystemError> {
1901 let Some(actor) = self.current(r) else { return Ok(()) };
1902 if actor.started || actor.status == Status::Stopped {
1903 return Ok(());
1904 }
1905 let logic = actor.logic.clone();
1906 self.actors.get_mut(&r.address).expect("current").started = true;
1907 let effects = self.scratch.as_mut().and_then(|s| s.initial_effects.remove(r)).unwrap_or_default();
1908 self.effects_for(r, effects)?;
1909 let active = self.current(r).is_some_and(|a| a.status == Status::Active);
1910 if active {
1911 if let Some((timeout, delay)) = logic.async_timeout() {
1912 let shown = match &timeout {
1913 Value::String(s) => s.clone(),
1914 other => other.to_string(),
1915 };
1916 let error =
1917 json!({ "@error": "TimeoutError", "message": format!("Async logic timed out after {shown}.") });
1918 self.schedule(
1919 r,
1920 delay,
1921 TimerEvent::Other(Box::new(json!({ "type": "xstate.async.reject", "data": error }))),
1922 )?;
1923 }
1924 }
1925 Ok(())
1926 }
1927
1928 fn stop(&mut self, r: &ActorRef) -> Result<(), SystemError> {
1929 if !self.current(r).is_some_and(|a| a.status == Status::Active) {
1930 return Ok(());
1931 }
1932 let sequence = self.counters.sequence;
1933 self.counters.sequence += 1;
1934 self.process(Message {
1935 source: Some(r.clone()),
1936 target: r.clone(),
1937 event: QueuedEvent::Value(json!({ "type": "xstate.stop" })),
1938 sequence,
1939 timer_occurrence: None,
1940 })?;
1941 self.cancel(r, None);
1942 self.unregister(r);
1943 self.messages.retain(|m| m.target != *r);
1944 self.cancel_external(r);
1945 Ok(())
1946 }
1947
1948 fn unregister(&mut self, r: &ActorRef) {
1949 self.scratch().stopping.insert(r.clone());
1950 self.registry.retain(|_, v| v != r);
1951 }
1952
1953 fn cancel_external(&mut self, r: &ActorRef) {
1954 let ids: Vec<String> = self
1955 .external_effects
1956 .values()
1957 .filter(|e| {
1958 e.kind == EffectKind::Action
1959 && e.ty != "@xstate.cancelEffect"
1960 && e.ty != "@xstate.cleanup"
1961 && !(self.keep_actions && !e.ty.starts_with("@xstate."))
1962 && e.source == *r
1963 })
1964 .map(|e| e.id.clone())
1965 .collect();
1966 for id in ids {
1967 self.external_effects.shift_remove(&id);
1968 let cid = format!("{}:{}", self.execution_id, self.counters.effect);
1969 self.counters.effect += 1;
1970 let cancellation = ExternalEffect {
1971 id: cid.clone(),
1972 source: r.clone(),
1973 ty: "@xstate.cancelEffect".into(),
1974 kind: EffectKind::Action,
1975 params: Some(json!({ "effectId": id })),
1976 args: None,
1977 event: None,
1978 reason: None,
1979 exec: None,
1980 };
1981 self.scratch().out.push(cancellation.clone());
1982 self.external_effects.insert(cid, cancellation);
1983 }
1984 }
1985
1986 fn terminate(&mut self, r: &ActorRef) {
1987 let Some(actor) = self.current(r) else { return };
1988 let parent = actor.parent.clone();
1989 let id = actor.id.clone();
1990 let (status, output, error) = match &actor.snapshot {
1991 Some(s) => (s.status(), s.output(), s.error()),
1992 None => (actor.status, None, None),
1993 };
1994 self.cancel(r, None);
1995 self.cancel_external(r);
1996 if let Some(parent) = parent {
1997 let mut event = Map::new();
1998 if status == Status::Done {
1999 event.insert("type".into(), Value::String("xstate.done.actor".into()));
2000 if let Some(o) = output {
2001 event.insert("output".into(), o);
2002 }
2003 } else {
2004 event.insert("type".into(), Value::String("xstate.error.actor".into()));
2005 if let Some(e) = error {
2006 event.insert("error".into(), e);
2007 }
2008 }
2009 event.insert("actorId".into(), Value::String(id));
2010 event.insert("sessionId".into(), Value::String(r.incarnation.to_string()));
2011 self.enqueue(Some(r.clone()), parent, Value::Object(event), None);
2012 }
2013 }
2014
2015 fn process(&mut self, message: Message) -> Result<(), SystemError> {
2016 self.step()?;
2017 let Some(actor) = self.current(&message.target) else { return Ok(()) };
2018 if actor.status != Status::Active {
2019 return Ok(());
2020 }
2021 let event_type = message.event.event_type();
2022 if event_type == "xstate.timer" && message.timer_occurrence.is_none() {
2023 return Err(SystemError::Failed("Only the system scheduler may deliver a timer occurrence.".into()));
2024 }
2025 let logic = actor.logic.clone();
2026 if logic.is_internal_event_type(event_type) && message.source.as_ref() != Some(&message.target) {
2027 return Err(SystemError::Failed(format!(
2028 "Internal event '{event_type}' cannot be injected into a pure system."
2029 )));
2030 }
2031 if message.source.is_none()
2032 && (event_type == "xstate.after"
2033 || event_type.starts_with("xstate.after.")
2034 || event_type == "xstate.timeout"
2035 || event_type.starts_with("xstate.timeout."))
2036 {
2037 return Err(SystemError::Failed("Select a pending timer instead of injecting its internal event.".into()));
2038 }
2039 let target = message.target.clone();
2040 let entry = self.actors.get_mut(&target.address).expect("current");
2041 let previous_status = entry.status;
2042 let mut snapshot = entry.snapshot.take().expect("snapshot present outside its transition");
2043 let result = {
2044 let mut cx = Cx { sys: self, self_ref: target.clone() };
2045 match message.event {
2046 QueuedEvent::Value(event) => logic.transition(&mut snapshot, event, &mut cx),
2047 QueuedEvent::Timer(key, occurrence) => logic.timer_transition(&mut snapshot, key, occurrence, &mut cx),
2048 }
2049 };
2050 let effects = match result {
2051 Ok(effects) => effects,
2052 Err(e) => {
2053 self.store(&target, snapshot);
2054 if self.live_errors && e.is_execution_error() {
2057 return self.recover_or_fail(&target, e);
2058 }
2059 return Err(e);
2060 }
2061 };
2062 let status = snapshot.status();
2063 let effects = finalize(previous_status, false, status, effects);
2064 let reports_snapshot = self
2066 .current(&target)
2067 .is_some_and(|a| a.sync_snapshot == Some(true) && a.parent.is_some() && status == Status::Active);
2068 let data_for_parent = reports_snapshot.then(|| logic.snapshot_data(&*snapshot));
2069 self.store(&target, snapshot);
2070 self.effects_for(&target, effects)?;
2071 if let Some(actor) = self.current(&target) {
2072 if actor.sync_snapshot == Some(true) && status == Status::Active && actor.status == Status::Active {
2074 if let Some(parent) = actor.parent.clone() {
2075 let event = json!({
2076 "type": "xstate.snapshot.actor",
2077 "actorId": actor.id,
2078 "sessionId": actor.incarnation.to_string(),
2079 "snapshot": data_for_parent.unwrap_or(Value::Null),
2080 });
2081 self.enqueue(Some(target.clone()), parent, event, None);
2082 }
2083 }
2084 }
2085 Ok(())
2086 }
2087
2088 fn settle(&mut self) -> Result<(), SystemError> {
2089 while let Some(message) = self.messages.pop_front() {
2090 self.process(message)?;
2091 }
2092 Ok(())
2093 }
2094
2095 fn advance_to(&mut self, time: u64) -> Result<(), SystemError> {
2096 if time < self.now {
2097 return rejected("System time must be finite and cannot move backwards.");
2098 }
2099 self.settle()?;
2100 while self.fire_one(time)? {}
2101 self.now = time;
2102 Ok(())
2103 }
2104
2105 fn fire_one(&mut self, time: u64) -> Result<bool, SystemError> {
2108 while let Some(&Reverse((due, sequence, occurrence))) = self.deadlines.peek() {
2109 if due > time {
2112 return Ok(false);
2113 }
2114 let current_key = self
2115 .timers
2116 .iter()
2117 .find(|(_, t)| t.occurrence == occurrence && t.sequence == sequence)
2118 .map(|(k, _)| k.clone());
2119 let Some(key) = current_key else {
2120 self.deadlines.pop();
2121 continue;
2122 };
2123 if due > time {
2124 return Ok(false);
2125 }
2126 self.step()?;
2127 self.deadlines.pop();
2128 let timer = self.timers.shift_remove(&key).expect("found");
2129 self.now = self.now.max(timer.due_at);
2130 let Some(actor) = self.current(&timer.source) else { return Ok(true) };
2131 if actor.status != Status::Active {
2132 return Ok(true);
2133 }
2134 if timer.event.is_machine_timer() {
2135 let key = timer.event.machine_key();
2136 let pending = match (&key, &actor.snapshot) {
2137 (Some(k), Some(s)) => s.timer_pending(k),
2138 _ => false,
2139 };
2140 if !pending {
2141 return Ok(true);
2142 }
2143 }
2144 let event = match timer.event {
2145 TimerEvent::Other(event) => QueuedEvent::Value(*event),
2146 TimerEvent::Key(key, occurrence) => QueuedEvent::Timer(key, occurrence),
2147 };
2148 self.enqueue_event(Some(timer.source.clone()), timer.source.clone(), event, Some(timer.occurrence));
2149 self.settle()?;
2150 return Ok(true);
2151 }
2152 Ok(false)
2153 }
2154
2155 pub fn fire_next_timer(&mut self, time: u64) -> Result<Option<Vec<ExternalEffect>>, SystemError> {
2159 crate::ops::count(crate::ops::Op::SystemCall);
2160 self.begin();
2161 if time < self.now {
2162 return rejected("System time must be finite and cannot move backwards.");
2163 }
2164 self.settle()?;
2165 let fired = self.fire_one(time)?;
2166 let effects = sys_end(self);
2167 Ok(fired.then_some(effects))
2168 }
2169
2170 pub fn advance(&mut self, time: u64) -> Result<Vec<ExternalEffect>, SystemError> {
2173 crate::ops::count(crate::ops::Op::SystemCall);
2174 self.begin();
2175 self.advance_to(time)?;
2176 Ok(sys_end(self))
2177 }
2178
2179 pub fn send(&mut self, address: &str, event: Value) -> Result<Vec<ExternalEffect>, SystemError> {
2182 crate::ops::count(crate::ops::Op::SystemCall);
2183 self.begin();
2184 let ty = event.get("type").and_then(Value::as_str).unwrap_or("");
2185 if ty == "xstate.timer" {
2186 let Some(actor) = self.actors.get(address) else {
2187 return rejected(format!("Unknown actor address '{address}'."));
2188 };
2189 let r = actor.reference();
2190 let occurrence = event.get("occurrence").and_then(Value::as_u64);
2191 let Some(due) =
2192 self.timers.values().find(|t| t.source == r && Some(t.occurrence) == occurrence).map(|t| t.due_at)
2193 else {
2194 return rejected("Select a current timer occurrence.");
2195 };
2196 self.advance_to(due)?;
2197 return Ok(sys_end(self));
2198 }
2199 self.advance_to(self.now)?;
2200 let Some(actor) = self.actors.get(address) else {
2201 return rejected(format!("Unknown actor address '{address}'."));
2202 };
2203 let r = actor.reference();
2204 let status = actor.status;
2205 if ty == "xstate.system.effect.result" {
2206 let effect_id = event.get("effectId").and_then(Value::as_str).unwrap_or("");
2207 let inner = event.get("event").cloned();
2208 let valid = self.external_effects.get(effect_id).is_some_and(|e| {
2209 *e.source.address == *address
2210 && (inner.is_none()
2211 || (e.source.incarnation == r.incarnation
2212 && status == Status::Active
2213 && e.ty != "@xstate.cancelEffect"
2214 && e.ty != "@xstate.cleanup"))
2215 });
2216 if !valid {
2217 return rejected("External effect result does not match its owner or is stale.");
2218 }
2219 self.external_effects.shift_remove(effect_id);
2220 if let Some(inner) = inner {
2221 self.enqueue(Some(r.clone()), r, inner, None);
2222 self.settle()?;
2223 }
2224 return Ok(sys_end(self));
2225 }
2226 if ty == "xstate.stop" {
2227 self.stop(&r)?;
2228 self.settle()?;
2229 return Ok(sys_end(self));
2230 }
2231 if ty.starts_with("xstate.async.") || ty.starts_with("xstate.logic.effect.") {
2232 return rejected("Deliver external work results with xstate.system.effect.result.");
2233 }
2234 self.enqueue(None, r, event, None);
2235 self.settle()?;
2236 Ok(sys_end(self))
2237 }
2238
2239 pub fn resolve_effect(
2242 &mut self,
2243 effect_id: &str,
2244 event: Option<Value>,
2245 ) -> Result<Vec<ExternalEffect>, SystemError> {
2246 crate::ops::count(crate::ops::Op::SystemCall);
2247 let Some(effect) = self.external_effects.get(effect_id) else {
2248 return rejected("External effect result does not match its owner or is stale.");
2249 };
2250 let address = effect.source.address.to_string();
2251 let mut result = json!({ "type": "xstate.system.effect.result", "effectId": effect_id });
2252 if let Some(e) = event {
2253 result["event"] = e;
2254 }
2255 self.send(&address, result)
2256 }
2257
2258 pub fn acknowledge(&mut self, effect_id: &str) -> bool {
2262 !self.external_effects.is_empty() && self.external_effects.shift_remove(effect_id).is_some()
2263 }
2264
2265 pub fn to_json(&self) -> Value {
2267 let mut actors = Map::new();
2268 for (address, a) in self.actors.iter() {
2269 let mut m = Map::new();
2270 m.insert("id".into(), Value::String(a.id.clone()));
2271 m.insert("address".into(), Value::String(address.to_string()));
2272 m.insert("incarnation".into(), Value::String(a.incarnation.to_string()));
2273 m.insert("src".into(), Value::String(a.src.to_string()));
2274 if let Some(v) = &a.logic_version {
2275 m.insert("logicVersion".into(), Value::String(v.to_string()));
2276 }
2277 if let Some(p) = &a.parent {
2278 m.insert("parent".into(), p.to_json());
2279 }
2280 if let Some(k) = &a.registry_key {
2281 m.insert("registryKey".into(), Value::String(k.to_string()));
2282 }
2283 if let Some(s) = a.sync_snapshot {
2284 m.insert("syncSnapshot".into(), Value::Bool(s));
2285 }
2286 m.insert("started".into(), Value::Bool(a.started));
2287 if let Some(i) = &a.input {
2288 m.insert("input".into(), (**i).clone());
2289 }
2290 m.insert("snapshot".into(), a.snapshot_data(Some(&a.logic)));
2291 actors.insert(address.to_string(), Value::Object(m));
2292 }
2293 let registry: Map<String, Value> = self.registry.iter().map(|(k, v)| (k.clone(), v.to_json())).collect();
2294 let timers: Vec<Value> = self
2295 .timers
2296 .values()
2297 .map(|t| {
2298 json!({
2299 "source": t.source.to_json(),
2300 "occurrence": t.occurrence,
2301 "scheduledAt": t.scheduled_at,
2302 "dueAt": t.due_at,
2303 "sequence": t.sequence,
2304 "event": t.event.to_value(),
2305 })
2306 })
2307 .collect();
2308 let effects: Map<String, Value> = self.external_effects.iter().map(|(k, e)| (k.clone(), e.to_json())).collect();
2309 let messages: Vec<Value> = self
2310 .messages
2311 .iter()
2312 .map(|m| {
2313 let mut o = Map::new();
2314 if let Some(s) = &m.source {
2315 o.insert("source".into(), s.to_json());
2316 }
2317 o.insert("target".into(), m.target.to_json());
2318 o.insert("event".into(), m.event.to_value());
2319 o.insert("sequence".into(), json!(m.sequence));
2320 if let Some(t) = m.timer_occurrence {
2321 o.insert("timerOccurrence".into(), json!(t));
2322 }
2323 Value::Object(o)
2324 })
2325 .collect();
2326 let mut counters = Map::with_capacity(4);
2329 counters.insert("actor".into(), Value::from(self.counters.actor));
2330 counters.insert("timer".into(), Value::from(self.counters.timer));
2331 counters.insert("sequence".into(), Value::from(self.counters.sequence));
2332 counters.insert("effect".into(), Value::from(self.counters.effect));
2333 let mut out = Map::with_capacity(9);
2334 out.insert("root".into(), Value::String(self.root.to_string()));
2335 out.insert("executionId".into(), Value::String(self.execution_id.to_string()));
2336 out.insert("now".into(), Value::from(self.now));
2337 out.insert("actors".into(), Value::Object(actors));
2338 out.insert("registry".into(), Value::Object(registry));
2339 out.insert("messages".into(), Value::Array(messages));
2340 out.insert("timers".into(), Value::Array(timers));
2341 out.insert("externalEffects".into(), Value::Object(effects));
2342 out.insert("counters".into(), Value::Object(counters));
2343 Value::Object(out)
2344 }
2345
2346 pub fn from_json(logic: &SystemLogic, data: &Value, max_steps: usize) -> Result<Self, SystemError> {
2348 let bad = |what: &str| SystemError::Rejected(format!("invalid system snapshot: {what}"));
2349 let defs = definitions(logic);
2350 let mut actors = ActorMap::default();
2351 for (address, a) in data.get("actors").and_then(Value::as_object).ok_or_else(|| bad("actors"))? {
2352 let src = a.get("src").and_then(Value::as_str).ok_or_else(|| bad("src"))?.to_owned();
2353 let l = defs
2354 .iter()
2355 .find(|(k, _)| *k == src)
2356 .map(|(_, l)| l.clone())
2357 .ok_or_else(|| SystemError::Rejected(format!("Missing actor definition '{src}'.")))?;
2358 let logic_version = a.get("logicVersion").and_then(Value::as_str).map(str::to_owned);
2359 if logic_version.as_deref() != l.version() {
2360 return Err(SystemError::Rejected(format!("Actor definition/version mismatch for '{address}'.")));
2361 }
2362 let data = a.get("snapshot").ok_or_else(|| bad("snapshot"))?;
2363 let snapshot = match l.restore(data) {
2364 Ok(snapshot) => snapshot,
2365 Err(e) => match FailedStart::from_data(data) {
2366 Some(failed) => Box::new(failed),
2367 None => return Err(e),
2368 },
2369 };
2370 let address: Arc<str> = address.as_str().into();
2371 actors.insert(ActorEntry {
2372 id: a.get("id").and_then(Value::as_str).ok_or_else(|| bad("id"))?.to_owned(),
2373 address,
2374 incarnation: a
2375 .get("incarnation")
2376 .and_then(Value::as_str)
2377 .and_then(|s| s.parse().ok())
2378 .ok_or_else(|| bad("incarnation"))?,
2379 src: definition_key(src),
2380 logic: l,
2381 logic_version: logic_version.map(Box::from),
2382 parent: a.get("parent").and_then(ActorRef::from_json),
2383 registry_key: a.get("registryKey").and_then(Value::as_str).map(Box::from),
2384 sync_snapshot: a.get("syncSnapshot").and_then(Value::as_bool),
2385 started: a.get("started").and_then(Value::as_bool).unwrap_or(false),
2386 input: a.get("input").cloned().map(Box::new),
2387 status: snapshot.status(),
2388 snapshot: Some(snapshot),
2389 });
2390 }
2391 let registry = data
2392 .get("registry")
2393 .and_then(Value::as_object)
2394 .map(|m| m.iter().filter_map(|(k, v)| Some((k.clone(), ActorRef::from_json(v)?))).collect())
2395 .unwrap_or_default();
2396 let mut timers = IndexMap::default();
2397 let mut deadlines = BinaryHeap::new();
2398 for t in data.get("timers").and_then(Value::as_array).into_iter().flatten() {
2399 let timer = SystemTimer {
2400 source: ActorRef::from_json(t.get("source").ok_or_else(|| bad("timer source"))?)
2401 .ok_or_else(|| bad("timer source"))?,
2402 occurrence: t.get("occurrence").and_then(Value::as_u64).ok_or_else(|| bad("occurrence"))?,
2403 scheduled_at: t.get("scheduledAt").and_then(Value::as_u64).unwrap_or(0),
2404 due_at: t.get("dueAt").and_then(Value::as_u64).ok_or_else(|| bad("dueAt"))?,
2405 sequence: t.get("sequence").and_then(Value::as_u64).unwrap_or(0),
2406 event: TimerEvent::from_value(t.get("event").cloned().ok_or_else(|| bad("timer event"))?),
2407 };
2408 deadlines.push(Reverse((timer.due_at, timer.sequence, timer.occurrence)));
2409 timers.insert(system_timer_key(&timer.source, &timer.event), timer);
2410 }
2411 let mut external_effects = IndexMap::default();
2412 for (id, e) in data.get("externalEffects").and_then(Value::as_object).into_iter().flatten() {
2413 external_effects.insert(id.clone(), ExternalEffect::from_json(e).ok_or_else(|| bad("effect"))?);
2414 }
2415 let message = |m: &Value| {
2416 Some(Message {
2417 source: match m.get("source") {
2418 None => None,
2419 Some(r) => Some(ActorRef::from_json(r)?),
2420 },
2421 target: ActorRef::from_json(m.get("target")?)?,
2422 event: QueuedEvent::Value(m.get("event")?.clone()),
2423 sequence: m.get("sequence")?.as_u64()?,
2424 timer_occurrence: match m.get("timerOccurrence") {
2425 None => None,
2426 Some(n) => Some(n.as_u64()?),
2427 },
2428 })
2429 };
2430 let messages = match data.get("messages") {
2431 None => VecDeque::new(),
2432 Some(Value::Array(items)) => {
2433 items.iter().map(|m| message(m).ok_or_else(|| bad("message"))).collect::<Result<_, _>>()?
2434 }
2435 Some(_) => return Err(bad("messages")),
2436 };
2437 let c = data.get("counters").ok_or_else(|| bad("counters"))?;
2438 let counter = |k: &str| c.get(k).and_then(Value::as_u64).unwrap_or(0);
2439 Ok(Self {
2440 logic: logic.clone(),
2441 defs: None,
2442 execution_id: execution_id(data.get("executionId").and_then(Value::as_str).unwrap_or("system").to_owned()),
2443 root: {
2444 let root = data.get("root").and_then(Value::as_str).unwrap_or("");
2445 actors.get_key_value(root).map_or_else(|| Arc::from(root), |(k, _)| k.clone())
2446 },
2447 now: data.get("now").and_then(Value::as_u64).unwrap_or(0),
2448 actors,
2449 registry,
2450 messages,
2451 timers,
2452 deadlines,
2453 external_effects,
2454 transient_effects: false,
2455 keep_actions: false,
2456 live_errors: false,
2457 root_failure: None,
2458 counters: Counters {
2459 actor: counter("actor"),
2460 timer: counter("timer"),
2461 sequence: counter("sequence"),
2462 effect: counter("effect"),
2463 },
2464 max_steps: max_steps.max(1),
2465 scratch: None,
2466 remaining: 0,
2467 })
2468 }
2469}
2470
2471fn sys_end(sys: &mut System) -> Vec<ExternalEffect> {
2472 if sys.messages.is_empty() {
2476 return_message_queue(std::mem::take(&mut sys.messages));
2477 }
2478 let Some(mut scratch) = sys.scratch.take() else { return Vec::new() };
2479 let out = std::mem::take(&mut scratch.out);
2480 return_scratch(scratch);
2481 out
2482}
2483
2484thread_local! {
2485 #[allow(clippy::vec_box)]
2488 static SCRATCH: std::cell::RefCell<Vec<Box<Scratch>>> = const { std::cell::RefCell::new(Vec::new()) };
2489}
2490
2491fn take_scratch() -> Box<Scratch> {
2492 SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default()
2493}
2494
2495fn return_scratch(mut scratch: Box<Scratch>) {
2496 if scratch.initial_effects.capacity() > 64 || scratch.stopping.capacity() > 64 {
2497 return;
2498 }
2499 scratch.initial_effects.clear();
2500 scratch.stopping.clear();
2501 let _ = SCRATCH.try_with(|p| {
2503 let mut pool = p.borrow_mut();
2504 if pool.len() < 16 {
2505 pool.push(scratch);
2506 }
2507 });
2508}
2509
2510thread_local! {
2511 static MESSAGE_QUEUES: std::cell::RefCell<Vec<VecDeque<Message>>> = const { std::cell::RefCell::new(Vec::new()) };
2513}
2514
2515fn take_message_queue() -> VecDeque<Message> {
2516 MESSAGE_QUEUES.with(|p| p.borrow_mut().pop()).unwrap_or_default()
2517}
2518
2519fn return_message_queue(queue: VecDeque<Message>) {
2520 if queue.capacity() > 0 && queue.capacity() <= 64 {
2521 let _ = MESSAGE_QUEUES.try_with(|p| {
2523 let mut pool = p.borrow_mut();
2524 if pool.len() < 16 {
2525 pool.push(queue);
2526 }
2527 });
2528 }
2529}
2530
2531fn finalize(previous: Status, initial: bool, status: Status, mut effects: Vec<Effect>) -> Vec<Effect> {
2534 let became_terminal = matches!(status, Status::Done | Status::Error);
2535 let was_terminal = !initial && matches!(previous, Status::Done | Status::Error);
2536 if became_terminal && !was_terminal && !effects.iter().any(|e| matches!(e, Effect::Terminate)) {
2537 effects.push(Effect::Terminate);
2538 }
2539 effects
2540}
2541
2542struct Cx<'a> {
2543 sys: &'a mut System,
2544 self_ref: ActorRef,
2545}
2546
2547impl Context for Cx<'_> {
2548 fn self_ref(&self) -> ActorRef {
2549 self.self_ref.clone()
2550 }
2551
2552 fn now(&self) -> u64 {
2553 self.sys.now
2554 }
2555
2556 fn parent_ref(&self) -> Option<ActorRef> {
2557 self.sys.current(&self.self_ref).and_then(|a| a.parent.clone())
2558 }
2559
2560 fn self_id(&self) -> String {
2561 self.sys.current(&self.self_ref).map(|a| a.id.clone()).unwrap_or_default()
2562 }
2563
2564 fn allocate(&mut self, logic: &Arc<dyn Logic>, options: AllocateOptions) -> Result<ActorRef, SystemError> {
2565 self.sys.allocate(logic, options)
2566 }
2567
2568 fn initialize(&mut self, actor: &ActorRef, input: Option<Value>) -> Result<(), SystemError> {
2569 self.sys.initialize_actor(actor, input)
2570 }
2571
2572 fn status_of(&self, actor: &ActorRef) -> Status {
2573 self.sys.current(actor).map_or(Status::Stopped, |a| a.status)
2574 }
2575
2576 fn unregister(&mut self, actor: &ActorRef) {
2577 self.sys.unregister(actor);
2578 }
2579
2580 fn live_errors(&self) -> bool {
2581 self.sys.live_errors
2582 }
2583}
2584
2585struct CheckCx<'a> {
2588 sys: &'a System,
2589 self_ref: ActorRef,
2590}
2591
2592impl Context for CheckCx<'_> {
2593 fn self_ref(&self) -> ActorRef {
2594 self.self_ref.clone()
2595 }
2596
2597 fn now(&self) -> u64 {
2598 self.sys.now
2599 }
2600
2601 fn parent_ref(&self) -> Option<ActorRef> {
2602 self.sys.current(&self.self_ref).and_then(|a| a.parent.clone())
2603 }
2604
2605 fn self_id(&self) -> String {
2606 self.sys.current(&self.self_ref).map(|a| a.id.clone()).unwrap_or_default()
2607 }
2608
2609 fn allocate(&mut self, _logic: &Arc<dyn Logic>, _options: AllocateOptions) -> Result<ActorRef, SystemError> {
2610 Err(SystemError::Failed("A check cannot create actors.".into()))
2611 }
2612
2613 fn initialize(&mut self, _actor: &ActorRef, _input: Option<Value>) -> Result<(), SystemError> {
2614 Err(SystemError::Failed("A check cannot create actors.".into()))
2615 }
2616
2617 fn status_of(&self, actor: &ActorRef) -> Status {
2618 self.sys.current(actor).map_or(Status::Stopped, |a| a.status)
2619 }
2620
2621 fn unregister(&mut self, _actor: &ActorRef) {}
2622
2623 fn live_errors(&self) -> bool {
2624 self.sys.live_errors
2625 }
2626}
2627
2628pub fn parse_status(data: &Value) -> Result<Status, SystemError> {
2630 data.get("status")
2631 .and_then(Value::as_str)
2632 .and_then(Status::parse)
2633 .ok_or_else(|| SystemError::Rejected("snapshot data has no valid status".into()))
2634}
2635
2636pub fn downcast<T: 'static>(snapshot: &dyn AnySnapshot) -> Option<&T> {
2638 snapshot.as_any().downcast_ref::<T>()
2639}
2640
2641pub struct SystemView<'a> {
2645 sys: &'a System,
2646 compact: bool,
2647}
2648
2649struct RefView<'a>(&'a ActorRef);
2650
2651impl Serialize for RefView<'_> {
2652 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2653 let mut m = s.serialize_map(Some(2))?;
2654 m.serialize_entry("@actor", &*self.0.address)?;
2655 m.serialize_entry("incarnation", &self.0.incarnation.to_string())?;
2656 m.end()
2657 }
2658}
2659
2660struct EntryView<'a>(&'a ActorEntry, bool);
2661
2662impl Serialize for EntryView<'_> {
2663 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2664 let (a, compact) = (self.0, self.1);
2665 let len = 6 - usize::from(compact)
2667 + usize::from(a.logic_version.is_some())
2668 + usize::from(a.parent.is_some())
2669 + usize::from(a.registry_key.is_some())
2670 + usize::from(a.sync_snapshot.is_some())
2671 + usize::from(a.input.is_some());
2672 let mut m = s.serialize_map(Some(len))?;
2673 m.serialize_entry("id", &a.id)?;
2674 if !compact {
2675 m.serialize_entry("address", &*a.address)?;
2676 }
2677 m.serialize_entry("incarnation", &a.incarnation.to_string())?;
2678 m.serialize_entry("src", &*a.src)?;
2679 if let Some(v) = &a.logic_version {
2680 m.serialize_entry("logicVersion", &**v)?;
2681 }
2682 if let Some(p) = &a.parent {
2683 m.serialize_entry("parent", &RefView(p))?;
2684 }
2685 if let Some(k) = &a.registry_key {
2686 m.serialize_entry("registryKey", &**k)?;
2687 }
2688 if let Some(v) = a.sync_snapshot {
2689 m.serialize_entry("syncSnapshot", &v)?;
2690 }
2691 m.serialize_entry("started", &a.started)?;
2692 if let Some(i) = &a.input {
2693 m.serialize_entry("input", i)?;
2694 }
2695 match &a.snapshot {
2696 Some(snap) if !snap.as_any().is::<FailedStart>() => {
2697 m.serialize_entry("snapshot", &*a.logic.snapshot_serialize(&**snap, compact))?
2698 }
2699 _ => m.serialize_entry("snapshot", &a.snapshot_data(Some(&a.logic)))?,
2700 }
2701 m.end()
2702 }
2703}
2704
2705struct ActorsView<'a>(&'a System, bool);
2706
2707impl Serialize for ActorsView<'_> {
2708 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2709 let mut m = s.serialize_map(Some(self.0.actors.len()))?;
2710 for (address, a) in self.0.actors.iter() {
2711 m.serialize_entry(&**address, &EntryView(a, self.1))?;
2712 }
2713 m.end()
2714 }
2715}
2716
2717struct TimerView<'a>(&'a SystemTimer);
2718
2719impl Serialize for TimerView<'_> {
2720 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2721 let t = self.0;
2722 let mut m = s.serialize_map(Some(6))?;
2723 m.serialize_entry("source", &RefView(&t.source))?;
2724 m.serialize_entry("occurrence", &t.occurrence)?;
2725 m.serialize_entry("scheduledAt", &t.scheduled_at)?;
2726 m.serialize_entry("dueAt", &t.due_at)?;
2727 m.serialize_entry("sequence", &t.sequence)?;
2728 m.serialize_entry("event", &t.event)?;
2729 m.end()
2730 }
2731}
2732
2733struct Seq<I>(std::cell::RefCell<Option<I>>);
2734
2735impl<I: Iterator<Item = T>, T: Serialize> Serialize for Seq<I> {
2736 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2737 let items = self.0.borrow_mut().take().expect("serialized once");
2738 let len = match items.size_hint() {
2739 (low, Some(high)) if low == high => Some(low),
2740 _ => None,
2741 };
2742 let mut seq = s.serialize_seq(len)?;
2743 for item in items {
2744 seq.serialize_element(&item)?;
2745 }
2746 seq.end()
2747 }
2748}
2749
2750impl Serialize for SystemView<'_> {
2751 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2752 let (sys, compact) = (self.sys, self.compact);
2753 let keep_execution_id = !compact || sys.execution_id != "system";
2756 let (keep_registry, keep_messages, keep_timers, keep_effects) = if compact {
2757 (
2758 !sys.registry.is_empty(),
2759 !sys.messages.is_empty(),
2760 !sys.timers.is_empty(),
2761 !sys.external_effects.is_empty(),
2762 )
2763 } else {
2764 (true, true, true, true)
2765 };
2766 let len = 4 + [keep_execution_id, keep_registry, keep_messages, keep_timers, keep_effects]
2767 .iter()
2768 .filter(|k| **k)
2769 .count();
2770 let mut m = s.serialize_map(Some(len))?;
2771 m.serialize_entry("root", &*sys.root)?;
2772 if keep_execution_id {
2773 m.serialize_entry("executionId", &sys.execution_id)?;
2774 }
2775 m.serialize_entry("now", &sys.now)?;
2776 m.serialize_entry("actors", &ActorsView(sys, compact))?;
2777 if keep_registry {
2778 m.serialize_entry("registry", &RegistryView(&sys.registry))?;
2779 }
2780 let rest = if sys.messages.is_empty() && sys.external_effects.is_empty() { None } else { Some(sys.to_json()) };
2782 if keep_messages {
2783 match &rest {
2784 Some(v) => m.serialize_entry("messages", &v["messages"])?,
2785 None => m.serialize_entry("messages", &[(); 0])?,
2786 }
2787 }
2788 if keep_timers {
2789 m.serialize_entry("timers", &Seq(std::cell::RefCell::new(Some(sys.timers.values().map(TimerView)))))?;
2790 }
2791 if keep_effects {
2792 match &rest {
2793 Some(v) => m.serialize_entry("externalEffects", &v["externalEffects"])?,
2794 None => m.serialize_entry("externalEffects", &Map::new())?,
2795 }
2796 }
2797 m.serialize_entry("counters", &CountersView(&sys.counters))?;
2798 m.end()
2799 }
2800}
2801
2802struct RegistryView<'a>(&'a IndexMap<String, ActorRef, FixedState>);
2803
2804impl Serialize for RegistryView<'_> {
2805 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2806 s.collect_map(self.0.iter().map(|(k, r)| (k, RefView(r))))
2807 }
2808}
2809
2810struct CountersView<'a>(&'a Counters);
2811
2812impl Serialize for CountersView<'_> {
2813 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2814 let c = self.0;
2815 let mut m = s.serialize_map(Some(4))?;
2816 m.serialize_entry("actor", &c.actor)?;
2817 m.serialize_entry("timer", &c.timer)?;
2818 m.serialize_entry("sequence", &c.sequence)?;
2819 m.serialize_entry("effect", &c.effect)?;
2820 m.end()
2821 }
2822}
2823
2824impl System {
2825 pub fn view(&self) -> SystemView<'_> {
2828 SystemView { sys: self, compact: false }
2829 }
2830
2831 pub fn compact_view(&self) -> SystemView<'_> {
2839 SystemView { sys: self, compact: true }
2840 }
2841}
2842
2843#[cfg(test)]
2844mod tests {
2845 use super::*;
2846
2847 #[test]
2848 fn timer_keys() {
2849 let r = ActorRef { address: "a".into(), incarnation: 0 };
2850 let key = |event: Value| system_timer_key(&r, &TimerEvent::from_value(event));
2851 let seq = key(json!({"type":"xstate.timer","seq":0}));
2852 assert_eq!(seq, system_timer_key_for(&r, &TimerKey::Seq(0)));
2853 assert_eq!(seq, r#""a",0,seq,0"#);
2854 assert_ne!(seq, key(json!({"type":"xstate.timer","id":"0"})));
2855 let after = json!({"type":"xstate.after","delay":10,"stateId":"m.a","extra":1});
2856 let k = key(json!({"type":"xstate.timer","event":after}));
2857 let pattern = json!({"event":{"stateId":"m.a","type":"xstate.after","delay":10}});
2858 let ten = AfterDelay::Number(10.into());
2859 assert_eq!(TimerKey::of_timer_event(&pattern), Some(TimerKey::After { delay: ten, state_id: "m.a".into() }));
2860 assert_eq!(k, system_timer_key_for(&r, &TimerKey::of_timer_event(&pattern).unwrap()));
2861 assert_eq!(k, r#""a",0,event,{"type":"xstate.after","delay":10,"stateId":"m.a"}"#);
2862 let typed = json!({"type":"xstate.timer","event":{"type":"xstate.after","delay":"short","stateId":"m.a"}});
2864 assert!(matches!(TimerEvent::from_value(typed.clone()), TimerEvent::Key(TimerKey::After { .. }, None)));
2865 assert_eq!(key(typed.clone()), r#""a",0,event,{"type":"xstate.after","delay":"short","stateId":"m.a"}"#);
2866 assert_eq!(
2867 key(json!({"type":"xstate.timer","seq":1.5})),
2868 r#""a",0,seq,1.5"#,
2869 "a seq that is not a whole number keeps its own key"
2870 );
2871 assert_eq!(key(json!({"type":"xstate.async.reject"})), r#""a",0,"xstate.async.reject""#);
2872 let escaped = ActorRef { address: "q\"\\\n\u{1}é".into(), incarnation: 12 };
2873 assert_eq!(
2874 system_timer_key_for(&escaped, &TimerKey::Id("i".into())),
2875 format!("{},12,id,\"i\"", Value::String("q\"\\\n\u{1}é".into()))
2876 );
2877 for event in [
2878 typed,
2879 json!({"type":"xstate.timer","id":"t"}),
2880 json!({"type":"xstate.timer","seq":3}),
2881 json!({"type":"xstate.timer","seq":1.5}),
2882 json!({"type":"xstate.timer","event":{"type":"xstate.timeout.state","stateId":"m.b"}}),
2883 json!({"type":"xstate.timer","event":{"stateId":"m.b","type":"xstate.timeout.state"}}),
2884 json!({"type":"xstate.timer","event":{"type":"xstate.timeout.actor","actorId":"c","sessionId":"1"}}),
2885 json!({"type":"xstate.timer","event":{"type":"custom","x":1}}),
2886 json!({"type":"xstate.async.reject","data":{}}),
2887 json!({"seq":3,"type":"xstate.timer"}),
2888 ] {
2889 let parsed = TimerEvent::from_value(event.clone());
2890 assert_eq!(parsed.to_value().to_string(), event.to_string());
2891 assert_eq!(serde_json::to_string(&parsed).unwrap(), event.to_string());
2892 let expected = TimerKey::of_timer_event(&event).filter(|_| event["type"] == TIMER);
2893 assert_eq!(parsed.machine_key(), expected);
2894 assert_eq!(
2895 system_timer_key(&r, &parsed),
2896 system_timer_key(&r, &TimerEvent::Other(Box::new(event.clone())))
2897 );
2898 }
2899 assert_eq!(encode_address_segment("a/b%"), "a%2Fb%25");
2900 }
2901}