use std::sync::Arc;
use std::time::Duration as StdDuration;
use async_trait::async_trait;
use rumqttc::{AsyncClient, Event, EventLoop, Incoming, MqttOptions, Outgoing, QoS};
use tokio::sync::{Mutex, broadcast};
use super::{Channel, Delivery, DeliveryFailure, Notifier};
#[derive(Debug, Clone)]
pub struct MqttConfig {
pub url: String,
pub client_id: String,
pub username: Option<String>,
pub password: Option<String>,
pub keep_alive: StdDuration,
pub retain: bool,
pub qos: QoS,
pub publish_timeout: StdDuration,
pub queue_capacity: usize,
}
impl Default for MqttConfig {
fn default() -> Self {
Self {
url: "mqtt://localhost:1883".into(),
client_id: format!("openadr-vtn-{}", std::process::id()),
username: None,
password: None,
keep_alive: StdDuration::from_secs(30),
retain: false,
qos: QoS::AtLeastOnce,
publish_timeout: StdDuration::from_secs(15),
queue_capacity: 128,
}
}
}
impl MqttConfig {
pub fn new(url: impl Into<String>) -> Self {
Self {
url: url.into(),
..Default::default()
}
}
pub fn with_credentials(
mut self,
username: impl Into<String>,
password: impl Into<String>,
) -> Self {
self.username = Some(username.into());
self.password = Some(password.into());
self
}
pub fn retained(mut self) -> Self {
self.retain = true;
self
}
pub fn with_client_id(mut self, id: impl Into<String>) -> Self {
self.client_id = id.into();
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum MqttError {
#[error("invalid broker URL: {0}")]
Url(String),
#[error("could not queue the publish: {0}")]
Queue(String),
#[error("the broker did not acknowledge the publish within {0:?}")]
Unacknowledged(StdDuration),
#[error("the broker connection dropped: {0}")]
Disconnected(String),
}
impl MqttError {
pub fn is_retriable(&self) -> bool {
!matches!(self, MqttError::Url(_))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Wire {
Sent(u16),
Acked(u16),
Dropped,
}
#[derive(Debug)]
pub struct MqttNotifier {
client: AsyncClient,
config: MqttConfig,
wire: broadcast::Sender<Wire>,
writing: Mutex<()>,
loop_task: tokio::task::JoinHandle<()>,
}
impl Drop for MqttNotifier {
fn drop(&mut self) {
self.loop_task.abort();
}
}
impl MqttNotifier {
pub fn connect(config: MqttConfig) -> Result<Arc<Self>, MqttError> {
let options = build_options(&config)?;
let (client, event_loop) = AsyncClient::new(options, config.queue_capacity);
let (wire, _) = broadcast::channel(config.queue_capacity.max(16) * 4);
let loop_task = tokio::spawn(run_event_loop(event_loop, wire.clone()));
Ok(Arc::new(Self {
client,
config,
wire,
writing: Mutex::new(()),
loop_task,
}))
}
pub fn url(&self) -> &str {
&self.config.url
}
async fn publish(&self, topic: &str, payload: Vec<u8>) -> Result<(), MqttError> {
let deadline = tokio::time::Instant::now() + self.config.publish_timeout;
if self.config.qos == QoS::AtMostOnce {
return self
.client
.try_publish(topic, self.config.qos, self.config.retain, payload)
.map_err(|e| MqttError::Queue(e.to_string()));
}
let (pkid, mut events) = {
let _writing = self.writing.lock().await;
let mut events = self.wire.subscribe();
self.client
.try_publish(topic, self.config.qos, self.config.retain, payload)
.map_err(|e| MqttError::Queue(e.to_string()))?;
let pkid = wait_for(&mut events, deadline, |wire| match wire {
Wire::Sent(pkid) => Some(pkid),
_ => None,
})
.await?;
(pkid, events)
};
wait_for(&mut events, deadline, |wire| match wire {
Wire::Acked(acked) if acked == pkid => Some(()),
_ => None,
})
.await
}
}
async fn wait_for<T>(
events: &mut broadcast::Receiver<Wire>,
deadline: tokio::time::Instant,
want: impl Fn(Wire) -> Option<T>,
) -> Result<T, MqttError> {
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
tokio::time::timeout(remaining, async {
loop {
match events.recv().await {
Ok(wire) => {
if let Wire::Dropped = wire {
return Err(MqttError::Disconnected(
"connection lost mid-publish".into(),
));
}
if let Some(found) = want(wire) {
return Ok(found);
}
}
Err(broadcast::error::RecvError::Lagged(n)) => {
return Err(MqttError::Disconnected(format!(
"publisher fell {n} events behind its own event loop"
)));
}
Err(broadcast::error::RecvError::Closed) => {
return Err(MqttError::Disconnected("event loop stopped".into()));
}
}
}
})
.await
.map_err(|_| MqttError::Unacknowledged(remaining))?
}
#[async_trait]
impl Notifier for MqttNotifier {
fn handles(&self, channel: Channel) -> bool {
channel == Channel::Mqtt
}
async fn deliver(&self, delivery: &Delivery, _attempt: u32) -> Result<(), DeliveryFailure> {
let Some(topic) = delivery.route.topic() else {
return Err(DeliveryFailure::permanent(
"the MQTT transport was handed a delivery with no topic",
));
};
let payload = serde_json::to_vec(&delivery.notification).map_err(|e| {
DeliveryFailure::permanent(format!("notification is not encodable: {e}"))
})?;
match self.publish(topic, payload).await {
Ok(()) => {
tracing::debug!(
topic,
object = %delivery.notification.object.object_type(),
operation = %delivery.notification.operation,
"notification published"
);
Ok(())
}
Err(e) => {
tracing::debug!(topic, error = %e, retriable = e.is_retriable(), "publish failed");
Err(if e.is_retriable() {
DeliveryFailure::retriable(e.to_string())
} else {
DeliveryFailure::permanent(e.to_string())
})
}
}
}
fn name(&self) -> &'static str {
"mqtt"
}
}
fn build_options(config: &MqttConfig) -> Result<MqttOptions, MqttError> {
let mut options =
crate::mqtt::broker_options(&config.url, &config.client_id, config.keep_alive)
.map_err(MqttError::Url)?;
if let Some(username) = &config.username {
options.set_credentials(
username.clone(),
config.password.clone().unwrap_or_default(),
);
}
Ok(options)
}
async fn run_event_loop(mut event_loop: EventLoop, wire: broadcast::Sender<Wire>) {
loop {
match event_loop.poll().await {
Ok(Event::Outgoing(Outgoing::Publish(pkid))) => {
let _ = wire.send(Wire::Sent(pkid));
}
Ok(Event::Incoming(Incoming::PubAck(ack))) => {
let _ = wire.send(Wire::Acked(ack.pkid));
}
Ok(Event::Incoming(Incoming::ConnAck(_))) => {
tracing::info!("connected to the MQTT broker");
}
Ok(_) => {}
Err(e) => {
tracing::warn!(error = %e, "MQTT connection error; reconnecting");
let _ = wire.send(Wire::Dropped);
tokio::time::sleep(StdDuration::from_secs(1)).await;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn broker_urls_pick_the_right_port_and_transport() {
let plain = build_options(&MqttConfig::new("mqtt://broker.example.com")).unwrap();
assert_eq!(plain.broker_address(), ("broker.example.com".into(), 1883));
let tls = build_options(&MqttConfig::new("mqtts://broker.example.com")).unwrap();
assert_eq!(tls.broker_address(), ("broker.example.com".into(), 8883));
let explicit = build_options(&MqttConfig::new("mqtt://broker.example.com:2883")).unwrap();
assert_eq!(
explicit.broker_address(),
("broker.example.com".into(), 2883)
);
}
#[test]
fn an_unusable_broker_url_is_refused_rather_than_retried() {
let err = build_options(&MqttConfig::new("https://broker.example.com")).unwrap_err();
assert!(matches!(err, MqttError::Url(_)));
assert!(
!err.is_retriable(),
"no number of attempts turns https into mqtt"
);
assert!(build_options(&MqttConfig::new("not a url")).is_err());
}
#[test]
fn a_broker_that_is_down_is_worth_another_attempt() {
assert!(MqttError::Disconnected("reset".into()).is_retriable());
assert!(MqttError::Unacknowledged(StdDuration::from_secs(1)).is_retriable());
assert!(MqttError::Queue("full".into()).is_retriable());
}
#[test]
fn credentials_reach_the_options() {
let config =
MqttConfig::new("mqtt://broker.example.com").with_credentials("ven-1", "token");
let options = build_options(&config).unwrap();
let login = options.credentials().expect("credentials were set");
assert_eq!(login.username, "ven-1");
assert_eq!(login.password, "token");
}
}