aimdb-core 2.0.0

Type-safe async data pipelines — one Rust codebase from MCU to cloud
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! Error handling for AimDB core operations
//!
//! This module provides a streamlined error type system that works across all AimDB
//! target platforms: MCU (no_std), edge devices and cloud environments.
//!
//! # Platform Compatibility
//!
//! Every variant has a single shape on all targets: context fields use
//! `alloc::string::String`, which is available everywhere (the crate
//! unconditionally requires `alloc`), and `Display`/`Error` come from
//! `thiserror` (no_std-capable since 2.x). Only variants that wrap std types
//! (`Io`, `Json`) are gated on the `std` feature.
//!
//! # Error Categories
//!
//! The [`DbError`] enum covers only the errors actually constructed by AimDB:
//!
//! - **Network**: Connection failures, timeout errors
//! - **Buffer**: Full, lagged, closed, or empty buffers
//! - **Database**: Record not found, invalid operations
//! - **Configuration**: Missing required configuration; mistakes collected by `build()`
//! - **Runtime**: Runtime adapter errors
//! - **Transform**: Dependency-graph cycles, missing transform inputs
//! - **I/O & JSON**: Standard library integrations (std only)
//!
//! Layer-specific errors live with their layer: the blocking facade has
//! `aimdb_sync::SyncError`, connectors have their own error types wrapping
//! `DbError` where needed.

use alloc::string::String;
use alloc::vec::Vec;
use thiserror::Error;

#[cfg(feature = "std")]
use std::io;

/// One configuration mistake found while configuring an `AimDbBuilder`.
///
/// Builder methods never panic on user mistakes; they record one of these and
/// `build()` reports **all** of them at once via
/// [`DbError::InvalidConfiguration`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigError {
    /// Key of the record the mistake belongs to. Errors recorded before the
    /// key is known (inside `TypedRecord` setters) carry an empty key that
    /// `build()` fills in when draining.
    pub record_key: String,
    /// Connector URL, for link-related mistakes.
    pub url: Option<String>,
    /// Human-readable description of the mistake.
    pub message: String,
}

impl ConfigError {
    /// Builds a `ConfigError`.
    pub fn new(
        record_key: impl Into<String>,
        url: Option<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            record_key: record_key.into(),
            url,
            message: message.into(),
        }
    }
}

impl core::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        // Graph-level findings (cycles) span records and carry no single key.
        if !self.record_key.is_empty() {
            write!(f, "record '{}'", self.record_key)?;
            if let Some(url) = &self.url {
                write!(f, " ({url})")?;
            }
            write!(f, ": ")?;
        } else if let Some(url) = &self.url {
            write!(f, "({url}): ")?;
        }
        write!(f, "{}", self.message)
    }
}

/// Joins collected configuration errors for `InvalidConfiguration`'s `Display`.
fn join_config_errors(errors: &[ConfigError]) -> String {
    use core::fmt::Write;
    let mut out = String::new();
    for (i, e) in errors.iter().enumerate() {
        if i > 0 {
            out.push_str("; ");
        }
        let _ = write!(out, "{e}");
    }
    out
}

