Skip to main content

flexpool_telemetry/
store.rs

1//! The bounded live store (SR-003): per asset the latest value per quantity, up to 15 minutes of
2//! recent values and two days of quarter-hour aggregates. Memory is fixed per declared asset; values
3//! for undeclared assets are refused, and no input rate makes a series grow past its cap.
4
5use std::collections::{BTreeMap, HashMap, VecDeque};
6
7use flexpool_core::AssetId;
8use serde::Serialize;
9
10use crate::quality::{Flags, Quality, Quantity, Reading, classify};
11use crate::{QUARTER_SECS, quarter_start};
12
13/// Recent values are kept for this long.
14pub const RECENT_SECS: i64 = 900;
15/// At most this many recent values per asset and quantity.
16pub const RECENT_MAX: usize = 900;
17/// At most this many quarter aggregates per asset (two days).
18pub const QUARTERS_MAX: usize = 192;
19/// A sample this much older than the latest means the receiving clock stepped back: the series
20/// starts again instead of freezing on a value from the "future".
21pub const CLOCK_STEP_SECS: i64 = 60;
22
23/// What happened to a pushed value.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Pushed {
26    /// Stored.
27    Stored,
28    /// Slightly older than the latest (reordered): dropped.
29    Dropped,
30    /// Much older than the latest: the clock stepped back; the series was restarted with it.
31    Reset,
32    /// No such asset.
33    Undeclared,
34}
35
36/// One quarter hour of an asset.
37#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
38pub struct QuarterAggregate {
39    /// Quarter start, Unix seconds.
40    pub start: i64,
41    /// Time-weighted mean of good power values, kW; `None` without good values.
42    pub mean_power_kw: Option<f64>,
43    /// The last good state of charge in the quarter, %.
44    pub last_soc: Option<f64>,
45    /// Share of the quarter covered by good power values, 0–1.
46    pub good_share: f64,
47}
48
49/// One recent instant: power and state of charge taken at the same source time.
50#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
51pub struct Recent {
52    /// Source time, Unix seconds.
53    pub at: i64,
54    /// Power, kW.
55    pub power_kw: Option<f64>,
56    /// State of charge, %.
57    pub soc: Option<f64>,
58}
59
60/// An asset now: its readings and its overall quality (that of its power).
61#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
62pub struct AssetNow {
63    /// Power now.
64    pub power: Option<Reading>,
65    /// State of charge now (batteries).
66    pub soc: Option<Reading>,
67    /// Since when the asset has had no connection, Unix seconds.
68    pub offline_since: Option<i64>,
69    /// The asset's quality: offline without a connection or a power value, else the power's.
70    pub quality: Quality,
71}
72
73impl AssetNow {
74    /// An asset without data.
75    #[must_use]
76    pub const fn offline(since: Option<i64>) -> Self {
77        Self {
78            power: None,
79            soc: None,
80            offline_since: since,
81            quality: Quality::Offline,
82        }
83    }
84
85    /// Builds the asset's state from its readings.
86    #[must_use]
87    pub fn from_readings(power: Option<Reading>, soc: Option<Reading>) -> Self {
88        Self {
89            power,
90            soc,
91            offline_since: None,
92            quality: power.map_or(Quality::Offline, |p| p.quality),
93        }
94    }
95}
96
97/// A closed quarter as stored: 16 bytes instead of the 48 of [`QuarterAggregate`] (SC-003).
98#[derive(Debug, Clone, Copy)]
99struct Packed {
100    /// Quarter start / 900.
101    index: u32,
102    /// Mean good power, kW; NaN without good values.
103    mean: f32,
104    /// Last good state of charge, %; NaN without one.
105    soc: f32,
106    /// Good seconds, 0–900.
107    good: u16,
108}
109
110/// Bytes one stored quarter takes.
111pub const QUARTER_BYTES: usize = size_of::<Packed>();
112
113impl Packed {
114    fn pack(q: QuarterAggregate) -> Self {
115        #[expect(
116            clippy::cast_possible_truncation,
117            clippy::cast_sign_loss,
118            reason = "quarters since 1970 fit u32; good seconds ≤ 900"
119        )]
120        Self {
121            index: (q.start / QUARTER_SECS) as u32,
122            mean: q.mean_power_kw.map_or(f32::NAN, |v| v as f32),
123            soc: q.last_soc.map_or(f32::NAN, |v| v as f32),
124            good: (q.good_share * 900.0).round() as u16,
125        }
126    }
127
128    fn unpack(self) -> QuarterAggregate {
129        let some = |v: f32| (!v.is_nan()).then_some(f64::from(v));
130        QuarterAggregate {
131            start: i64::from(self.index) * QUARTER_SECS,
132            mean_power_kw: some(self.mean),
133            last_soc: some(self.soc),
134            good_share: f64::from(self.good) / 900.0,
135        }
136    }
137}
138
139#[derive(Debug, Clone, Copy)]
140struct Sample {
141    at: i64,
142    value: f32,
143    flags: Flags,
144}
145
146#[derive(Debug, Clone, Copy)]
147struct Accumulator {
148    start: i64,
149    energy_kws: f64,
150    good_secs: i64,
151    last_soc: Option<f32>,
152}
153
154impl Accumulator {
155    const fn new(start: i64) -> Self {
156        Self {
157            start,
158            energy_kws: 0.0,
159            good_secs: 0,
160            last_soc: None,
161        }
162    }
163
164    fn finish(self) -> QuarterAggregate {
165        QuarterAggregate {
166            start: self.start,
167            #[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
168            mean_power_kw: (self.good_secs > 0).then(|| self.energy_kws / self.good_secs as f64),
169            last_soc: self.last_soc.map(f64::from),
170            #[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
171            good_share: (self.good_secs as f64 / QUARTER_SECS as f64).min(1.0),
172        }
173    }
174}
175
176#[derive(Debug, Clone)]
177struct Series {
178    rated_kw: f64,
179    limit: i64,
180    latest: [Option<Sample>; 2],
181    recent: [VecDeque<(i64, f32)>; 2],
182    quarters: VecDeque<Packed>,
183    open: Option<Accumulator>,
184    /// The last good power value: credited from `.0` to the next value or `.2` (its stale limit).
185    held: Option<(i64, f32, i64)>,
186    offline_since: Option<i64>,
187}
188
189impl Series {
190    fn new(rated_kw: f64, limit: i64) -> Self {
191        Self {
192            rated_kw,
193            limit,
194            latest: [None, None],
195            recent: [VecDeque::new(), VecDeque::new()],
196            quarters: VecDeque::new(),
197            open: None,
198            held: None,
199            offline_since: None,
200        }
201    }
202
203    fn good_at_arrival(&self, q: Quantity, s: Sample) -> bool {
204        classify(
205            q,
206            f64::from(s.value),
207            s.at,
208            s.at,
209            self.limit,
210            s.flags,
211            self.rated_kw,
212        ) == Quality::Good
213    }
214
215    /// The accumulator for quarter `start`, closing older ones.
216    fn accumulator(&mut self, start: i64) -> Option<&mut Accumulator> {
217        match self.open {
218            Some(acc) if acc.start > start => return None, // out of order: ignore
219            Some(acc) if acc.start < start => {
220                self.quarters.push_back(Packed::pack(acc.finish()));
221                // The open quarter counts against the cap too.
222                while self.quarters.len() >= QUARTERS_MAX {
223                    self.quarters.pop_front();
224                }
225                self.open = Some(Accumulator::new(start));
226            }
227            Some(_) => {}
228            None => self.open = Some(Accumulator::new(start)),
229        }
230        self.open.as_mut()
231    }
232
233    /// Adds power `v` held over `[from, to)` to the quarters it spans.
234    fn hold(&mut self, mut from: i64, to: i64, v: f32) {
235        while from < to {
236            let q = quarter_start(from);
237            let end = (q + QUARTER_SECS).min(to);
238            if let Some(acc) = self.accumulator(q) {
239                #[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
240                let secs = (end - from) as f64;
241                acc.energy_kws += f64::from(v) * secs;
242                acc.good_secs += end - from;
243            }
244            from = end;
245        }
246    }
247
248    /// Credits the held power up to `to` (bounded by its stale limit) and keeps holding from there.
249    fn credit(&mut self, to: i64) {
250        if let Some((from, v, until)) = self.held {
251            let end = to.min(until);
252            if end > from {
253                self.hold(from, end, v);
254                self.held = (end < until).then_some((end, v, until));
255            }
256        }
257    }
258
259    fn push(&mut self, q: Quantity, s: Sample) -> Pushed {
260        let i = q.index();
261        if let Some(l) = self.latest[i]
262            && s.at < l.at
263        {
264            if l.at - s.at <= CLOCK_STEP_SECS {
265                return Pushed::Dropped; // reordered: never rewrite the past
266            }
267            // The clock stepped back: what we hold is dated in the future. Start again.
268            *self = Self::new(self.rated_kw, self.limit);
269            self.push(q, s);
270            return Pushed::Reset;
271        }
272        self.latest[i] = Some(s);
273        let ring = &mut self.recent[i];
274        while ring.front().is_some_and(|(t, _)| *t <= s.at - RECENT_SECS)
275            || ring.len() >= RECENT_MAX
276        {
277            ring.pop_front();
278        }
279        ring.push_back((s.at, s.value));
280        let good = self.good_at_arrival(q, s);
281        // Whatever arrives, the held power is credited up to now first, so moving to a new quarter
282        // never loses time in the old one.
283        self.credit(s.at);
284        match q {
285            Quantity::Power => {
286                self.held = good.then_some((s.at, s.value, s.at + self.limit));
287                if good {
288                    // Opens the quarter even before any time has passed in it.
289                    let _ = self.accumulator(quarter_start(s.at));
290                }
291            }
292            Quantity::Soc => {
293                if good && let Some(acc) = self.accumulator(quarter_start(s.at)) {
294                    acc.last_soc = Some(s.value);
295                }
296            }
297        }
298        Pushed::Stored
299    }
300
301    fn reading(&self, q: Quantity, now: i64) -> Option<Reading> {
302        self.latest[q.index()].map(|s| Reading {
303            value: f64::from(s.value),
304            at: s.at,
305            quality: classify(
306                q,
307                f64::from(s.value),
308                s.at,
309                now,
310                self.limit,
311                s.flags,
312                self.rated_kw,
313            ),
314        })
315    }
316}
317
318/// The live store for the declared assets.
319#[derive(Debug, Clone, Default)]
320pub struct Store {
321    series: HashMap<AssetId, Series>,
322}
323
324impl Store {
325    /// A store for `assets`: `(id, rated kW, stale limit in seconds)`. Assets start offline.
326    pub fn new(assets: impl IntoIterator<Item = (AssetId, f64, i64)>) -> Self {
327        Self {
328            series: assets
329                .into_iter()
330                .map(|(id, rated, limit)| (id, Series::new(rated, limit)))
331                .collect(),
332        }
333    }
334
335    /// An asset's stale limit in seconds.
336    #[must_use]
337    pub fn limit(&self, asset: &AssetId) -> Option<i64> {
338        self.series.get(asset).map(|s| s.limit)
339    }
340
341    /// Sets an asset's stale limit; `false` for an undeclared asset.
342    pub fn set_limit(&mut self, asset: &AssetId, limit: i64) -> bool {
343        self.series
344            .get_mut(asset)
345            .map(|s| s.limit = limit)
346            .is_some()
347    }
348
349    /// Records a value taken at `at`.
350    pub fn push(
351        &mut self,
352        asset: &AssetId,
353        quantity: Quantity,
354        value: f64,
355        at: i64,
356        flags: Flags,
357    ) -> Pushed {
358        let Some(series) = self.series.get_mut(asset) else {
359            return Pushed::Undeclared;
360        };
361        #[expect(
362            clippy::cast_possible_truncation,
363            reason = "measurements fit f32; plausibility runs on the stored value"
364        )]
365        let value = value as f32;
366        series.offline_since = None;
367        series.push(quantity, Sample { at, value, flags })
368    }
369
370    /// Marks an asset as without connection since `since` — keeping the first loss when it was
371    /// already offline — or connected again with `None`. Held power stops counting as good at the loss.
372    pub fn set_offline(&mut self, asset: &AssetId, since: Option<i64>) {
373        if let Some(s) = self.series.get_mut(asset) {
374            match since {
375                Some(t) => {
376                    s.credit(t);
377                    s.held = None;
378                    s.offline_since.get_or_insert(t);
379                }
380                None => s.offline_since = None,
381            }
382        }
383    }
384
385    /// The asset as of `now`; `None` for an undeclared asset.
386    #[must_use]
387    pub fn now(&self, asset: &AssetId, now: i64) -> Option<AssetNow> {
388        let s = self.series.get(asset)?;
389        if s.offline_since.is_some() {
390            return Some(AssetNow::offline(s.offline_since));
391        }
392        Some(AssetNow::from_readings(
393            s.reading(Quantity::Power, now),
394            s.reading(Quantity::Soc, now),
395        ))
396    }
397
398    /// Quarter aggregates with a start in `[from, to)`, as of `now` (the open quarter partly).
399    #[must_use]
400    pub fn quarters(&self, asset: &AssetId, from: i64, to: i64, now: i64) -> Vec<QuarterAggregate> {
401        let Some(s) = self.series.get(asset) else {
402            return Vec::new();
403        };
404        let mut view = s.clone();
405        view.credit(now);
406        view.quarters
407            .iter()
408            .map(|p| p.unpack())
409            .chain(view.open.map(Accumulator::finish))
410            .filter(|q| q.start >= from && q.start < to && q.start <= now)
411            .collect()
412    }
413
414    /// Recent values (≤ 15 minutes before `now`), oldest first.
415    #[must_use]
416    pub fn recent(&self, asset: &AssetId, now: i64) -> Vec<Recent> {
417        let Some(s) = self.series.get(asset) else {
418            return Vec::new();
419        };
420        let mut by_time: BTreeMap<i64, Recent> = BTreeMap::new();
421        for q in Quantity::ALL {
422            for &(at, v) in &s.recent[q.index()] {
423                if at <= now - RECENT_SECS || at > now {
424                    continue;
425                }
426                let r = by_time.entry(at).or_insert(Recent {
427                    at,
428                    power_kw: None,
429                    soc: None,
430                });
431                match q {
432                    Quantity::Power => r.power_kw = Some(f64::from(v)),
433                    Quantity::Soc => r.soc = Some(f64::from(v)),
434                }
435            }
436        }
437        by_time.into_values().collect()
438    }
439
440    /// How many values the asset holds: `(recent power, recent soc, quarters)` — for the caps' tests.
441    #[must_use]
442    pub fn held(&self, asset: &AssetId) -> Option<(usize, usize, usize)> {
443        self.series.get(asset).map(|s| {
444            (
445                s.recent[0].len(),
446                s.recent[1].len(),
447                s.quarters.len() + usize::from(s.open.is_some()),
448            )
449        })
450    }
451}