mirror of
https://github.com/csehviktor/status-monitor.git
synced 2026-04-28 16:27:34 +02:00
implement storage + improve code
This commit is contained in:
@@ -1,22 +1,24 @@
|
||||
use rumqttd::{Broker, Config};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::bridge::ClientManager;
|
||||
use crate::{bridge::ClientManager, storage::StorageRepositoryImpl};
|
||||
use super::subscriber::MqttSubscriber;
|
||||
|
||||
pub struct MqttBroker {
|
||||
broker: &'static mut Broker,
|
||||
clients: Arc<ClientManager>,
|
||||
storage: Arc<StorageRepositoryImpl>,
|
||||
}
|
||||
|
||||
impl MqttBroker {
|
||||
pub async fn new(cfg: Config) -> Self {
|
||||
pub async fn new(cfg: Config, storage: Arc<StorageRepositoryImpl>) -> Self {
|
||||
let clients = Arc::new(ClientManager::new());
|
||||
let broker: &'static mut Broker = Box::leak(Box::new(Broker::new(cfg)));
|
||||
|
||||
Self {
|
||||
broker,
|
||||
clients,
|
||||
storage,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +27,7 @@ impl MqttBroker {
|
||||
}
|
||||
|
||||
pub async fn run(self) -> anyhow::Result<()> {
|
||||
let mut subscriber = MqttSubscriber::new(&self.broker, self.clients);
|
||||
let mut subscriber = MqttSubscriber::new(&self.broker, self.clients, self.storage.inner());
|
||||
|
||||
println!("starting mqtt broker on specified port");
|
||||
|
||||
|
||||
@@ -2,21 +2,23 @@ use rumqttd::{local::LinkRx, Broker, Notification};
|
||||
use common::{StatusMessage, MQTT_TOPIC};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::bridge::ClientManager;
|
||||
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>) -> Self {
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +29,10 @@ impl MqttSubscriber {
|
||||
|
||||
if let Ok(payload_str) = payload.to_string() {
|
||||
self.clients.broadcast(payload_str).await;
|
||||
|
||||
if let Err(e) = self.storage.record_message(&payload.agent).await {
|
||||
eprintln!("failed to record message for {}: {}", &payload.agent, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user