loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
use std::{
    fmt,
    ops::Deref,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::Duration,
};

use rumqttc::{Event, Incoming, Outgoing};

use super::{BoxConnectionFuture, Close, Connect, ConnectionError, ConnectionSpec, Verify};

pub use rumqttc::{AsyncClient as MqttClient, MqttOptions};

/// 同时持有 MQTT 客户端和后台事件循环的连接。
pub struct MqttConnection {
    client: MqttClient,
    connected: Arc<AtomicBool>,
    event_task: Option<tokio::task::JoinHandle<()>>,
}

impl MqttConnection {
    #[must_use]
    pub const fn client(&self) -> &MqttClient {
        &self.client
    }

    #[must_use]
    pub fn is_connected(&self) -> bool {
        self.connected.load(Ordering::Acquire)
            && self
                .event_task
                .as_ref()
                .is_some_and(|task| !task.is_finished())
    }
}

impl fmt::Debug for MqttConnection {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("MqttConnection")
            .field("connected", &self.is_connected())
            .finish_non_exhaustive()
    }
}

impl Deref for MqttConnection {
    type Target = MqttClient;

    fn deref(&self) -> &Self::Target {
        &self.client
    }
}

impl Drop for MqttConnection {
    fn drop(&mut self) {
        // 调用方忘记显式 close 时也必须终止事件循环,避免后台任务永久脱离运行。
        if let Some(event_task) = self.event_task.take() {
            event_task.abort();
        }
        self.connected.store(false, Ordering::Release);
    }
}

/// MQTT 3.1.1 异步客户端连接器。
#[derive(Clone)]
#[must_use = "连接器配置需要传给 connect 才会生效"]
pub struct MqttConnector {
    name: String,
    enabled: bool,
    options: MqttOptions,
    channel_capacity: usize,
    connect_timeout: Duration,
    shutdown_timeout: Duration,
}

impl MqttConnector {
    pub fn new(options: MqttOptions) -> Self {
        Self {
            name: "mqtt".to_owned(),
            enabled: true,
            options,
            channel_capacity: 10,
            connect_timeout: Duration::from_secs(10),
            shutdown_timeout: Duration::from_secs(5),
        }
    }

    /// 从 MQTT URL 创建连接器。
    ///
    /// # Errors
    ///
    /// URL 无法按 MQTT 连接参数解析时返回错误。
    pub fn from_url(url: impl Into<String>) -> Result<Self, ConnectionError> {
        Ok(Self::new(MqttOptions::parse_url(url.into())?))
    }

    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    pub const fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    pub const fn with_channel_capacity(mut self, capacity: usize) -> Self {
        self.channel_capacity = capacity;
        self
    }

    /// 设置等待代理服务器首次返回 CONNACK 的最长时间。
    pub const fn with_connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    pub const fn with_shutdown_timeout(mut self, timeout: Duration) -> Self {
        self.shutdown_timeout = timeout;
        self
    }
}

impl fmt::Debug for MqttConnector {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("MqttConnector")
            .field("name", &self.name)
            .field("enabled", &self.enabled)
            // MqttOptions 可能包含用户名和密码,不能直接输出。
            .field("options", &"[已隐藏]")
            .field("channel_capacity", &self.channel_capacity)
            .field("connect_timeout", &self.connect_timeout)
            .field("shutdown_timeout", &self.shutdown_timeout)
            .finish()
    }
}

impl ConnectionSpec for MqttConnector {
    type Connection = MqttConnection;
    type Error = ConnectionError;

    fn name(&self) -> &str {
        &self.name
    }

    fn enabled(&self) -> bool {
        self.enabled
    }
}

impl Connect for MqttConnector {
    fn connect(&self) -> BoxConnectionFuture<'_, Self::Connection, Self::Error> {
        Box::pin(async move {
            if self.channel_capacity == 0 {
                return Err(ConnectionError::InvalidConfig {
                    connector: "MQTT",
                    message: "事件通道容量必须大于 0",
                });
            }
            if self.connect_timeout.is_zero() {
                return Err(ConnectionError::InvalidConfig {
                    connector: "MQTT",
                    message: "首次连接超时必须大于 0",
                });
            }
            if self.shutdown_timeout.is_zero() {
                return Err(ConnectionError::InvalidConfig {
                    connector: "MQTT",
                    message: "关闭超时必须大于 0",
                });
            }

            let (client, mut event_loop) =
                MqttClient::new(self.options.clone(), self.channel_capacity);

            // 只有收到 CONNACK 才算连接完成,避免把尚未连接的通道句柄交给业务层。
            let wait_for_connection = async {
                loop {
                    if matches!(
                        event_loop.poll().await?,
                        Event::Incoming(Incoming::ConnAck(_))
                    ) {
                        return Ok::<(), ConnectionError>(());
                    }
                }
            };
            tokio::time::timeout(self.connect_timeout, wait_for_connection)
                .await
                .map_err(|_| ConnectionError::MqttConnectTimeout(self.connect_timeout))??;

            let connected = Arc::new(AtomicBool::new(true));
            let task_connected = connected.clone();
            let connector_name = self.name.clone();
            let event_task = tokio::spawn(async move {
                loop {
                    match event_loop.poll().await {
                        Ok(Event::Incoming(Incoming::ConnAck(_))) => {
                            task_connected.store(true, Ordering::Release);
                        }
                        Ok(Event::Outgoing(Outgoing::Disconnect)) => {
                            task_connected.store(false, Ordering::Release);
                            break;
                        }
                        Ok(_) => {}
                        Err(error) => {
                            task_connected.store(false, Ordering::Release);
                            // EventLoop 会在下一次 poll 时自动尝试重连,因此这里只记录状态。
                            tracing::warn!(
                                connector = connector_name,
                                error = %error,
                                "MQTT 连接中断,等待事件循环自动重连"
                            );
                        }
                    }
                }
            });

            Ok(MqttConnection {
                client,
                connected,
                event_task: Some(event_task),
            })
        })
    }
}

impl Verify for MqttConnector {
    fn verify<'a>(
        &'a self,
        connection: &'a Self::Connection,
    ) -> BoxConnectionFuture<'a, (), Self::Error> {
        Box::pin(async move {
            if connection.is_connected() {
                Ok(())
            } else {
                Err(ConnectionError::MqttDisconnected)
            }
        })
    }
}

impl Close for MqttConnector {
    fn close(&self, connection: Self::Connection) -> BoxConnectionFuture<'_, (), Self::Error> {
        Box::pin(async move {
            let mut connection = connection;

            connection.client.disconnect().await?;
            let Some(mut event_task) = connection.event_task.take() else {
                connection.connected.store(false, Ordering::Release);
                return Ok(());
            };
            if let Ok(task_result) =
                tokio::time::timeout(self.shutdown_timeout, &mut event_task).await
            {
                task_result?;
            } else {
                // 代理不可达时 DISCONNECT 可能无法消费,超时后终止后台任务避免停机卡死。
                event_task.abort();
                let _ = event_task.await;
                return Err(ConnectionError::MqttShutdownTimeout(self.shutdown_timeout));
            }
            connection.connected.store(false, Ordering::Release);
            Ok(())
        })
    }
}