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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Run-encoded entries: many evenly spaced samples under one entry header.
//!
//! A single `f32` sample costs 20 bytes of entry overhead plus a 1-byte schema
//! tag to store 4 bytes of data — **84% overhead**. For a burst of samples taken
//! at a fixed cadence, almost all of that is repetition: the same sensor id, and
//! a timestamp the previous one already implies.
//!
//! A *run* stores the burst as one entry:
//!
//! ```text
//! payload = [ schema_version : u8 ] [ interval : u64 LE ] [ count : u16 LE ] [ T ; count ]
//! ```
//!
//! with the entry header's `timestamp` holding the first sample's, so sample `i`
//! is at `base + i * interval`. Thirty-two `f32` samples cost 148 bytes instead
//! of 800.
//!
//! # A run is invisible to readers
//!
//! Every read path expands a run back into the samples it holds, so
//! `query_range`, `latest`, `oldest` and `count` deliver **exactly what
//! [`append_sensor`](crate::LogSinkExt::append_sensor) of the same samples would
//! have delivered** — same headers, same `[version][value]` payloads, same
//! order. Only [`read_from`](crate::SensorDb::read_from) sees the run as one
//! entry, because replication copies entries and a replica should keep the
//! amortisation rather than unpack it.
//!
//! That transparency is what makes runs a pure storage optimisation: a caller
//! can start using them without changing a single read.
//!
//! # Why the marker and not the payload
//!
//! An entry is a run because its header carries
//! [`ENTRY_MARKER_RUN`](crate::entry::ENTRY_MARKER_RUN) instead of
//! [`ENTRY_MARKER`](crate::entry::ENTRY_MARKER) — a field the entry header CRC
//! covers and the raw [`append`](crate::LogSink::append) path cannot write.
//!
//! The alternative — flagging a run in the payload, say with the high bit of the
//! schema tag — was tried and reverted. It cannot work, because a raw payload is
//! *arbitrary bytes*: any payload whose first byte happened to have bit 7 set
//! would read as a run, and the sector index would inherit its invented time
//! span. `tests/model.rs` caught exactly that, on a workload containing no typed
//! data at all. A marker in the header is structural: the raw API always writes
//! `0xAA`, so a run is a run.
//!
//! # Runs are a typed-API feature
//!
//! [`Run::of`] takes `&[T]` for a [`SensorData`] type, because the frame carries
//! a schema tag and expansion produces `[version][value]` payloads — which is
//! precisely what the typed single-sample path writes. There is deliberately no
//! untyped constructor: an untagged run would expand into payloads that no read
//! path could interpret.

use zerocopy::IntoBytes;

use crate::entry::{EntryHeader, EntryKind};
use crate::error::Error;
use crate::schema::SCHEMA_TAG_SIZE;
use crate::typed::SensorData;

/// Bytes a run frame prepends to its samples: the schema tag, the interval, and
/// the sample count.
///
/// A run of `n` values of `T` therefore occupies
/// `ENTRY_OVERHEAD + RUN_FRAME_SIZE + n * size_of::<T>()` bytes of flash,
/// against `n * (ENTRY_OVERHEAD + SCHEMA_TAG_SIZE + size_of::<T>())` for the
/// same samples appended one at a time.
pub const RUN_FRAME_SIZE: usize = SCHEMA_TAG_SIZE + 8 + 2;

/// Offset of the `interval` field within a run payload.
const INTERVAL_AT: usize = SCHEMA_TAG_SIZE;

/// Offset of the `count` field within a run payload.
const COUNT_AT: usize = INTERVAL_AT + 8;

/// Evenly spaced samples of one sensor, ready to be appended as a single entry.
///
/// Construct with [`Run::of`], which validates everything an appender would
/// otherwise have to re-check, and hand it to
/// [`append_run`](crate::LogSink::append_run):
///
/// ```ignore
/// use sensor_db::{LogSink, Run};
///
/// let burst: [Temperature; 32] = collect_burst();
/// db.append_run(&Run::of(t0, 10_000, &burst)?)?;
/// ```
///
/// The samples are borrowed, not copied: the driver writes the frame header and
/// then the sample bytes straight into its page buffer.
#[derive(Debug, Clone, Copy)]
pub struct Run<'a> {
    sensor_id: u16,
    base_timestamp: u64,
    interval: u64,
    schema_version: u8,
    count: u16,
    samples: &'a [u8],
}

