Skip to main content

trillium_channels/
channel_event.rs

1use crate::Version;
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::borrow::Cow;
5
6/// # The messages passed between server and connected clients.
7///
8/// ChannelEvents contain a topic, event, payload, and if sent from a
9/// client, a unique reference identifier that can be used to respond to
10/// this event.
11///
12/// Most interfaces in this crate take an `Into<ChannelEvent>` instead of a ChannelEvent directly,
13/// so that you can either implement `Into<ChannelEvent>` for relevant types, or use these tuple
14/// From implementations:
15///
16/// ```
17/// use trillium_channels::ChannelEvent;
18/// use serde_json::{json, Value, to_string};
19/// let event: ChannelEvent = ("topic", "event").into();
20/// assert_eq!(event.topic(), "topic");
21/// assert_eq!(event.event(), "event");
22/// assert_eq!(event.payload(), &json!({}));
23///
24/// let event: ChannelEvent = ("topic", "event", &json!({"some": "payload"})).into();
25/// assert_eq!(event.topic(), "topic");
26/// assert_eq!(event.event(), "event");
27/// assert_eq!(to_string(event.payload()).unwrap(), r#"{"some":"payload"}"#);
28///
29/// #[derive(serde::Serialize)]
30/// struct SomePayload { payload: &'static str };
31/// let event: ChannelEvent = ("topic", "event", &SomePayload { payload: "anything" }).into();
32/// assert_eq!(event.topic(), "topic");
33/// assert_eq!(event.event(), "event");
34/// assert_eq!(to_string(event.payload()).unwrap(), r#"{"payload":"anything"}"#);
35
36#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
37pub struct ChannelEvent {
38    pub(crate) topic: Cow<'static, str>,
39    pub(crate) event: Cow<'static, str>,
40    pub(crate) payload: Value,
41
42    #[serde(rename = "ref")]
43    pub(crate) reference: Option<Cow<'static, str>>,
44
45    #[serde(rename = "join_ref")]
46    pub(crate) join_reference: Option<Cow<'static, str>>,
47}
48
49impl ChannelEvent {
50    /// Construct a new ChannelEvent with the same reference as this
51    /// ChannelEvent. Note that this is the only way of setting the
52    /// reference on an event.
53    ///
54    /// The `event` argument can be either a `String` or, more commonly, a `&'static str`.
55    ///
56    /// The topic will always be the same as the source ChannelEvent's topic.
57    pub fn build_reply(
58        &self,
59        event: impl Into<Cow<'static, str>>,
60        payload: &impl Serialize,
61    ) -> ChannelEvent {
62        self.try_build_reply(event, payload).unwrap()
63    }
64
65    pub(crate) fn try_build_reply(
66        &self,
67        event: impl Into<Cow<'static, str>>,
68        payload: &impl Serialize,
69    ) -> serde_json::Result<ChannelEvent> {
70        Ok(ChannelEvent {
71            topic: self.topic.clone(),
72            event: event.into(),
73            payload: match serde_json::to_value(payload)? {
74                Value::Null => Value::Object(Default::default()),
75                other => other,
76            },
77            reference: self.reference.clone(),
78            join_reference: self.join_reference.clone(),
79        })
80    }
81
82    pub(crate) fn serialize(&self, version: Version) -> serde_json::Result<String> {
83        match version {
84            Version::V1 => serde_json::to_string(&self),
85
86            Version::V2 => serde_json::to_string(&(
87                &self.join_reference,
88                &self.reference,
89                &self.topic,
90                &self.event,
91                &self.payload,
92            )),
93        }
94    }
95
96    pub(crate) fn deserialize(string: &str, version: Version) -> serde_json::Result<Self> {
97        match version {
98            Version::V1 => serde_json::from_str(string),
99            Version::V2 => {
100                let (join_reference, reference, topic, event, payload): (
101                    Option<String>,
102                    Option<String>,
103                    String,
104                    String,
105                    Value,
106                ) = serde_json::from_str(string)?;
107                Ok(Self {
108                    join_reference: join_reference.map(Into::into),
109                    reference: reference.map(Into::into),
110                    topic: topic.into(),
111                    event: event.into(),
112                    payload,
113                })
114            }
115        }
116    }
117
118    /// Returns this ChannelEvent's topic
119    pub fn topic(&self) -> &str {
120        &self.topic
121    }
122
123    /// Returns this ChannelEvent's event
124    pub fn event(&self) -> &str {
125        &self.event
126    }
127
128    /// Returns this ChannelEvent's payload as a Value
129    pub fn payload(&self) -> &Value {
130        &self.payload
131    }
132
133    /// Returns the reference field ("ref" in json) for this ChannelEvent,
134    /// if one was provided by the client
135    pub fn reference(&self) -> Option<&str> {
136        self.reference.as_deref()
137    }
138
139    /// Constructs a new ChannelEvent from topic, event, and a
140    /// serializable payload. Use &() if no payload is needed.
141    ///
142    /// Note that the reference cannot be set this way. To set a
143    /// reference, use [`ChannelEvent::build_reply`]
144    pub fn new(
145        topic: impl Into<Cow<'static, str>>,
146        event: impl Into<Cow<'static, str>>,
147        payload: &impl Serialize,
148    ) -> Self {
149        Self {
150            topic: topic.into(),
151            event: event.into(),
152            payload: match serde_json::to_value(payload).unwrap() {
153                Value::Null => Value::Object(Default::default()),
154                other => other,
155            },
156            reference: None,
157            join_reference: None,
158        }
159    }
160
161    /// returns true if this ChannelEvent is used by the phoenix-channels compatability layer
162    ///
163    /// currently that means the topic is `"phoenix"` or the event is `"phx_join"` or `"phx_leave"`
164    pub(crate) fn is_system_event(&self) -> bool {
165        self.topic == "phoenix" || self.event == "phx_join" || self.event == "phx_leave"
166    }
167}
168
169impl<T, E> From<(T, E)> for ChannelEvent
170where
171    T: Into<Cow<'static, str>>,
172    E: Into<Cow<'static, str>>,
173{
174    fn from(te: (T, E)) -> Self {
175        let (topic, event) = te;
176        Self::new(topic, event, &())
177    }
178}
179
180impl<T, E, P> From<(T, E, P)> for ChannelEvent
181where
182    T: Into<Cow<'static, str>>,
183    E: Into<Cow<'static, str>>,
184    P: Serialize,
185{
186    fn from(tep: (T, E, P)) -> Self {
187        let (topic, event, payload) = tep;
188        Self::new(topic, event, &payload)
189    }
190}