hdp_worker/
publisher.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use async_nats::Client;
use bytes::Bytes;
use prost::Message;

pub struct Publisher {
    client: Client,
    worker_id: String,
}

impl Publisher {
    pub fn new(client: Client, worker_id: String) -> Self {
        Self { client, worker_id }
    }

    pub async fn publish<T: Message>(&self, message: T) -> Result<(), String> {
        let data = message.encode_to_vec();
        self.client
            .publish(format!("HDP.worker.{}", self.worker_id), data.into())
            .await
            .map_err(|e| e.to_string())?;
        Ok(())
    }

    pub async fn publish_raw(&self, data: Bytes) -> Result<(), String> {
        self.client
            .publish(format!("HDP.worker.{}", self.worker_id), data)
            .await
            .map_err(|e| e.to_string())?;
        Ok(())
    }

    pub async fn publish_to<T: Message>(&self, topic: String, message: T) -> Result<(), String> {
        let data = message.encode_to_vec();
        self.client
            .publish(topic, data.into())
            .await
            .map_err(|e| e.to_string())?;
        Ok(())
    }
}