impl<'a> Run<'a> {
    /// Describe a run of `T` values, the first at `base_timestamp` and each
    /// subsequent one `interval` later.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidRun`] if `samples` is empty or longer than `u16::MAX`,
    /// if `T` is zero-sized, if the last sample's timestamp would overflow
    /// `u64`, or if the frame would exceed the `u16` payload length the entry
    /// header can carry. Whether it fits a *page* is the appending log's
    /// question, and it answers [`Error::PayloadTooLarge`].
    pub fn of<T: SensorData>(
        base_timestamp: u64,
        interval: u64,
        samples: &'a [T],
    ) -> Result<Self, Error> {
        let stride = core::mem::size_of::<T>();
        if stride == 0 {
            return Err(Error::InvalidRun);
        }
        let count = u16::try_from(samples.len())
            .ok()
            .filter(|&n| n > 0)
            .ok_or(Error::InvalidRun)?;

        // The run is unreadable if its own last timestamp is not representable,
        // so refuse to write it rather than storing samples that read back
        // clamped. Checked here, once, which is what lets every reader use
        // saturating arithmetic without hiding a defect.
        interval
            .checked_mul(u64::from(count - 1))
            .and_then(|span| base_timestamp.checked_add(span))
            .ok_or(Error::InvalidRun)?;

        let bytes = samples.as_bytes();
        if RUN_FRAME_SIZE + bytes.len() > u16::MAX as usize {
            return Err(Error::InvalidRun);
        }

        Ok(Self {
            sensor_id: T::SENSOR_ID,
            base_timestamp,
            interval,
            schema_version: T::SCHEMA_VERSION,
            count,
            samples: bytes,
        })
    }

    /// The sensor id the samples are stored under.
    pub fn sensor_id(&self) -> u16 {
        self.sensor_id
    }

    /// Timestamp of the first sample, which is the entry header's timestamp.
    pub fn base_timestamp(&self) -> u64 {
        self.base_timestamp
    }

    /// Timestamp step between consecutive samples.
    pub fn interval(&self) -> u64 {
        self.interval
    }

    /// How many samples the run holds; never zero.
    pub fn count(&self) -> u32 {
        u32::from(self.count)
    }

    /// Timestamp of the last sample.
    pub fn span_end(&self) -> u64 {
        // Cannot overflow: `of` rejected a run whose end is not representable.
        self.base_timestamp + self.interval * u64::from(self.count - 1)
    }

    /// Bytes the run occupies as an entry payload.
    pub fn payload_len(&self) -> usize {
        RUN_FRAME_SIZE + self.samples.len()
    }

    /// The sample bytes, `count * size_of::<T>()` of them.
    pub(crate) fn samples(&self) -> &'a [u8] {
        self.samples
    }

    /// Write the frame header — everything before the samples — into `buf`.
    ///
    /// # Panics
    ///
    /// If `buf` is shorter than [`RUN_FRAME_SIZE`]. Callers size it from
    /// [`payload_len`](Self::payload_len).
    pub(crate) fn write_frame(&self, buf: &mut [u8]) {
        buf[0] = self.schema_version;
        buf[INTERVAL_AT..INTERVAL_AT + 8].copy_from_slice(&self.interval.to_le_bytes());
        buf[COUNT_AT..COUNT_AT + 2].copy_from_slice(&self.count.to_le_bytes());
    }
}

/// The frame of a stored run, read back from the payload of an entry carrying
/// [`ENTRY_MARKER_RUN`](crate::entry::ENTRY_MARKER_RUN).
///
/// Borrows nothing: it is the four numbers that describe the samples, so a
/// caller can hold it while still handing the payload buffer out mutably to
/// [`tagged_sample`](Self::tagged_sample).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RunFrame {
    schema_version: u8,
    interval: u64,
    count: u32,
    stride: usize,
}

