sensor-db 0.1.0

Append-only sensor database for NOR flash on embedded devices
Documentation
//! Error types for sensor-db.

use core::fmt;
use embedded_storage::nor_flash::NorFlashErrorKind;

/// Database error type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// Flash operation failed.
    Flash(NorFlashErrorKind),
    /// Database is not mounted.
    NotMounted,
    /// Database is already mounted.
    AlreadyMounted,
    /// Payload exceeds maximum size for a single entry.
    PayloadTooLarge,
    /// Provided buffer is too small for the entry payload.
    BufferTooSmall,
    /// Entry CRC mismatch or invalid marker.
    CorruptEntry,
    /// No space available in flash (all sectors full or reserved).
    NoSpace,
    /// Invalid configuration parameters.
    InvalidConfig,
    /// Sector count exceeds MAX_SECTORS const generic.
    TooManySectors,
    /// Data size does not match expected type size.
    SizeMismatch {
        /// Size of the type the caller asked for.
        expected: usize,
        /// Size of the payload actually stored.
        actual: usize,
    },
    /// The entry was written under a different schema version of its type.
    ///
    /// The struct bound to this sensor ID has changed since the entry was
    /// stored. See [`SensorData::SCHEMA_VERSION`](crate::SensorData::SCHEMA_VERSION)
    /// for how to read both eras out of one log.
    SchemaMismatch {
        /// `SCHEMA_VERSION` of the type the caller asked for.
        expected: u8,
        /// Schema version tagged into the stored payload.
        found: u8,
    },
    /// Failed to interpret bytes as the target type.
    InvalidData,
    /// A [`Run`](crate::Run)'s parameters cannot be encoded as a single entry.
    ///
    /// The sample slice was empty or longer than `u16::MAX`, the sample type is
    /// zero-sized, the last sample's timestamp would overflow `u64`, or the
    /// frame would exceed the `u16` payload length an entry header can carry.
    /// Whether the run fits a flash *page* is a separate question, answered by
    /// [`PayloadTooLarge`](Self::PayloadTooLarge).
    InvalidRun,
    /// Arithmetic overflow in offset calculation.
    Overflow,
    /// No removable volume is attached.
    NotAttached,
    /// A volume is already attached; detach it first.
    AlreadyAttached,
    /// The volume disappeared or faulted mid-operation.
    ///
    /// Detach and re-attach to recover. Note that a genuine flash fault on the
    /// medium is indistinguishable from removal at the driver level, so this is
    /// a policy verdict rather than a hardware report — see
    /// [`Removable`](crate::Removable) for drivers that can tell the difference.
    VolumeLost,
    /// The volume belongs to a different logical log.
    ///
    /// Returned instead of treating the medium as blank, which would erase
    /// another device's data.
    ForeignVolume {
        /// The `log_id` this database expects (0 if anonymous).
        expected: u32,
        /// The `log_id` found on the medium.
        found: u32,
    },
    /// The medium is formatted with a version this build cannot read.
    UnsupportedVersion {
        /// The format version found on the medium.
        found: u8,
    },
    /// Source and destination geometries are incompatible for replication.
    ///
    /// The destination's page size must be at least the source's, or entries
    /// near the source's maximum payload could never be copied.
    GeometryMismatch,
    /// The on-medium replication cursor is unreadable or structurally invalid.
    CorruptCursor,
    /// This database was mounted without a full index and cannot serve reads.
    ///
    /// See [`MountMode::HeadersOnly`](crate::db::MountMode).
    ReadsUnavailable,
    /// The requested flash region intersects the database's own sectors.
    ///
    /// Raised by [`SensorDb::with_region`](crate::SensorDb::with_region) and its
    /// async counterpart, which broker access to *other* things living on the
    /// same chip. Writing inside the database region behind the database's back
    /// corrupts the log, and the damage would not surface until a later mount.
    RegionOverlap {
        /// First byte of the database region.
        db_base: u32,
        /// Byte after the last byte of the database region.
        db_end: u32,
    },
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Flash(kind) => write!(f, "flash error: {:?}", kind),
            Error::NotMounted => write!(f, "database not mounted"),
            Error::AlreadyMounted => write!(f, "database already mounted"),
            Error::PayloadTooLarge => write!(f, "payload too large"),
            Error::BufferTooSmall => write!(f, "buffer too small"),
            Error::CorruptEntry => write!(f, "corrupt entry"),
            Error::NoSpace => write!(f, "no space available"),
            Error::InvalidConfig => write!(f, "invalid configuration"),
            Error::TooManySectors => write!(f, "too many sectors for MAX_SECTORS"),
            Error::SizeMismatch { expected, actual } => {
                write!(
                    f,
                    "size mismatch: expected {} bytes, got {}",
                    expected, actual
                )
            }
            Error::SchemaMismatch { expected, found } => {
                write!(
                    f,
                    "schema mismatch: expected version {}, found {}",
                    expected, found
                )
            }
            Error::InvalidData => {
                write!(f, "invalid data: failed to interpret bytes as target type")
            }
            Error::InvalidRun => write!(f, "run cannot be encoded as a single entry"),
            Error::Overflow => write!(f, "arithmetic overflow in offset calculation"),
            Error::NotAttached => write!(f, "no volume attached"),
            Error::AlreadyAttached => write!(f, "a volume is already attached"),
            Error::VolumeLost => write!(f, "volume lost mid-operation"),
            Error::ForeignVolume { expected, found } => write!(
                f,
                "foreign volume: expected log id {}, found {}",
                expected, found
            ),
            Error::UnsupportedVersion { found } => {
                write!(f, "unsupported sector format version {}", found)
            }
            Error::GeometryMismatch => write!(f, "incompatible flash geometry for replication"),
            Error::CorruptCursor => write!(f, "corrupt replication cursor"),
            Error::ReadsUnavailable => {
                write!(
                    f,
                    "database mounted without a full index; reads unavailable"
                )
            }
            Error::RegionOverlap { db_base, db_end } => write!(
                f,
                "region overlaps the database's own sectors [{}, {})",
                db_base, db_end
            ),
        }
    }
}

