sensor-db 0.1.0

Append-only sensor database for NOR flash on embedded devices
Documentation
//! # sensor-db
//!
//! Append-only sensor database for NOR flash on embedded devices.
//!
//! Designed for the RP2350 (Raspberry Pi Pico 2) and similar Cortex-M
//! microcontrollers with external or internal QSPI NOR flash.
//!
//! ## Architecture
//!
//! ```text
//! ┌───────────────────────────────────────────────┐
//! │  SensorLogger  (clock injection)              │
//! │  (generic over the ports — never over a log)  │
//! ├───────────────────────────────────────────────┤
//! │  LogSink / LogSource  (capability ports)      │
//! │  ├── append · append_run · sync               │
//! │  ├── latest · oldest · count · query_range    │
//! │  └── typed API via the *Ext mixins            │
//! ├───────────────────────────────────────────────┤
//! │  TieredDb  (optional: removable media)        │
//! │  ├── routes append() onboard ↔ card           │
//! │  └── Spooler (copies onboard → card)          │
//! ├───────────────────────────────────────────────┤
//! │  SensorDb / SensorDbAsync  (high-level API)   │
//! │  ├── append / sync / latest / query_range     │
//! │  ├── compact / format / stats                 │
//! │  ├── mount (footers + rebuild index)          │
//! │  └── read_from (replication stream)           │
//! ├───────────────────────────────────────────────┤
//! │  Sector ring  (circular buffer of sectors)    │
//! │  ├── SectorHeader (28 B, SD05: magic+version  │
//! │  │   +log_id+epoch+seq+erase_cnt+crc)         │
//! │  ├── SectorFooter (52 B, SDF2, last page:     │
//! │  │   the summary, written at seal time)       │
//! │  └── SectorSummary (in-RAM, per-sector)       │
//! ├───────────────────────────────────────────────┤
//! │  Entry log  (sequential within pages)         │
//! │  ├── EntryHeader + payload + CRC-32C          │
//! │  ├── Two-phase commit (flags 0xFF→0x00)       │
//! │  └── Page-buffered writes (one RAM page)      │
//! ├───────────────────────────────────────────────┤
//! │  embedded-storage NorFlash trait               │
//! │  embedded-storage-async (async feature)       │
//! │  (RP2350 internal / external SPI / mock)      │
//! └───────────────────────────────────────────────┘
//! ```
//!
//! ## Quick Start (Sync)
//!
//! ```ignore
//! use sensor_db::SensorDb;
//!
//! // RP2350: 256-byte pages, up to 512 sectors (2 MB region)
//! let mut db: SensorDb<_, 256, 512> = SensorDb::new(
//!     flash,            // embassy_rp::flash::Flash
//!     0x0020_0000,      // base offset: 2 MB into flash
//!     512,              // sector count
//!     2,                // reserved sectors for headroom
//! )?;
//!
//! db.mount()?;
//!
//! // Write sensor data
//! db.append(0x01, timestamp_us, &temperature_bytes)?;
//!
//! // Query latest reading
//! let mut buf = [0u8; 64];
//! if let Some((header, n)) = db.latest(0x01, &mut buf)? {
//!     let payload = &buf[..n];
//!     // ...
//! }
//!
//! // Range query with callback
//! db.query_range(Some(0x01), t_start, t_end, |hdr, payload| {
//!     // process each matching entry
//!     true // return false to stop early
//! })?;
//! ```
//!
//! ## Quick Start (Async)
//!
//! Enable the `async` feature in `Cargo.toml`:
//!
//! ```ignore
//! use sensor_db::SensorDbAsync;
//!
//! let mut db: SensorDbAsync<_, 256, 512> = SensorDbAsync::new(
//!     flash, 0x0020_0000, 512, 2,
//! )?;
//! db.mount().await?;
//! db.append(0x01, timestamp_us, &temperature_bytes).await?;
//! ```

#![no_std]
#![deny(unsafe_code)]
#![deny(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]

pub mod db;
pub mod entry;
pub mod error;
pub mod logger;
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub mod mock;
pub mod partition;
pub mod port;
pub mod registry;
pub mod run;
pub mod schema;
pub mod sector;
pub mod spool;
pub mod typed;