impl RunFrame {
    /// Read the frame out of a run's payload, or `None` if the payload is not a
    /// well-formed run.
    ///
    /// The marker already says the writer meant a run, and the entry CRC says
    /// these are the bytes it wrote — so this rejects only what no writer of
    /// this crate can produce: no samples, a zero count, or a sample region that
    /// does not divide evenly into `count` samples. Callers treat `None` exactly
    /// as they treat a CRC failure, which keeps every scan walking a sector the
    /// same way.
    pub(crate) fn parse(payload: &[u8]) -> Option<Self> {
        // Strictly greater: a run with no room for even one sample is malformed.
        if payload.len() <= RUN_FRAME_SIZE {
            return None;
        }

        let mut interval = [0u8; 8];
        interval.copy_from_slice(&payload[INTERVAL_AT..INTERVAL_AT + 8]);
        let count = u32::from(u16::from_le_bytes([
            payload[COUNT_AT],
            payload[COUNT_AT + 1],
        ]));
        if count == 0 {
            return None;
        }

        let body = payload.len() - RUN_FRAME_SIZE;
        if !body.is_multiple_of(count as usize) {
            return None;
        }

        Some(Self {
            schema_version: payload[0],
            interval: u64::from_le_bytes(interval),
            count,
            // Non-zero: `body >= 1` and `count` divides it, so `count <= body`.
            stride: body / count as usize,
        })
    }

    /// How many samples the run holds; never zero.
    pub(crate) fn count(&self) -> u32 {
        self.count
    }

    /// Timestamp of sample `index`, counting from the entry header's `base`.
    ///
    /// Saturating, which cannot bite a run this crate wrote: [`Run::of`] refuses
    /// one whose end is not representable.
    pub(crate) fn timestamp_at(&self, base: u64, index: u32) -> u64 {
        base.saturating_add(self.interval.saturating_mul(u64::from(index)))
    }

    /// Timestamp of the last sample — how far past the entry header's timestamp
    /// this entry reaches.
    pub(crate) fn span_end(&self, base: u64) -> u64 {
        self.timestamp_at(base, self.count - 1)
    }

    /// The header sample `index` would have carried had it been appended alone.
    pub(crate) fn header_at(&self, sensor_id: u16, base: u64, index: u32) -> EntryHeader {
        EntryHeader {
            sensor_id,
            timestamp: self.timestamp_at(base, index),
            // Always representable: the whole run fit a `u16` payload length.
            payload_len: (SCHEMA_TAG_SIZE + self.stride) as u16,
            // An expanded sample is indistinguishable from one appended alone,
            // and that includes its kind.
            kind: EntryKind::Single,
        }
    }

    /// Sample `index` as a schema-tagged payload — byte for byte what
    /// `append_sensor` would have stored for that sample alone.
    ///
    /// # The tag byte is written in place
    ///
    /// A tagged payload is `[version][value]`, and the run stores the version
    /// *once*, at the front. Rather than copy the sample into a scratch buffer
    /// to put a tag in front of it, this writes the version into the byte
    /// immediately preceding sample `index` and hands out the two together.
    ///
    /// That byte is the last byte of sample `index - 1` — already delivered, in
    /// a forward walk — or, for `index == 0`, the high byte of `count`, which
    /// this frame has already read. Nothing that is still needed is overwritten,
    /// and the buffer holds a copy of flash, so the medium is untouched.
    ///
    /// # Panics
    ///
    /// If `index >= count` or `payload` is not the run's whole payload.
    pub(crate) fn tagged_sample<'a>(&self, payload: &'a mut [u8], index: u32) -> &'a [u8] {
        debug_assert!(index < self.count);
        let start = RUN_FRAME_SIZE + index as usize * self.stride;
        payload[start - SCHEMA_TAG_SIZE] = self.schema_version;
        &payload[start - SCHEMA_TAG_SIZE..start + self.stride]
    }

    /// Copy sample `index` into `out` as a schema-tagged payload, returning its
    /// length, or `None` if `out` cannot hold it.
    ///
    /// The copying twin of [`tagged_sample`](Self::tagged_sample), for the
    /// readers whose payload is behind a shared reference — the page buffer,
    /// and a replication stream's callback — or who are filling a caller's
    /// output buffer anyway and would gain nothing from writing in place.
    pub(crate) fn write_tagged_sample(
        &self,
        payload: &[u8],
        index: u32,
        out: &mut [u8],
    ) -> Option<usize> {
        debug_assert!(index < self.count);
        let len = SCHEMA_TAG_SIZE + self.stride;
        if out.len() < len {
            return None;
        }
        let start = RUN_FRAME_SIZE + index as usize * self.stride;
        out[0] = self.schema_version;
        out[SCHEMA_TAG_SIZE..len].copy_from_slice(&payload[start..start + self.stride]);
        Some(len)
    }
}

