Skip to main content

sensor_db/
error.rs

1//! Error types for sensor-db.
2
3use core::fmt;
4use embedded_storage::nor_flash::NorFlashErrorKind;
5
6/// Database error type.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8#[non_exhaustive]
9pub enum Error {
10    /// Flash operation failed.
11    Flash(NorFlashErrorKind),
12    /// Database is not mounted.
13    NotMounted,
14    /// Database is already mounted.
15    AlreadyMounted,
16    /// Payload exceeds maximum size for a single entry.
17    PayloadTooLarge,
18    /// Provided buffer is too small for the entry payload.
19    BufferTooSmall,
20    /// Entry CRC mismatch or invalid marker.
21    CorruptEntry,
22    /// No space available in flash (all sectors full or reserved).
23    NoSpace,
24    /// Invalid configuration parameters.
25    InvalidConfig,
26    /// Sector count exceeds MAX_SECTORS const generic.
27    TooManySectors,
28    /// Data size does not match expected type size.
29    SizeMismatch {
30        /// Size of the type the caller asked for.
31        expected: usize,
32        /// Size of the payload actually stored.
33        actual: usize,
34    },
35    /// The entry was written under a different schema version of its type.
36    ///
37    /// The struct bound to this sensor ID has changed since the entry was
38    /// stored. See [`SensorData::SCHEMA_VERSION`](crate::SensorData::SCHEMA_VERSION)
39    /// for how to read both eras out of one log.
40    SchemaMismatch {
41        /// `SCHEMA_VERSION` of the type the caller asked for.
42        expected: u8,
43        /// Schema version tagged into the stored payload.
44        found: u8,
45    },
46    /// Failed to interpret bytes as the target type.
47    InvalidData,
48    /// A [`Run`](crate::Run)'s parameters cannot be encoded as a single entry.
49    ///
50    /// The sample slice was empty or longer than `u16::MAX`, the sample type is
51    /// zero-sized, the last sample's timestamp would overflow `u64`, or the
52    /// frame would exceed the `u16` payload length an entry header can carry.
53    /// Whether the run fits a flash *page* is a separate question, answered by
54    /// [`PayloadTooLarge`](Self::PayloadTooLarge).
55    InvalidRun,
56    /// Arithmetic overflow in offset calculation.
57    Overflow,
58    /// No removable volume is attached.
59    NotAttached,
60    /// A volume is already attached; detach it first.
61    AlreadyAttached,
62    /// The volume disappeared or faulted mid-operation.
63    ///
64    /// Detach and re-attach to recover. Note that a genuine flash fault on the
65    /// medium is indistinguishable from removal at the driver level, so this is
66    /// a policy verdict rather than a hardware report — see
67    /// [`Removable`](crate::Removable) for drivers that can tell the difference.
68    VolumeLost,
69    /// The volume belongs to a different logical log.
70    ///
71    /// Returned instead of treating the medium as blank, which would erase
72    /// another device's data.
73    ForeignVolume {
74        /// The `log_id` this database expects (0 if anonymous).
75        expected: u32,
76        /// The `log_id` found on the medium.
77        found: u32,
78    },
79    /// The medium is formatted with a version this build cannot read.
80    UnsupportedVersion {
81        /// The format version found on the medium.
82        found: u8,
83    },
84    /// Source and destination geometries are incompatible for replication.
85    ///
86    /// The destination's page size must be at least the source's, or entries
87    /// near the source's maximum payload could never be copied.
88    GeometryMismatch,
89    /// The on-medium replication cursor is unreadable or structurally invalid.
90    CorruptCursor,
91    /// This database was mounted without a full index and cannot serve reads.
92    ///
93    /// See [`MountMode::HeadersOnly`](crate::db::MountMode).
94    ReadsUnavailable,
95    /// The requested flash region intersects the database's own sectors.
96    ///
97    /// Raised by [`SensorDb::with_region`](crate::SensorDb::with_region) and its
98    /// async counterpart, which broker access to *other* things living on the
99    /// same chip. Writing inside the database region behind the database's back
100    /// corrupts the log, and the damage would not surface until a later mount.
101    RegionOverlap {
102        /// First byte of the database region.
103        db_base: u32,
104        /// Byte after the last byte of the database region.
105        db_end: u32,
106    },
107}
108
109impl fmt::Display for Error {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        match self {
112            Error::Flash(kind) => write!(f, "flash error: {:?}", kind),
113            Error::NotMounted => write!(f, "database not mounted"),
114            Error::AlreadyMounted => write!(f, "database already mounted"),
115            Error::PayloadTooLarge => write!(f, "payload too large"),
116            Error::BufferTooSmall => write!(f, "buffer too small"),
117            Error::CorruptEntry => write!(f, "corrupt entry"),
118            Error::NoSpace => write!(f, "no space available"),
119            Error::InvalidConfig => write!(f, "invalid configuration"),
120            Error::TooManySectors => write!(f, "too many sectors for MAX_SECTORS"),
121            Error::SizeMismatch { expected, actual } => {
122                write!(
123                    f,
124                    "size mismatch: expected {} bytes, got {}",
125                    expected, actual
126                )
127            }
128            Error::SchemaMismatch { expected, found } => {
129                write!(
130                    f,
131                    "schema mismatch: expected version {}, found {}",
132                    expected, found
133                )
134            }
135            Error::InvalidData => {
136                write!(f, "invalid data: failed to interpret bytes as target type")
137            }
138            Error::InvalidRun => write!(f, "run cannot be encoded as a single entry"),
139            Error::Overflow => write!(f, "arithmetic overflow in offset calculation"),
140            Error::NotAttached => write!(f, "no volume attached"),
141            Error::AlreadyAttached => write!(f, "a volume is already attached"),
142            Error::VolumeLost => write!(f, "volume lost mid-operation"),
143            Error::ForeignVolume { expected, found } => write!(
144                f,
145                "foreign volume: expected log id {}, found {}",
146                expected, found
147            ),
148            Error::UnsupportedVersion { found } => {
149                write!(f, "unsupported sector format version {}", found)
150            }
151            Error::GeometryMismatch => write!(f, "incompatible flash geometry for replication"),
152            Error::CorruptCursor => write!(f, "corrupt replication cursor"),
153            Error::ReadsUnavailable => {
154                write!(
155                    f,
156                    "database mounted without a full index; reads unavailable"
157                )
158            }
159            Error::RegionOverlap { db_base, db_end } => write!(
160                f,
161                "region overlaps the database's own sectors [{}, {})",
162                db_base, db_end
163            ),
164        }
165    }
166}
167
168impl core::error::Error for Error {}
169
170impl<E: embedded_storage::nor_flash::NorFlashError> From<E> for Error {
171    fn from(e: E) -> Self {
172        Error::Flash(e.kind())
173    }
174}
175
176#[cfg(feature = "defmt")]
177impl defmt::Format for Error {
178    fn format(&self, f: defmt::Formatter) {
179        match self {
180            Error::Flash(kind) => defmt::write!(f, "flash error: {:?}", defmt::Debug2Format(kind)),
181            Error::NotMounted => defmt::write!(f, "database not mounted"),
182            Error::AlreadyMounted => defmt::write!(f, "database already mounted"),
183            Error::PayloadTooLarge => defmt::write!(f, "payload too large"),
184            Error::BufferTooSmall => defmt::write!(f, "buffer too small"),
185            Error::CorruptEntry => defmt::write!(f, "corrupt entry"),
186            Error::NoSpace => defmt::write!(f, "no space available"),
187            Error::InvalidConfig => defmt::write!(f, "invalid configuration"),
188            Error::TooManySectors => defmt::write!(f, "too many sectors for MAX_SECTORS"),
189            Error::SizeMismatch { expected, actual } => {
190                defmt::write!(
191                    f,
192                    "size mismatch: expected {} bytes, got {}",
193                    expected,
194                    actual
195                )
196            }
197            Error::SchemaMismatch { expected, found } => {
198                defmt::write!(
199                    f,
200                    "schema mismatch: expected version {}, found {}",
201                    expected,
202                    found
203                )
204            }
205            Error::InvalidData => {
206                defmt::write!(f, "invalid data: failed to interpret bytes as target type")
207            }
208            Error::InvalidRun => defmt::write!(f, "run cannot be encoded as a single entry"),
209            Error::Overflow => defmt::write!(f, "arithmetic overflow in offset calculation"),
210            Error::NotAttached => defmt::write!(f, "no volume attached"),
211            Error::AlreadyAttached => defmt::write!(f, "a volume is already attached"),
212            Error::VolumeLost => defmt::write!(f, "volume lost mid-operation"),
213            Error::ForeignVolume { expected, found } => defmt::write!(
214                f,
215                "foreign volume: expected log id {}, found {}",
216                expected,
217                found
218            ),
219            Error::UnsupportedVersion { found } => {
220                defmt::write!(f, "unsupported sector format version {}", found)
221            }
222            Error::GeometryMismatch => {
223                defmt::write!(f, "incompatible flash geometry for replication")
224            }
225            Error::CorruptCursor => defmt::write!(f, "corrupt replication cursor"),
226            Error::ReadsUnavailable => {
227                defmt::write!(
228                    f,
229                    "database mounted without a full index; reads unavailable"
230                )
231            }
232            Error::RegionOverlap { db_base, db_end } => defmt::write!(
233                f,
234                "region overlaps the database's own sectors [{}, {})",
235                db_base,
236                db_end
237            ),
238        }
239    }
240}