sensor-db 0.1.0

Append-only sensor database for NOR flash on embedded devices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Capability ports: what a caller needs from a log, without naming which log.
//!
//! [`SensorDb`](crate::SensorDb) and [`TieredDb`](crate::TieredDb) are two
//! different things — one log, or an onboard log plus a removable replica — but
//! everything layered on top of them wants the same two capabilities: somewhere
//! to put a sample ([`LogSink`]) and somewhere to read samples back
//! ([`LogSource`]). Naming the capability instead of the concrete type is what
//! lets [`SensorLogger`](crate::SensorLogger) and the typed API work over
//! either.
//!
//! # The ports are narrow; the conveniences are mixins
//!
//! `LogSink` is two methods and `LogSource` is four — the operations an
//! implementor genuinely has to *do*. Everything derivable from them (the typed
//! API: `append_sensor`, `latest_sensor`, `query_sensor`, …) lives in the
//! blanket-implemented extension traits [`LogSinkExt`] and [`LogSourceExt`],
//! where it is defined exactly once and cannot be customised — the
//! `SensorData` → bytes mapping must be uniform or two implementors would
//! disagree about what a stored entry means.
//!
//! Import the `Ext` trait to get those methods:
//!
//! ```ignore
//! use sensor_db::port::{LogSinkExt, LogSourceExt};
//!
//! fn record<L: LogSinkExt>(log: &mut L, t: u64) -> Result<(), Error> {
//!     log.append_sensor(t, &Temperature { celsius: 25.5 })
//! }
//! ```
//!
//! # The same methods exist inherently on the logs, and that is deliberate
//!
//! [`SensorDb`](crate::SensorDb) and [`TieredDb`](crate::TieredDb) each carry
//! their own `append_sensor` / `latest_sensor` / … with signatures identical to
//! these. It is the ordinary Rust split, not a second API: the inherent method is
//! what you call on a concrete log with no `use` line, and the mixin is what
//! generic code binds on. Method resolution prefers the inherent one, so which
//! is in scope never changes behaviour — both forward to the same framing in
//! [`schema`](crate::schema).
//!
//! There is deliberately nothing else. Earlier revisions also offered a
//! `Sensor<T>` handle and a value-first `SensorDataExt` (`value.store(&mut db, t)`);
//! both were restatements of the two above, and five spellings of one operation
//! is a documentation burden with no answer to "which one should I use".
//!
//! # Async
//!
//! [`LogSinkAsync`] and [`LogSourceAsync`] mirror them. Both are defined
//! unconditionally, feature or no feature: a trait definition costs nothing to
//! compile and gating it would force callers to gate their own generic code.
//! The `async` feature gates the *implementations*
//! ([`SensorDbAsync`](crate::SensorDbAsync),
//! [`TieredDbAsync`](crate::TieredDbAsync)), which are the parts that need
//! `embedded-storage-async`.
//!
//! # `&mut self`, even for reads
//!
//! Reading flash is a `&mut` operation — `ReadNorFlash::read` takes `&mut self`
//! — and for [`TieredDb`](crate::TieredDb) it is doubly so, since answering a
//! query means streaming the onboard log from the replication watermark. So
//! [`LogSource`] takes `&mut self`, and the inherent methods on the logs agree
//! with it.
//!
//! They did not always. `SensorDb` once held its driver in a `RefCell` to offer
//! `&self` reads, which made it `!Sync` — so the only way to share one was a
//! `Mutex`, which yields `&mut` regardless — while splitting every read into two
//! shapes and adding a re-entrancy panic to guard against. Removing it cost the
//! `&self` reads and bought back one uniform signature.

use core::future::Future;

use zerocopy::{Immutable, IntoBytes};

use crate::entry::EntryHeader;
use crate::error::Error;
use crate::run::Run;
use crate::schema::{Tagged, read_tagged, tag, untag, untag_payload};
use crate::typed::SensorData;

// ---------------------------------------------------------------------------
// Write capability
// ---------------------------------------------------------------------------

