implement storage + improve code

This commit is contained in:
csehviktor
2025-07-06 02:28:29 +02:00
parent d2a82e973b
commit bf9d1e4da6
14 changed files with 357 additions and 62 deletions
+5 -3
View File
@@ -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");
+8 -2
View File
@@ -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);
}
}
}
}