/// Deliver the samples an entry holds whose timestamps fall in `[t_start, t_end]`.
///
/// One callback per *sample*, which is what makes a run indistinguishable from
/// the same samples appended one at a time — the transparency the whole feature
/// rests on. A single-sample entry is delivered as itself, unfiltered by any
/// framing, so the raw API is untouched.
///
/// `payload` is written through: see [`RunFrame::tagged_sample`]. It must be a
/// buffer holding a *copy* of the entry, which every caller already has, since
/// payloads reach them through a read into scratch.
///
/// Returns `true` if the callback asked to stop.
#[allow(clippy::too_many_arguments)]
pub(crate) fn deliver_samples(
    is_run: bool,
    sensor_id: u16,
    base: u64,
    payload: &mut [u8],
    t_start: u64,
    t_end: u64,
    count: &mut u32,
    callback: &mut dyn FnMut(&EntryHeader, &[u8]) -> bool,
) -> bool {
    let frame = match is_run {
        true => match RunFrame::parse(payload) {
            Some(frame) => frame,
            // Rejected upstream by the same test that rejects a bad CRC; this
            // is the belt to that braces.
            None => return false,
        },
        false => {
            if base < t_start || base > t_end {
                return false;
            }
            *count += 1;
            let header = EntryHeader {
                sensor_id,
                timestamp: base,
                payload_len: payload.len() as u16,
                kind: EntryKind::Single,
            };
            return !callback(&header, payload);
        }
    };

    for index in 0..frame.count() {
        let timestamp = frame.timestamp_at(base, index);
        // Ascending and unsigned, so once past the end nothing later qualifies.
        if timestamp > t_end {
            break;
        }
        if timestamp < t_start {
            continue;
        }
        *count += 1;
        let header = frame.header_at(sensor_id, base, index);
        if !callback(&header, frame.tagged_sample(payload, index)) {
            return true;
        }
    }

    false
}

/// How many samples an entry delivers: one, unless it is a well-formed run.
///
/// The single place that answers "what does this entry count as", so the index,
/// `count` and `query_range` cannot drift apart.
pub(crate) fn samples_in(is_run: bool, payload: &[u8]) -> u32 {
    if !is_run {
        return 1;
    }
    RunFrame::parse(payload).map_or(0, |frame| frame.count())
}

#[cfg(test)]
mod tests {
    use super::*;
    use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

    #[derive(FromBytes, IntoBytes, KnownLayout, Immutable, Debug, Clone, Copy, PartialEq)]
    #[repr(C)]
    struct Reading {
        raw: u32,
    }

    impl SensorData for Reading {
        const SENSOR_ID: u16 = 0x42;
        const SCHEMA_VERSION: u8 = 3;
    }

    /// Lay a `Run` out the way an appending driver does.
    fn encode(run: &Run<'_>) -> heapless::Vec<u8, 512> {
        let mut buf = heapless::Vec::new();
        buf.resize(run.payload_len(), 0).unwrap();
        run.write_frame(&mut buf[..RUN_FRAME_SIZE]);
        buf[RUN_FRAME_SIZE..].copy_from_slice(run.samples());
        buf
    }

    #[test]
    fn a_run_round_trips_through_its_own_frame() {
        let samples = [Reading { raw: 1 }, Reading { raw: 2 }, Reading { raw: 3 }];
        let run = Run::of(1_000, 25, &samples).unwrap();

        assert_eq!(run.sensor_id(), 0x42);
        assert_eq!(run.count(), 3);
        assert_eq!(run.span_end(), 1_050);
        assert_eq!(run.payload_len(), RUN_FRAME_SIZE + 12);

        let mut payload = encode(&run);
        let frame = RunFrame::parse(&payload).unwrap();

        assert_eq!(frame.count(), 3);
        assert_eq!(frame.span_end(1_000), 1_050);
        for (i, sample) in samples.iter().enumerate() {
            let i = i as u32;
            assert_eq!(frame.timestamp_at(1_000, i), 1_000 + 25 * u64::from(i));
            let tagged = frame.tagged_sample(&mut payload, i);
            assert_eq!(tagged[0], Reading::SCHEMA_VERSION);
            assert_eq!(&tagged[1..], sample.as_bytes());
        }
    }

