Skip to main content

aimdb_core/
error.rs

1//! Error handling for AimDB core operations
2//!
3//! This module provides a streamlined error type system that works across all AimDB
4//! target platforms: MCU (no_std), edge devices and cloud environments.
5//!
6//! # Platform Compatibility
7//!
8//! Every variant has a single shape on all targets: context fields use
9//! `alloc::string::String`, which is available everywhere (the crate
10//! unconditionally requires `alloc`), and `Display`/`Error` come from
11//! `thiserror` (no_std-capable since 2.x). Only variants that wrap std types
12//! (`Io`, `Json`) are gated on the `std` feature.
13//!
14//! # Error Categories
15//!
16//! The [`DbError`] enum covers only the errors actually constructed by AimDB:
17//!
18//! - **Network**: Connection failures, timeout errors
19//! - **Buffer**: Full, lagged, closed, or empty buffers
20//! - **Database**: Record not found, invalid operations
21//! - **Configuration**: Missing required configuration; mistakes collected by `build()`
22//! - **Runtime**: Runtime adapter errors
23//! - **Transform**: Dependency-graph cycles, missing transform inputs
24//! - **I/O & JSON**: Standard library integrations (std only)
25//!
26//! Layer-specific errors live with their layer: the blocking facade has
27//! `aimdb_sync::SyncError`, connectors have their own error types wrapping
28//! `DbError` where needed.
29
30use alloc::string::String;
31use alloc::vec::Vec;
32use thiserror::Error;
33
34#[cfg(feature = "std")]
35use std::io;
36
37/// One configuration mistake found while configuring an `AimDbBuilder`.
38///
39/// Builder methods never panic on user mistakes; they record one of these and
40/// `build()` reports **all** of them at once via
41/// [`DbError::InvalidConfiguration`].
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct ConfigError {
44    /// Key of the record the mistake belongs to. Errors recorded before the
45    /// key is known (inside `TypedRecord` setters) carry an empty key that
46    /// `build()` fills in when draining.
47    pub record_key: String,
48    /// Connector URL, for link-related mistakes.
49    pub url: Option<String>,
50    /// Human-readable description of the mistake.
51    pub message: String,
52}
53
54impl ConfigError {
55    /// Builds a `ConfigError`.
56    pub fn new(
57        record_key: impl Into<String>,
58        url: Option<String>,
59        message: impl Into<String>,
60    ) -> Self {
61        Self {
62            record_key: record_key.into(),
63            url,
64            message: message.into(),
65        }
66    }
67}
68
69impl core::fmt::Display for ConfigError {
70    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
71        // Graph-level findings (cycles) span records and carry no single key.
72        if !self.record_key.is_empty() {
73            write!(f, "record '{}'", self.record_key)?;
74            if let Some(url) = &self.url {
75                write!(f, " ({url})")?;
76            }
77            write!(f, ": ")?;
78        } else if let Some(url) = &self.url {
79            write!(f, "({url}): ")?;
80        }
81        write!(f, "{}", self.message)
82    }
83}
84
85/// Joins collected configuration errors for `InvalidConfiguration`'s `Display`.
86fn join_config_errors(errors: &[ConfigError]) -> String {
87    use core::fmt::Write;
88    let mut out = String::new();
89    for (i, e) in errors.iter().enumerate() {
90        if i > 0 {
91            out.push_str("; ");
92        }
93        let _ = write!(out, "{e}");
94    }
95    out
96}
97
98/// Streamlined error type for AimDB operations
99///
100/// Only includes errors that are actually used in the codebase,
101/// removing theoretical/unused error variants for simplicity.
102///
103/// `#[non_exhaustive]`: match on [`DbError::kind`] where you only need to know
104/// what to do about the failure.
105#[derive(Debug, Error)]
106#[non_exhaustive]
107pub enum DbError {
108    // ===== Network Errors =====
109    /// Connection or timeout failures
110    #[error("Connection failed to {endpoint}: {reason}")]
111    ConnectionFailed { endpoint: String, reason: String },
112
113    // ===== Buffer Errors =====
114    /// Buffer is full and cannot accept more items
115    #[error("Buffer full: {buffer_name} ({size} items)")]
116    BufferFull { size: u32, buffer_name: String },
117
118    /// Consumer lagged behind producer (SPMC ring buffers)
119    #[error("Consumer lagged by {lag_count} messages")]
120    BufferLagged { lag_count: u64, buffer_name: String },
121
122    /// Buffer channel has been closed (shutdown)
123    #[error("Buffer channel closed: {buffer_name}")]
124    BufferClosed { buffer_name: String },
125
126    /// Non-blocking receive found no pending values
127    #[error("Buffer empty: no pending values")]
128    BufferEmpty,
129
130    // ===== Database Errors =====
131    /// Record type not found in database (legacy, by type name)
132    #[error("Record type not found: {record_name}")]
133    RecordNotFound { record_name: String },
134
135    /// Record key not found in registry
136    #[error("Record key not found: {key}")]
137    RecordKeyNotFound { key: String },
138
139    /// RecordId out of bounds or invalid
140    #[error("Invalid record ID: {id}")]
141    InvalidRecordId { id: u32 },
142
143    /// Type mismatch when accessing record by ID
144    #[error("Type mismatch: expected {expected_type}, record {record_id} has different type")]
145    TypeMismatch {
146        record_id: u32,
147        expected_type: String,
148    },
149
150    /// Invalid operation attempted
151    #[error("Invalid operation '{operation}': {reason}")]
152    InvalidOperation { operation: String, reason: String },
153
154    /// Permission denied for operation
155    #[error("Permission denied: {operation}")]
156    PermissionDenied { operation: String },
157
158    // ===== Configuration Errors =====
159    /// Missing required configuration parameter
160    #[error("Missing configuration parameter: {parameter}")]
161    MissingConfiguration { parameter: String },
162
163    /// Configuration mistakes collected by `AimDbBuilder::build()` — one
164    /// entry per finding, so a single run surfaces every mistake.
165    #[error("invalid configuration ({} error(s)): {}", errors.len(), join_config_errors(errors))]
166    InvalidConfiguration { errors: Vec<ConfigError> },
167
168    // ===== Runtime Errors =====
169    /// Runtime execution error (task spawning, scheduling, etc.)
170    #[error("Runtime error: {message}")]
171    RuntimeError { message: String },
172
173    // ===== Internal Errors =====
174    /// Internal error for unexpected conditions
175    #[error("Internal error (0x{code:04X}): {message}")]
176    Internal { code: u32, message: String },
177
178    // ===== Transform / Dependency Graph Errors =====
179    /// Transform dependency graph contains a cycle
180    #[error("Cyclic dependency detected among records: {records:?}")]
181    CyclicDependency { records: Vec<String> },
182
183    /// Transform input key references a record that was not registered
184    #[error("Transform on '{output_key}' references unregistered input '{input_key}'")]
185    TransformInputNotFound {
186        output_key: String,
187        input_key: String,
188    },
189
190    // ===== Standard Library Integrations (std only) =====
191    /// I/O operation error
192    #[cfg(feature = "std")]
193    #[error("I/O error: {source}")]
194    Io {
195        #[from]
196        source: io::Error,
197    },
198
199    /// I/O operation error with context
200    #[cfg(feature = "std")]
201    #[error("I/O error: {context}: {source}")]
202    IoWithContext {
203        context: String,
204        #[source]
205        source: io::Error,
206    },
207
208    /// JSON serialization error
209    #[cfg(feature = "std")]
210    #[error("JSON error: {source}")]
211    Json {
212        #[from]
213        source: serde_json::Error,
214    },
215
216    /// JSON serialization error with context
217    #[cfg(feature = "std")]
218    #[error("JSON error: {context}: {source}")]
219    JsonWithContext {
220        context: String,
221        #[source]
222        source: serde_json::Error,
223    },
224}
225
226// Through `Display` (`thiserror`), not a derive: the `std`-only variants carry
227// `io::Error` / `serde_json::Error`, which do not implement `defmt::Format`,
228// and docs.rs builds with every feature on, `std` and `defmt` together.
229#[cfg(feature = "defmt")]
230impl defmt::Format for DbError {
231    fn format(&self, f: defmt::Formatter) {
232        defmt::write!(f, "{}", defmt::Display2Format(self))
233    }
234}
235
236// ===== DbError Implementation =====
237impl DbError {
238    /// Builds a [`RuntimeError`](DbError::RuntimeError).
239    pub fn runtime_error(message: impl Into<String>) -> Self {
240        DbError::RuntimeError {
241            message: message.into(),
242        }
243    }
244
245    /// Builds a [`PermissionDenied`](DbError::PermissionDenied).
246    pub fn permission_denied(operation: impl Into<String>) -> Self {
247        DbError::PermissionDenied {
248            operation: operation.into(),
249        }
250    }
251
252    /// Builds a [`RecordKeyNotFound`](DbError::RecordKeyNotFound).
253    pub fn record_key_not_found(key: impl Into<String>) -> Self {
254        DbError::RecordKeyNotFound { key: key.into() }
255    }
256
257    /// Builds a [`MissingConfiguration`](DbError::MissingConfiguration).
258    pub fn missing_configuration(parameter: impl Into<String>) -> Self {
259        DbError::MissingConfiguration {
260            parameter: parameter.into(),
261        }
262    }
263}
264
265/// What a caller does about a [`DbError`]: retry, resubscribe, stop, or fix
266/// something — and which something.
267///
268/// Match on this rather than on [`DbError`]'s variants when you only need to
269/// know what to do. A new variant is a compile error in [`DbError::kind`]
270/// rather than a silent reclassification at every downstream wildcard.
271#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
272#[non_exhaustive]
273pub enum DbErrorKind {
274    /// Nothing available, or no room, *right now*. Retry.
275    Retry,
276
277    /// Values dropped because this reader fell behind. Note the gap, continue.
278    Lagged,
279
280    /// The database or buffer is shutting down. Stop; retrying cannot help.
281    Closed,
282
283    /// An I/O or connection failure. Retry, or fix the deployment.
284    Transport,
285
286    /// A payload could not be encoded or decoded. Fix the schema or the sender.
287    Data,
288
289    /// The record graph is misconfigured. Fix it before starting.
290    Configuration,
291
292    /// This call was wrong for this record. Fix the call site.
293    Usage,
294
295    /// The database's own machinery or its host. Report a bug.
296    Internal,
297}
298
299impl DbError {
300    /// Classify the failure by what the caller can do about it.
301    ///
302    /// Exhaustive inside the crate that owns the enum: a variant added later
303    /// fails to compile here instead of falling into a downstream wildcard.
304    pub fn kind(&self) -> DbErrorKind {
305        match self {
306            Self::BufferEmpty | Self::BufferFull { .. } => DbErrorKind::Retry,
307
308            Self::BufferLagged { .. } => DbErrorKind::Lagged,
309
310            Self::BufferClosed { .. } => DbErrorKind::Closed,
311
312            Self::ConnectionFailed { .. } => DbErrorKind::Transport,
313
314            Self::MissingConfiguration { .. }
315            | Self::InvalidConfiguration { .. }
316            | Self::CyclicDependency { .. }
317            | Self::TransformInputNotFound { .. } => DbErrorKind::Configuration,
318
319            Self::RecordNotFound { .. }
320            | Self::RecordKeyNotFound { .. }
321            | Self::InvalidRecordId { .. }
322            | Self::TypeMismatch { .. }
323            | Self::InvalidOperation { .. }
324            | Self::PermissionDenied { .. } => DbErrorKind::Usage,
325
326            Self::RuntimeError { .. } | Self::Internal { .. } => DbErrorKind::Internal,
327
328            #[cfg(feature = "std")]
329            Self::Io { .. } | Self::IoWithContext { .. } => DbErrorKind::Transport,
330
331            #[cfg(feature = "std")]
332            Self::Json { .. } | Self::JsonWithContext { .. } => DbErrorKind::Data,
333        }
334    }
335}
336
337/// Type alias for Results using DbError
338pub type DbResult<T> = Result<T, DbError>;
339
340// ============================================================================
341// Error Conversions
342// ============================================================================
343
344/// Convert executor errors to database errors
345///
346/// This allows engine plumbing to return `ExecutorError` while the core
347/// database works with `DbError` for consistency across the API.
348impl From<crate::executor::ExecutorError> for DbError {
349    fn from(err: crate::executor::ExecutorError) -> Self {
350        use crate::executor::ExecutorError;
351
352        match err {
353            ExecutorError::QueueClosed => DbError::runtime_error("join queue closed"),
354        }
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361    use alloc::string::ToString;
362    use alloc::vec;
363
364    #[test]
365    fn test_error_size_constraint() {
366        let size = core::mem::size_of::<DbError>();
367        assert!(
368            size <= 64,
369            "DbError size ({} bytes) exceeds 64-byte embedded limit",
370            size
371        );
372    }
373
374    #[test]
375    fn test_invalid_configuration_display() {
376        let err = DbError::InvalidConfiguration {
377            errors: vec![
378                ConfigError::new(
379                    "rec.a",
380                    Some("mqtt://broker/a".to_string()),
381                    "missing serializer",
382                ),
383                ConfigError::new("rec.b", None, "duplicate producer"),
384            ],
385        };
386
387        let s = err.to_string();
388        assert!(s.contains("2 error(s)"), "got: {s}");
389        assert!(
390            s.contains("record 'rec.a' (mqtt://broker/a): missing serializer"),
391            "got: {s}"
392        );
393        assert!(s.contains("record 'rec.b': duplicate producer"), "got: {s}");
394    }
395
396    #[test]
397    fn test_helper_constructors() {
398        assert!(matches!(
399            DbError::runtime_error("boom"),
400            DbError::RuntimeError { .. }
401        ));
402        assert!(matches!(
403            DbError::permission_denied("write"),
404            DbError::PermissionDenied { .. }
405        ));
406        assert!(matches!(
407            DbError::record_key_not_found("k"),
408            DbError::RecordKeyNotFound { .. }
409        ));
410        assert!(matches!(
411            DbError::missing_configuration("p"),
412            DbError::MissingConfiguration { .. }
413        ));
414    }
415
416    #[cfg(feature = "std")]
417    #[test]
418    fn test_io_json_conversions() {
419        let io_error = std::io::Error::other("File not found");
420        let db_error: DbError = io_error.into();
421        assert!(matches!(db_error, DbError::Io { .. }));
422
423        let json_error = serde_json::from_str::<serde_json::Value>("invalid").unwrap_err();
424        let db_error: DbError = json_error.into();
425        assert!(matches!(db_error, DbError::Json { .. }));
426    }
427
428    #[test]
429    fn kind_maps_each_variant_to_its_action() {
430        use DbErrorKind::*;
431
432        assert_eq!(DbError::BufferEmpty.kind(), Retry);
433        assert_eq!(
434            DbError::BufferFull {
435                size: 8,
436                buffer_name: "b".to_string()
437            }
438            .kind(),
439            Retry
440        );
441
442        assert_eq!(
443            DbError::BufferLagged {
444                lag_count: 3,
445                buffer_name: "b".to_string()
446            }
447            .kind(),
448            Lagged
449        );
450
451        assert_eq!(
452            DbError::BufferClosed {
453                buffer_name: "b".to_string()
454            }
455            .kind(),
456            Closed
457        );
458
459        assert_eq!(
460            DbError::ConnectionFailed {
461                endpoint: "e".to_string(),
462                reason: "r".to_string()
463            }
464            .kind(),
465            Transport
466        );
467
468        assert_eq!(DbError::missing_configuration("p").kind(), Configuration);
469        assert_eq!(
470            DbError::InvalidConfiguration { errors: vec![] }.kind(),
471            Configuration
472        );
473        assert_eq!(
474            DbError::CyclicDependency { records: vec![] }.kind(),
475            Configuration
476        );
477        assert_eq!(
478            DbError::TransformInputNotFound {
479                output_key: "o".to_string(),
480                input_key: "i".to_string()
481            }
482            .kind(),
483            Configuration
484        );
485
486        assert_eq!(
487            DbError::RecordNotFound {
488                record_name: "r".to_string()
489            }
490            .kind(),
491            Usage
492        );
493        assert_eq!(DbError::record_key_not_found("k").kind(), Usage);
494        assert_eq!(DbError::InvalidRecordId { id: 9 }.kind(), Usage);
495        assert_eq!(
496            DbError::TypeMismatch {
497                expected_type: "T".to_string(),
498                record_id: 1
499            }
500            .kind(),
501            Usage
502        );
503        assert_eq!(
504            DbError::InvalidOperation {
505                operation: "o".to_string(),
506                reason: "r".to_string()
507            }
508            .kind(),
509            Usage
510        );
511        assert_eq!(DbError::permission_denied("op").kind(), Usage);
512
513        assert_eq!(DbError::runtime_error("m").kind(), Internal);
514        assert_eq!(
515            DbError::Internal {
516                code: 1,
517                message: "m".to_string()
518            }
519            .kind(),
520            Internal
521        );
522    }
523
524    #[cfg(feature = "std")]
525    #[test]
526    fn kind_maps_the_std_only_variants() {
527        let io: DbError = std::io::Error::other("x").into();
528        assert_eq!(io.kind(), DbErrorKind::Transport);
529
530        let json: DbError = serde_json::from_str::<serde_json::Value>("nope")
531            .unwrap_err()
532            .into();
533        assert_eq!(json.kind(), DbErrorKind::Data);
534    }
535
536    /// A caller that cannot tell these apart retries forever on a dead buffer.
537    #[test]
538    fn retry_and_closed_stay_distinguishable() {
539        assert_ne!(
540            DbError::BufferEmpty.kind(),
541            DbError::BufferClosed {
542                buffer_name: "b".to_string()
543            }
544            .kind()
545        );
546    }
547}