use std::sync::Arc;
use std::time::Duration as StdDuration;
use async_trait::async_trait;
use super::{Channel, Delivery, DeliveryFailure, Notifier};
use crate::mqtt::{BrokerAddress, Connection, ConnectionConfig, Incoming, QoS};
pub use crate::mqtt::MqttError;
#[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,
}
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),
}
}
}
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)]
pub struct MqttNotifier {
connection: Arc<Connection>,
config: MqttConfig,
}
impl MqttNotifier {
pub fn connect(config: MqttConfig) -> Result<Arc<Self>, MqttError> {
let address = BrokerAddress::parse(&config.url)?;
let (events, mut incoming) = tokio::sync::mpsc::channel(32);
let connection = Connection::open(
address,
ConnectionConfig {
client_id: config.client_id.clone(),
username: config.username.clone(),
password: config.password.clone(),
keep_alive: config.keep_alive,
ack_timeout: config.publish_timeout,
..Default::default()
},
Vec::new(),
events,
);
tokio::spawn(async move {
while let Some(event) = incoming.recv().await {
match event {
Incoming::Connected(ack) => tracing::info!(
session_present = ack.session_present,
"connected to the MQTT broker"
),
Incoming::Disconnected(why) => {
tracing::warn!(reason = %why, "MQTT connection lost")
}
Incoming::Message { topic, .. } => {
tracing::warn!(%topic, "the publisher received a message it never asked for")
}
}
}
});
Ok(Arc::new(Self { connection, config }))
}
pub fn url(&self) -> &str {
&self.config.url
}
pub fn is_connected(&self) -> bool {
self.connection.is_connected()
}
async fn publish(&self, topic: &str, payload: Vec<u8>) -> Result<(), MqttError> {
tokio::time::timeout(
self.config.publish_timeout,
self.connection
.publish(topic, payload, self.config.qos, self.config.retain),
)
.await
.map_err(|_| MqttError::Timeout(self.config.publish_timeout))?
}
}
#[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"
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn broker_urls_pick_the_right_port_and_transport() {
let plain =
BrokerAddress::parse(&MqttConfig::new("mqtt://broker.example.com").url).unwrap();
assert_eq!(
(plain.host(), plain.port(), plain.is_tls()),
("broker.example.com", 1883, false)
);
let tls = BrokerAddress::parse(&MqttConfig::new("mqtts://broker.example.com").url).unwrap();
assert_eq!(
(tls.host(), tls.port(), tls.is_tls()),
("broker.example.com", 8883, true)
);
let explicit =
BrokerAddress::parse(&MqttConfig::new("mqtt://broker.example.com:2883").url).unwrap();
assert_eq!(explicit.port(), 2883);
}
#[test]
fn an_unusable_broker_url_is_refused_rather_than_retried() {
let err = BrokerAddress::parse("https://broker.example.com").unwrap_err();
assert!(matches!(err, MqttError::Url(_)));
assert!(
!err.is_retriable(),
"no number of attempts turns https into mqtt"
);
assert!(BrokerAddress::parse("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::Timeout(StdDuration::from_secs(1)).is_retriable());
assert!(MqttError::Refused(5, "not authorized").is_retriable());
}
#[test]
fn credentials_reach_the_connection_config() {
let config =
MqttConfig::new("mqtt://broker.example.com").with_credentials("ven-1", "token");
assert_eq!(config.username.as_deref(), Some("ven-1"));
assert_eq!(config.password.as_deref(), Some("token"));
}
#[test]
fn the_only_qualities_of_service_are_the_two_that_can_complete() {
assert_eq!(MqttConfig::default().qos, QoS::AtLeastOnce);
}
}