Skip to main content

doido_cable/
cable.rs

1use crate::protocol::ServerMessage;
2use crate::pubsub::PubSub;
3use doido_core::Result;
4use serde_json::Value;
5use std::sync::Arc;
6
7pub struct Cable {
8    pubsub: Arc<dyn PubSub>,
9}
10
11impl Cable {
12    pub fn new(pubsub: Arc<dyn PubSub>) -> Self {
13        Self { pubsub }
14    }
15
16    /// Publish a raw string to `stream`.
17    pub async fn broadcast_to(&self, stream: &str, message: &str) -> Result<()> {
18        self.pubsub.publish(stream, message).await
19    }
20
21    /// Broadcast a structured ActionCable message (identifier + data) to a
22    /// stream from anywhere in the app (Rails `Channel.broadcast_to`). Subscribers
23    /// receive it as a JSON [`ServerMessage`].
24    pub async fn broadcast(&self, stream: &str, identifier: &str, message: Value) -> Result<()> {
25        let frame = ServerMessage::new(identifier, message);
26        self.pubsub.publish(stream, &frame.to_json()?).await
27    }
28
29    /// The underlying pub/sub backend (e.g. to subscribe a connection).
30    pub fn pubsub(&self) -> &Arc<dyn PubSub> {
31        &self.pubsub
32    }
33}