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};
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) {
if let Some(event_task) = self.event_task.take() {
event_task.abort();
}
self.connected.store(false, Ordering::Release);
}
}
#[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),
}
}
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
}
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)
.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);
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);
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 {
event_task.abort();
let _ = event_task.await;
return Err(ConnectionError::MqttShutdownTimeout(self.shutdown_timeout));
}
connection.connected.store(false, Ordering::Release);
Ok(())
})
}
}