wactorz_core/
publish.rs

1//! Lightweight publish channel: actors post (topic, payload) tuples; the
2//! server task bridges them to the real MQTT broker.
3
4use serde::Serialize;
5use tokio::sync::mpsc;
6
7/// Cloneable sender handle used by actors to publish MQTT-like events.
8#[derive(Clone, Debug)]
9pub struct EventPublisher {
10    tx: mpsc::UnboundedSender<(String, Vec<u8>)>,
11}
12
13impl EventPublisher {
14    /// Create a linked (publisher, receiver) pair.
15    pub fn channel() -> (Self, mpsc::UnboundedReceiver<(String, Vec<u8>)>) {
16        let (tx, rx) = mpsc::unbounded_channel();
17        (Self { tx }, rx)
18    }
19
20    /// Publish a serialisable value to `topic`.
21    pub fn publish<T: Serialize>(&self, topic: impl Into<String>, payload: &T) {
22        match serde_json::to_vec(payload) {
23            Ok(bytes) => {
24                let _ = self.tx.send((topic.into(), bytes));
25            }
26            Err(e) => tracing::warn!("EventPublisher serialize error: {e}"),
27        }
28    }
29
30    /// Publish raw bytes.
31    pub fn publish_raw(&self, topic: impl Into<String>, payload: Vec<u8>) {
32        let _ = self.tx.send((topic.into(), payload));
33    }
34}