xmachines_runtime/
migrate.rs1use 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#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
29#[serde(deny_unknown_fields)]
30pub struct Migration {
31 #[serde(default)]
34 pub states: IndexMap<String, String, FixedState>,
35 #[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 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 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 data.remove("value");
108 }
109 if let Some(Value::Object(history)) = data.get_mut("historyValue") {
110 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 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 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 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
170fn 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}