/// Somewhere sensor samples can be appended and made durable.
///
/// Three methods, each a thing an implementor genuinely has to *do*. A sink that
/// could only append would let a caller believe data was safe when it was still
/// in a RAM page buffer, and one that exposed the ring, the sectors or the
/// geometry would stop being implementable by anything but a `SensorDb`.
///
/// [`append_run`](Self::append_run) is here rather than in the mixin because a
/// run is a *different entry* — it carries its own marker — so it cannot be
/// derived from `append`, and a sink that stored a run's frame as an ordinary
/// payload would produce entries no read path could interpret.
pub trait LogSink {
    /// Append a sample.
    fn append(&mut self, sensor_id: u16, timestamp: u64, payload: &[u8]) -> Result<(), Error>;

    /// Append a [run](crate::run): many evenly spaced samples under one header.
    ///
    /// Invisible to every read — a run expands back into the samples it holds,
    /// so this stores exactly what [`append_sensor`](LogSinkExt::append_sensor)
    /// of the same samples would have, in a fraction of the flash.
    fn append_run(&mut self, run: &Run<'_>) -> Result<(), Error>;

    /// Make everything appended so far durable.
    fn sync(&mut self) -> Result<(), Error>;
}

/// Typed conveniences over any [`LogSink`].
///
/// Blanket-implemented, so implementing `LogSink` is enough to get these — and
/// they cannot be overridden, which is the point: how a [`SensorData`] value
/// becomes payload bytes has to be identical everywhere, or the same entry
/// would read back differently depending on which log wrote it.
pub trait LogSinkExt: LogSink {
    /// Append a value's bytes under an explicit sensor ID.
    ///
    /// Raw: the bytes go to flash as they are, with no schema tag. Entries
    /// written this way are not readable through the `*_sensor` methods.
    fn append_value<T: IntoBytes + Immutable>(
        &mut self,
        sensor_id: u16,
        timestamp: u64,
        data: &T,
    ) -> Result<(), Error> {
        self.append(sensor_id, timestamp, data.as_bytes())
    }

    /// Append a value under the sensor ID its type declares.
    ///
    /// The payload is the type's
    /// [`SCHEMA_VERSION`](SensorData::SCHEMA_VERSION) followed by the value's
    /// bytes, so a later firmware reading the same sensor ID can tell an entry
    /// of its own era from one of an older one.
    fn append_sensor<T: SensorData>(&mut self, timestamp: u64, data: &T) -> Result<(), Error> {
        let framed = tag(data);
        self.append(T::SENSOR_ID, timestamp, framed.bytes())
    }
}

impl<L: LogSink + ?Sized> LogSinkExt for L {}

// ---------------------------------------------------------------------------
// Read capability
// ---------------------------------------------------------------------------

/// Somewhere sensor samples can be read back.
///
/// Payloads are delivered into a caller-provided buffer or to a callback, never
/// allocated — this crate is `no_std` and has no allocator to reach for.
pub trait LogSource {
    /// The most recent entry for a sensor, or `None` if it has none.
    ///
    /// Returns the header and the payload length written into `buf`.
    ///
    /// # Errors
    /// - `BufferTooSmall` if `buf` cannot hold the payload
    fn latest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error>;

    /// The oldest retained entry for a sensor, or `None` if it has none.
    ///
    /// # Errors
    /// - `BufferTooSmall` if `buf` cannot hold the payload
    fn oldest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> Result<Option<(EntryHeader, usize)>, Error>;

    /// Entries retained for a sensor, or for every sensor if `None`.
    fn count(&mut self, sensor_id: Option<u16>) -> Result<u32, Error>;