#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub mod async_db;

// Re-export main public types at crate root for convenience
pub use db::{
    CompactScope, DbConfig, DbStats, LogPosition, MountMode, MountStats, ReadCursor, SensorDb,
    SpoolStats,
};
pub use entry::EntryHeader;
pub use error::Error;
pub use logger::{SensorLogger, SensorLoggerAsync};
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub use mock::{FlashOps, MockFlash, MockFlashError, PowerLossMode, RemovableFlash};
pub use partition::{Partition, PartitionError};
pub use port::{
    LogSink, LogSinkAsync, LogSinkAsyncExt, LogSinkExt, LogSource, LogSourceAsync,
    LogSourceAsyncExt, LogSourceExt,
};
pub use run::{RUN_FRAME_SIZE, Run};
pub use schema::SCHEMA_TAG_SIZE;
pub use sector::{LogId, SectorState, SectorSummary};
pub use spool::{Removable, SpoolBudget, Spooler, TieredDb, WriteMode, WritePolicy};
pub use typed::SensorData;

/// Re-export of the `zerocopy` version this crate was built against.
///
/// `SensorData` is bounded on `zerocopy`'s traits, so `zerocopy` is a *public*
/// dependency: a payload type must derive the same `FromBytes`/`IntoBytes` this
/// crate names, from the same version. Importing them through here rather than
/// from your own dependency makes a version skew impossible to introduce
/// silently — the failure mode otherwise is `the trait bound
/// `Temperature: FromBytes` is not satisfied` pointing at a type that plainly
/// derives it.
///
/// ```ignore
/// use sensor_db::zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
/// ```
///
/// `zerocopy` must still appear in your `Cargo.toml`, because its derives
/// expand to absolute `::zerocopy::` paths. Keep the version in step with this
/// re-export.
pub use zerocopy;

/// Derive [`SensorData`], binding a type to a sensor ID.
///
/// Requires the `derive` feature. See the macro's own documentation for the
/// `#[sensor(id = ..., version = ...)]` attribute.
#[cfg(feature = "derive")]
#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
pub use sensor_db_derive::SensorData;

#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use async_db::SensorDbAsync;
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use spool::{SpoolerAsync, TieredDbAsync};

/// Every public value type that reports state must format under `defmt`.
///
/// A generic function's body is type-checked whether or not it is ever called,
/// so this is a compile-time check that costs nothing at runtime and cannot be
/// skipped. It is written this way rather than as a `#[test]` because a test
/// *binary* linking `defmt` needs a global logger this crate does not provide —
/// which is the same reason `--all-features` must never reach a cargo command
/// that links one.
///
/// The rule it enforces: if a caller can hold it and would want it in a log
/// line, it formats. The feature previously covered [`Error`] and four wire
/// types but none of the statistics, which is the half an operator actually
/// reads.
#[cfg(feature = "defmt")]
#[allow(dead_code)]
fn defmt_covers_every_reported_type() {
    fn formats<T: defmt::Format>() {}

    // The log's own state.
    formats::<DbStats>();
    formats::<DbConfig>();
    formats::<MountStats>();
    formats::<MountMode>();
    formats::<CompactScope>();
    formats::<LogId>();
    formats::<LogPosition>();
    formats::<ReadCursor>();
    formats::<SectorState>();
    formats::<SectorSummary>();
    formats::<sector::SectorClass>();
    formats::<entry::EntryKind>();
    formats::<Error>();

    // Replication, where an operator is watching a card fill and drain.
    formats::<SpoolStats>();
    formats::<SpoolBudget>();
    formats::<spool::SpoolProgress>();
    formats::<spool::Attached>();
    formats::<spool::VolumeFill>();
    formats::<spool::RunFingerprint>();
    formats::<spool::policy::CursorScan>();
    formats::<spool::policy::SlotPlan>();
    formats::<spool::CursorKind>();
    formats::<spool::CursorRegion>();
    formats::<spool::cursor::SlotAddress>();
    formats::<WriteMode>();
    formats::<WritePolicy>();
    formats::<db::Replicated>();
}