stablesats_shared/pubsub/
publisher.rs

1use fred::prelude::*;
2
3use super::config::*;
4use super::error::PublisherError;
5use super::message::*;
6
7pub struct Publisher {
8    client: RedisClient,
9}
10
11impl Publisher {
12    pub async fn new(PubSubConfig { host }: PubSubConfig) -> Result<Self, PublisherError> {
13        let mut config = RedisConfig::default();
14        if let Some(host) = host {
15            config.server = ServerConfig::new_centralized(host, 6379);
16        }
17        let client = RedisClient::new(config);
18        let _ = client.connect(None);
19        client
20            .wait_for_connect()
21            .await
22            .map_err(PublisherError::InitialConnection)?;
23        Ok(Self { client })
24    }
25
26    pub async fn publish<P: MessagePayload>(&self, payload: P) -> Result<(), PublisherError> {
27        let payload_str = serde_json::to_string(&Envelope::new(payload))?;
28        self.client
29            .publish(<P as MessagePayload>::channel(), payload_str)
30            .await?;
31        Ok(())
32    }
33}