Skip to main content

aimdb_core/
transport.rs

1//! Protocol-agnostic per-route configuration and publish errors.
2//!
3//! Core knows schemes and key/value options, never protocol semantics.
4
5use alloc::{string::String, vec::Vec};
6
7/// Protocol-agnostic connector configuration
8///
9/// Carries the route's key/value options to the connector
10/// ([`RouteInfo::config`](crate::RouteInfo::config)). Only the
11/// genuinely protocol-agnostic `timeout_ms` is a typed field; every
12/// protocol-specific knob (e.g. MQTT's `qos`/`retain`) travels in
13/// [`protocol_options`](ConnectorConfig::protocol_options) and is interpreted
14/// by the connector with its own defaults. Connector crates expose typed
15/// setters as extension traits over the link builders (e.g. the MQTT
16/// connector's `MqttLinkExt`).
17///
18/// The record a route belongs to is not part of it: core sets that on the
19/// route ([`RouteInfo::record_index`](crate::RouteInfo::record_index)), out of
20/// reach of a link's query.
21#[derive(Debug, Clone)]
22#[non_exhaustive]
23pub struct ConnectorConfig {
24    /// Optional timeout in milliseconds for the publish/operation, as
25    /// interpreted by the connector
26    pub timeout_ms: Option<u32>,
27
28    /// Protocol-specific options as key-value pairs
29    /// Allows custom configuration without polluting the base struct
30    pub protocol_options: Vec<(String, String)>,
31}
32
33impl Default for ConnectorConfig {
34    fn default() -> Self {
35        Self {
36            timeout_ms: Some(5000),
37            protocol_options: Vec::new(),
38        }
39    }
40}
41
42impl ConnectorConfig {
43    /// Build a config from a route's URL-query key/value pairs.
44    ///
45    /// Only the protocol-agnostic `timeout_ms` (the last occurrence wins) is
46    /// lifted into a typed field; every other key is passed through verbatim in
47    /// [`protocol_options`](ConnectorConfig::protocol_options) for the
48    /// connector to interpret with its own defaults.
49    pub fn from_query(query: &[(String, String)]) -> ConnectorConfig {
50        let mut cfg = ConnectorConfig::default();
51        for (k, v) in query {
52            match k.as_str() {
53                "timeout_ms" => {
54                    if let Ok(n) = v.parse::<u32>() {
55                        cfg.timeout_ms = Some(n);
56                    }
57                }
58                _ => cfg.protocol_options.push((k.clone(), v.clone())),
59            }
60        }
61        cfg
62    }
63}
64
65/// Error that can occur during connector publishing
66///
67/// Uses an enum instead of String for better performance in `no_std` environments
68/// and to enable defmt logging support in Embassy.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum PublishError {
71    /// Failed to connect to endpoint
72    ConnectionFailed,
73    /// Message payload too large for buffer
74    MessageTooLarge,
75    /// Quality of Service level not supported
76    UnsupportedQoS,
77    /// Network or operation timeout occurred
78    Timeout,
79    /// Buffer full, cannot queue message
80    BufferFull,
81    /// Invalid destination (topic, segment, endpoint)
82    InvalidDestination,
83}
84
85#[cfg(feature = "defmt")]
86impl defmt::Format for PublishError {
87    fn format(&self, f: defmt::Formatter) {
88        match self {
89            Self::ConnectionFailed => defmt::write!(f, "ConnectionFailed"),
90            Self::MessageTooLarge => defmt::write!(f, "MessageTooLarge"),
91            Self::UnsupportedQoS => defmt::write!(f, "UnsupportedQoS"),
92            Self::Timeout => defmt::write!(f, "Timeout"),
93            Self::BufferFull => defmt::write!(f, "BufferFull"),
94            Self::InvalidDestination => defmt::write!(f, "InvalidDestination"),
95        }
96    }
97}
98
99#[cfg(feature = "std")]
100impl std::fmt::Display for PublishError {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        match self {
103            Self::ConnectionFailed => write!(f, "Failed to connect to endpoint"),
104            Self::MessageTooLarge => write!(f, "Message payload too large"),
105            Self::UnsupportedQoS => write!(f, "QoS level not supported"),
106            Self::Timeout => write!(f, "Operation timeout"),
107            Self::BufferFull => write!(f, "Buffer full, cannot queue message"),
108            Self::InvalidDestination => write!(f, "Invalid destination"),
109        }
110    }
111}
112
113#[cfg(feature = "std")]
114impl std::error::Error for PublishError {}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    #[test]
121    fn test_connector_config_default() {
122        let config = ConnectorConfig::default();
123        assert_eq!(config.timeout_ms, Some(5000));
124        assert_eq!(config.protocol_options.len(), 0);
125    }
126
127    #[test]
128    fn test_publish_error_copy() {
129        let err = PublishError::ConnectionFailed;
130        let err2 = err; // Should be Copy
131        assert_eq!(err, err2);
132    }
133}