Skip to main content

sensor_db/
port.rs

1//! Capability ports: what a caller needs from a log, without naming which log.
2//!
3//! [`SensorDb`](crate::SensorDb) and [`TieredDb`](crate::TieredDb) are two
4//! different things — one log, or an onboard log plus a removable replica — but
5//! everything layered on top of them wants the same two capabilities: somewhere
6//! to put a sample ([`LogSink`]) and somewhere to read samples back
7//! ([`LogSource`]). Naming the capability instead of the concrete type is what
8//! lets [`SensorLogger`](crate::SensorLogger) and the typed API work over
9//! either.
10//!
11//! # The ports are narrow; the conveniences are mixins
12//!
13//! `LogSink` is two methods and `LogSource` is four — the operations an
14//! implementor genuinely has to *do*. Everything derivable from them (the typed
15//! API: `append_sensor`, `latest_sensor`, `query_sensor`, …) lives in the
16//! blanket-implemented extension traits [`LogSinkExt`] and [`LogSourceExt`],
17//! where it is defined exactly once and cannot be customised — the
18//! `SensorData` → bytes mapping must be uniform or two implementors would
19//! disagree about what a stored entry means.
20//!
21//! Import the `Ext` trait to get those methods:
22//!
23//! ```ignore
24//! use sensor_db::port::{LogSinkExt, LogSourceExt};
25//!
26//! fn record<L: LogSinkExt>(log: &mut L, t: u64) -> Result<(), Error> {
27//!     log.append_sensor(t, &Temperature { celsius: 25.5 })
28//! }
29//! ```
30//!
31//! # The same methods exist inherently on the logs, and that is deliberate
32//!
33//! [`SensorDb`](crate::SensorDb) and [`TieredDb`](crate::TieredDb) each carry
34//! their own `append_sensor` / `latest_sensor` / … with signatures identical to
35//! these. It is the ordinary Rust split, not a second API: the inherent method is
36//! what you call on a concrete log with no `use` line, and the mixin is what
37//! generic code binds on. Method resolution prefers the inherent one, so which
38//! is in scope never changes behaviour — both forward to the same framing in
39//! [`schema`](crate::schema).
40//!
41//! There is deliberately nothing else. Earlier revisions also offered a
42//! `Sensor<T>` handle and a value-first `SensorDataExt` (`value.store(&mut db, t)`);
43//! both were restatements of the two above, and five spellings of one operation
44//! is a documentation burden with no answer to "which one should I use".
45//!
46//! # Async
47//!
48//! [`LogSinkAsync`] and [`LogSourceAsync`] mirror them. Both are defined
49//! unconditionally, feature or no feature: a trait definition costs nothing to
50//! compile and gating it would force callers to gate their own generic code.
51//! The `async` feature gates the *implementations*
52//! ([`SensorDbAsync`](crate::SensorDbAsync),
53//! [`TieredDbAsync`](crate::TieredDbAsync)), which are the parts that need
54//! `embedded-storage-async`.
55//!
56//! # `&mut self`, even for reads
57//!
58//! Reading flash is a `&mut` operation — `ReadNorFlash::read` takes `&mut self`
59//! — and for [`TieredDb`](crate::TieredDb) it is doubly so, since answering a
60//! query means streaming the onboard log from the replication watermark. So
61//! [`LogSource`] takes `&mut self`, and the inherent methods on the logs agree
62//! with it.
63//!
64//! They did not always. `SensorDb` once held its driver in a `RefCell` to offer
65//! `&self` reads, which made it `!Sync` — so the only way to share one was a
66//! `Mutex`, which yields `&mut` regardless — while splitting every read into two
67//! shapes and adding a re-entrancy panic to guard against. Removing it cost the
68//! `&self` reads and bought back one uniform signature.
69
70use core::future::Future;
71
72use zerocopy::{Immutable, IntoBytes};
73
74use crate::entry::EntryHeader;
75use crate::error::Error;
76use crate::run::Run;
77use crate::schema::{Tagged, read_tagged, tag, untag, untag_payload};
78use crate::typed::SensorData;
79
80// ---------------------------------------------------------------------------
81// Write capability
82// ---------------------------------------------------------------------------
83
84/// Somewhere sensor samples can be appended and made durable.
85///
86/// Three methods, each a thing an implementor genuinely has to *do*. A sink that
87/// could only append would let a caller believe data was safe when it was still
88/// in a RAM page buffer, and one that exposed the ring, the sectors or the
89/// geometry would stop being implementable by anything but a `SensorDb`.
90///
91/// [`append_run`](Self::append_run) is here rather than in the mixin because a
92/// run is a *different entry* — it carries its own marker — so it cannot be
93/// derived from `append`, and a sink that stored a run's frame as an ordinary
94/// payload would produce entries no read path could interpret.
95pub trait LogSink {
96    /// Append a sample.
97    fn append(&mut self, sensor_id: u16, timestamp: u64, payload: &[u8]) -> Result<(), Error>;
98
99    /// Append a [run](crate::run): many evenly spaced samples under one header.
100    ///
101    /// Invisible to every read — a run expands back into the samples it holds,
102    /// so this stores exactly what [`append_sensor`](LogSinkExt::append_sensor)
103    /// of the same samples would have, in a fraction of the flash.
104    fn append_run(&mut self, run: &Run<'_>) -> Result<(), Error>;
105
106    /// Make everything appended so far durable.
107    fn sync(&mut self) -> Result<(), Error>;
108}
109
110/// Typed conveniences over any [`LogSink`].
111///
112/// Blanket-implemented, so implementing `LogSink` is enough to get these — and
113/// they cannot be overridden, which is the point: how a [`SensorData`] value
114/// becomes payload bytes has to be identical everywhere, or the same entry
115/// would read back differently depending on which log wrote it.
116pub trait LogSinkExt: LogSink {
117    /// Append a value's bytes under an explicit sensor ID.
118    ///
119    /// Raw: the bytes go to flash as they are, with no schema tag. Entries
120    /// written this way are not readable through the `*_sensor` methods.
121    fn append_value<T: IntoBytes + Immutable>(
122        &mut self,
123        sensor_id: u16,
124        timestamp: u64,
125        data: &T,
126    ) -> Result<(), Error> {
127        self.append(sensor_id, timestamp, data.as_bytes())
128    }
129
130    /// Append a value under the sensor ID its type declares.
131    ///
132    /// The payload is the type's
133    /// [`SCHEMA_VERSION`](SensorData::SCHEMA_VERSION) followed by the value's
134    /// bytes, so a later firmware reading the same sensor ID can tell an entry
135    /// of its own era from one of an older one.
136    fn append_sensor<T: SensorData>(&mut self, timestamp: u64, data: &T) -> Result<(), Error> {
137        let framed = tag(data);
138        self.append(T::SENSOR_ID, timestamp, framed.bytes())
139    }
140}
141
142impl<L: LogSink + ?Sized> LogSinkExt for L {}
143
144// ---------------------------------------------------------------------------
145// Read capability
146// ---------------------------------------------------------------------------
147
148/// Somewhere sensor samples can be read back.
149///
150/// Payloads are delivered into a caller-provided buffer or to a callback, never
151/// allocated — this crate is `no_std` and has no allocator to reach for.
152pub trait LogSource {
153    /// The most recent entry for a sensor, or `None` if it has none.
154    ///
155    /// Returns the header and the payload length written into `buf`.
156    ///
157    /// # Errors
158    /// - `BufferTooSmall` if `buf` cannot hold the payload
159    fn latest(
160        &mut self,
161        sensor_id: u16,
162        buf: &mut [u8],
163    ) -> Result<Option<(EntryHeader, usize)>, Error>;
164
165    /// The oldest retained entry for a sensor, or `None` if it has none.
166    ///
167    /// # Errors
168    /// - `BufferTooSmall` if `buf` cannot hold the payload
169    fn oldest(
170        &mut self,
171        sensor_id: u16,
172        buf: &mut [u8],
173    ) -> Result<Option<(EntryHeader, usize)>, Error>;
174
175    /// Entries retained for a sensor, or for every sensor if `None`.
176    fn count(&mut self, sensor_id: Option<u16>) -> Result<u32, Error>;
177
178    /// Entries whose timestamp lies in `[t_start, t_end]`, in log order.
179    ///
180    /// The callback returns `false` to stop, which stops *after* consuming the
181    /// entry offered — the opposite of
182    /// [`SensorDb::read_from`](crate::SensorDb::read_from), which is a
183    /// replication stream rather than a query.
184    ///
185    /// The callback is `&mut dyn` rather than a generic parameter so that this
186    /// trait stays object-safe; the per-entry indirection is nothing beside the
187    /// flash read that produced the entry.
188    ///
189    /// # Returns
190    /// The number of entries delivered.
191    fn query_range(
192        &mut self,
193        sensor_id: Option<u16>,
194        t_start: u64,
195        t_end: u64,
196        callback: &mut dyn FnMut(&EntryHeader, &[u8]) -> bool,
197    ) -> Result<u32, Error>;
198}
199
200/// Typed conveniences over any [`LogSource`].
201///
202/// # What counts as a `T`
203///
204/// A typed payload is the type's
205/// [`SCHEMA_VERSION`](SensorData::SCHEMA_VERSION) followed by `size_of::<T>()`
206/// bytes, so an entry stored under `T::SENSOR_ID` qualifies only if both agree.
207/// The single-entry reads deserialise into a `Tagged<T>`-sized buffer and say
208/// which half failed: a wrong length reports `SizeMismatch` when short and
209/// `BufferTooSmall` when long, a wrong version reports `SchemaMismatch` naming
210/// the version found.
211///
212/// [`query_sensor`](Self::query_sensor) instead *skips* entries that are not a
213/// `T`, because a query that aborted on the first stale entry could never reach
214/// the good ones behind it. That is also the migration path: two types sharing a
215/// sensor ID at different versions each read their own era.
216///
217/// The header handed back describes the *entry*, so its `payload_len` counts the
218/// schema tag as well as the value.
219pub trait LogSourceExt: LogSource {
220    /// The most recent value for a sensor type.
221    fn latest_sensor<T: SensorData>(&mut self) -> Result<Option<(EntryHeader, T)>, Error> {
222        read_tagged(|buf| self.latest(T::SENSOR_ID, buf))
223    }
224
225    /// The oldest retained value for a sensor type.
226    fn oldest_sensor<T: SensorData>(&mut self) -> Result<Option<(EntryHeader, T)>, Error> {
227        read_tagged(|buf| self.oldest(T::SENSOR_ID, buf))
228    }
229
230    /// Entries retained for a sensor type.
231    fn count_sensor<T: SensorData>(&mut self) -> Result<u32, Error> {
232        self.count(Some(T::SENSOR_ID))
233    }
234
235    /// Values for a sensor type whose timestamp lies in `[t_start, t_end]`.
236    ///
237    /// # Returns
238    /// The number of entries delivered — entries skipped for a wrong schema
239    /// version or payload length are not counted.
240    fn query_sensor<T: SensorData, C>(
241        &mut self,
242        t_start: u64,
243        t_end: u64,
244        mut callback: C,
245    ) -> Result<u32, Error>
246    where
247        C: FnMut(&EntryHeader, &T) -> bool,
248    {
249        let mut delivered = 0u32;
250
251        self.query_range(
252            Some(T::SENSOR_ID),
253            t_start,
254            t_end,
255            &mut |header: &EntryHeader, payload: &[u8]| {
256                let Some(value) = untag_payload::<T>(payload) else {
257                    return true;
258                };
259                delivered += 1;
260                callback(header, &value)
261            },
262        )?;
263
264        Ok(delivered)
265    }
266
267    /// Every retained value for a sensor type, in log order.
268    fn query_all_sensor<T: SensorData, C>(&mut self, callback: C) -> Result<u32, Error>
269    where
270        C: FnMut(&EntryHeader, &T) -> bool,
271    {
272        self.query_sensor(0, u64::MAX, callback)
273    }
274}
275
276impl<L: LogSource + ?Sized> LogSourceExt for L {}
277
278// ---------------------------------------------------------------------------
279// Async mirrors
280// ---------------------------------------------------------------------------
281
282/// Async mirror of [`LogSink`].
283///
284/// Methods return `impl Future` rather than being `async fn` so the returned
285/// futures carry no implicit `Send` bound — an executor like Embassy runs them
286/// on one core and does not need it.
287pub trait LogSinkAsync {
288    /// Append a sample.
289    fn append(
290        &mut self,
291        sensor_id: u16,
292        timestamp: u64,
293        payload: &[u8],
294    ) -> impl Future<Output = Result<(), Error>>;
295
296    /// Append a [run](crate::run): many evenly spaced samples under one header.
297    fn append_run(&mut self, run: &Run<'_>) -> impl Future<Output = Result<(), Error>>;
298
299    /// Make everything appended so far durable.
300    fn sync(&mut self) -> impl Future<Output = Result<(), Error>>;
301}
302
303/// Async mirror of [`LogSinkExt`].
304pub trait LogSinkAsyncExt: LogSinkAsync {
305    /// Append a value's bytes under an explicit sensor ID, untagged.
306    fn append_value<T: IntoBytes + Immutable>(
307        &mut self,
308        sensor_id: u16,
309        timestamp: u64,
310        data: &T,
311    ) -> impl Future<Output = Result<(), Error>> {
312        self.append(sensor_id, timestamp, data.as_bytes())
313    }
314
315    /// Append a value under the sensor ID its type declares, schema-tagged.
316    #[allow(clippy::manual_async_fn)]
317    fn append_sensor<T: SensorData>(
318        &mut self,
319        timestamp: u64,
320        data: &T,
321    ) -> impl Future<Output = Result<(), Error>> {
322        // The framed copy has to outlive the await, so it is bound here rather
323        // than being a temporary in the call.
324        async move {
325            let framed = tag(data);
326            self.append(T::SENSOR_ID, timestamp, framed.bytes()).await
327        }
328    }
329}
330
331impl<L: LogSinkAsync + ?Sized> LogSinkAsyncExt for L {}
332
333/// Async mirror of [`LogSource`].
334///
335/// Not object-safe — a trait with `impl Future` returns cannot be — so generic
336/// code over this port dispatches statically. That is the default this crate
337/// wants anyway.
338pub trait LogSourceAsync {
339    /// The most recent entry for a sensor, or `None` if it has none.
340    fn latest(
341        &mut self,
342        sensor_id: u16,
343        buf: &mut [u8],
344    ) -> impl Future<Output = Result<Option<(EntryHeader, usize)>, Error>>;
345
346    /// The oldest retained entry for a sensor, or `None` if it has none.
347    fn oldest(
348        &mut self,
349        sensor_id: u16,
350        buf: &mut [u8],
351    ) -> impl Future<Output = Result<Option<(EntryHeader, usize)>, Error>>;
352
353    /// Entries retained for a sensor, or for every sensor if `None`.
354    fn count(&mut self, sensor_id: Option<u16>) -> impl Future<Output = Result<u32, Error>>;
355
356    /// Entries whose timestamp lies in `[t_start, t_end]`, in log order.
357    ///
358    /// The callback is synchronous: it inspects a payload the driver has
359    /// already read, so there is nothing for it to await.
360    fn query_range(
361        &mut self,
362        sensor_id: Option<u16>,
363        t_start: u64,
364        t_end: u64,
365        callback: &mut dyn FnMut(&EntryHeader, &[u8]) -> bool,
366    ) -> impl Future<Output = Result<u32, Error>>;
367}
368
369/// Async mirror of [`LogSourceExt`], with the same payload-size contract.
370pub trait LogSourceAsyncExt: LogSourceAsync {
371    /// The most recent value for a sensor type.
372    #[allow(clippy::manual_async_fn)]
373    fn latest_sensor<T: SensorData>(
374        &mut self,
375    ) -> impl Future<Output = Result<Option<(EntryHeader, T)>, Error>> {
376        async {
377            let mut framed = Tagged::<T>::empty();
378            let found = self.latest(T::SENSOR_ID, framed.bytes_mut()).await?;
379            untag(found, framed)
380        }
381    }
382
383    /// The oldest retained value for a sensor type.
384    #[allow(clippy::manual_async_fn)]
385    fn oldest_sensor<T: SensorData>(
386        &mut self,
387    ) -> impl Future<Output = Result<Option<(EntryHeader, T)>, Error>> {
388        async {
389            let mut framed = Tagged::<T>::empty();
390            let found = self.oldest(T::SENSOR_ID, framed.bytes_mut()).await?;
391            untag(found, framed)
392        }
393    }
394
395    /// Entries retained for a sensor type.
396    fn count_sensor<T: SensorData>(&mut self) -> impl Future<Output = Result<u32, Error>> {
397        self.count(Some(T::SENSOR_ID))
398    }
399
400    /// Values for a sensor type whose timestamp lies in `[t_start, t_end]`.
401    #[allow(clippy::manual_async_fn)]
402    fn query_sensor<T: SensorData, C>(
403        &mut self,
404        t_start: u64,
405        t_end: u64,
406        mut callback: C,
407    ) -> impl Future<Output = Result<u32, Error>>
408    where
409        C: FnMut(&EntryHeader, &T) -> bool,
410    {
411        async move {
412            let mut delivered = 0u32;
413
414            self.query_range(
415                Some(T::SENSOR_ID),
416                t_start,
417                t_end,
418                &mut |header: &EntryHeader, payload: &[u8]| {
419                    let Some(value) = untag_payload::<T>(payload) else {
420                        return true;
421                    };
422                    delivered += 1;
423                    callback(header, &value)
424                },
425            )
426            .await?;
427
428            Ok(delivered)
429        }
430    }
431
432    /// Every retained value for a sensor type, in log order.
433    fn query_all_sensor<T: SensorData, C>(
434        &mut self,
435        callback: C,
436    ) -> impl Future<Output = Result<u32, Error>>
437    where
438        C: FnMut(&EntryHeader, &T) -> bool,
439    {
440        self.query_sensor(0, u64::MAX, callback)
441    }
442}
443
444impl<L: LogSourceAsync + ?Sized> LogSourceAsyncExt for L {}