use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU16, Ordering};
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::{Mutex, mpsc, oneshot};
use super::codec::{self, ConnAck, Connect, Packet, Publish, QoS};
use super::{BrokerAddress, MqttError};
#[derive(Debug, Clone)]
pub enum Incoming {
Message {
topic: String,
payload: Vec<u8>,
},
Connected(ConnAck),
Disconnected(String),
}
#[derive(Debug, Clone)]
pub struct ConnectionConfig {
pub client_id: String,
pub username: Option<String>,
pub password: Option<String>,
pub keep_alive: Duration,
pub max_backoff: Duration,
pub ack_timeout: Duration,
}
impl Default for ConnectionConfig {
fn default() -> Self {
Self {
client_id: String::new(),
username: None,
password: None,
keep_alive: Duration::from_secs(30),
max_backoff: Duration::from_secs(30),
ack_timeout: Duration::from_secs(15),
}
}
}
enum Command {
Publish {
publish: Publish,
done: oneshot::Sender<Result<(), MqttError>>,
},
Subscribe {
packet_id: u16,
filters: Vec<(String, QoS)>,
done: oneshot::Sender<Result<Vec<u8>, MqttError>>,
},
}
#[derive(Debug)]
pub struct Connection {
commands: mpsc::Sender<Command>,
next_id: AtomicU16,
connected: Arc<AtomicBool>,
task: tokio::task::JoinHandle<()>,
address: BrokerAddress,
}
impl Drop for Connection {
fn drop(&mut self) {
self.task.abort();
}
}
impl Connection {
pub fn open(
address: BrokerAddress,
config: ConnectionConfig,
subscriptions: Vec<(String, QoS)>,
events: mpsc::Sender<Incoming>,
) -> Arc<Self> {
let (commands, rx) = mpsc::channel(256);
let connected = Arc::new(AtomicBool::new(false));
let task = tokio::spawn(run(
address.clone(),
config,
subscriptions,
rx,
events,
connected.clone(),
));
Arc::new(Self {
commands,
next_id: AtomicU16::new(1),
connected,
task,
address,
})
}
pub fn is_connected(&self) -> bool {
self.connected.load(Ordering::Relaxed)
}
pub fn address(&self) -> &BrokerAddress {
&self.address
}
fn allocate_id(&self) -> u16 {
loop {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
if id != 0 {
return id;
}
}
}
pub async fn publish(
&self,
topic: &str,
payload: Vec<u8>,
qos: QoS,
retain: bool,
) -> Result<(), MqttError> {
let packet_id = match qos {
QoS::AtMostOnce => None,
QoS::AtLeastOnce => Some(self.allocate_id()),
};
let publish = Publish {
topic: topic.to_string(),
qos,
retain,
dup: false,
packet_id,
payload,
};
let (done, wait) = oneshot::channel();
self.commands
.send(Command::Publish { publish, done })
.await
.map_err(|_| MqttError::Disconnected("the connection task has stopped".into()))?;
wait.await.map_err(|_| {
MqttError::Disconnected("the connection task dropped the publish".into())
})?
}
pub async fn subscribe(&self, filters: Vec<(String, QoS)>) -> Result<Vec<u8>, MqttError> {
let (done, wait) = oneshot::channel();
self.commands
.send(Command::Subscribe {
packet_id: self.allocate_id(),
filters,
done,
})
.await
.map_err(|_| MqttError::Disconnected("the connection task has stopped".into()))?;
wait.await.map_err(|_| {
MqttError::Disconnected("the connection task dropped the subscribe".into())
})?
}
}
pub(crate) type Stream = Box<dyn Duplex>;
pub trait Duplex: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send {}
impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send> Duplex for T {}
#[derive(Default)]
struct Pending {
publishes: BTreeMap<u16, oneshot::Sender<Result<(), MqttError>>>,
subscribes: BTreeMap<u16, oneshot::Sender<Result<Vec<u8>, MqttError>>>,
}
impl Pending {
fn fail_all(&mut self, why: &str) {
for (_, tx) in core::mem::take(&mut self.publishes) {
let _ = tx.send(Err(MqttError::Disconnected(why.to_string())));
}
for (_, tx) in core::mem::take(&mut self.subscribes) {
let _ = tx.send(Err(MqttError::Disconnected(why.to_string())));
}
}
}
async fn run(
address: BrokerAddress,
config: ConnectionConfig,
subscriptions: Vec<(String, QoS)>,
mut commands: mpsc::Receiver<Command>,
events: mpsc::Sender<Incoming>,
connected: Arc<AtomicBool>,
) {
let mut backoff = Duration::from_millis(250);
let pending: Arc<Mutex<Pending>> = Arc::default();
loop {
match session(
&address,
&config,
&subscriptions,
&mut commands,
&events,
&pending,
&connected,
)
.await
{
Ok(()) => {
return;
}
Err(e) => {
connected.store(false, Ordering::Relaxed);
pending.lock().await.fail_all(&e.to_string());
let _ = events.send(Incoming::Disconnected(e.to_string())).await;
tracing::warn!(error = %e, broker = %address, "MQTT connection lost; reconnecting");
tokio::time::sleep(backoff).await;
backoff = (backoff * 2).min(config.max_backoff);
}
}
}
}
async fn session(
address: &BrokerAddress,
config: &ConnectionConfig,
subscriptions: &[(String, QoS)],
commands: &mut mpsc::Receiver<Command>,
events: &mpsc::Sender<Incoming>,
pending: &Arc<Mutex<Pending>>,
connected: &Arc<AtomicBool>,
) -> Result<(), MqttError> {
let mut stream = address.connect().await?;
stream
.write_all(&codec::encode_connect(&Connect {
client_id: config.client_id.clone(),
keep_alive_secs: config.keep_alive.as_secs().clamp(1, u64::from(u16::MAX)) as u16,
clean_session: false,
username: config.username.clone(),
password: config.password.clone(),
}))
.await
.map_err(|e| MqttError::Disconnected(e.to_string()))?;
let mut buf = Vec::with_capacity(4096);
let ack = match read_packet(&mut stream, &mut buf, config.ack_timeout).await? {
Some(Packet::ConnAck(ack)) => ack,
_ => {
return Err(MqttError::Disconnected(
"the broker did not answer CONNECT with a CONNACK".into(),
));
}
};
if !ack.is_accepted() {
return Err(MqttError::Refused(ack.code, ack.reason()));
}
connected.store(true, Ordering::Relaxed);
let _ = events.send(Incoming::Connected(ack)).await;
if !subscriptions.is_empty() && !ack.session_present {
let packet = codec::encode_subscribe(u16::MAX, subscriptions);
stream
.write_all(&packet)
.await
.map_err(|e| MqttError::Disconnected(e.to_string()))?;
tracing::info!(
filters = subscriptions.len(),
"the broker restored no session; re-subscribing"
);
}
let mut ping = tokio::time::interval(config.keep_alive);
ping.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
ping.tick().await;
loop {
tokio::select! {
command = commands.recv() => {
let Some(command) = command else {
let _ = write(&mut stream, &codec::encode_disconnect()).await;
let _ = stream.shutdown().await;
return Ok(());
};
dispatch(command, &mut stream, pending).await?;
}
packet = read_packet(&mut stream, &mut buf, config.ack_timeout * 100) => {
match packet? {
Some(Packet::PubAck(id)) => {
if let Some(tx) = pending.lock().await.publishes.remove(&id) {
let _ = tx.send(Ok(()));
}
}
Some(Packet::SubAck { packet_id, codes }) => {
if let Some(tx) = pending.lock().await.subscribes.remove(&packet_id) {
let _ = tx.send(Ok(codes));
}
}
Some(Packet::Publish(publish)) => {
if let Some(id) = publish.packet_id {
stream.write_all(&codec::encode_puback(id)).await
.map_err(|e| MqttError::Disconnected(e.to_string()))?;
}
let _ = events
.send(Incoming::Message {
topic: publish.topic,
payload: publish.payload,
})
.await;
}
Some(Packet::ConnAck(_)) => {
return Err(MqttError::Disconnected(
"the broker sent a second CONNACK".into(),
));
}
Some(Packet::PingResp) | None => {}
}
}
_ = ping.tick() => {
stream.write_all(&codec::encode_pingreq()).await
.map_err(|e| MqttError::Disconnected(e.to_string()))?;
}
}
}
}
async fn dispatch(
command: Command,
stream: &mut Stream,
pending: &Arc<Mutex<Pending>>,
) -> Result<(), MqttError> {
match command {
Command::Publish { publish, done } if publish.qos == QoS::AtMostOnce => {
let result = write(stream, &codec::encode_publish(&publish)).await;
let _ = done.send(result.clone());
result
}
Command::Publish { publish, done } => {
let id = publish
.packet_id
.expect("a QoS 1 publish carries an identifier");
let bytes = codec::encode_publish(&publish);
pending.lock().await.publishes.insert(id, done);
if let Err(e) = write(stream, &bytes).await {
if let Some(tx) = pending.lock().await.publishes.remove(&id) {
let _ = tx.send(Err(e.clone()));
}
return Err(e);
}
Ok(())
}
Command::Subscribe {
packet_id,
filters,
done,
} => {
let bytes = codec::encode_subscribe(packet_id, &filters);
pending.lock().await.subscribes.insert(packet_id, done);
if let Err(e) = write(stream, &bytes).await {
if let Some(tx) = pending.lock().await.subscribes.remove(&packet_id) {
let _ = tx.send(Err(e.clone()));
}
return Err(e);
}
Ok(())
}
}
}
async fn write(stream: &mut Stream, bytes: &[u8]) -> Result<(), MqttError> {
stream
.write_all(bytes)
.await
.map_err(|e| MqttError::Disconnected(e.to_string()))
}
async fn read_packet(
stream: &mut Stream,
buf: &mut Vec<u8>,
timeout: Duration,
) -> Result<Option<Packet>, MqttError> {
loop {
match codec::decode(buf) {
Ok(Some((packet, used))) => {
buf.drain(..used);
return Ok(packet);
}
Ok(None) => {}
Err(e) => return Err(MqttError::Protocol(e)),
}
let mut chunk = [0u8; 4096];
let n = tokio::time::timeout(timeout, stream.read(&mut chunk))
.await
.map_err(|_| MqttError::Disconnected("the broker went quiet".into()))?
.map_err(|e| MqttError::Disconnected(e.to_string()))?;
if n == 0 {
return Err(MqttError::Disconnected(
"the broker closed the connection".into(),
));
}
buf.extend_from_slice(&chunk[..n]);
}
}