1mod recovery;
2
3use std::collections::BTreeMap;
4
5use super::*;
6use crate::wire::{Read, Status};
7
8pub enum BackendEvent {
10 Reply(Box<Message>),
12 Acknowledged {
14 request_id: String,
15 error_number: u64,
16 },
17 StateUpdated,
19 Presence(Status),
21 Stale,
23}
24
25#[derive(Clone, Serialize, Deserialize)]
26#[serde(deny_unknown_fields)]
27struct Submitted {
28 at: u64,
29 #[serde(deserialize_with = "recovery::read_control")]
30 control: Control,
31}
32
33#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
36enum Setting {
37 ConsumptionLimit,
38 ProductionLimit,
39 ConsumptionFailsafe,
40 ProductionFailsafe,
41 Trust,
42 Notify,
43}
44
45impl Setting {
46 fn of(control: &Control) -> Result<Self, EngineError> {
47 if let Some(power) = &control.limits {
49 Ok(if power.consumption.is_some() {
50 Self::ConsumptionLimit
51 } else {
52 Self::ProductionLimit
53 })
54 } else if let Some(power) = &control.failsafes {
55 Ok(if power.consumption.is_some() {
56 Self::ConsumptionFailsafe
57 } else {
58 Self::ProductionFailsafe
59 })
60 } else if control.trust.is_some() {
61 Ok(Self::Trust)
62 } else if control.notify.is_some() {
63 Ok(Self::Notify)
64 } else {
65 Err(EngineError::Unexpected)
66 }
67 }
68}
69
70enum Pending {
71 Control(Submitted),
72 Read {
73 parameters: Vec<String>,
74 raced_at: Option<i64>,
75 },
76}
77
78pub struct Backend {
80 route: String,
81 source: String,
82 capacity: usize,
83 pending: BTreeMap<String, Pending>,
84 observations: observations::Observations,
85 confirmed: BTreeMap<Setting, Submitted>,
86 origin: u64,
87 offset: u64,
88 last_tick: u64,
89 last_utc: i64,
90}
91
92impl Backend {
93 pub fn new(route: impl Into<String>, source: impl Into<String>, capacity: usize) -> Self {
96 Self {
97 route: route.into(),
98 source: source.into(),
99 capacity,
100 pending: BTreeMap::new(),
101 observations: Default::default(),
102 confirmed: BTreeMap::new(),
103 origin: 0,
104 offset: 0,
105 last_tick: 0,
106 last_utc: 0,
107 }
108 }
109
110 pub fn state(&self) -> Option<&State> {
113 self.observations.state.as_ref()
114 }
115
116 pub fn property_observed_at(&self, field: &str) -> Option<i64> {
119 self.observations.property_time(field)
120 }
121
122 pub fn meter_observed_at(&self, id: &str) -> Option<i64> {
124 self.observations.meter_time(id)
125 }
126
127 pub fn cancel(&mut self, id: &str) -> bool {
130 self.pending.remove(id).is_some()
131 }
132
133 pub fn pending_controls(&self) -> impl Iterator<Item = (&str, &Control)> {
136 self.pending.iter().filter_map(|(id, p)| match p {
137 Pending::Control(submitted) => Some((id.as_str(), &submitted.control)),
138 Pending::Read { .. } => None,
139 })
140 }
141
142 pub fn confirmed_settings(&mut self, now: Clock) -> Result<Control, EngineError> {
145 let elapsed = self.clock(now)?;
146 let mut cumulative = Control::default();
147 let mut deadlines = Deadlines::default();
148 for submitted in self.confirmed.values() {
149 let request = &submitted.control;
150 deadlines.update(request, submitted.at)?;
151 merge_power(&mut cumulative.limits, &request.limits);
152 merge_power(&mut cumulative.failsafes, &request.failsafes);
153 if request.trust.is_some() {
154 cumulative.trust.clone_from(&request.trust);
155 }
156 if request.notify.is_some() {
157 cumulative.notify.clone_from(&request.notify);
158 }
159 }
160 deadlines.apply(&mut cumulative.limits, elapsed);
161 Ok(cumulative)
162 }
163
164 fn clock(&mut self, now: Clock) -> Result<u64, EngineError> {
165 let tick = now
166 .elapsed_seconds
167 .checked_sub(self.origin)
168 .and_then(|t| self.offset.checked_add(t))
169 .ok_or(EngineError::Clock)?;
170 if tick < self.last_tick || now.unix_seconds < self.last_utc {
171 return Err(EngineError::Clock);
172 }
173 self.last_tick = tick;
174 self.last_utc = now.unix_seconds;
175 Ok(tick)
176 }
177
178 pub fn send_control(
180 &mut self,
181 id: &str,
182 request: Control,
183 now: Clock,
184 ) -> Result<Message, EngineError> {
185 if self.pending.contains_key(id) {
186 return Err(EngineError::IdConflict);
187 }
188 let received_at = self.clock(now)?;
189 if self
190 .pending_controls()
191 .any(|(_, other)| conflicts(other, &request))
192 {
193 return Err(EngineError::Busy);
194 }
195 if self.pending_controls().count() >= self.capacity {
196 return Err(EngineError::Capacity);
197 }
198 Deadlines::default().update(&request, received_at)?;
199 let message = checked(Message::new(
200 id,
201 &self.source,
202 Payload::Control(request.clone()),
203 ))?;
204 self.pending.insert(
205 id.to_owned(),
206 Pending::Control(Submitted {
207 control: request,
208 at: received_at,
209 }),
210 );
211 Ok(message)
212 }
213
214 pub fn read(&mut self, id: &str, parameters: Vec<String>) -> Result<Message, EngineError> {
216 if self.pending.contains_key(id) {
217 return Err(EngineError::IdConflict);
218 }
219 if self.capacity == 0 {
220 return Err(EngineError::Capacity);
221 }
222 if self
223 .pending
224 .values()
225 .any(|p| matches!(p, Pending::Read { .. }))
226 {
227 return Err(EngineError::Busy);
228 }
229 let message = checked(Message::new(
230 id,
231 &self.source,
232 Payload::Read(Read {
233 parameters: parameters.clone(),
234 }),
235 ))?;
236 self.pending.insert(
237 id.to_owned(),
238 Pending::Read {
239 parameters,
240 raced_at: None,
241 },
242 );
243 Ok(message)
244 }
245
246 pub fn receive(
248 &mut self,
249 route: &str,
250 message: &Message,
251 reply_id: &str,
252 now: Clock,
253 ) -> Result<BackendEvent, EngineError> {
254 if route != self.route {
255 return Err(EngineError::Route);
256 }
257 message.validate()?;
258 self.clock(now)?;
259 match &message.payload {
260 Payload::State(state) => self.receive_state(message.relation.as_deref(), state),
261 Payload::LocalDeviceStatus(status) if message.relation.is_none() => {
262 Ok(BackendEvent::Presence(status.clone()))
263 }
264 Payload::Ack(result) => {
265 let id = message.relation.as_deref().unwrap_or(&message.id);
266 let pending = self.pending.get(id).ok_or(EngineError::Unexpected)?;
267 if result.error_number == 0 {
268 let Pending::Control(submitted) = pending else {
269 return Err(EngineError::Unexpected);
270 };
271 self.confirmed
272 .insert(Setting::of(&submitted.control)?, submitted.clone());
273 }
274 self.pending.remove(id);
275 Ok(BackendEvent::Acknowledged {
276 request_id: id.to_owned(),
277 error_number: result.error_number,
278 })
279 }
280 Payload::Read(read) if message.relation.is_none() && read.parameters.is_empty() => {
281 if self.pending_controls().next().is_some() {
282 return Err(EngineError::ReconciliationRequired);
283 }
284 let desired = self.confirmed_settings(now)?;
285 let reply = Message::new(reply_id, &self.source, desired).related_to(&message.id);
286 let reply = checked(reply).map_err(|_| EngineError::DesiredState)?;
287 Ok(BackendEvent::Reply(Box::new(reply)))
288 }
289 _ => Err(EngineError::Unexpected),
290 }
291 }
292
293 fn receive_state(
294 &mut self,
295 relation: Option<&str>,
296 incoming: &State,
297 ) -> Result<BackendEvent, EngineError> {
298 let read = relation
299 .map(|id| match self.pending.get(id) {
300 Some(Pending::Read {
301 parameters,
302 raced_at,
303 }) => Ok((parameters.as_slice(), *raced_at)),
304 _ => Err(EngineError::Unexpected),
305 })
306 .transpose()?;
307 let changed = self
308 .observations
309 .apply(incoming, read, self.capacity, &self.source)?;
310 if let Some(id) = relation {
311 self.pending.remove(id);
312 } else if let Some(fields) = &changed {
313 for pending in self.pending.values_mut() {
314 if let Pending::Read {
315 parameters,
316 raced_at,
317 } = pending
318 {
319 if fields
320 .iter()
321 .any(|key| parameters.is_empty() || parameters.iter().any(|s| s == key))
322 {
323 *raced_at = Some(raced_at.unwrap_or(0).max(incoming.timestamp));
324 }
325 }
326 }
327 }
328 Ok(if changed.is_some() {
329 BackendEvent::StateUpdated
330 } else {
331 BackendEvent::Stale
332 })
333 }
334}