/// Streamlined error type for AimDB operations
///
/// Only includes errors that are actually used in the codebase,
/// removing theoretical/unused error variants for simplicity.
///
/// `#[non_exhaustive]`: match on [`DbError::kind`] where you only need to know
/// what to do about the failure.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DbError {
    // ===== Network Errors =====
    /// Connection or timeout failures
    #[error("Connection failed to {endpoint}: {reason}")]
    ConnectionFailed { endpoint: String, reason: String },

    // ===== Buffer Errors =====
    /// Buffer is full and cannot accept more items
    #[error("Buffer full: {buffer_name} ({size} items)")]
    BufferFull { size: u32, buffer_name: String },

    /// Consumer lagged behind producer (SPMC ring buffers)
    #[error("Consumer lagged by {lag_count} messages")]
    BufferLagged { lag_count: u64, buffer_name: String },

    /// Buffer channel has been closed (shutdown)
    #[error("Buffer channel closed: {buffer_name}")]
    BufferClosed { buffer_name: String },

    /// Non-blocking receive found no pending values
    #[error("Buffer empty: no pending values")]
    BufferEmpty,

    // ===== Database Errors =====
    /// Record type not found in database (legacy, by type name)
    #[error("Record type not found: {record_name}")]
    RecordNotFound { record_name: String },

    /// Record key not found in registry
    #[error("Record key not found: {key}")]
    RecordKeyNotFound { key: String },

    /// RecordId out of bounds or invalid
    #[error("Invalid record ID: {id}")]
    InvalidRecordId { id: u32 },

    /// Type mismatch when accessing record by ID
    #[error("Type mismatch: expected {expected_type}, record {record_id} has different type")]
    TypeMismatch {
        record_id: u32,
        expected_type: String,
    },

    /// Invalid operation attempted
    #[error("Invalid operation '{operation}': {reason}")]
    InvalidOperation { operation: String, reason: String },

    /// Permission denied for operation
    #[error("Permission denied: {operation}")]
    PermissionDenied { operation: String },

    // ===== Configuration Errors =====
    /// Missing required configuration parameter
    #[error("Missing configuration parameter: {parameter}")]
    MissingConfiguration { parameter: String },

    /// Configuration mistakes collected by `AimDbBuilder::build()` — one
    /// entry per finding, so a single run surfaces every mistake.
    #[error("invalid configuration ({} error(s)): {}", errors.len(), join_config_errors(errors))]
    InvalidConfiguration { errors: Vec<ConfigError> },

    // ===== Runtime Errors =====
    /// Runtime execution error (task spawning, scheduling, etc.)
    #[error("Runtime error: {message}")]
    RuntimeError { message: String },

    // ===== Internal Errors =====
    /// Internal error for unexpected conditions
    #[error("Internal error (0x{code:04X}): {message}")]
    Internal { code: u32, message: String },

    // ===== Transform / Dependency Graph Errors =====
    /// Transform dependency graph contains a cycle
    #[error("Cyclic dependency detected among records: {records:?}")]
    CyclicDependency { records: Vec<String> },

    /// Transform input key references a record that was not registered
    #[error("Transform on '{output_key}' references unregistered input '{input_key}'")]
    TransformInputNotFound {
        output_key: String,
        input_key: String,
    },

    // ===== Standard Library Integrations (std only) =====
    /// I/O operation error
    #[cfg(feature = "std")]
    #[error("I/O error: {source}")]
    Io {
        #[from]
        source: io::Error,
    },

    /// I/O operation error with context
    #[cfg(feature = "std")]
    #[error("I/O error: {context}: {source}")]
    IoWithContext {
        context: String,
        #[source]
        source: io::Error,
    },

    /// JSON serialization error
    #[cfg(feature = "std")]
    #[error("JSON error: {source}")]
    Json {
        #[from]
        source: serde_json::Error,
    },

    /// JSON serialization error with context
    #[cfg(feature = "std")]
    #[error("JSON error: {context}: {source}")]
    JsonWithContext {
        context: String,
        #[source]
        source: serde_json::Error,
    },
}

// ===== DbError Implementation =====
impl DbError {
    /// Builds a [`RuntimeError`](DbError::RuntimeError).
    pub fn runtime_error(message: impl Into<String>) -> Self {
        DbError::RuntimeError {
            message: message.into(),
        }
    }

    /// Builds a [`PermissionDenied`](DbError::PermissionDenied).
    pub fn permission_denied(operation: impl Into<String>) -> Self {
        DbError::PermissionDenied {
            operation: operation.into(),
        }
    }

    /// Builds a [`RecordKeyNotFound`](DbError::RecordKeyNotFound).
    pub fn record_key_not_found(key: impl Into<String>) -> Self {
        DbError::RecordKeyNotFound { key: key.into() }
    }

