rs-zero 0.2.21

Rust-first microservice framework inspired by go-zero engineering practices
Documentation
use std::time::Duration;

use rumqttc::{MqttOptions, QoS};

use crate::mqtt::{MqttError, MqttResult};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MqttQoS {
    AtMostOnce,
    AtLeastOnce,
    ExactlyOnce,
}

impl From<MqttQoS> for QoS {
    fn from(value: MqttQoS) -> Self {
        match value {
            MqttQoS::AtMostOnce => QoS::AtMostOnce,
            MqttQoS::AtLeastOnce => QoS::AtLeastOnce,
            MqttQoS::ExactlyOnce => QoS::ExactlyOnce,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MqttSubscription {
    pub topic: String,
    pub qos: MqttQoS,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MqttReconnectConfig {
    pub initial_delay: Duration,
    pub max_delay: Duration,
}

impl Default for MqttReconnectConfig {
    fn default() -> Self {
        Self {
            initial_delay: Duration::from_millis(200),
            max_delay: Duration::from_secs(5),
        }
    }
}

impl MqttReconnectConfig {
    pub fn delay_for_attempt(&self, attempt: u32) -> Duration {
        let multiplier = 1u32.checked_shl(attempt).unwrap_or(u32::MAX);
        let delay = self.initial_delay.saturating_mul(multiplier);
        delay.min(self.max_delay)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct MqttBrokerUrl {
    host: String,
    port: u16,
    tls: bool,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MqttClientAuthConfig {
    pub cert: Vec<u8>,
    pub key: Vec<u8>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MqttTlsConfig {
    pub enabled: bool,
    pub ca: Option<Vec<u8>>,
    pub client_auth: Option<MqttClientAuthConfig>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MqttTopicLabelMode {
    Full,
    Subscription,
    Disabled,
}

impl Default for MqttTopicLabelMode {
    fn default() -> Self {
        Self::Subscription
    }
}

#[derive(Debug, Clone)]
pub struct MqttConfig {
    pub client_id: String,
    pub host: String,
    pub port: u16,
    pub username: Option<String>,
    pub password: Option<String>,
    pub keep_alive: Duration,
    pub clean_session: bool,
    pub inflight: usize,
    pub subscriptions: Vec<MqttSubscription>,
    pub reconnect: MqttReconnectConfig,
    pub handler_timeout: Option<Duration>,
    pub tls: MqttTlsConfig,
    pub topic_label_mode: MqttTopicLabelMode,
    #[cfg(feature = "observability")]
    pub metrics_registry: Option<crate::observability::MetricsRegistry>,
}

impl Default for MqttConfig {
    fn default() -> Self {
        Self {
            client_id: "rs-zero-mqtt".to_string(),
            host: "127.0.0.1".to_string(),
            port: 1883,
            username: None,
            password: None,
            keep_alive: Duration::from_secs(30),
            clean_session: true,
            inflight: 10,
            subscriptions: Vec::new(),
            reconnect: MqttReconnectConfig::default(),
            handler_timeout: Some(Duration::from_secs(5)),
            tls: MqttTlsConfig::default(),
            topic_label_mode: MqttTopicLabelMode::default(),
            #[cfg(feature = "observability")]
            metrics_registry: None,
        }
    }
}

fn parse_broker_url(value: &str) -> MqttResult<MqttBrokerUrl> {
    let url = url::Url::parse(value).map_err(|error| {
        MqttError::InvalidConfig(format!("mqtt broker url parse failed: {error}"))
    })?;
    if !url.username().is_empty() || url.password().is_some() {
        return Err(MqttError::InvalidConfig(
            "mqtt broker url credentials are not supported; use username/password fields"
                .to_string(),
        ));
    }
    if !(url.path().is_empty() || url.path() == "/")
        || url.query().is_some()
        || url.fragment().is_some()
    {
        return Err(MqttError::InvalidConfig(
            "mqtt broker url must not include path, query or fragment".to_string(),
        ));
    }

    let (tls, default_port) = match url.scheme() {
        "mqtt" | "tcp" => (false, 1883),
        "mqtts" | "ssl" => (true, 8883),
        other => {
            return Err(MqttError::InvalidConfig(format!(
                "unsupported mqtt broker scheme: {other}"
            )));
        }
    };
    let host = url.host_str().ok_or_else(|| {
        MqttError::InvalidConfig("mqtt broker url host cannot be empty".to_string())
    })?;

    Ok(MqttBrokerUrl {
        host: host.to_string(),
        port: url.port().unwrap_or(default_port),
        tls,
    })
}

impl MqttConfig {
    pub fn from_url(client_id: impl Into<String>, url: &str) -> MqttResult<Self> {
        let broker = parse_broker_url(url)?;
        Ok(Self {
            client_id: client_id.into(),
            host: broker.host,
            port: broker.port,
            tls: MqttTlsConfig {
                enabled: broker.tls,
                ..MqttTlsConfig::default()
            },
            ..MqttConfig::default()
        })
    }

    pub fn validate(&self) -> MqttResult<()> {
        if self.client_id.trim().is_empty() {
            return Err(MqttError::InvalidConfig(
                "client_id cannot be empty".to_string(),
            ));
        }
        if self.host.trim().is_empty() {
            return Err(MqttError::InvalidConfig("host cannot be empty".to_string()));
        }
        if self.inflight == 0 {
            return Err(MqttError::InvalidConfig(
                "inflight must be greater than zero".to_string(),
            ));
        }
        if self.inflight > u16::MAX as usize {
            return Err(MqttError::InvalidConfig(
                "inflight cannot exceed u16::MAX".to_string(),
            ));
        }
        if self.reconnect.initial_delay > self.reconnect.max_delay {
            return Err(MqttError::InvalidConfig(
                "reconnect initial_delay cannot exceed max_delay".to_string(),
            ));
        }
        for subscription in &self.subscriptions {
            if subscription.topic.trim().is_empty() {
                return Err(MqttError::InvalidConfig(
                    "subscription topic cannot be empty".to_string(),
                ));
            }
        }
        if let Some(client_auth) = &self.tls.client_auth {
            if !self.tls.enabled {
                return Err(MqttError::InvalidConfig(
                    "mqtt mTLS client auth requires TLS transport via mqtts://, ssl:// or explicit tls.enabled=true"
                        .to_string(),
                ));
            }
            if self.tls.ca.is_none() {
                return Err(MqttError::InvalidConfig(
                    "mqtt mTLS requires ca certificate file with current rumqttc simple TLS config"
                        .to_string(),
                ));
            }
            if client_auth.cert.is_empty() || client_auth.key.is_empty() {
                return Err(MqttError::InvalidConfig(
                    "mqtt tls client auth cert and key cannot be empty".to_string(),
                ));
            }
        }
        Ok(())
    }

    pub fn to_mqtt_options(&self) -> MqttResult<MqttOptions> {
        self.validate()?;

        let mut options = MqttOptions::new(&self.client_id, &self.host, self.port);
        options.set_keep_alive(self.keep_alive);
        options.set_clean_session(self.clean_session);
        options.set_inflight(self.inflight as u16);
        if let (Some(username), Some(password)) = (&self.username, &self.password) {
            options.set_credentials(username, password);
        }
        if self.tls.enabled {
            let transport = match (&self.tls.ca, &self.tls.client_auth) {
                (Some(ca), client_auth) => rumqttc::Transport::tls(
                    ca.clone(),
                    client_auth
                        .as_ref()
                        .map(|auth| (auth.cert.clone(), auth.key.clone())),
                    None,
                ),
                (None, None) => rumqttc::Transport::tls_with_default_config(),
                (None, Some(_)) => unreachable!("mTLS without CA is rejected by validate"),
            };
            options.set_transport(transport);
        }
        Ok(options)
    }

    pub fn topic_label(&self, topic: &str) -> String {
        self.topic_label_mode.label_for(topic, &self.subscriptions)
    }
}

impl MqttTopicLabelMode {
    pub fn label_for(&self, topic: &str, subscriptions: &[MqttSubscription]) -> String {
        match self {
            Self::Full => topic.to_string(),
            Self::Disabled => "disabled".to_string(),
            Self::Subscription => subscriptions
                .iter()
                .find(|subscription| topic_matches_filter(&subscription.topic, topic))
                .map(|subscription| subscription.topic.clone())
                .unwrap_or_else(|| "unmatched".to_string()),
        }
    }
}

fn topic_matches_filter(filter: &str, topic: &str) -> bool {
    let mut filter_segments = filter.split('/').peekable();
    let mut topic_segments = topic.split('/').peekable();

    while let Some(filter_segment) = filter_segments.next() {
        match filter_segment {
            "#" => return filter_segments.peek().is_none(),
            "+" => {
                if topic_segments.next().is_none() {
                    return false;
                }
            }
            literal => {
                if topic_segments.next() != Some(literal) {
                    return false;
                }
            }
        }
    }

    topic_segments.next().is_none()
}