    #[test]
    fn an_expanded_sample_is_byte_for_byte_a_single_append() {
        // The transparency invariant, at the framing level: what `tagged_sample`
        // hands out must equal what the single-sample path stores.
        let samples = [Reading { raw: 0xDEAD_BEEF }, Reading { raw: 7 }];
        let run = Run::of(0, 1, &samples).unwrap();
        let mut payload = encode(&run);
        let frame = frame_of(&payload);

        for (i, sample) in samples.iter().enumerate() {
            let single = crate::schema::tag(sample);
            assert_eq!(frame.tagged_sample(&mut payload, i as u32), single.bytes());
        }
    }

    fn frame_of(payload: &[u8]) -> RunFrame {
        RunFrame::parse(payload).unwrap()
    }

    #[test]
    fn the_headers_a_run_expands_to_are_the_ones_single_appends_would_carry() {
        let samples = [Reading { raw: 1 }; 4];
        let run = Run::of(500, 10, &samples).unwrap();
        let frame = frame_of(&encode(&run));

        for i in 0..4u32 {
            assert_eq!(
                frame.header_at(Reading::SENSOR_ID, 500, i),
                EntryHeader {
                    sensor_id: Reading::SENSOR_ID,
                    timestamp: 500 + 10 * u64::from(i),
                    payload_len: (SCHEMA_TAG_SIZE + 4) as u16,
                    kind: EntryKind::Single,
                }
            );
        }
    }

    #[test]
    fn a_single_sample_run_is_legal_and_spans_nothing() {
        let run = Run::of(9, 1_000, &[Reading { raw: 1 }]).unwrap();
        assert_eq!(run.count(), 1);
        assert_eq!(run.span_end(), 9);

        let frame = frame_of(&encode(&run));
        assert_eq!(frame.span_end(9), 9);
    }

    #[test]
    fn a_zero_interval_run_stacks_every_sample_on_one_timestamp() {
        let run = Run::of(4, 0, &[Reading { raw: 1 }; 3]).unwrap();
        assert_eq!(run.span_end(), 4);

        let frame = frame_of(&encode(&run));
        assert_eq!(frame.timestamp_at(4, 2), 4);
    }

    #[test]
    fn an_empty_run_is_rejected_rather_than_stored_as_nothing() {
        assert_eq!(
            Run::of::<Reading>(0, 1, &[]).unwrap_err(),
            Error::InvalidRun
        );
    }

    #[test]
    fn a_run_whose_last_timestamp_would_overflow_is_refused() {
        // The check is on the *last* sample, not the first: this base is fine.
        assert!(Run::of(u64::MAX, 0, &[Reading { raw: 1 }; 4]).is_ok());
        assert_eq!(
            Run::of(u64::MAX - 1, 1, &[Reading { raw: 1 }; 4]).unwrap_err(),
            Error::InvalidRun
        );
        assert_eq!(
            Run::of(0, u64::MAX, &[Reading { raw: 1 }; 3]).unwrap_err(),
            Error::InvalidRun
        );
    }

    #[test]
    fn a_payload_that_is_not_a_well_formed_run_parses_to_nothing() {
        // Too short to hold a sample.
        assert!(RunFrame::parse(&[0u8; RUN_FRAME_SIZE]).is_none());
        assert!(RunFrame::parse(&[]).is_none());

        // A zero count would divide by zero.
        let mut payload = [0u8; RUN_FRAME_SIZE + 4];
        assert!(RunFrame::parse(&payload).is_none());

        // A count that does not divide the sample region evenly.
        payload[COUNT_AT] = 3;
        assert!(RunFrame::parse(&payload).is_none());

        payload[COUNT_AT] = 4;
        assert_eq!(RunFrame::parse(&payload).unwrap().stride, 1);
    }

    #[test]
    fn samples_in_answers_for_both_entry_kinds() {
        let run = Run::of(0, 1, &[Reading { raw: 1 }; 5]).unwrap();
        assert_eq!(samples_in(true, &encode(&run)), 5);
        assert_eq!(samples_in(false, &encode(&run)), 1);
        // A malformed run contributes nothing, matching the scans that skip it.
        assert_eq!(samples_in(true, &[0u8; 4]), 0);
    }
}