Skip to main content

cls_eedi/engine/backend/
recovery.rs

1//! Backend recovery stores confirmed settings and outstanding control requests.
2//! Observations and read requests belong to the prior connection and must be refreshed.
3use super::*;
4use serde::{de::Error as _, Deserializer};
5use serde_json::value::RawValue;
6
7#[derive(Serialize, Deserialize)]
8#[serde(deny_unknown_fields)]
9struct Journal {
10    version: u8,
11    route: String,
12    source: String,
13    capacity: usize,
14    tick: u64,
15    utc: i64,
16    #[serde(deserialize_with = "bounded::<_, _, 6>")]
17    confirmed: Vec<Submitted>,
18    #[serde(deserialize_with = "bounded::<_, _, 4>")]
19    outstanding: Vec<(String, Submitted)>,
20}
21
22// Limit the number of decoded entries before building an attacker-sized journal model.
23fn bounded<'de, D, T, const MAX: usize>(d: D) -> Result<Vec<T>, D::Error>
24where
25    D: Deserializer<'de>,
26    T: Deserialize<'de>,
27{
28    use serde::de::{SeqAccess, Visitor};
29    struct Items<T, const MAX: usize>(std::marker::PhantomData<T>);
30    impl<'de, T: Deserialize<'de>, const MAX: usize> Visitor<'de> for Items<T, MAX> {
31        type Value = Vec<T>;
32        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33            write!(f, "at most {MAX} journal entries")
34        }
35        fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<T>, A::Error> {
36            let mut out = Vec::new();
37            while let Some(item) = seq.next_element()? {
38                if out.len() == MAX {
39                    return Err(A::Error::custom("too many journal entries"));
40                }
41                out.push(item);
42            }
43            Ok(out)
44        }
45    }
46    d.deserialize_seq(Items::<T, MAX>(std::marker::PhantomData))
47}
48
49// Network controls accept unknown extensions; stored, versioned controls must round trip
50// without dropping or changing fields. Typed deserialization rejects duplicate known keys.
51pub(super) fn read_control<'de, D: Deserializer<'de>>(d: D) -> Result<Control, D::Error> {
52    let raw = Box::<RawValue>::deserialize(d)?;
53    if raw.get().len() > crate::wire::MAX_MESSAGE_BYTES {
54        return Err(D::Error::custom("saved control too large"));
55    }
56    let control: Control = serde_json::from_str(raw.get()).map_err(D::Error::custom)?;
57    let original: serde_json::Value = serde_json::from_str(raw.get()).map_err(D::Error::custom)?;
58    if original != serde_json::to_value(&control).map_err(D::Error::custom)? {
59        return Err(D::Error::custom("invalid saved control shape"));
60    }
61    Ok(control)
62}
63
64impl Backend {
65    fn journal_byte_limit(&self) -> usize {
66        // Six replaceable settings, up to four pending property families and framing.
67        // JSON may escape each byte of a deployment-provided route or source.
68        let messages = (7 + self.capacity.min(4)) * crate::wire::MAX_MESSAGE_BYTES;
69        let identity = self
70            .route
71            .len()
72            .saturating_add(self.source.len())
73            .saturating_mul(6);
74        messages.saturating_add(identity)
75    }
76
77    /// Checkpoint before publishing a newly registered control and again after its ACK.
78    /// Store these potentially credential-bearing bytes atomically under exclusive route ownership.
79    pub fn checkpoint(&mut self, now: Clock) -> Result<Vec<u8>, EngineError> {
80        let tick = self.clock(now)?;
81        let outstanding = self
82            .pending
83            .iter()
84            .filter_map(|(id, pending)| match pending {
85                Pending::Control(submitted) => Some((id.clone(), submitted.clone())),
86                Pending::Read { .. } => None,
87            })
88            .collect();
89        let journal = Journal {
90            version: 1,
91            route: self.route.clone(),
92            source: self.source.clone(),
93            capacity: self.capacity,
94            tick,
95            utc: now.unix_seconds,
96            confirmed: self.confirmed.values().cloned().collect(),
97            outstanding,
98        };
99        let bytes = serde_json::to_vec(&journal).map_err(|_| EngineError::Checkpoint)?;
100        if bytes.len() > self.journal_byte_limit() {
101            return Err(EngineError::Capacity);
102        }
103        Ok(bytes)
104    }
105
106    /// Recover using externally provisioned route, source and capacity. Restored commands
107    /// await the original ACK. A state read can reconcile uncertain equipment while conflicting
108    /// writes and desired-control replies stay blocked. Explicit cancellation abandons correlation.
109    pub fn restore(mut self, bytes: &[u8], now: Clock) -> Result<Self, EngineError> {
110        if bytes.len() > self.journal_byte_limit() {
111            return Err(EngineError::Checkpoint);
112        }
113        let journal: Journal =
114            serde_json::from_slice(bytes).map_err(|_| EngineError::Checkpoint)?;
115        if journal.version != 1
116            || journal.utc < 0
117            || journal.route != self.route
118            || journal.source != self.source
119            || journal.capacity != self.capacity
120            || journal.outstanding.len() > self.capacity
121            || (self.capacity == 0 && !journal.confirmed.is_empty())
122        {
123            return Err(EngineError::Checkpoint);
124        }
125        let downtime = now
126            .unix_seconds
127            .checked_sub(journal.utc)
128            .and_then(|t| u64::try_from(t).ok())
129            .ok_or(EngineError::Clock)?;
130        let resumed = journal
131            .tick
132            .checked_add(downtime)
133            .ok_or(EngineError::Clock)?;
134        let validate = |id: &str, item: &Submitted| -> Result<(), EngineError> {
135            if item.at > journal.tick {
136                return Err(EngineError::Checkpoint);
137            }
138            Message::new(id, &self.source, item.control.clone())
139                .encode()
140                .map_err(|_| EngineError::Checkpoint)?;
141            Deadlines::default()
142                .update(&item.control, item.at)
143                .map_err(|_| EngineError::Checkpoint)
144        };
145        let mut confirmed = BTreeMap::new();
146        for item in journal.confirmed {
147            validate("", &item)?;
148            let setting = Setting::of(&item.control).map_err(|_| EngineError::Checkpoint)?;
149            if confirmed.insert(setting, item).is_some() {
150                return Err(EngineError::Checkpoint);
151            }
152        }
153        let mut pending = BTreeMap::new();
154        let mut occupied = [false; 4];
155        for (id, item) in journal.outstanding {
156            validate(&id, &item)?;
157            // Same-family controls are serialized. An older unresolved record could
158            // otherwise replace a newer confirmed setting when its delayed ACK arrives.
159            if confirmed
160                .values()
161                .any(|prior| prior.at > item.at && conflicts(&prior.control, &item.control))
162            {
163                return Err(EngineError::Checkpoint);
164            }
165            for (busy, requested) in occupied.iter_mut().zip(families(&item.control)) {
166                if *busy && requested {
167                    return Err(EngineError::Checkpoint);
168                }
169                *busy |= requested;
170            }
171            if pending.insert(id, Pending::Control(item)).is_some() {
172                return Err(EngineError::Checkpoint);
173            }
174        }
175        self.origin = now.elapsed_seconds;
176        self.offset = resumed;
177        self.last_tick = resumed;
178        self.last_utc = now.unix_seconds;
179        self.pending = pending;
180        self.confirmed = confirmed;
181        self.observations = Default::default();
182        Ok(self)
183    }
184}