Files
status-monitor/server/src/broker/subscriber.rs
T
2025-07-15 01:08:51 +02:00

49 lines
1.4 KiB
Rust

use common::{MQTT_TOPIC, StatusMessage};
use rumqttd::{Broker, Notification, local::LinkRx};
use std::sync::Arc;
use crate::{bridge::ClientManager, storage::StorageRepository};
pub struct MqttSubscriber {
link_rx: LinkRx,
clients: Arc<ClientManager>,
storage: Arc<dyn StorageRepository>,
}
impl MqttSubscriber {
pub fn new(
broker: &Broker,
clients: Arc<ClientManager>,
storage: Arc<dyn StorageRepository>,
) -> Self {
let (mut link_tx, link_rx) = broker.link("internal-subscriber").unwrap();
link_tx.subscribe(MQTT_TOPIC).unwrap();
Self {
link_rx,
clients,
storage,
}
}
pub async fn run(&mut self) -> anyhow::Result<()> {
while let Ok(notification) = self.link_rx.next().await {
if let Notification::Forward(forward) = notification.unwrap() {
let payload = StatusMessage::try_from(&forward.publish.payload[..])?;
self.clients.broadcast(&payload).await;
if let Err(e) = self.storage.record_uptime(&payload.agent).await {
eprintln!("failed to record uptime for {}: {}", &payload.agent, e);
}
if let Err(e) = self.storage.record_message(&payload).await {
eprintln!("failed to record message for {}: {}", &payload.agent, e);
}
}
}
Ok(())
}
}