hdp_worker/
publisher.rs

1use async_nats::Client;
2use bytes::Bytes;
3use prost::Message;
4
5pub struct Publisher {
6    client: Client,
7    worker_id: String,
8}
9
10impl Publisher {
11    pub fn new(client: Client, worker_id: String) -> Self {
12        Self { client, worker_id }
13    }
14
15    pub async fn publish<T: Message>(&self, message: T) -> Result<(), String> {
16        let data = message.encode_to_vec();
17        self.client
18            .publish(format!("HDP.worker.{}", self.worker_id), data.into())
19            .await
20            .map_err(|e| e.to_string())?;
21        Ok(())
22    }
23
24    pub async fn publish_raw(&self, data: Bytes) -> Result<(), String> {
25        self.client
26            .publish(format!("HDP.worker.{}", self.worker_id), data)
27            .await
28            .map_err(|e| e.to_string())?;
29        Ok(())
30    }
31
32    pub async fn publish_to<T: Message>(&self, topic: String, message: T) -> Result<(), String> {
33        let data = message.encode_to_vec();
34        self.client
35            .publish(topic, data.into())
36            .await
37            .map_err(|e| e.to_string())?;
38        Ok(())
39    }
40}