1use alloc::string::String;
31use alloc::vec::Vec;
32use thiserror::Error;
33
34#[cfg(feature = "std")]
35use std::io;
36
37#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct ConfigError {
44 pub record_key: String,
48 pub url: Option<String>,
50 pub message: String,
52}
53
54impl ConfigError {
55 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 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
85fn 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#[derive(Debug, Error)]
106#[non_exhaustive]
107pub enum DbError {
108 #[error("Connection failed to {endpoint}: {reason}")]
111 ConnectionFailed { endpoint: String, reason: String },
112
113 #[error("Buffer full: {buffer_name} ({size} items)")]
116 BufferFull { size: u32, buffer_name: String },
117
118 #[error("Consumer lagged by {lag_count} messages")]
120 BufferLagged { lag_count: u64, buffer_name: String },
121
122 #[error("Buffer channel closed: {buffer_name}")]
124 BufferClosed { buffer_name: String },
125
126 #[error("Buffer empty: no pending values")]
128 BufferEmpty,
129
130 #[error("Record type not found: {record_name}")]
133 RecordNotFound { record_name: String },
134
135 #[error("Record key not found: {key}")]
137 RecordKeyNotFound { key: String },
138
139 #[error("Invalid record ID: {id}")]
141 InvalidRecordId { id: u32 },
142
143 #[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 #[error("Invalid operation '{operation}': {reason}")]
152 InvalidOperation { operation: String, reason: String },
153
154 #[error("Permission denied: {operation}")]
156 PermissionDenied { operation: String },
157
158 #[error("Missing configuration parameter: {parameter}")]
161 MissingConfiguration { parameter: String },
162
163 #[error("invalid configuration ({} error(s)): {}", errors.len(), join_config_errors(errors))]
166 InvalidConfiguration { errors: Vec<ConfigError> },
167
168 #[error("Runtime error: {message}")]
171 RuntimeError { message: String },
172
173 #[error("Internal error (0x{code:04X}): {message}")]
176 Internal { code: u32, message: String },
177
178 #[error("Cyclic dependency detected among records: {records:?}")]
181 CyclicDependency { records: Vec<String> },
182
183 #[error("Transform on '{output_key}' references unregistered input '{input_key}'")]
185 TransformInputNotFound {
186 output_key: String,
187 input_key: String,
188 },
189
190 #[cfg(feature = "std")]
193 #[error("I/O error: {source}")]
194 Io {
195 #[from]
196 source: io::Error,
197 },
198
199 #[cfg(feature = "std")]
201 #[error("I/O error: {context}: {source}")]
202 IoWithContext {
203 context: String,
204 #[source]
205 source: io::Error,
206 },
207
208 #[cfg(feature = "std")]
210 #[error("JSON error: {source}")]
211 Json {
212 #[from]
213 source: serde_json::Error,
214 },
215
216 #[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#[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
236impl DbError {
238 pub fn runtime_error(message: impl Into<String>) -> Self {
240 DbError::RuntimeError {
241 message: message.into(),
242 }
243 }
244
245 pub fn permission_denied(operation: impl Into<String>) -> Self {
247 DbError::PermissionDenied {
248 operation: operation.into(),
249 }
250 }
251
252 pub fn record_key_not_found(key: impl Into<String>) -> Self {
254 DbError::RecordKeyNotFound { key: key.into() }
255 }
256
257 pub fn missing_configuration(parameter: impl Into<String>) -> Self {
259 DbError::MissingConfiguration {
260 parameter: parameter.into(),
261 }
262 }
263}
264
265#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
272#[non_exhaustive]
273pub enum DbErrorKind {
274 Retry,
276
277 Lagged,
279
280 Closed,
282
283 Transport,
285
286 Data,
288
289 Configuration,
291
292 Usage,
294
295 Internal,
297}
298
299impl DbError {
300 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
337pub type DbResult<T> = Result<T, DbError>;
339
340impl 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 #[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}