Skip to main content

cls_eedi/engine/device/
recovery.rs

1//! Application-owned crash recovery records and invariants.
2use super::*;
3
4impl Provisioning {
5    fn byte_limit(&self) -> usize {
6        // A journal entry fits its original wire message plus metadata. Extra slots
7        // cover provisioning, state and JSON framing.
8        self.capacity
9            .saturating_add(4)
10            .saturating_mul(crate::wire::MAX_MESSAGE_BYTES + 2048)
11    }
12}
13
14// A repeated ledger key would silently replace the earlier equipment outcome in a
15// plain BTreeMap deserialization. Treat an ambiguous journal as damaged.
16pub(super) fn read_ledger<'de, D>(input: D) -> Result<BTreeMap<String, Entry>, D::Error>
17where
18    D: serde::Deserializer<'de>,
19{
20    use serde::de::{Error, MapAccess, Visitor};
21    struct Entries;
22    impl<'de> Visitor<'de> for Entries {
23        type Value = BTreeMap<String, Entry>;
24
25        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26            f.write_str("a journal with unique IDs")
27        }
28        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
29            let mut entries = BTreeMap::new();
30            while let Some((id, entry)) = map.next_entry()? {
31                if entries.insert(id, entry).is_some() {
32                    return Err(A::Error::custom("duplicate journal ID"));
33                }
34            }
35            Ok(entries)
36        }
37    }
38    input.deserialize_map(Entries)
39}
40
41impl Checkpoint {
42    fn validate(&self, expected: &Provisioning) -> Result<(), EngineError> {
43        if self.version != 4
44            || &self.provisioning != expected
45            || self.ledger.len() > expected.capacity
46            || self.last_utc < 0
47            || self
48                .state
49                .measurements
50                .as_ref()
51                .is_some_and(|m| m.len() > expected.capacity)
52            || (expected.subsequent && self.state.trust.is_some())
53            || (self.trust_revision != 0) != self.state.trust.is_some()
54        {
55            return Err(EngineError::Checkpoint);
56        }
57        let validate = |message: Message| {
58            message
59                .encode()
60                .map(|_| ())
61                .map_err(|_| EngineError::Checkpoint)
62        };
63        validate(Message::new(
64            "validate",
65            &expected.source,
66            Payload::State(self.state.clone()),
67        ))?;
68        for (end, limit) in self.deadlines.0.into_iter().zip([
69            self.state
70                .limits
71                .as_ref()
72                .and_then(|p| p.consumption.as_ref()),
73            self.state
74                .limits
75                .as_ref()
76                .and_then(|p| p.production.as_ref()),
77        ]) {
78            let duration = limit.and_then(|l| l.duration);
79            let consistent = match (end, duration) {
80                (None, None) => true,
81                (Some(end), Some(duration)) => end
82                    .checked_sub(u64::from(duration))
83                    .is_some_and(|start| start <= self.last_tick),
84                _ => false,
85            };
86            if !consistent {
87                return Err(EngineError::Checkpoint);
88            }
89        }
90        if let Some(next) = self.next_notification {
91            let interval = self
92                .state
93                .notify
94                .as_ref()
95                .and_then(|n| n.interval)
96                .ok_or(EngineError::Checkpoint)?;
97            if next.saturating_sub(self.last_tick) > u64::from(interval) {
98                return Err(EngineError::Checkpoint);
99            }
100        }
101
102        let mut occupied = [false; 4];
103        for (id, entry) in &self.ledger {
104            if entry.received > self.last_tick {
105                return Err(EngineError::Checkpoint);
106            }
107            match (&entry.execution, entry.finished) {
108                (Execution::Done(0 | 2 | 3 | 4), Some(finished))
109                    if (entry.received..=self.last_tick).contains(&finished) =>
110                {
111                    if !entry.related {
112                        ack(&expected.source, id, 0).map_err(|_| EngineError::Checkpoint)?;
113                    }
114                }
115                (Execution::Pending { command, .. }, None) => {
116                    if expected.subsequent && command.trust.is_some() {
117                        return Err(EngineError::Checkpoint);
118                    }
119                    let requested = families(command);
120                    if !requested.contains(&true) {
121                        return Err(EngineError::Checkpoint);
122                    }
123                    for (busy, family) in occupied.iter_mut().zip(requested) {
124                        if *busy && family {
125                            return Err(EngineError::Checkpoint);
126                        }
127                        *busy |= family;
128                    }
129                    let mut message = Message::new(id, "", command.clone());
130                    if entry.related {
131                        message = message.related_to("");
132                    }
133                    validate(message)?;
134                    Deadlines::default()
135                        .update(command, entry.received)
136                        .map_err(|_| EngineError::Checkpoint)?;
137                }
138                _ => return Err(EngineError::Checkpoint),
139            }
140        }
141        Ok(())
142    }
143}
144
145impl LocalDevice {
146    /// Create a point-in-time checkpoint. It can contain pairing secrets. Store atomically
147    /// under application access controls, before actuation and before sending its acknowledgement.
148    pub fn checkpoint(&mut self, now: Clock) -> Result<Vec<u8>, EngineError> {
149        self.tick(now)?;
150        let bytes = serde_json::to_vec(&self.journal).map_err(|_| EngineError::Checkpoint)?;
151        if bytes.len() > self.journal.provisioning.byte_limit() {
152            return Err(EngineError::Capacity);
153        }
154        Ok(bytes)
155    }
156
157    /// Resume from an application-controlled checkpoint using externally provisioned identity,
158    /// target kind, capacity and replay window. Use a fresh engine and synchronized UTC.
159    /// Commit checkpoints atomically with one writer per route and protect them against rollback.
160    /// Recovered pending operations remain blocked from dispatch until equipment confirms their outcome.
161    pub fn restore(mut self, bytes: &[u8], now: Clock) -> Result<Self, EngineError> {
162        let byte_limit = self.journal.provisioning.byte_limit();
163        if bytes.len() > byte_limit {
164            return Err(EngineError::Checkpoint);
165        }
166        let mut journal: Checkpoint =
167            serde_json::from_slice(bytes).map_err(|_| EngineError::Checkpoint)?;
168        journal.validate(&self.journal.provisioning)?;
169        let downtime = now
170            .unix_seconds
171            .checked_sub(journal.last_utc)
172            .and_then(|t| u64::try_from(t).ok())
173            .ok_or(EngineError::Clock)?;
174        self.origin = now.elapsed_seconds;
175        self.offset = journal
176            .last_tick
177            .checked_add(downtime)
178            .ok_or(EngineError::Clock)?;
179        for entry in journal.ledger.values_mut() {
180            if let Execution::Pending { reconcile, .. } = &mut entry.execution {
181                *reconcile = true;
182            }
183            // Downtime ages physical limits, but cannot alone authorize a repeated write.
184            if let Some(finished) = &mut entry.finished {
185                *finished = finished.checked_add(downtime).ok_or(EngineError::Clock)?;
186            }
187        }
188        self.journal = journal;
189        self.awaiting_control = None;
190        self.tick(now)?;
191        Ok(self)
192    }
193}