trillium_channels/
channel_client.rs1use 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#[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 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 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 pub async fn reply_ok(&self, event: &ChannelEvent, payload: &impl Serialize) {
68 self.reply(event, "ok", payload).await;
69 }
70
71 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 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 #[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 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 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 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}