Skip to main content

cls_eedi/engine/
mod.rs

1//! Deterministic, per-route CLS.EEDI roles. Callers own clocks, MQTT and equipment.
2//!
3//! Keep one engine per authorized target. Checkpoint a local device before issuing
4//! its requested equipment operation and again before publishing its completion.
5//! On restart, reconcile pending IDs with equipment. A lost acknowledgement can
6//! then be replayed without executing the operation again.
7
8mod backend;
9mod device;
10mod observations;
11
12pub use backend::{Backend, BackendEvent};
13pub use device::{DeviceEvent, InstalledCertificate, LocalDevice, Outcome};
14use serde::{Deserialize, Serialize};
15
16use crate::wire::{Control, Message, Payload, Power, State, WireError};
17
18/// Synchronized UTC and monotonic seconds sampled together by the application.
19#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
20pub struct Clock {
21    /// Seconds since the Unix epoch.
22    pub unix_seconds: i64,
23    /// Seconds from an arbitrary process-local monotonic origin.
24    pub elapsed_seconds: u64,
25}
26
27impl Clock {
28    /// Construct a clock sample. The engine rejects negative UTC or regressing elapsed time.
29    pub const fn new(unix_seconds: i64, elapsed_seconds: u64) -> Self {
30        Self {
31            unix_seconds,
32            elapsed_seconds,
33        }
34    }
35}
36
37/// Application or protocol interaction errors. Display never contains payload data.
38#[derive(Debug, thiserror::Error)]
39pub enum EngineError {
40    /// The supplied route differs from the provisioned target.
41    #[error("publication does not match the engine route")]
42    Route,
43    /// The peer sent an unexpected message or correlated it to a different exchange.
44    #[error("unexpected message type or relation")]
45    Unexpected,
46    /// Another operation for this property, or another read, is in flight.
47    #[error("a conflicting request is already in flight")]
48    Busy,
49    /// Capacity is exhausted. No existing pending operation was evicted.
50    #[error("engine capacity exhausted")]
51    Capacity,
52    /// Repeated IDs with different content cannot share a completion.
53    #[error("request ID reused with different content")]
54    IdConflict,
55    /// Equipment may already have acted. Reconcile its observed outcome before completion.
56    #[error("equipment outcome requires reconciliation")]
57    ReconciliationRequired,
58    /// The caller must supply synchronized UTC and a monotonic elapsed clock.
59    #[error("clock regressed or deadline cannot be represented")]
60    Clock,
61    /// Stored state is damaged, from an unsupported revision or for a different route.
62    #[error("invalid device checkpoint")]
63    Checkpoint,
64    /// Trust readback must contain the certificate's SKI supplied by the equipment.
65    #[error("a verified trust readback is required")]
66    TrustReadback,
67    /// A pairing observation is stale, ambiguous or inconsistent with the active credential.
68    #[error("pairing result does not match the active trust replacement")]
69    PairingMismatch,
70    /// A multi-direction desired state has no unambiguous 1.2.0 control encoding.
71    #[error("accumulated settings cannot be expressed in one legal control reply")]
72    DesiredState,
73    /// The message violates the wire contract.
74    #[error(transparent)]
75    Wire(#[from] WireError),
76}
77
78fn checked(message: Message) -> Result<Message, EngineError> {
79    message.encode()?;
80    Ok(message)
81}
82
83fn families(c: &Control) -> [bool; 4] {
84    [
85        c.limits.is_some(),
86        c.failsafes.is_some(),
87        c.trust.is_some(),
88        c.notify.is_some(),
89    ]
90}
91
92fn conflicts(a: &Control, b: &Control) -> bool {
93    families(a)
94        .into_iter()
95        .zip(families(b))
96        .any(|(a, b)| a && b)
97}
98
99fn merge_power<T: Clone>(current: &mut Option<Power<T>>, patch: &Option<Power<T>>) {
100    if let Some(patch) = patch {
101        let slot = current.get_or_insert_with(|| Power {
102            consumption: None,
103            production: None,
104        });
105        if patch.consumption.is_some() {
106            slot.consumption.clone_from(&patch.consumption);
107        }
108        if patch.production.is_some() {
109            slot.production.clone_from(&patch.production);
110        }
111    }
112}
113
114/// Absolute deadlines in engine elapsed seconds, one per power direction.
115#[derive(Default, Serialize, Deserialize)]
116struct Deadlines([Option<u64>; 2]);
117
118impl Deadlines {
119    fn update(&mut self, c: &Control, received_at: u64) -> Result<(), EngineError> {
120        if let Some(power) = &c.limits {
121            for (slot, limit) in self
122                .0
123                .iter_mut()
124                .zip([&power.consumption, &power.production])
125            {
126                if let Some(limit) = limit {
127                    *slot = limit
128                        .duration
129                        .map(|d| {
130                            received_at
131                                .checked_add(u64::from(d))
132                                .ok_or(EngineError::Clock)
133                        })
134                        .transpose()?;
135                }
136            }
137        }
138        Ok(())
139    }
140
141    fn apply(&self, power: &mut Option<Power<crate::wire::Limit>>, now: u64) {
142        if let Some(power) = power {
143            for (slot, limit) in self
144                .0
145                .iter()
146                .zip([&mut power.consumption, &mut power.production])
147            {
148                if let (Some(expires), Some(limit)) = (slot, limit) {
149                    let left = expires.saturating_sub(now);
150                    if left == 0 {
151                        limit.active = false;
152                        limit.duration = None;
153                    } else {
154                        limit.duration = Some(u32::try_from(left).unwrap_or(u32::MAX));
155                    }
156                }
157            }
158        }
159    }
160}
161
162const FIELDS: [&str; 6] = [
163    "limits",
164    "failsafes",
165    "trust",
166    "notify",
167    "measurements",
168    "supportedEebusUseCases",
169];
170
171fn filter_state(mut state: State, fields: &[String]) -> State {
172    if !fields.is_empty() {
173        for field in FIELDS {
174            if !fields.iter().any(|f| f == field) {
175                clear_field(&mut state, field);
176            }
177        }
178    }
179    state
180}
181
182fn clear_field(state: &mut State, field: &str) {
183    match field {
184        "limits" => state.limits = None,
185        "failsafes" => state.failsafes = None,
186        "trust" => state.trust = None,
187        "notify" => state.notify = None,
188        "measurements" => state.measurements = None,
189        "supportedEebusUseCases" => state.supported_eebus_use_cases = None,
190        _ => {}
191    }
192}
193
194fn ack(source: &str, relation: &str, error_number: u64) -> Result<Message, EngineError> {
195    checked(
196        Message::new(
197            relation,
198            source,
199            Payload::Ack(crate::wire::Ack { error_number }),
200        )
201        .related_to(relation),
202    )
203}