    /// Builds a [`MissingConfiguration`](DbError::MissingConfiguration).
    pub fn missing_configuration(parameter: impl Into<String>) -> Self {
        DbError::MissingConfiguration {
            parameter: parameter.into(),
        }
    }
}

/// What a caller does about a [`DbError`]: retry, resubscribe, stop, or fix
/// something — and which something.
///
/// Match on this rather than on [`DbError`]'s variants when you only need to
/// know what to do. A new variant is a compile error in [`DbError::kind`]
/// rather than a silent reclassification at every downstream wildcard.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DbErrorKind {
    /// Nothing available, or no room, *right now*. Retry.
    Retry,

    /// Values dropped because this reader fell behind. Note the gap, continue.
    Lagged,

    /// The database or buffer is shutting down. Stop; retrying cannot help.
    Closed,

    /// An I/O or connection failure. Retry, or fix the deployment.
    Transport,

    /// A payload could not be encoded or decoded. Fix the schema or the sender.
    Data,

    /// The record graph is misconfigured. Fix it before starting.
    Configuration,

    /// This call was wrong for this record. Fix the call site.
    Usage,

    /// The database's own machinery or its host. Report a bug.
    Internal,
}

impl DbError {
    /// Classify the failure by what the caller can do about it.
    ///
    /// Exhaustive inside the crate that owns the enum: a variant added later
    /// fails to compile here instead of falling into a downstream wildcard.
    pub fn kind(&self) -> DbErrorKind {
        match self {
            Self::BufferEmpty | Self::BufferFull { .. } => DbErrorKind::Retry,

            Self::BufferLagged { .. } => DbErrorKind::Lagged,

            Self::BufferClosed { .. } => DbErrorKind::Closed,

            Self::ConnectionFailed { .. } => DbErrorKind::Transport,

            Self::MissingConfiguration { .. }
            | Self::InvalidConfiguration { .. }
            | Self::CyclicDependency { .. }
            | Self::TransformInputNotFound { .. } => DbErrorKind::Configuration,

            Self::RecordNotFound { .. }
            | Self::RecordKeyNotFound { .. }
            | Self::InvalidRecordId { .. }
            | Self::TypeMismatch { .. }
            | Self::InvalidOperation { .. }
            | Self::PermissionDenied { .. } => DbErrorKind::Usage,

            Self::RuntimeError { .. } | Self::Internal { .. } => DbErrorKind::Internal,

            #[cfg(feature = "std")]
            Self::Io { .. } | Self::IoWithContext { .. } => DbErrorKind::Transport,

            #[cfg(feature = "std")]
            Self::Json { .. } | Self::JsonWithContext { .. } => DbErrorKind::Data,
        }
    }
}

/// Type alias for Results using DbError
pub type DbResult<T> = Result<T, DbError>;

// ============================================================================
// Error Conversions
// ============================================================================

