Skip to main content

sensor_db/spool/
blocking.rs

1//! Blocking store-and-forward drivers: [`Spooler`] and [`TieredDb`].
2
3use embedded_storage::nor_flash::{NorFlash, ReadNorFlash};
4use zerocopy::IntoBytes;
5
6use crate::db::{LogPosition, Replicated, SensorDb, SpoolStats};
7use crate::entry::EntryHeader;
8use crate::error::Error;
9use crate::run::{Run, deliver_samples, samples_in};
10use crate::sector::LogId;
11use crate::spool::cursor::{CURSOR_RECORD_SIZE, CursorRegion, SpoolCursorWire};
12use crate::spool::policy::{
13    Attached, BatchSector, CursorFold, CursorScan, EraseTally, RunFingerprint, SpoolBudget,
14    SpoolFailure, SpoolProgress, SpoolerState, VolumeFill,
15};
16use crate::spool::port::Removable;
17use crate::spool::tier::{
18    PROMOTE_MAX_BATCHES, TierMode, WriteMode, WritePolicy, merge, volume_gone,
19};
20
21/// State of the removable volume the spooler owns.
22///
23/// Modelled as a type rather than an `Option` plus a flag so that "attached but
24/// broken" cannot be confused with "attached and usable".
25enum Slot<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize> {
26    /// Nothing attached.
27    Empty,
28    /// Attached and usable.
29    Ready(SensorDb<C, PAGE_SIZE, MAX_SECTORS>),
30    /// A flash operation failed. The database is retained so the application can
31    /// still detach and inspect it, but no further replication is attempted.
32    Faulted(SensorDb<C, PAGE_SIZE, MAX_SECTORS>),
33}
34
35/// Copies a log onto a removable volume, and remembers how far it got.
36///
37/// The spooler owns the volume and borrows the source on each pass, which
38/// matches the physical situation: the card comes and goes, the spooler is the
39/// long-lived thing.
40///
41/// # What it guarantees
42///
43/// - **No loss.** The source's replication watermark advances only after the
44///   replica's copy is durable, so an interruption anywhere re-copies rather
45///   than skips.
46/// - **Bounded duplication.** A power cut or an unclean removal replays at most
47///   the batch that was in flight — [`SpoolBudget::max_entries`] entries.
48/// - **In practice, none.** [`attach`](Self::attach) reads the replica to find
49///   how much of an interrupted batch it kept, and [`reconcile`](Self::reconcile)
50///   skips exactly that much on the source. The bound above is what remains when
51///   the two sides cannot be made to agree.
52/// - **Nothing is written to a foreign volume.** A medium belonging to a
53///   different log is rejected at [`attach`](Self::attach).
54///
55/// # RAM
56///
57/// One page buffer for cursor records, plus about 64 bytes of state.
58pub struct Spooler<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize> {
59    slot: Slot<C, PAGE_SIZE, MAX_SECTORS>,
60    /// Every decision this spooler makes, shared verbatim with the async one.
61    state: SpoolerState,
62    scratch: [u8; PAGE_SIZE],
63}
64
65/// Inspection that needs no flash access, and therefore no trait bounds.
66impl<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize> Spooler<C, PAGE_SIZE, MAX_SECTORS> {
67    /// Whether a volume is attached, faulted or not.
68    pub fn is_attached(&self) -> bool {
69        !matches!(self.slot, Slot::Empty)
70    }
71
72    /// Whether the attached volume has faulted and needs detaching.
73    pub fn is_faulted(&self) -> bool {
74        matches!(self.slot, Slot::Faulted(_))
75    }
76
77    /// Source position replication will resume from, if a volume is attached.
78    pub fn resume_point(&self) -> Option<LogPosition> {
79        self.is_attached().then(|| self.state.resume())
80    }
81
82    /// Identity of the log this spooler replicates.
83    pub fn source_log(&self) -> Option<LogId> {
84        self.state.source_log()
85    }
86
87    /// Layout of the cursor region on the volume.
88    pub fn region(&self) -> CursorRegion {
89        *self.state.region()
90    }
91
92    /// Entries of an interrupted batch that the replica already holds and the
93    /// next pass will skip rather than copy again.
94    ///
95    /// Non-zero only between an [`attach`](Self::attach) that found an
96    /// unfinished batch and the [`reconcile`](Self::reconcile) or
97    /// [`spool`](Self::spool) that applies the skip.
98    pub fn pending_reconciliation(&self) -> u32 {
99        self.state.pending_reconciliation()
100    }
101}
102
103impl<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize> Spooler<C, PAGE_SIZE, MAX_SECTORS>
104where
105    C: NorFlash + ReadNorFlash,
106{
107    /// Create a spooler for a log with the given identity.
108    ///
109    /// `cursor_base` is a byte offset on the *volume*, and the region it names
110    /// must lie **outside** the volume's database region — the cursor is
111    /// metadata about the copy, not part of the copied log.
112    ///
113    /// That is checked, not merely documented: every cursor access goes through
114    /// [`SensorDb::with_region`](crate::SensorDb::with_region), so a region that
115    /// intersects the volume's sectors fails [`attach`](Self::attach) with
116    /// [`Error::RegionOverlap`] instead of overwriting replicated entries. The
117    /// check lands at `attach` rather than here because a spooler does not know
118    /// the volume's geometry until one is attached.
119    ///
120    /// # Arguments
121    /// - `source_log`: identity of the log being replicated. A volume carrying
122    ///   cursor records for a different log is rejected at
123    ///   [`attach`](Self::attach).
124    /// - `cursor_base`: start of the two-sector cursor region on the volume
125    /// - `sector_size`: the volume's erase size
126    ///
127    /// # Errors
128    /// - `InvalidConfig` if the geometry cannot hold cursor records
129    /// - `Overflow` if the region runs past the end of the address space
130    pub fn new(
131        source_log: Option<LogId>,
132        cursor_base: u32,
133        sector_size: u32,
134    ) -> Result<Self, Error> {
135        Ok(Self {
136            slot: Slot::Empty,
137            state: SpoolerState::new(source_log, cursor_base, sector_size, PAGE_SIZE as u32)?,
138            scratch: [0xFF; PAGE_SIZE],
139        })
140    }
141
142    /// Attach a mounted volume and read its cursor.
143    ///
144    /// The application mounts the volume itself, because only it knows whether
145    /// the volume should be indexed for reads
146    /// ([`MountMode`](crate::db::MountMode)).
147    ///
148    /// # Reconciling an interrupted batch
149    ///
150    /// When the newest cursor record is an intent with no commit, the batch it
151    /// describes was cut short somewhere — but the replica itself knows exactly
152    /// how far it got. The intent names the replica position its first entry
153    /// landed at, so reading the replica forward from there counts what survived.
154    /// That count is remembered and skipped on the source side by
155    /// [`reconcile`](Self::reconcile), which the next [`spool`](Self::spool)
156    /// pass calls if the application has not.
157    ///
158    /// This is what makes reinsertion exactly-once rather than at-least-once.
159    /// It degrades to the old bounded-duplicate behaviour when the count cannot
160    /// be trusted — see [`Attached::recovered_entries`].
161    ///
162    /// # Errors
163    /// - `AlreadyAttached` if a volume is already attached
164    /// - `NotMounted` if the volume has not been mounted
165    /// - `ForeignVolume` if its cursor belongs to a different log
166    pub fn attach(
167        &mut self,
168        volume: SensorDb<C, PAGE_SIZE, MAX_SECTORS>,
169    ) -> Result<Attached, Error> {
170        if !matches!(self.slot, Slot::Empty) {
171            return Err(Error::AlreadyAttached);
172        }
173        if !volume.is_mounted() {
174            return Err(Error::NotMounted);
175        }
176
177        let mut volume = volume;
178        // Attaching to a spooler *is* the declaration that this volume is a
179        // replica. Without this it would roll a fresh sector on the first
180        // appended entry after every insertion, to record an epoch that means
181        // nothing here — and on a full ring that evicts the oldest sector each
182        // time the card goes in.
183        volume.mark_as_replica();
184        let scan = scan_cursor(&mut volume, &self.state)?;
185        let landed = fingerprint_landed(&mut volume, &scan)?;
186
187        let attached = self.state.adopt_scan(scan, landed);
188        self.slot = Slot::Ready(volume);
189        Ok(attached)
190    }
191
192    /// Skip the part of an interrupted batch the replica already holds.
193    ///
194    /// Reads the source forward over exactly the entries
195    /// [`attach`](Self::attach) found durable on the replica and advances the
196    /// resume point past them, so the next pass copies only the remainder.
197    /// Without this the whole batch replays and the replica ends up holding
198    /// duplicates — bounded by [`SpoolBudget::max_entries`], but real.
199    ///
200    /// Idempotent and cheap: a no-op unless an attach found an unfinished batch,
201    /// and the next [`spool`](Self::spool) calls it anyway. Call it directly only
202    /// to see the reconciled resume point before spooling — as
203    /// [`TieredDb::attach`] does, so the watermark it restores is exact.
204    ///
205    /// The skip is abandoned, leaving the batch to replay whole, whenever the
206    /// two sides do not agree:
207    ///
208    /// - the source ring has wrapped past the resume point, so the entries the
209    ///   replica holds are gone and skipping the same *count* from the new tail
210    ///   would step over entries that were never copied;
211    /// - the source run does not [fingerprint](RunFingerprint) the same as the
212    ///   replica's copy of it.
213    ///
214    /// Both fall back to duplicating, never to skipping. Duplication is bounded
215    /// and visible; a wrong skip is silent loss.
216    ///
217    /// # Returns
218    /// The number of entries skipped.
219    ///
220    /// [`TieredDb::attach`]: crate::spool::TieredDb::attach
221    pub fn reconcile<S, const SP: usize, const SS: usize>(
222        &mut self,
223        source: &mut SensorDb<S, SP, SS>,
224    ) -> Result<u32, Error>
225    where
226        S: NorFlash + ReadNorFlash,
227    {
228        let landed = self.state.take_pending();
229        if landed.is_empty() {
230            return Ok(0);
231        }
232
233        let mut found = RunFingerprint::new();
234        let mut moved = Replicated::NONE;
235        let cursor = source.read_from(
236            self.state.resume(),
237            landed.entries(),
238            |_, header, payload| {
239                found.push(header.sensor_id, header.timestamp);
240                moved.push(samples_in(header.is_run(), payload));
241                Ok(true)
242            },
243        )?;
244        if !self.state.accept_skip(&landed, &found, &cursor) {
245            return Ok(0);
246        }
247
248        // These entries are on the replica; the source may reclaim their sectors.
249        source.note_spooled(cursor.next, moved);
250        Ok(cursor.entries)
251    }
252
253    /// Mark the attached volume faulted and borrow it.
254    ///
255    /// Returns the volume so the caller can still reach data held in its RAM
256    /// page buffer — which survives the medium being physically pulled, because
257    /// the processor is still running. Returns `None` when nothing is attached.
258    pub fn fault(&mut self) -> Option<&mut SensorDb<C, PAGE_SIZE, MAX_SECTORS>> {
259        // Only move out of the slot when there is something to transition.
260        // Taking unconditionally would drop an already-faulted volume on the
261        // floor, along with whatever it still held in RAM.
262        if matches!(self.slot, Slot::Ready(_))
263            && let Slot::Ready(volume) = core::mem::replace(&mut self.slot, Slot::Empty)
264        {
265            self.slot = Slot::Faulted(volume);
266        }
267        match &mut self.slot {
268            Slot::Faulted(volume) => Some(volume),
269            _ => None,
270        }
271    }
272
273    /// Detach the volume, returning it to the application.
274    ///
275    /// Also clears a fault, so a volume that errored can be re-attached after
276    /// the application has decided what to do about it.
277    pub fn detach(&mut self) -> Option<SensorDb<C, PAGE_SIZE, MAX_SECTORS>> {
278        let taken = core::mem::replace(&mut self.slot, Slot::Empty);
279        self.state.reset();
280        match taken {
281            Slot::Empty => None,
282            Slot::Ready(volume) | Slot::Faulted(volume) => Some(volume),
283        }
284    }
285
286    /// The attached volume, if it is usable.
287    pub fn volume(&self) -> Option<&SensorDb<C, PAGE_SIZE, MAX_SECTORS>> {
288        match &self.slot {
289            Slot::Ready(v) => Some(v),
290            _ => None,
291        }
292    }
293
294    /// The attached volume, if it is usable.
295    pub fn volume_mut(&mut self) -> Option<&mut SensorDb<C, PAGE_SIZE, MAX_SECTORS>> {
296        match &mut self.slot {
297            Slot::Ready(v) => Some(v),
298            _ => None,
299        }
300    }
301
302    /// How much room is left on the attached volume.
303    ///
304    /// `None` when nothing is attached. A **faulted** volume still answers, from
305    /// the index it had when it faulted: how full the medium was at the moment
306    /// it went is exactly what an operator wants to know afterwards.
307    pub fn volume_fill(&self) -> Option<VolumeFill> {
308        let volume = match &self.slot {
309            Slot::Empty => return None,
310            Slot::Ready(v) | Slot::Faulted(v) => v,
311        };
312        Some(VolumeFill::from_stats(&volume.stats()))
313    }
314
315    /// Copy up to `budget.max_entries` durable source entries onto the volume.
316    ///
317    /// A batch never spans two source sectors, so each cursor record names
318    /// exactly one source epoch. That usually costs nothing — a sector holds far
319    /// more entries than a typical budget — and it is what lets a reader
320    /// attribute copied entries to a particular run of the source device.
321    ///
322    /// Only entries that are already durable on the source are copied. Call
323    /// [`SensorDb::sync`] on the source first to include its buffered tail.
324    ///
325    /// # Errors
326    /// - `NotAttached` if no volume is attached
327    /// - `VolumeLost` if the volume errored; detach and re-attach to recover
328    /// - `GeometryMismatch` if the volume's pages are smaller than the source's
329    pub fn spool<S, const SP: usize, const SS: usize>(
330        &mut self,
331        source: &mut SensorDb<S, SP, SS>,
332        budget: SpoolBudget,
333    ) -> Result<SpoolProgress, Error>
334    where
335        S: NorFlash + ReadNorFlash,
336    {
337        // Checked before any I/O, and before the intent record: an entry near
338        // the source's maximum payload could never be copied onto a volume with
339        // smaller pages, so the spooler would livelock retrying it forever.
340        if SP > PAGE_SIZE {
341            return Err(Error::GeometryMismatch);
342        }
343
344        match self.slot {
345            Slot::Empty => return Err(Error::NotAttached),
346            Slot::Faulted(_) => return Err(Error::VolumeLost),
347            Slot::Ready(_) => {}
348        }
349
350        match self.spool_inner(source, budget) {
351            Ok(progress) => Ok(progress),
352            // A flash error on the *volume* is treated as "the volume is gone".
353            // A driver cannot distinguish a yanked card from a genuine fault —
354            // both surface as `NorFlashErrorKind::Other` — so this is a policy
355            // decision, not a hardware report. Drivers that *can* tell the
356            // difference should implement `Removable` and use `spool_if_present`.
357            //
358            // A flash error on the source is reported as itself: the device's
359            // own storage failing says nothing about the card, and faulting the
360            // card for it would condemn the wrong part.
361            Err(f) if !f.from_source && matches!(f.error, Error::Flash(_)) => {
362                self.fault();
363                Err(Error::VolumeLost)
364            }
365            Err(f) => Err(f.error),
366        }
367    }
368
369    fn spool_inner<S, const SP: usize, const SS: usize>(
370        &mut self,
371        source: &mut SensorDb<S, SP, SS>,
372        budget: SpoolBudget,
373    ) -> Result<SpoolProgress, SpoolFailure>
374    where
375        S: NorFlash + ReadNorFlash,
376    {
377        // Failures are tagged with the side they came from, because faulting the
378        // volume is the wrong response to the source's flash failing. A bare `?`
379        // attributes to the volume; source operations say so explicitly.
380        //
381        // Step over whatever an interrupted batch already delivered, so this
382        // pass copies the remainder rather than the whole batch again.
383        SpoolFailure::from_source(self.reconcile(source))?;
384
385        // Destructure so the closure below can borrow the volume while the
386        // spooler's own state stays reachable.
387        let Self {
388            slot,
389            state,
390            scratch,
391        } = self;
392        let Slot::Ready(volume) = slot else {
393            return Err(Error::NotAttached.into());
394        };
395
396        let from = state.resume();
397        let mut erased = EraseTally::new(volume.sectors_erased());
398
399        // Probe before writing an intent: an idle poll must not burn two cursor
400        // slots. `Ok(false)` rejects the entry, so this consumes nothing.
401        let probe = SpoolFailure::from_source(source.read_from(from, 1, |_, _, _| Ok(false)))?;
402        if probe.exhausted {
403            return Ok(SpoolProgress::idle(from, probe.gap));
404        }
405
406        // The batch is confined to one source sector, so this epoch describes
407        // every entry in it.
408        let source_epoch =
409            SpoolFailure::from_source(source.sector_epoch_at(probe.next))?.unwrap_or(0);
410
411        let batch = state.plan_batch(source_epoch, volume.head_position(), budget);
412        if let Some((start, end)) = batch.erase(state.region()) {
413            // Erase the sector being moved *into*. The one being left still
414            // holds valid records at this moment, so the resume point is never
415            // unrecoverable.
416            let region = state.region();
417            volume
418                .with_region(region.base(), region.total_size(), |p| p.erase(start, end))?
419                .map_err(Error::from)?;
420            erased.cursor_erase();
421        }
422
423        write_record(
424            volume,
425            state.region(),
426            batch.sector(),
427            batch.intent_slot(),
428            &batch.intent(),
429            scratch,
430        )?;
431
432        let mut copied = Replicated::NONE;
433        let mut last_timestamp = 0u64;
434        let mut batch_sector = BatchSector::new();
435        // The one operation that reads the source and writes the volume in the
436        // same call, so the side has to be recorded from inside the callback.
437        let mut volume_failed = false;
438
439        let cursor = source
440            .read_from(from, budget.max_entries, |pos, header, payload| {
441                if !batch_sector.admits(pos.sequence) {
442                    return Ok(false);
443                }
444                // `append_framed`, not `append`: a run must land on the replica
445                // as a run. Stored as an ordinary payload its frame would be one
446                // opaque sample that no read on the card could interpret, and
447                // the amortisation the run exists for would be lost as well.
448                volume
449                    .append_framed(header, payload)
450                    .inspect_err(|_| volume_failed = true)?;
451                copied.push(samples_in(header.is_run(), payload));
452                last_timestamp = header.timestamp;
453                Ok(true)
454            })
455            .map_err(|error| SpoolFailure {
456                error,
457                from_source: !volume_failed,
458            })?;
459
460        // Make the copy durable *before* the commit record claims it is.
461        volume.sync()?;
462
463        write_record(
464            volume,
465            state.region(),
466            batch.sector(),
467            batch.commit_slot(),
468            &batch.commit(cursor.next, copied, last_timestamp),
469            scratch,
470        )?;
471
472        // Only now is it safe to let the source consider this replicated.
473        state.commit_batch(&batch, cursor.next);
474        source.note_spooled(cursor.next, copied);
475
476        Ok(SpoolProgress {
477            entries_copied: copied.entries,
478            committed_upto: cursor.next,
479            caught_up: cursor.exhausted,
480            gap: cursor.gap,
481            volume_erased: erased.total(volume.sectors_erased()),
482        })
483    }
484
485    /// Copy until the replica is level with the source, or `max_batches` passes
486    /// have run.
487    ///
488    /// The bound exists so a caller with a large backlog can still service other
489    /// work between calls rather than blocking indefinitely.
490    pub fn spool_until_caught_up<S, const SP: usize, const SS: usize>(
491        &mut self,
492        source: &mut SensorDb<S, SP, SS>,
493        budget: SpoolBudget,
494        max_batches: u32,
495    ) -> Result<SpoolProgress, Error>
496    where
497        S: NorFlash + ReadNorFlash,
498    {
499        let mut total = SpoolProgress {
500            committed_upto: self.state.resume(),
501            ..SpoolProgress::default()
502        };
503        for _ in 0..max_batches {
504            let progress = self.spool(source, budget)?;
505            total.absorb(&progress);
506            if progress.caught_up {
507                break;
508            }
509        }
510        Ok(total)
511    }
512}
513
514impl<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize> Spooler<C, PAGE_SIZE, MAX_SECTORS>
515where
516    C: NorFlash + ReadNorFlash + Removable,
517{
518    /// Like [`spool`](Self::spool), but skip the pass when the driver reports
519    /// the medium absent.
520    ///
521    /// Available only when the volume's driver can answer that question. It lets
522    /// a clean removal be noticed *before* a write fails, which keeps a genuine
523    /// fault distinguishable from a yank.
524    ///
525    /// Returns `Ok(None)` when the medium is absent.
526    pub fn spool_if_present<S, const SP: usize, const SS: usize>(
527        &mut self,
528        source: &mut SensorDb<S, SP, SS>,
529        budget: SpoolBudget,
530    ) -> Result<Option<SpoolProgress>, Error>
531    where
532        S: NorFlash + ReadNorFlash,
533    {
534        let present = match &mut self.slot {
535            Slot::Empty => return Err(Error::NotAttached),
536            Slot::Faulted(_) => return Err(Error::VolumeLost),
537            Slot::Ready(volume) => volume.driver_mut().is_present(),
538        };
539        if !present {
540            return Ok(None);
541        }
542        self.spool(source, budget).map(Some)
543    }
544
545    /// Whether the driver reports the attached medium as present.
546    ///
547    /// `false` when nothing is attached.
548    pub fn is_present(&mut self) -> bool {
549        match &mut self.slot {
550            Slot::Ready(volume) => volume.driver_mut().is_present(),
551            _ => false,
552        }
553    }
554}
555
556/// Read every cursor slot on the volume and work out where to resume.
557fn scan_cursor<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize>(
558    volume: &mut SensorDb<C, PAGE_SIZE, MAX_SECTORS>,
559    state: &SpoolerState,
560) -> Result<CursorScan, Error>
561where
562    C: NorFlash + ReadNorFlash,
563{
564    let region = *state.region();
565    let expected = state.expected_log();
566    let mut fold = CursorFold::new();
567    let mut buf = [0u8; CURSOR_RECORD_SIZE];
568
569    for at in region.slots() {
570        volume.with_region(region.base(), region.total_size(), |p| {
571            p.read(at.offset, &mut buf)
572        })??;
573        fold.feed(at, &buf, expected)?;
574    }
575
576    Ok(fold.finish())
577}
578
579/// Fingerprint what an interrupted batch actually managed to store.
580///
581/// The intent record names where on the replica the batch's first entry landed,
582/// and nothing is appended after a batch except the next batch — which never
583/// started, or its intent would be the newest record. So everything at or after
584/// that position is exactly what this batch delivered.
585///
586/// What makes a run untrustworthy, and why the read runs one past the budget,
587/// is [`CursorScan::accept_landed`] and [`CursorScan::landed_probe`].
588fn fingerprint_landed<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize>(
589    volume: &mut SensorDb<C, PAGE_SIZE, MAX_SECTORS>,
590    scan: &CursorScan,
591) -> Result<RunFingerprint, Error>
592where
593    C: NorFlash + ReadNorFlash,
594{
595    let Some((dest, limit)) = scan.landed_probe() else {
596        return Ok(RunFingerprint::new());
597    };
598    let mut run = RunFingerprint::new();
599    let cursor = volume.read_from(dest, limit, |_, header, _| {
600        run.push(header.sensor_id, header.timestamp);
601        Ok(true)
602    })?;
603    Ok(scan.accept_landed(run, &cursor))
604}
605
606/// Serialise a cursor record into a page-sized slot.
607fn write_record<C, const PAGE_SIZE: usize, const MAX_SECTORS: usize>(
608    volume: &mut SensorDb<C, PAGE_SIZE, MAX_SECTORS>,
609    region: &CursorRegion,
610    sector: u8,
611    slot: u32,
612    record: &SpoolCursorWire,
613    scratch: &mut [u8; PAGE_SIZE],
614) -> Result<(), Error>
615where
616    C: NorFlash + ReadNorFlash,
617{
618    scratch.fill(0xFF);
619    scratch[..CURSOR_RECORD_SIZE].copy_from_slice(record.as_bytes());
620    let offset = region.slot_offset(sector, slot);
621    volume.with_region(region.base(), region.total_size(), |p| {
622        p.write(offset, &scratch[..])
623    })??;
624    Ok(())
625}
626
627// =============================================================================
628// TieredDb
629// =============================================================================
630
631/// An onboard log plus a removable volume, with `append` routed between them.
632///
633/// This is the application-facing type for a device that collects data with no
634/// network link and offloads it by carrying a card to a computer.
635///
636/// A device with no card slot does not need this: use [`SensorDb`] directly and
637/// pay nothing.
638///
639/// # Reads
640///
641/// Queries span both logs. The union is exact and needs no de-duplication: the
642/// volume holds everything up to the replication watermark, the onboard log
643/// holds the un-replicated tail, and where they overlap the data is identical.
644pub struct TieredDb<S, C, const SP: usize, const SS: usize, const CP: usize, const CS: usize> {
645    onboard: SensorDb<S, SP, SS>,
646    spooler: Spooler<C, CP, CS>,
647    /// Where `append` writes, and every rule about when that moves.
648    tier: TierMode,
649}
650
651impl<S, C, const SP: usize, const SS: usize, const CP: usize, const CS: usize>
652    TieredDb<S, C, SP, SS, CP, CS>
653where
654    S: NorFlash + ReadNorFlash,
655    C: NorFlash + ReadNorFlash,
656{
657    /// Combine a mounted onboard log with a spooler for the removable volume.
658    ///
659    /// # Errors
660    /// - `NotMounted` if the onboard log is not mounted
661    /// - `GeometryMismatch` if the volume's pages are smaller than the onboard
662    ///   log's, which would make entries near the maximum payload impossible to
663    ///   copy
664    pub fn new(
665        onboard: SensorDb<S, SP, SS>,
666        spooler: Spooler<C, CP, CS>,
667        policy: WritePolicy,
668    ) -> Result<Self, Error> {
669        if !onboard.is_mounted() {
670            return Err(Error::NotMounted);
671        }
672        if SP > CP {
673            return Err(Error::GeometryMismatch);
674        }
675        Ok(Self {
676            onboard,
677            spooler,
678            tier: TierMode::new(policy),
679        })
680    }
681
682    /// Attach a mounted volume and seed the onboard watermark from its cursor.
683    ///
684    /// The cursor is the only record of what has been replicated — `mount`
685    /// cannot recover it — so this is what tells the onboard ring which sectors
686    /// are safe to overwrite first.
687    ///
688    /// An interrupted batch is reconciled here rather than on the first spool
689    /// pass, so the watermark restored accounts for what the replica already
690    /// holds. [`Attached::resume_from`] is the reconciled position, and
691    /// [`Attached::recovered_entries`] says how far past the raw cursor it is.
692    ///
693    /// # Errors
694    ///
695    /// A late error — from the boundary scan
696    /// [`restore_spool_watermark`](SensorDb::restore_spool_watermark) makes to
697    /// count exactly what is already replicated, or from the source read
698    /// reconciliation performs — leaves the volume **attached and draining**.
699    /// What suffers is the reported `unspooled_entries`, and at worst the
700    /// replay of one batch, so a caller that cares more about draining than
701    /// about the count may treat it as a warning; the underlying onboard-flash
702    /// fault will resurface, attributed, on the next
703    /// [`spool_step`](Self::spool_step), which reconciles itself.
704    pub fn attach(&mut self, volume: SensorDb<C, CP, CS>) -> Result<Attached, Error> {
705        let mut attached = self.spooler.attach(volume)?;
706
707        // Before the fallible part, so an `Err` cannot strand an attached volume
708        // behind a mode that will not drain it.
709        self.tier.attached();
710
711        // Recompute the accounting from the *committed* cursor before
712        // reconciling, not after. `reconcile` advances the watermark itself,
713        // through `note_spooled`, which only adds the entries it skipped — and
714        // `restore_spool_watermark` does nothing once the watermark has already
715        // reached the position it is handed. Reconciling first therefore left
716        // everything the committed cursor covered permanently uncounted, so the
717        // log reported a backlog it had already replicated for the rest of its
718        // life.
719        self.onboard.restore_spool_watermark(attached.resume_from)?;
720
721        self.spooler.reconcile(&mut self.onboard)?;
722        if let Some(resume) = self.spooler.resume_point() {
723            attached.resume_from = resume;
724        }
725        Ok(attached)
726    }
727
728    /// Detach the volume. Samples continue to land in the onboard log.
729    ///
730    /// Under [`WritePolicy::CardFirst`] this first rescues anything the volume
731    /// still held in RAM into the onboard log, so removing a card mid-page
732    /// loses nothing. Use [`detach_without_recovery`](Self::detach_without_recovery)
733    /// if the volume's buffer should be abandoned instead.
734    pub fn detach(&mut self) -> Option<SensorDb<C, CP, CS>> {
735        // Ignore the result: a rescue that cannot land onboard is worth
736        // reporting, but not at the cost of stranding the volume.
737        let _ = self.recover_from_volume_loss();
738        self.tier.fell_back();
739        self.spooler.detach()
740    }
741
742    /// Detach the volume without rescuing its RAM buffer.
743    ///
744    /// Anything appended to the volume since its last successful
745    /// [`sync`](Self::sync) is discarded.
746    pub fn detach_without_recovery(&mut self) -> Option<SensorDb<C, CP, CS>> {
747        self.tier.fell_back();
748        self.spooler.detach()
749    }
750
751    /// Append a sample.
752    ///
753    /// **Never fails because of the volume.** Under
754    /// [`WritePolicy::OnboardFirst`] the volume is not on the write path at all.
755    /// Under [`WritePolicy::CardFirst`] a sample that cannot reach the volume is
756    /// written to the onboard log instead, along with everything the volume had
757    /// buffered in RAM — so a card pulled mid-page costs nothing.
758    pub fn append(&mut self, sensor_id: u16, timestamp: u64, payload: &[u8]) -> Result<(), Error> {
759        if !self.tier.writes_to_volume() {
760            return self.onboard.append(sensor_id, timestamp, payload);
761        }
762
763        let attempt = match self.spooler.volume_mut() {
764            Some(volume) => volume.append(sensor_id, timestamp, payload),
765            None => Err(Error::NotAttached),
766        };
767
768        match attempt {
769            Ok(()) => Ok(()),
770            // The medium went away. Rescue whatever it still held in RAM, then
771            // write this sample onboard as if the card had never been there.
772            Err(e) if volume_gone(&e) => {
773                self.recover_from_volume_loss()?;
774                self.onboard.append(sensor_id, timestamp, payload)
775            }
776            Err(e) => Err(e),
777        }
778    }
779
780    /// Append a [run](crate::run), routed exactly as [`append`](Self::append) is.
781    ///
782    /// A run written to the card stays a run there, and one written onboard is
783    /// replicated as a run, so the amortisation survives the whole journey.
784    pub fn append_run(&mut self, run: &Run<'_>) -> Result<(), Error> {
785        if !self.tier.writes_to_volume() {
786            return self.onboard.append_run(run);
787        }
788
789        let attempt = match self.spooler.volume_mut() {
790            Some(volume) => volume.append_run(run),
791            None => Err(Error::NotAttached),
792        };
793
794        match attempt {
795            Ok(()) => Ok(()),
796            Err(e) if volume_gone(&e) => {
797                self.recover_from_volume_loss()?;
798                self.onboard.append_run(run)
799            }
800            Err(e) => Err(e),
801        }
802    }
803
804    /// Flush the buffered tail of whichever log is being written.
805    ///
806    /// For the onboard log this is also what makes its tail eligible for
807    /// replication: [`spool_step`] only copies entries that are already durable.
808    ///
809    /// [`spool_step`]: Self::spool_step
810    pub fn sync(&mut self) -> Result<(), Error> {
811        if !self.tier.writes_to_volume() {
812            return self.onboard.sync();
813        }
814
815        let attempt = match self.spooler.volume_mut() {
816            Some(volume) => volume.sync(),
817            None => Err(Error::NotAttached),
818        };
819
820        match attempt {
821            Ok(()) => Ok(()),
822            Err(e) if volume_gone(&e) => {
823                // Everything that failed to reach the medium is still in its RAM
824                // buffer, and lands onboard instead.
825                self.recover_from_volume_loss()?;
826                self.onboard.sync()
827            }
828            Err(e) => Err(e),
829        }
830    }
831
832    /// Fall back to the onboard log, rescuing whatever the volume held in RAM.
833    ///
834    /// A yank is not a power loss: the processor is still running, so samples
835    /// sitting in the volume's page buffer are still readable and can be
836    /// re-appended somewhere that exists. This touches no flash on the volume,
837    /// so it works with the medium physically gone.
838    ///
839    /// Returns the number of samples rescued.
840    fn recover_from_volume_loss(&mut self) -> Result<u32, Error> {
841        let Self {
842            onboard,
843            spooler,
844            tier,
845        } = self;
846        tier.fell_back();
847
848        let Some(volume) = spooler.fault() else {
849            return Ok(0);
850        };
851        // `append_framed`: a run rescued from the card's RAM buffer has to land
852        // onboard as a run, or its frame becomes an unreadable single sample.
853        volume.drain_unflushed(|header, payload| onboard.append_framed(header, payload))
854    }
855
856    /// Promote to [`WriteMode::Direct`] if the backlog is fully replicated.
857    ///
858    /// Only under [`WritePolicy::CardFirst`]. Draining to completion *before*
859    /// switching is what keeps the volume's log in timestamp order: if direct
860    /// writes resumed while a backlog was still being copied, live samples and
861    /// older ones would interleave.
862    ///
863    /// The `sync` here costs one onboard page write per attach cycle — the
864    /// buffered tail has to become durable before it can be replicated, and it
865    /// has to be replicated before the onboard log can be left behind.
866    fn try_promote(&mut self, budget: SpoolBudget) -> Result<(), Error> {
867        if !self
868            .tier
869            .may_promote(self.spooler.is_attached(), self.spooler.is_faulted())
870        {
871            return Ok(());
872        }
873
874        self.onboard.sync()?;
875        let progress =
876            self.spooler
877                .spool_until_caught_up(&mut self.onboard, budget, PROMOTE_MAX_BATCHES)?;
878        if progress.caught_up {
879            self.tier.promoted();
880        }
881        Ok(())
882    }
883
884    /// Run one replication pass, if a volume is attached.
885    ///
886    /// Returns `Ok(None)` when no volume is attached — the normal state while
887    /// the card is out, and not an error.
888    ///
889    /// A volume that has **faulted** is different: it returns
890    /// [`Error::VolumeLost`] on every call until
891    /// [`detach`](Self::detach) is called. Reporting that as `Ok(None)` would
892    /// let a card that fell out mid-write look identical to no card at all, and
893    /// the backlog would grow silently until the ring started dropping it.
894    pub fn spool_step(&mut self, budget: SpoolBudget) -> Result<Option<SpoolProgress>, Error> {
895        if !self
896            .tier
897            .ready_to_spool(self.spooler.is_attached(), self.spooler.is_faulted())?
898        {
899            return Ok(None);
900        }
901        let progress = self.spooler.spool(&mut self.onboard, budget)?;
902        self.tier.spooled();
903        if progress.caught_up {
904            self.try_promote(budget)?;
905        }
906        Ok(Some(progress))
907    }
908
909    /// Replicate until the volume is level with the onboard log, or
910    /// `max_batches` passes have run.
911    ///
912    /// Same contract as [`spool_step`](Self::spool_step): `Ok(None)` means no
913    /// volume, while a faulted volume is an error.
914    pub fn drain(
915        &mut self,
916        budget: SpoolBudget,
917        max_batches: u32,
918    ) -> Result<Option<SpoolProgress>, Error> {
919        if !self
920            .tier
921            .ready_to_spool(self.spooler.is_attached(), self.spooler.is_faulted())?
922        {
923            return Ok(None);
924        }
925        let progress =
926            self.spooler
927                .spool_until_caught_up(&mut self.onboard, budget, max_batches)?;
928        self.tier.spooled();
929        if progress.caught_up {
930            self.try_promote(budget)?;
931        }
932        Ok(Some(progress))
933    }
934
935    /// Which log `append` is currently writing to.
936    pub fn mode(&self) -> WriteMode {
937        self.tier.mode()
938    }
939
940    /// The configured write policy.
941    pub fn policy(&self) -> WritePolicy {
942        self.tier.policy()
943    }
944
945    /// Whether a volume is attached.
946    pub fn is_attached(&self) -> bool {
947        self.spooler.is_attached()
948    }
949
950    /// Replication accounting for the onboard log.
951    pub fn spool_stats(&self) -> SpoolStats {
952        self.onboard.spool_stats()
953    }
954
955    /// How much room is left on the removable volume.
956    ///
957    /// `None` when no volume is attached. This is the warning an operator needs
958    /// before the swap window closes: nothing reports a full medium as an error,
959    /// because a ring overwriting its own tail is normal operation for a log.
960    ///
961    /// It matters most under [`WritePolicy::CardFirst`], where the volume holds
962    /// the only copy of everything written since it took over — see
963    /// [`VolumeFill`]. Under [`WritePolicy::OnboardFirst`] a full volume
964    /// overwrites a copy, and the onboard log's own
965    /// [`spool_stats`](Self::spool_stats) is the accounting that matters.
966    pub fn volume_fill(&self) -> Option<VolumeFill> {
967        self.spooler.volume_fill()
968    }
969
970    /// The attached volume, if one is attached and usable.
971    ///
972    /// Provided for inspection — status displays, diagnostics, and tests.
973    /// Appending to the replica behind the spooler's back will make the cursor
974    /// disagree with the volume's contents.
975    pub fn volume(&self) -> Option<&SensorDb<C, CP, CS>> {
976        self.spooler.volume()
977    }
978
979    /// The attached volume, if one is attached and usable.
980    ///
981    /// See [`volume`](Self::volume) for the caveat.
982    pub fn volume_mut(&mut self) -> Option<&mut SensorDb<C, CP, CS>> {
983        self.spooler.volume_mut()
984    }
985
986    /// The onboard log.
987    pub fn onboard(&self) -> &SensorDb<S, SP, SS> {
988        &self.onboard
989    }
990
991    /// The onboard log.
992    pub fn onboard_mut(&mut self) -> &mut SensorDb<S, SP, SS> {
993        &mut self.onboard
994    }
995
996    /// Consume this and return the parts.
997    pub fn into_parts(self) -> (SensorDb<S, SP, SS>, Spooler<C, CP, CS>) {
998        (self.onboard, self.spooler)
999    }
1000
1001    // -------------------------------------------------------------------------
1002    // Reads across both logs
1003    // -------------------------------------------------------------------------
1004
1005    /// The most recent entry for a sensor, across both logs.
1006    ///
1007    /// Exact. Where the two logs overlap they hold identical entries, so taking
1008    /// the later timestamp cannot be perturbed by the duplication.
1009    pub fn latest(
1010        &mut self,
1011        sensor_id: u16,
1012        buf: &mut [u8],
1013    ) -> Result<Option<(EntryHeader, usize)>, Error> {
1014        let onboard = self.onboard.latest(sensor_id, buf)?;
1015
1016        // Read the volume into a scratch view; `merge` copies it over only if it
1017        // wins, so the onboard read already in `buf` is not disturbed.
1018        let mut alt = [0u8; CP];
1019        let from_volume = match self.spooler.volume_mut() {
1020            Some(volume) => volume.latest(sensor_id, &mut alt)?,
1021            None => return Ok(onboard),
1022        };
1023
1024        merge(onboard, from_volume, &alt, buf, |v, o| v > o)
1025    }
1026
1027    /// The oldest entry for a sensor, across both logs.
1028    pub fn oldest(
1029        &mut self,
1030        sensor_id: u16,
1031        buf: &mut [u8],
1032    ) -> Result<Option<(EntryHeader, usize)>, Error> {
1033        let onboard = self.onboard.oldest(sensor_id, buf)?;
1034
1035        let mut alt = [0u8; CP];
1036        let from_volume = match self.spooler.volume_mut() {
1037            Some(volume) => volume.oldest(sensor_id, &mut alt)?,
1038            None => return Ok(onboard),
1039        };
1040
1041        merge(onboard, from_volume, &alt, buf, |v, o| v < o)
1042    }
1043
1044    /// Entries in a timestamp range, across both logs.
1045    ///
1046    /// Delivered card-first and then onboard, which is log order across the
1047    /// union: the card holds everything up to the replication watermark and the
1048    /// onboard log holds the un-replicated tail. Within each, entries arrive in
1049    /// write order — *not* timestamp order, the same caveat as
1050    /// [`SensorDb::query_range`].
1051    ///
1052    /// The union is exact and needs no de-duplication. Un-synced samples still
1053    /// sitting in a page buffer are included, so this sees everything
1054    /// [`latest`](Self::latest) would.
1055    ///
1056    /// Return `false` from the callback to stop, which — as in
1057    /// [`SensorDb::query_range`] — stops *after* consuming the entry offered.
1058    ///
1059    /// # Cost
1060    ///
1061    /// The onboard side is scanned from the watermark forward without the
1062    /// per-sector bloom filter or timestamp-range skipping that
1063    /// [`SensorDb::query_range`] uses, because those index by sector and the
1064    /// watermark cuts across one. That tail is small by construction — it is
1065    /// exactly what replication has not yet carried off — so the saving would be
1066    /// on the part that is already cheap.
1067    ///
1068    /// # Returns
1069    /// The number of entries delivered.
1070    ///
1071    /// # Errors
1072    /// - `ReadsUnavailable` if the card was mounted
1073    ///   [`HeadersOnly`](crate::db::MountMode::HeadersOnly)
1074    pub fn query_range<F>(
1075        &mut self,
1076        sensor_id: Option<u16>,
1077        t_start: u64,
1078        t_end: u64,
1079        mut callback: F,
1080    ) -> Result<u32, Error>
1081    where
1082        F: FnMut(&EntryHeader, &[u8]) -> bool,
1083    {
1084        let Some(volume) = self.spooler.volume_mut() else {
1085            // No card: the onboard log is all there is, and its own query path
1086            // is strictly better — it can skip sectors by bloom filter.
1087            return self
1088                .onboard
1089                .query_range(sensor_id, t_start, t_end, callback);
1090        };
1091
1092        let mut stopped = false;
1093        let mut delivered = {
1094            // `SensorDb::query_range` reports how many it delivered but not
1095            // whether the callback asked to stop, so record that here — the
1096            // onboard phase must not keep calling a callback that said stop.
1097            let mut watched = |header: &EntryHeader, payload: &[u8]| {
1098                let go = callback(header, payload);
1099                stopped |= !go;
1100                go
1101            };
1102            volume.query_range(sensor_id, t_start, t_end, &mut watched)?
1103        };
1104        if stopped {
1105            return Ok(delivered);
1106        }
1107
1108        // The onboard phases stream *entries*, so a run arrives whole and has to
1109        // be expanded here — the volume's own `query_range` did that internally.
1110        // `deliver_samples` frames each sample by writing through the payload, so
1111        // it needs a copy; one buffer serves both phases.
1112        let mut scratch = [0u8; SP];
1113        let mut expand =
1114            |header: &EntryHeader, payload: &[u8], delivered: &mut u32, callback: &mut F| {
1115                if sensor_id.is_some_and(|id| header.sensor_id != id) {
1116                    return false;
1117                }
1118                let Some(dst) = scratch.get_mut(..payload.len()) else {
1119                    return false;
1120                };
1121                dst.copy_from_slice(payload);
1122                deliver_samples(
1123                    header.is_run(),
1124                    header.sensor_id,
1125                    header.timestamp,
1126                    dst,
1127                    t_start,
1128                    t_end,
1129                    delivered,
1130                    callback,
1131                )
1132            };
1133
1134        // The onboard tail, from the watermark forward. `read_from` reads
1135        // `Ok(false)` as *rejecting* the entry rather than consuming it, but the
1136        // cursor it returns is discarded here, so the two conventions cannot
1137        // collide — and stopping there is what keeps an early exit cheap.
1138        let watermark = self.onboard.spool_stats().watermark;
1139        self.onboard
1140            .read_from(watermark, u32::MAX, |_, header, payload| {
1141                stopped = expand(header, payload, &mut delivered, &mut callback);
1142                Ok(!stopped)
1143            })?;
1144
1145        if stopped {
1146            return Ok(delivered);
1147        }
1148
1149        // ...and the tail that is still only in RAM. `read_from` stops at the
1150        // durable end by design; a reader must not.
1151        self.onboard.peek_unflushed(|header, payload| {
1152            if !stopped {
1153                stopped = expand(header, payload, &mut delivered, &mut callback);
1154            }
1155            Ok(())
1156        })?;
1157
1158        Ok(delivered)
1159    }
1160
1161    /// Every entry for a sensor across both logs, in log order.
1162    ///
1163    /// [`query_range`](Self::query_range) over the full timestamp range.
1164    pub fn query_all<F>(&mut self, sensor_id: Option<u16>, callback: F) -> Result<u32, Error>
1165    where
1166        F: FnMut(&EntryHeader, &[u8]) -> bool,
1167    {
1168        self.query_range(sensor_id, 0, u64::MAX, callback)
1169    }
1170
1171    /// Total entries across both logs, counted without double-counting.
1172    ///
1173    /// `sensor_id = None` is O(1): the volume's cached total plus the onboard
1174    /// log's un-replicated count.
1175    ///
1176    /// After an unclean removal the answer can over-count by at most
1177    /// [`SpoolBudget::max_entries`], the same bound that applies to duplicates
1178    /// on the volume.
1179    pub fn count(&mut self, sensor_id: Option<u16>) -> Result<u32, Error> {
1180        // Samples, not entries: `count` has to agree with what `query_range`
1181        // yields, and that expands runs.
1182        let unspooled = self.onboard.spool_stats().unspooled_samples;
1183
1184        let Some(volume) = self.spooler.volume_mut() else {
1185            // No volume: the onboard log is all there is.
1186            return self.onboard.count(sensor_id);
1187        };
1188
1189        match sensor_id {
1190            None => Ok(volume.count(None)?.saturating_add(unspooled)),
1191            Some(id) => {
1192                // Per-sensor needs a scan either way; the onboard side counts
1193                // only the un-replicated tail so nothing is counted twice.
1194                let on_volume = volume.count(Some(id))?;
1195                let watermark = self.onboard.spool_stats().watermark;
1196                let mut tail = 0u32;
1197                let mut tally = |header: &EntryHeader, payload: &[u8]| {
1198                    if header.sensor_id == id {
1199                        tail += samples_in(header.is_run(), payload);
1200                    }
1201                };
1202                self.onboard
1203                    .read_from(watermark, u32::MAX, |_, header, payload| {
1204                        tally(header, payload);
1205                        Ok(true)
1206                    })?;
1207                // `read_from` stops at the durable tail by design, so the third
1208                // phase is not optional: [`query_range`](Self::query_range) goes
1209                // on to `peek_unflushed`, and a `count` that stopped one phase
1210                // early reported zero for a sensor whose only entry was still in
1211                // the RAM page buffer.
1212                self.onboard.peek_unflushed(|header, payload| {
1213                    tally(header, payload);
1214                    Ok(())
1215                })?;
1216                Ok(on_volume.saturating_add(tail))
1217            }
1218        }
1219    }
1220}
1221
1222impl<S, C, const SP: usize, const SS: usize, const CP: usize, const CS: usize>
1223    TieredDb<S, C, SP, SS, CP, CS>
1224where
1225    S: NorFlash + ReadNorFlash,
1226    C: NorFlash + ReadNorFlash + Removable,
1227{
1228    /// Notice a removal before a write has to fail.
1229    ///
1230    /// Call this from a card-detect interrupt or a periodic poll. If the driver
1231    /// reports the medium absent, this rescues whatever it still held in RAM
1232    /// into the onboard log and falls back to [`WriteMode::Onboard`].
1233    ///
1234    /// Without it a removal is only discovered when a write fails, which is
1235    /// still safe — [`append`](Self::append) recovers the same way — but means
1236    /// the fault is indistinguishable from a genuine flash error.
1237    ///
1238    /// Returns the number of samples rescued; zero when the medium is present.
1239    pub fn check_presence(&mut self) -> Result<u32, Error> {
1240        if !self.spooler.is_attached() || self.spooler.is_faulted() {
1241            return Ok(0);
1242        }
1243        if self.spooler.is_present() {
1244            return Ok(0);
1245        }
1246        self.recover_from_volume_loss()
1247    }
1248
1249    /// Run one replication pass, skipping it when the medium reports absent.
1250    ///
1251    /// Combines [`check_presence`](Self::check_presence) with
1252    /// [`spool_step`](Self::spool_step): a clean removal is noticed and handled
1253    /// rather than surfacing as a failed write.
1254    pub fn spool_step_if_present(
1255        &mut self,
1256        budget: SpoolBudget,
1257    ) -> Result<Option<SpoolProgress>, Error> {
1258        self.check_presence()?;
1259        if !self.spooler.is_attached() || self.spooler.is_faulted() {
1260            return Ok(None);
1261        }
1262        self.spool_step(budget)
1263    }
1264}
1265
1266// ---------------------------------------------------------------------------
1267// Capability ports
1268// ---------------------------------------------------------------------------
1269//
1270// This is what the ports are for: a caller that only wants to record samples
1271// and read them back does not have to know whether a card is in the slot, and
1272// so `SensorLogger` and the typed API work over a tier just as they do over one
1273// log. Delegation only, spelled with UFCS so the inherent method is never
1274// reached through `self.`.
1275
1276impl<S, C, const SP: usize, const SS: usize, const CP: usize, const CS: usize> crate::port::LogSink
1277    for TieredDb<S, C, SP, SS, CP, CS>
1278where
1279    S: NorFlash + ReadNorFlash,
1280    C: NorFlash + ReadNorFlash,
1281{
1282    fn append(&mut self, sensor_id: u16, timestamp: u64, payload: &[u8]) -> Result<(), Error> {
1283        TieredDb::append(self, sensor_id, timestamp, payload)
1284    }
1285
1286    fn append_run(&mut self, run: &Run<'_>) -> Result<(), Error> {
1287        TieredDb::append_run(self, run)
1288    }
1289
1290    fn sync(&mut self) -> Result<(), Error> {
1291        TieredDb::sync(self)
1292    }
1293}
1294
1295impl<S, C, const SP: usize, const SS: usize, const CP: usize, const CS: usize>
1296    crate::port::LogSource for TieredDb<S, C, SP, SS, CP, CS>
1297where
1298    S: NorFlash + ReadNorFlash,
1299    C: NorFlash + ReadNorFlash,
1300{
1301    fn latest(
1302        &mut self,
1303        sensor_id: u16,
1304        buf: &mut [u8],
1305    ) -> Result<Option<(EntryHeader, usize)>, Error> {
1306        TieredDb::latest(self, sensor_id, buf)
1307    }
1308
1309    fn oldest(
1310        &mut self,
1311        sensor_id: u16,
1312        buf: &mut [u8],
1313    ) -> Result<Option<(EntryHeader, usize)>, Error> {
1314        TieredDb::oldest(self, sensor_id, buf)
1315    }
1316
1317    fn count(&mut self, sensor_id: Option<u16>) -> Result<u32, Error> {
1318        TieredDb::count(self, sensor_id)
1319    }
1320
1321    fn query_range(
1322        &mut self,
1323        sensor_id: Option<u16>,
1324        t_start: u64,
1325        t_end: u64,
1326        callback: &mut dyn FnMut(&EntryHeader, &[u8]) -> bool,
1327    ) -> Result<u32, Error> {
1328        TieredDb::query_range(self, sensor_id, t_start, t_end, callback)
1329    }
1330}
1331
1332impl<S, C, const SP: usize, const SS: usize, const CP: usize, const CS: usize> core::fmt::Debug
1333    for TieredDb<S, C, SP, SS, CP, CS>
1334{
1335    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1336        f.debug_struct("TieredDb")
1337            .field("policy", &self.tier.policy())
1338            .field("mode", &self.tier.mode())
1339            .field("attached", &self.spooler.is_attached())
1340            .finish_non_exhaustive()
1341    }
1342}