    /// Entries whose timestamp lies in `[t_start, t_end]`, in log order.
    ///
    /// The callback returns `false` to stop, which stops *after* consuming the
    /// entry offered — the opposite of
    /// [`SensorDb::read_from`](crate::SensorDb::read_from), which is a
    /// replication stream rather than a query.
    ///
    /// The callback is `&mut dyn` rather than a generic parameter so that this
    /// trait stays object-safe; the per-entry indirection is nothing beside the
    /// flash read that produced the entry.
    ///
    /// # Returns
    /// The number of entries delivered.
    fn query_range(
        &mut self,
        sensor_id: Option<u16>,
        t_start: u64,
        t_end: u64,
        callback: &mut dyn FnMut(&EntryHeader, &[u8]) -> bool,
    ) -> Result<u32, Error>;
}

/// Typed conveniences over any [`LogSource`].
///
/// # What counts as a `T`
///
/// A typed payload is the type's
/// [`SCHEMA_VERSION`](SensorData::SCHEMA_VERSION) followed by `size_of::<T>()`
/// bytes, so an entry stored under `T::SENSOR_ID` qualifies only if both agree.
/// The single-entry reads deserialise into a `Tagged<T>`-sized buffer and say
/// which half failed: a wrong length reports `SizeMismatch` when short and
/// `BufferTooSmall` when long, a wrong version reports `SchemaMismatch` naming
/// the version found.
///
/// [`query_sensor`](Self::query_sensor) instead *skips* entries that are not a
/// `T`, because a query that aborted on the first stale entry could never reach
/// the good ones behind it. That is also the migration path: two types sharing a
/// sensor ID at different versions each read their own era.
///
/// The header handed back describes the *entry*, so its `payload_len` counts the
/// schema tag as well as the value.
pub trait LogSourceExt: LogSource {
    /// The most recent value for a sensor type.
    fn latest_sensor<T: SensorData>(&mut self) -> Result<Option<(EntryHeader, T)>, Error> {
        read_tagged(|buf| self.latest(T::SENSOR_ID, buf))
    }

    /// The oldest retained value for a sensor type.
    fn oldest_sensor<T: SensorData>(&mut self) -> Result<Option<(EntryHeader, T)>, Error> {
        read_tagged(|buf| self.oldest(T::SENSOR_ID, buf))
    }

    /// Entries retained for a sensor type.
    fn count_sensor<T: SensorData>(&mut self) -> Result<u32, Error> {
        self.count(Some(T::SENSOR_ID))
    }

    /// Values for a sensor type whose timestamp lies in `[t_start, t_end]`.
    ///
    /// # Returns
    /// The number of entries delivered — entries skipped for a wrong schema
    /// version or payload length are not counted.
    fn query_sensor<T: SensorData, C>(
        &mut self,
        t_start: u64,
        t_end: u64,
        mut callback: C,
    ) -> Result<u32, Error>
    where
        C: FnMut(&EntryHeader, &T) -> bool,
    {
        let mut delivered = 0u32;

        self.query_range(
            Some(T::SENSOR_ID),
            t_start,
            t_end,
            &mut |header: &EntryHeader, payload: &[u8]| {
                let Some(value) = untag_payload::<T>(payload) else {
                    return true;
                };
                delivered += 1;
                callback(header, &value)
            },
        )?;

        Ok(delivered)
    }

    /// Every retained value for a sensor type, in log order.
    fn query_all_sensor<T: SensorData, C>(&mut self, callback: C) -> Result<u32, Error>
    where
        C: FnMut(&EntryHeader, &T) -> bool,
    {
        self.query_sensor(0, u64::MAX, callback)
    }
}

impl<L: LogSource + ?Sized> LogSourceExt for L {}

// ---------------------------------------------------------------------------
// Async mirrors
// ---------------------------------------------------------------------------

/// Async mirror of [`LogSink`].
///
/// Methods return `impl Future` rather than being `async fn` so the returned
/// futures carry no implicit `Send` bound — an executor like Embassy runs them
/// on one core and does not need it.
pub trait LogSinkAsync {
    /// Append a sample.
    fn append(
        &mut self,
        sensor_id: u16,
        timestamp: u64,
        payload: &[u8],
    ) -> impl Future<Output = Result<(), Error>>;

    /// Append a [run](crate::run): many evenly spaced samples under one header.
    fn append_run(&mut self, run: &Run<'_>) -> impl Future<Output = Result<(), Error>>;

    /// Make everything appended so far durable.
    fn sync(&mut self) -> impl Future<Output = Result<(), Error>>;
}

/// Async mirror of [`LogSinkExt`].
pub trait LogSinkAsyncExt: LogSinkAsync {
    /// Append a value's bytes under an explicit sensor ID, untagged.
    fn append_value<T: IntoBytes + Immutable>(
        &mut self,
        sensor_id: u16,
        timestamp: u64,
        data: &T,
    ) -> impl Future<Output = Result<(), Error>> {
        self.append(sensor_id, timestamp, data.as_bytes())
    }