impl core::error::Error for Error {}

impl<E: embedded_storage::nor_flash::NorFlashError> From<E> for Error {
    fn from(e: E) -> Self {
        Error::Flash(e.kind())
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for Error {
    fn format(&self, f: defmt::Formatter) {
        match self {
            Error::Flash(kind) => defmt::write!(f, "flash error: {:?}", defmt::Debug2Format(kind)),
            Error::NotMounted => defmt::write!(f, "database not mounted"),
            Error::AlreadyMounted => defmt::write!(f, "database already mounted"),
            Error::PayloadTooLarge => defmt::write!(f, "payload too large"),
            Error::BufferTooSmall => defmt::write!(f, "buffer too small"),
            Error::CorruptEntry => defmt::write!(f, "corrupt entry"),
            Error::NoSpace => defmt::write!(f, "no space available"),
            Error::InvalidConfig => defmt::write!(f, "invalid configuration"),
            Error::TooManySectors => defmt::write!(f, "too many sectors for MAX_SECTORS"),
            Error::SizeMismatch { expected, actual } => {
                defmt::write!(
                    f,
                    "size mismatch: expected {} bytes, got {}",
                    expected,
                    actual
                )
            }
            Error::SchemaMismatch { expected, found } => {
                defmt::write!(
                    f,
                    "schema mismatch: expected version {}, found {}",
                    expected,
                    found
                )
            }
            Error::InvalidData => {
                defmt::write!(f, "invalid data: failed to interpret bytes as target type")
            }
            Error::InvalidRun => defmt::write!(f, "run cannot be encoded as a single entry"),
            Error::Overflow => defmt::write!(f, "arithmetic overflow in offset calculation"),
            Error::NotAttached => defmt::write!(f, "no volume attached"),
            Error::AlreadyAttached => defmt::write!(f, "a volume is already attached"),
            Error::VolumeLost => defmt::write!(f, "volume lost mid-operation"),
            Error::ForeignVolume { expected, found } => defmt::write!(
                f,
                "foreign volume: expected log id {}, found {}",
                expected,
                found
            ),
            Error::UnsupportedVersion { found } => {
                defmt::write!(f, "unsupported sector format version {}", found)
            }
            Error::GeometryMismatch => {
                defmt::write!(f, "incompatible flash geometry for replication")
            }
            Error::CorruptCursor => defmt::write!(f, "corrupt replication cursor"),
            Error::ReadsUnavailable => {
                defmt::write!(
                    f,
                    "database mounted without a full index; reads unavailable"
                )
            }
            Error::RegionOverlap { db_base, db_end } => defmt::write!(
                f,
                "region overlaps the database's own sectors [{}, {})",
                db_base,
                db_end
            ),
        }
    }
}