use std::sync::Arc;
use std::time::Duration as StdDuration;
use rumqttc::{AsyncClient, Event, Incoming, QoS};
use super::{Meter, VenError, VenRuntime, Waker};
use crate::client::{Client, VirtualEndNode};
use crate::model::{MqttAuthentication, ObjectId};
#[derive(Debug, Clone)]
pub struct MqttPushConfig {
pub client_id: Option<String>,
pub keep_alive: StdDuration,
pub reconnect_delay: StdDuration,
pub queue_capacity: usize,
pub watch_programs: bool,
pub watch_own_objects: bool,
}
impl Default for MqttPushConfig {
fn default() -> Self {
Self {
client_id: None,
keep_alive: StdDuration::from_secs(30),
reconnect_delay: StdDuration::from_secs(1),
queue_capacity: 32,
watch_programs: true,
watch_own_objects: true,
}
}
}
#[derive(Debug)]
pub struct MqttPush {
topics: Vec<String>,
broker: String,
task: tokio::task::JoinHandle<()>,
}
impl Drop for MqttPush {
fn drop(&mut self) {
self.task.abort();
}
}
impl MqttPush {
pub async fn connect<M: Meter>(
ven: &VenRuntime<M>,
config: MqttPushConfig,
) -> Result<Option<Self>, VenError> {
let ven_id = ven.ven_id().ok_or(VenError::NotRegistered)?;
Self::start(ven.client(), &ven_id, ven.waker(), config).await
}
pub async fn start(
client: &Client<VirtualEndNode>,
ven_id: &ObjectId,
waker: Waker,
config: MqttPushConfig,
) -> Result<Option<Self>, VenError> {
let notifiers = client.notifiers().await?;
let Some(binding) = notifiers.mqtt else {
tracing::info!("this VTN offers no MQTT notifier; the VEN will poll");
return Ok(None);
};
let broker = binding
.uris
.first()
.cloned()
.ok_or_else(|| VenError::Protocol("the MQTT binding names no broker URI".into()))?;
let topics = Self::discover(client, ven_id, &config).await?;
if topics.is_empty() {
return Err(VenError::Protocol(
"the VTN named no topics this VEN may subscribe to".into(),
));
}
let client_id = config
.client_id
.clone()
.unwrap_or_else(|| format!("openadr-ven-{ven_id}"));
let mut options = crate::mqtt::broker_options(&broker, &client_id, config.keep_alive)
.map_err(VenError::Protocol)?;
if matches!(
binding.authentication,
MqttAuthentication::Oauth2BearerToken { .. }
) {
let token = client.access_token().await?.ok_or_else(|| {
VenError::Protocol(
"the broker wants the access token as its password, and this client has \
neither credentials nor a pre-shared token"
.into(),
)
})?;
let username = binding
.authentication
.resolve_username(client.client_id())
.ok_or_else(|| {
VenError::Protocol(
"the broker wants this VEN's clientID as its MQTT username, and a \
pre-shared bearer token does not say what that is — configure client \
credentials, or a fixed username in the VTN's binding"
.into(),
)
})?
.to_string();
options.set_credentials(username, token);
}
let (mqtt, event_loop) = AsyncClient::new(options, config.queue_capacity);
for topic in &topics {
mqtt.subscribe(topic.clone(), QoS::AtLeastOnce)
.await
.map_err(|e| VenError::Protocol(format!("could not subscribe: {e}")))?;
}
let task = tokio::spawn(run(
event_loop,
waker,
config.reconnect_delay,
Arc::new(mqtt),
));
tracing::info!(broker = %broker, topics = topics.len(), "subscribed to VTN notifications");
Ok(Some(Self {
topics,
broker,
task,
}))
}
pub fn topics(&self) -> &[String] {
&self.topics
}
pub fn broker(&self) -> &str {
&self.broker
}
async fn discover(
client: &Client<VirtualEndNode>,
ven_id: &ObjectId,
config: &MqttPushConfig,
) -> Result<Vec<String>, VenError> {
let mut paths = vec![format!("vens/{ven_id}/events")];
if config.watch_programs {
paths.push(format!("vens/{ven_id}/programs"));
}
if config.watch_own_objects {
paths.push(format!("vens/{ven_id}"));
paths.push(format!("vens/{ven_id}/resources"));
}
let mut topics = Vec::new();
for path in paths {
let response = match client.mqtt_topics(&path).await {
Ok(response) => response,
Err(e) if e.status() == Some(404) => {
tracing::debug!(path, "this VTN does not offer that topic endpoint");
continue;
}
Err(e) => return Err(e.into()),
};
let t = response.topics;
match t.all {
Some(all) => topics.push(all),
None => {
topics.extend(t.create);
topics.push(t.update);
topics.push(t.delete);
}
}
}
topics.sort();
topics.dedup();
Ok(topics)
}
}
async fn run(
mut event_loop: rumqttc::EventLoop,
waker: Waker,
reconnect_delay: StdDuration,
_client: Arc<AsyncClient>,
) {
loop {
match event_loop.poll().await {
Ok(Event::Incoming(Incoming::Publish(publish))) => {
tracing::debug!(topic = %publish.topic, "notification received; syncing early");
waker.wake();
}
Ok(Event::Incoming(Incoming::ConnAck(_))) => {
tracing::info!("connected to the MQTT broker");
waker.wake();
}
Ok(_) => {}
Err(e) => {
tracing::warn!(error = %e, "MQTT connection error; reconnecting");
tokio::time::sleep(reconnect_delay).await;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_wildcard_replaces_three_subscriptions_and_a_binding_without_one_does_not() {
use crate::model::{NotifierTopics, TopicsResponse};
let wildcard = TopicsResponse::under("events/vens/ven-1").topics;
assert_eq!(wildcard.all.as_deref(), Some("events/vens/ven-1/+"));
let plain = NotifierTopics {
create: Some("a/create".into()),
update: "a/update".into(),
delete: "a/delete".into(),
all: None,
};
let mut expanded: Vec<String> = Vec::new();
expanded.extend(plain.create.clone());
expanded.push(plain.update.clone());
expanded.push(plain.delete.clone());
assert_eq!(expanded, ["a/create", "a/update", "a/delete"]);
}
#[test]
fn the_default_client_id_is_per_ven_not_per_process() {
let config = MqttPushConfig::default();
assert!(config.client_id.is_none());
assert!(config.watch_programs && config.watch_own_objects);
}
}