    /// Append a value under the sensor ID its type declares, schema-tagged.
    #[allow(clippy::manual_async_fn)]
    fn append_sensor<T: SensorData>(
        &mut self,
        timestamp: u64,
        data: &T,
    ) -> impl Future<Output = Result<(), Error>> {
        // The framed copy has to outlive the await, so it is bound here rather
        // than being a temporary in the call.
        async move {
            let framed = tag(data);
            self.append(T::SENSOR_ID, timestamp, framed.bytes()).await
        }
    }
}

impl<L: LogSinkAsync + ?Sized> LogSinkAsyncExt for L {}

/// Async mirror of [`LogSource`].
///
/// Not object-safe — a trait with `impl Future` returns cannot be — so generic
/// code over this port dispatches statically. That is the default this crate
/// wants anyway.
pub trait LogSourceAsync {
    /// The most recent entry for a sensor, or `None` if it has none.
    fn latest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> impl Future<Output = Result<Option<(EntryHeader, usize)>, Error>>;

    /// The oldest retained entry for a sensor, or `None` if it has none.
    fn oldest(
        &mut self,
        sensor_id: u16,
        buf: &mut [u8],
    ) -> impl Future<Output = Result<Option<(EntryHeader, usize)>, Error>>;

    /// Entries retained for a sensor, or for every sensor if `None`.
    fn count(&mut self, sensor_id: Option<u16>) -> impl Future<Output = Result<u32, Error>>;

    /// Entries whose timestamp lies in `[t_start, t_end]`, in log order.
    ///
    /// The callback is synchronous: it inspects a payload the driver has
    /// already read, so there is nothing for it to await.
    fn query_range(
        &mut self,
        sensor_id: Option<u16>,
        t_start: u64,
        t_end: u64,
        callback: &mut dyn FnMut(&EntryHeader, &[u8]) -> bool,
    ) -> impl Future<Output = Result<u32, Error>>;
}

/// Async mirror of [`LogSourceExt`], with the same payload-size contract.
pub trait LogSourceAsyncExt: LogSourceAsync {
    /// The most recent value for a sensor type.
    #[allow(clippy::manual_async_fn)]
    fn latest_sensor<T: SensorData>(
        &mut self,
    ) -> impl Future<Output = Result<Option<(EntryHeader, T)>, Error>> {
        async {
            let mut framed = Tagged::<T>::empty();
            let found = self.latest(T::SENSOR_ID, framed.bytes_mut()).await?;
            untag(found, framed)
        }
    }

    /// The oldest retained value for a sensor type.
    #[allow(clippy::manual_async_fn)]
    fn oldest_sensor<T: SensorData>(
        &mut self,
    ) -> impl Future<Output = Result<Option<(EntryHeader, T)>, Error>> {
        async {
            let mut framed = Tagged::<T>::empty();
            let found = self.oldest(T::SENSOR_ID, framed.bytes_mut()).await?;
            untag(found, framed)
        }
    }

    /// Entries retained for a sensor type.
    fn count_sensor<T: SensorData>(&mut self) -> impl Future<Output = Result<u32, Error>> {
        self.count(Some(T::SENSOR_ID))
    }

    /// Values for a sensor type whose timestamp lies in `[t_start, t_end]`.
    #[allow(clippy::manual_async_fn)]
    fn query_sensor<T: SensorData, C>(
        &mut self,
        t_start: u64,
        t_end: u64,
        mut callback: C,
    ) -> impl Future<Output = Result<u32, Error>>
    where
        C: FnMut(&EntryHeader, &T) -> bool,
    {
        async move {
            let mut delivered = 0u32;

            self.query_range(
                Some(T::SENSOR_ID),
                t_start,
                t_end,
                &mut |header: &EntryHeader, payload: &[u8]| {
                    let Some(value) = untag_payload::<T>(payload) else {
                        return true;
                    };
                    delivered += 1;
                    callback(header, &value)
                },
            )
            .await?;

            Ok(delivered)
        }
    }

    /// Every retained value for a sensor type, in log order.
    fn query_all_sensor<T: SensorData, C>(
        &mut self,
        callback: C,
    ) -> impl Future<Output = Result<u32, Error>>
    where
        C: FnMut(&EntryHeader, &T) -> bool,
    {
        self.query_sensor(0, u64::MAX, callback)
    }
}

impl<L: LogSourceAsync + ?Sized> LogSourceAsyncExt for L {}