Skip to main content

xmachines_runtime/
migrate.rs

1//! Moving persisted actors from an earlier version of a machine onto the
2//! current one.
3//!
4//! A [`Migration`] rewrites a persisted system snapshot (XState's
5//! `SystemSnapshot`, as [`crate::System::to_json`] writes it) before it is
6//! restored: the root actor's state ids (its configuration, recorded
7//! history and the events of its pending timers, in the machine snapshot and
8//! in the system's timers, and the keys of its state inputs), a shallow patch
9//! merged into its context, and its
10//! `logicVersion`. The configuration is then completed for the new
11//! definition (ancestors of the mapped states, and the initial states of
12//! compound states left without an active child, all regions of parallel
13//! ones) and put in document order, as a fresh entry would order it. Like
14//! any restore, it runs no actions.
15
16use std::collections::BTreeSet;
17
18use indexmap::IndexMap;
19use serde::Deserialize;
20use serde_json::{Map, Value};
21
22use crate::core::{Kind, Nid};
23use crate::machine::Machine;
24use crate::system::FixedState;
25
26/// How snapshots of one earlier machine version become snapshots of the
27/// current one.
28#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
29#[serde(deny_unknown_fields)]
30pub struct Migration {
31    /// Earlier state id to current state id (`#` optional on both sides).
32    /// Ids that are not listed are kept.
33    #[serde(default)]
34    pub states: IndexMap<String, String, FixedState>,
35    /// Merged into the root actor's context (an object), key by key.
36    #[serde(default)]
37    pub context: Map<String, Value>,
38}
39
40fn bare(id: &str) -> &str {
41    id.strip_prefix('#').unwrap_or(id)
42}
43
44impl Migration {
45    fn map<'a>(&'a self, id: &'a str) -> &'a str {
46        self.states.get(id).or_else(|| self.states.get(&format!("#{id}"))).map_or(id, |to| bare(to))
47    }
48
49    /// Checks the migration against the current machine `to` (every target
50    /// exists) and, when the earlier definition is known, against it: every
51    /// mapped id exists there, and every earlier state that the current
52    /// machine lacks is mapped.
53    pub fn check<C, E, C2, E2>(&self, from: Option<&Machine<C, E>>, to: &Machine<C2, E2>) -> Result<(), String> {
54        for (old, new) in &self.states {
55            if to.node_by_id(bare(new)).is_none() {
56                return Err(format!(
57                    "migration target \"{new}\" (for \"{old}\") is not a state of the current machine"
58                ));
59            }
60            if let Some(from) = from {
61                if from.node_by_id(bare(old)).is_none() {
62                    return Err(format!("migrated state \"{old}\" is not a state of the earlier machine"));
63                }
64            }
65        }
66        if let Some(from) = from {
67            let unmapped: Vec<&str> = from
68                .state_ids()
69                .filter(|id| to.node_by_id(id).is_none() && self.map(id) == *id)
70                .filter(|id| !matches!(from.tree.kind(from.node_by_id(id).expect("own id")), Kind::History { .. }))
71                .collect();
72            if !unmapped.is_empty() {
73                return Err(format!(
74                    "states of the earlier machine missing from the current one need a mapping: {}",
75                    unmapped.join(", ")
76                ));
77            }
78        }
79        Ok(())
80    }
81
82    /// Rewrites `snapshot` (a whole system snapshot) for the machine `to`.
83    pub fn apply<C, E>(&self, snapshot: &mut Value, to: &Machine<C, E>) -> Result<(), String> {
84        let root = snapshot.get("root").and_then(Value::as_str).ok_or("the snapshot has no root")?.to_owned();
85        let actor = snapshot
86            .get_mut("actors")
87            .and_then(|a| a.get_mut(&root))
88            .and_then(Value::as_object_mut)
89            .ok_or("the snapshot has no root actor")?;
90        match to.version() {
91            Some(v) => actor.insert("logicVersion".into(), Value::String(v.to_owned())),
92            None => actor.remove("logicVersion"),
93        };
94        let data = actor.get_mut("snapshot").and_then(Value::as_object_mut).ok_or("the root actor has no snapshot")?;
95
96        if let Some(ids) = data.get("nodeIds").and_then(Value::as_array) {
97            let mut nodes = BTreeSet::new();
98            for id in ids {
99                let id = self.map(id.as_str().ok_or("a state id is not a string")?);
100                let n =
101                    to.node_by_id(id).ok_or_else(|| format!("state \"{id}\" does not exist in the current machine"))?;
102                nodes.insert(n);
103            }
104            let nodes = complete(to, nodes);
105            data.insert("nodeIds".into(), nodes.iter().map(|&n| Value::String(to.data(n).id.clone())).collect());
106            // Restore derives the value from the configuration.
107            data.remove("value");
108        }
109        if let Some(Value::Object(history)) = data.get_mut("historyValue") {
110            // Recorded history the current machine cannot hold is dropped:
111            // the history state then enters its default target.
112            let old = std::mem::take(history);
113            for (h, mut recorded) in old {
114                let h = self.map(&h);
115                let mut known = to.node_by_id(h).is_some();
116                for r in recorded.as_array_mut().into_iter().flatten() {
117                    if let Some(Value::String(id)) = r.get_mut("@stateNode") {
118                        *id = self.map(id).to_owned();
119                        known &= to.node_by_id(id).is_some();
120                    }
121                }
122                if known {
123                    history.insert(h.to_owned(), recorded);
124                }
125            }
126        }
127        if let Some(Value::Object(inputs)) = data.get_mut("stateInputs") {
128            // State inputs follow their states; those of states the current
129            // machine lacks are dropped.
130            let old = std::mem::take(inputs);
131            for (id, input) in old {
132                let id = self.map(&id);
133                if to.node_by_id(id).is_some() {
134                    inputs.insert(id.to_owned(), input);
135                }
136            }
137        }
138        for t in data.get_mut("timers").and_then(Value::as_array_mut).into_iter().flatten() {
139            self.map_event(t.get_mut("event"));
140        }
141        if !self.context.is_empty() {
142            match data.get_mut("context") {
143                Some(Value::Object(context)) => {
144                    for (k, v) in &self.context {
145                        context.insert(k.clone(), v.clone());
146                    }
147                }
148                _ => return Err("a context patch needs an object context".into()),
149            }
150        }
151        // The system's own timers of the root carry the same events.
152        for t in snapshot.get_mut("timers").and_then(Value::as_array_mut).into_iter().flatten() {
153            if t.get("source").and_then(|s| s.get("@actor")).and_then(Value::as_str) == Some(&root) {
154                if let Some(event) = t.get_mut("event") {
155                    self.map_event(event.get_mut("event"));
156                }
157            }
158        }
159        Ok(())
160    }
161
162    /// Maps the `stateId` of a lifecycle timer event.
163    fn map_event(&self, event: Option<&mut Value>) {
164        if let Some(Value::String(id)) = event.and_then(|e| e.get_mut("stateId")) {
165            *id = self.map(id).to_owned();
166        }
167    }
168}
169
170/// `nodes` with their ancestors and default descendants (initial states,
171/// all regions), in document order.
172fn complete<C, E>(m: &Machine<C, E>, mut nodes: BTreeSet<Nid>) -> BTreeSet<Nid> {
173    for n in nodes.clone() {
174        let mut p = m.tree.node(n).parent;
175        while let Some(a) = p {
176            nodes.insert(a);
177            p = m.tree.node(a).parent;
178        }
179    }
180    let mut pending: Vec<Nid> = nodes.iter().copied().collect();
181    while let Some(n) = pending.pop() {
182        let children = &m.tree.node(n).children;
183        let defaults: Vec<Nid> = match m.tree.kind(n) {
184            Kind::Compound if !children.iter().any(|c| nodes.contains(c)) => m.data(n).initial.to_vec(),
185            Kind::Parallel => children.iter().copied().filter(|c| !nodes.contains(c)).collect(),
186            _ => Vec::new(),
187        };
188        for d in defaults {
189            if nodes.insert(d) {
190                pending.push(d);
191            }
192        }
193    }
194    nodes
195}