Skip to main content

trillium_channels/
channel_conn.rs

1use crate::{ChannelClient, ChannelEvent};
2use serde::Serialize;
3use std::ops::{Deref, DerefMut};
4use trillium_websockets::WebSocketConn;
5
6/// A ChannelConn is a wrapper around a [`WebSocketConn`] that also
7/// contains a [`ChannelClient`]
8///
9/// It that provides convenient access to functions from the ChannelClient
10/// held in the WebSocketConn's TypeSet, and dereferences to the
11/// `WebSocketConn` for other functionality.
12#[derive(Debug)]
13pub struct ChannelConn<'a> {
14    pub(crate) conn: &'a mut WebSocketConn,
15}
16
17macro_rules! channel_client {
18    ($conn:expr_2021) => {
19        match $conn.client() {
20            Some(client) => client,
21            None => {
22                log::error!("could not unwrap client on {}:{}", file!(), line!());
23                return;
24            }
25        }
26    };
27}
28
29impl ChannelConn<'_> {
30    /// Borrow the channel client
31    pub fn client(&self) -> Option<&ChannelClient> {
32        self.state()
33    }
34
35    /// Borrow the websocket conn
36    pub fn conn(&self) -> &WebSocketConn {
37        self
38    }
39
40    /// Send a [`ChannelEvent`] to all connected clients. Note that
41    /// these messages will only reach clients that subscribe to the
42    /// event's topic.
43    pub fn broadcast(&self, event: impl Into<ChannelEvent>) {
44        channel_client!(self).broadcast(event);
45    }
46
47    /// Send a [`ChannelEvent`] to this specific client. Note that
48    /// this message will only be received if the client subscribes to
49    /// the event's topic.
50    pub async fn send_event(&self, event: impl Into<ChannelEvent>) {
51        channel_client!(self).send_event(event).await;
52    }
53
54    /// Send a `phx_reply` with status `"ok"` and the provided response payload.
55    /// The reply preserves the request's references and does not require a topic subscription.
56    pub async fn reply_ok(&self, event: &ChannelEvent, response: &impl Serialize) {
57        channel_client!(self).reply_ok(event, response).await;
58    }
59
60    /// Reject a join or push with a `phx_reply` with status `"error"`.
61    ///
62    /// The reply preserves the request's references and reaches the client even
63    /// if it has not joined the topic. This does not change its subscriptions.
64    pub async fn reject(&self, event: &ChannelEvent, error: &impl Serialize) {
65        channel_client!(self).reject(event, error).await;
66    }
67
68    /// Mark the client's channel for this event's topic as errored, by sending a `phx_error`.
69    ///
70    /// The Phoenix JavaScript client treats this as a crashed channel and rejoins it. The event
71    /// is only delivered if the client subscribes to the topic. To reject an individual join or
72    /// push, use [`Self::reject`] instead.
73    pub async fn mark_channel_errored(&self, event: &ChannelEvent, error: &impl Serialize) {
74        channel_client!(self)
75            .mark_channel_errored(event, error)
76            .await;
77    }
78
79    /// Mark the client's channel for this event's topic as errored.
80    #[deprecated(
81        since = "0.5.0",
82        note = "to refuse a join or push, use `reject`; to put the client's channel in an error \
83                state, use `mark_channel_errored`"
84    )]
85    pub async fn reply_error(&self, event: &ChannelEvent, error: &impl Serialize) {
86        channel_client!(self)
87            .mark_channel_errored(event, error)
88            .await;
89    }
90
91    /// Join a topic, sending an ok reply with the provided optional
92    /// value. This sends an ok reply to the client as well as adding the
93    /// topic to the client's subscriptions.
94    pub async fn allow_join(&self, event: &ChannelEvent, value: &impl Serialize) {
95        channel_client!(self).allow_join(event, value).await;
96    }
97
98    /// Leave a topic as requested by the provided channel event,
99    /// including the optional payload. This sends an ok reply to the
100    /// client as well as removing the channel from the client's
101    /// subscriptions.
102    pub async fn allow_leave(&self, event: &ChannelEvent, payload: &impl Serialize) {
103        channel_client!(self).allow_leave(event, payload).await;
104    }
105}
106
107impl Deref for ChannelConn<'_> {
108    type Target = WebSocketConn;
109
110    fn deref(&self) -> &Self::Target {
111        &*self.conn
112    }
113}
114
115impl DerefMut for ChannelConn<'_> {
116    fn deref_mut(&mut self) -> &mut Self::Target {
117        self.conn
118    }
119}