/// Convert executor errors to database errors
///
/// This allows engine plumbing to return `ExecutorError` while the core
/// database works with `DbError` for consistency across the API.
impl From<crate::executor::ExecutorError> for DbError {
    fn from(err: crate::executor::ExecutorError) -> Self {
        use crate::executor::ExecutorError;

        match err {
            ExecutorError::QueueClosed => DbError::runtime_error("join queue closed"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::ToString;
    use alloc::vec;

    #[test]
    fn test_error_size_constraint() {
        let size = core::mem::size_of::<DbError>();
        assert!(
            size <= 64,
            "DbError size ({} bytes) exceeds 64-byte embedded limit",
            size
        );
    }

    #[test]
    fn test_invalid_configuration_display() {
        let err = DbError::InvalidConfiguration {
            errors: vec![
                ConfigError::new(
                    "rec.a",
                    Some("mqtt://broker/a".to_string()),
                    "missing serializer",
                ),
                ConfigError::new("rec.b", None, "duplicate producer"),
            ],
        };

        let s = err.to_string();
        assert!(s.contains("2 error(s)"), "got: {s}");
        assert!(
            s.contains("record 'rec.a' (mqtt://broker/a): missing serializer"),
            "got: {s}"
        );
        assert!(s.contains("record 'rec.b': duplicate producer"), "got: {s}");
    }

    #[test]
    fn test_helper_constructors() {
        assert!(matches!(
            DbError::runtime_error("boom"),
            DbError::RuntimeError { .. }
        ));
        assert!(matches!(
            DbError::permission_denied("write"),
            DbError::PermissionDenied { .. }
        ));
        assert!(matches!(
            DbError::record_key_not_found("k"),
            DbError::RecordKeyNotFound { .. }
        ));
        assert!(matches!(
            DbError::missing_configuration("p"),
            DbError::MissingConfiguration { .. }
        ));
    }

    #[cfg(feature = "std")]
    #[test]
    fn test_io_json_conversions() {
        let io_error = std::io::Error::other("File not found");
        let db_error: DbError = io_error.into();
        assert!(matches!(db_error, DbError::Io { .. }));

        let json_error = serde_json::from_str::<serde_json::Value>("invalid").unwrap_err();
        let db_error: DbError = json_error.into();
        assert!(matches!(db_error, DbError::Json { .. }));
    }

    #[test]
    fn kind_maps_each_variant_to_its_action() {
        use DbErrorKind::*;

        assert_eq!(DbError::BufferEmpty.kind(), Retry);
        assert_eq!(
            DbError::BufferFull {
                size: 8,
                buffer_name: "b".to_string()
            }
            .kind(),
            Retry
        );

        assert_eq!(
            DbError::BufferLagged {
                lag_count: 3,
                buffer_name: "b".to_string()
            }
            .kind(),
            Lagged
        );

        assert_eq!(
            DbError::BufferClosed {
                buffer_name: "b".to_string()
            }
            .kind(),
            Closed
        );

        assert_eq!(
            DbError::ConnectionFailed {
                endpoint: "e".to_string(),
                reason: "r".to_string()
            }
            .kind(),
            Transport
        );

        assert_eq!(DbError::missing_configuration("p").kind(), Configuration);
        assert_eq!(
            DbError::InvalidConfiguration { errors: vec![] }.kind(),
            Configuration
        );
        assert_eq!(
            DbError::CyclicDependency { records: vec![] }.kind(),
            Configuration
        );
        assert_eq!(
            DbError::TransformInputNotFound {
                output_key: "o".to_string(),
                input_key: "i".to_string()
            }
            .kind(),
            Configuration
        );

        assert_eq!(
            DbError::RecordNotFound {
                record_name: "r".to_string()
            }
            .kind(),
            Usage
        );
        assert_eq!(DbError::record_key_not_found("k").kind(), Usage);
        assert_eq!(DbError::InvalidRecordId { id: 9 }.kind(), Usage);
        assert_eq!(
            DbError::TypeMismatch {
                expected_type: "T".to_string(),
                record_id: 1
            }
            .kind(),
            Usage
        );
        assert_eq!(
            DbError::InvalidOperation {
                operation: "o".to_string(),
                reason: "r".to_string()
            }
            .kind(),
            Usage
        );
        assert_eq!(DbError::permission_denied("op").kind(), Usage);

        assert_eq!(DbError::runtime_error("m").kind(), Internal);
        assert_eq!(
            DbError::Internal {
                code: 1,
                message: "m".to_string()
            }
            .kind(),
            Internal
        );
    }

    #[cfg(feature = "std")]
    #[test]
    fn kind_maps_the_std_only_variants() {
        let io: DbError = std::io::Error::other("x").into();
        assert_eq!(io.kind(), DbErrorKind::Transport);

        let json: DbError = serde_json::from_str::<serde_json::Value>("nope")
            .unwrap_err()
            .into();
        assert_eq!(json.kind(), DbErrorKind::Data);
    }

    /// A caller that cannot tell these apart retries forever on a dead buffer.
    #[test]
    fn retry_and_closed_stay_distinguishable() {
        assert_ne!(
            DbError::BufferEmpty.kind(),
            DbError::BufferClosed {
                buffer_name: "b".to_string()
            }
            .kind()
        );
    }
}