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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use async_nats::Client;
use bytes::Bytes;
use prost::Message;
use crate::error::WorkerError;

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

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

    /// Publishes a protobuf message to a worker-specific topic
    pub async fn publish<T: Message>(&self, message: T) -> Result<(), WorkerError> {
        let data = message.encode_to_vec();
        self.client
            .publish(
                format!("HDP.worker.{}", self.worker_id),
                data.into()
            )
            .await
            .map_err(|e| WorkerError::NatsError(e.to_string()))?;

        Ok(())
    }

    /// Publishes raw bytes to a worker-specific topic
    pub async fn publish_raw(&self, data: Bytes) -> Result<(), WorkerError> {
        self.client
            .publish(
                format!("HDP.worker.{}", self.worker_id),
                data
            )
            .await
            .map_err(|e| WorkerError::NatsError(e.to_string()))?;

        Ok(())
    }

    /// Publishes a protobuf message to a custom topic
    pub async fn publish_to<T: Message>(&self, topic: String, message: T) -> Result<(), WorkerError> {
        let data = message.encode_to_vec();
        self.client
            .publish(topic, data.into())
            .await
            .map_err(|e| WorkerError::NatsError(e.to_string()))?;

        Ok(())
    }
}