use std::{sync::Arc, time::Instant};
use rumqttc::{AsyncClient, Event, EventLoop, Incoming};
use tracing::{debug, info, warn};
use crate::{
core::{CoreError, Service, ServiceFuture, ShutdownToken},
mqtt::{MqttConfig, MqttError, MqttHandler, MqttMessage, MqttResult},
};
pub struct MqttService<H> {
name: String,
config: MqttConfig,
handler: Arc<H>,
}
impl<H> MqttService<H>
where
H: MqttHandler,
{
pub fn new(config: MqttConfig, handler: H) -> Self {
Self {
name: "mqtt".to_string(),
config,
handler: Arc::new(handler),
}
}
pub fn named(name: impl Into<String>, config: MqttConfig, handler: H) -> Self {
Self {
name: name.into(),
config,
handler: Arc::new(handler),
}
}
}
impl<H> Service for MqttService<H>
where
H: MqttHandler,
{
fn name(&self) -> &str {
&self.name
}
fn start(&self, shutdown: ShutdownToken) -> ServiceFuture<'_> {
Box::pin(async move {
if shutdown.is_cancelled() {
return Ok(());
}
self.config
.validate()
.map_err(|error| CoreError::Service(error.to_string()))?;
run_with_reconnect(&self.name, &self.config, self.handler.clone(), shutdown)
.await
.map_err(|error| CoreError::Service(error.to_string()))
})
}
}
async fn run_with_reconnect<H>(
service_name: &str,
config: &MqttConfig,
handler: Arc<H>,
shutdown: ShutdownToken,
) -> MqttResult<()>
where
H: MqttHandler,
{
let mut attempt = 0;
loop {
match run_once(service_name, config, handler.clone(), shutdown.clone()).await {
Ok(()) => return Ok(()),
Err(error) if shutdown.is_cancelled() => return Err(error),
Err(error) => {
let delay = config.reconnect.delay_for_attempt(attempt);
warn!(
service = service_name,
attempt,
?delay,
error = %error,
"mqtt reconnect scheduled"
);
attempt = attempt.saturating_add(1);
tokio::select! {
_ = shutdown.cancelled() => return Ok(()),
_ = tokio::time::sleep(delay) => {}
}
}
}
}
}
async fn run_once<H>(
service_name: &str,
config: &MqttConfig,
handler: Arc<H>,
shutdown: ShutdownToken,
) -> MqttResult<()>
where
H: MqttHandler,
{
let options = config.to_mqtt_options()?;
let (client, mut eventloop) = AsyncClient::new(options, config.inflight);
record_event(config, service_name, "connect", "success");
subscribe_all(&client, service_name, config).await?;
poll_loop(service_name, config, handler, &mut eventloop, shutdown).await
}
#[doc(hidden)]
pub async fn handle_message_for_test<H>(
service_name: &str,
config: &MqttConfig,
handler: &H,
message: MqttMessage,
) -> MqttResult<()>
where
H: MqttHandler,
{
handle_message(service_name, config, handler, message).await
}
async fn subscribe_all(
client: &AsyncClient,
service_name: &str,
config: &MqttConfig,
) -> MqttResult<()> {
for subscription in &config.subscriptions {
let result = client
.subscribe(&subscription.topic, subscription.qos.into())
.await
.map_err(|error| MqttError::Subscribe(error.to_string()));
record_event(
config,
service_name,
"subscribe",
if result.is_ok() { "success" } else { "error" },
);
result?;
info!(topic = %subscription.topic, "mqtt subscribed");
}
Ok(())
}
async fn poll_loop<H>(
service_name: &str,
config: &MqttConfig,
handler: Arc<H>,
eventloop: &mut EventLoop,
shutdown: ShutdownToken,
) -> MqttResult<()>
where
H: MqttHandler,
{
loop {
tokio::select! {
_ = shutdown.cancelled() => {
info!("mqtt service shutdown requested");
return Ok(());
}
event = eventloop.poll() => {
match event.map_err(|error| MqttError::EventLoop(error.to_string()))? {
Event::Incoming(Incoming::Publish(publish)) => {
handle_message(
service_name,
config,
handler.as_ref(),
MqttMessage::from(publish),
)
.await?;
}
other => {
debug!(event = ?other, "mqtt event observed");
}
}
}
}
}
}
async fn handle_message<H>(
service_name: &str,
config: &MqttConfig,
handler: &H,
message: MqttMessage,
) -> MqttResult<()>
where
H: MqttHandler,
{
let topic = message.topic().to_string();
let started = Instant::now();
let result = if let Some(timeout) = config.handler_timeout {
tokio::time::timeout(timeout, handler.handle(message))
.await
.map_err(|_| MqttError::HandlerTimeout)?
} else {
handler.handle(message).await
};
if let Err(error) = &result {
warn!(topic, error = %error, "mqtt handler failed");
}
record_message(
config,
service_name,
&topic,
if result.is_ok() { "success" } else { "error" },
started.elapsed(),
);
result
}
#[cfg(feature = "observability")]
fn record_event(config: &MqttConfig, service: &str, event: &str, outcome: &str) {
if let Some(metrics) = &config.metrics_registry {
metrics.record_mqtt_event(service, event, outcome);
}
}
#[cfg(not(feature = "observability"))]
fn record_event(_config: &MqttConfig, _service: &str, _event: &str, _outcome: &str) {}
#[cfg(feature = "observability")]
fn record_message(
config: &MqttConfig,
service: &str,
topic: &str,
outcome: &str,
duration: std::time::Duration,
) {
if let Some(metrics) = &config.metrics_registry {
metrics.record_mqtt_message(service, topic, outcome, duration);
}
}
#[cfg(not(feature = "observability"))]
fn record_message(
_config: &MqttConfig,
_service: &str,
_topic: &str,
_outcome: &str,
_duration: std::time::Duration,
) {
}