Skip to main content

trillium_channels/
channel_client.rs

1use crate::{
2    ChannelEvent, Version,
3    client_receiver::{ClientReceiver, OutboundEvent},
4    subscriptions::Subscriptions,
5};
6use async_broadcast::{Receiver, Sender as BroadcastSender};
7use async_channel::Sender;
8use serde::Serialize;
9use trillium::log_error;
10use trillium_websockets::Message;
11
12/// # Communicate with the connected client.
13///
14/// Note that although each client is unique and represents a specific
15/// websocket connection, the ChannelClient can be cloned and moved
16/// elsewhere if needed and any updates to the topic subscriptions
17/// will be kept synchronized across clones.
18#[derive(Debug, Clone)]
19pub struct ChannelClient {
20    subscriptions: Subscriptions,
21    sender: Sender<OutboundEvent>,
22    broadcast_sender: BroadcastSender<ChannelEvent>,
23    version: Version,
24}
25
26impl ChannelClient {
27    pub(crate) fn new(
28        broadcast_sender: BroadcastSender<ChannelEvent>,
29        broadcast_receiver: Receiver<ChannelEvent>,
30        version: Version,
31    ) -> (Self, ClientReceiver) {
32        let (sender, individual) = async_channel::unbounded();
33        let subscriptions = Subscriptions::default();
34        (
35            Self {
36                subscriptions: subscriptions.clone(),
37                sender,
38                broadcast_sender,
39                version,
40            },
41            ClientReceiver::new(individual, broadcast_receiver, subscriptions, version),
42        )
43    }
44
45    /// Send a [`ChannelEvent`] to all connected clients. Note that
46    /// these messages will only reach clients that subscribe to the
47    /// event's topic.
48    pub fn broadcast(&self, event: impl Into<ChannelEvent>) {
49        let mut event = event.into();
50        event.reference = None;
51        log_error!(self.broadcast_sender.try_broadcast(event));
52    }
53
54    /// Send a [`ChannelEvent`] to this specific client. Note that
55    /// this message will only be received if the client subscribes to
56    /// the event's topic.
57    pub async fn send_event(&self, event: impl Into<ChannelEvent>) {
58        log_error!(
59            self.sender
60                .send(OutboundEvent::Individual(event.into()))
61                .await
62        );
63    }
64
65    /// Send a `phx_reply` with status `"ok"` and the provided response payload.
66    /// The reply preserves the request's references and does not require a topic subscription.
67    pub async fn reply_ok(&self, event: &ChannelEvent, payload: &impl Serialize) {
68        self.reply(event, "ok", payload).await;
69    }
70
71    /// Reject a join or push with a `phx_reply` with status `"error"`.
72    ///
73    /// The reply preserves the request's references and reaches the client even
74    /// if it has not joined the topic. This does not change its subscriptions.
75    pub async fn reject(&self, event: &ChannelEvent, error: &impl Serialize) {
76        self.reply(event, "error", error).await;
77    }
78
79    async fn reply(&self, event: &ChannelEvent, status: &'static str, response: &impl Serialize) {
80        #[derive(serde::Serialize)]
81        struct Reply<'a, S> {
82            status: &'static str,
83            response: &'a S,
84        }
85
86        match event.try_build_reply("phx_reply", &Reply { status, response }) {
87            Ok(reply) => log_error!(self.sender.send(OutboundEvent::Reply(reply)).await),
88            Err(error) => log::error!("could not serialize channel reply: {error}"),
89        }
90    }
91
92    /// Mark the client's channel for this event's topic as errored, by sending a `phx_error`.
93    ///
94    /// The Phoenix JavaScript client treats this as a crashed channel and rejoins it. The event
95    /// is only delivered if the client subscribes to the topic. To reject an individual join or
96    /// push, use [`Self::reject`] instead.
97    pub async fn mark_channel_errored(&self, event: &ChannelEvent, error: &impl Serialize) {
98        match event.try_build_reply("phx_error", error) {
99            Ok(reply) => self.send_event(reply).await,
100            Err(error) => log::error!("could not serialize channel error: {error}"),
101        }
102    }
103
104    /// Mark the client's channel for this event's topic as errored.
105    #[deprecated(
106        since = "0.5.0",
107        note = "to refuse a join or push, use `reject`; to put the client's channel in an error \
108                state, use `mark_channel_errored`"
109    )]
110    pub async fn reply_error(&self, event: &ChannelEvent, error: &impl Serialize) {
111        self.mark_channel_errored(event, error).await;
112    }
113
114    /// Join a topic, sending an ok reply with the provided optional
115    /// value. This sends an ok reply to the client as well as adding the
116    /// topic to the client's subscriptions.
117    ///
118    /// Use `&()` as the payload if no payload is needed.
119    pub async fn allow_join(&self, event: &ChannelEvent, payload: &impl Serialize) {
120        if event.event() != "phx_join" {
121            log::error!(
122                "allow_join called with an event other than phx_join: {:?}",
123                event
124            );
125            return;
126        }
127        self.subscriptions.join(event.topic.to_string());
128        self.reply_ok(event, payload).await;
129    }
130
131    /// Leave a topic as requested by the provided channel event,
132    /// including the optional payload. This sends an ok reply to the
133    /// client as well as removing the channel from the client's
134    /// subscriptions.
135    ///
136    /// Use `&()` as the payload if no payload is needed.
137    pub async fn allow_leave(&self, event: &ChannelEvent, payload: &impl Serialize) {
138        if event.event() != "phx_leave" {
139            log::error!(
140                "allow_leave called with an event other than phx_leave: {:?}",
141                event
142            );
143            return;
144        }
145        self.subscriptions.leave(&event.topic);
146        self.reply_ok(event, payload).await;
147    }
148
149    /// Borrow this client's subscriptions
150    pub fn subscriptions(&self) -> &Subscriptions {
151        &self.subscriptions
152    }
153
154    pub(crate) fn deserialize(&self, message: Message) -> Option<ChannelEvent> {
155        let string = message.to_text().ok()?;
156        ChannelEvent::deserialize(string, self.version).ok()
157    }
158}