twilight_model/gateway/
frame.rs

1//! Raw Websocket frame.
2//!
3//! This is mostly equivalent to the underlying websocket library's message, but
4//! this intermediary exists to prevent exposing it in the public API. Messages
5//! constructed are equivalent to what the underlying library will receive. The
6//! input will not be checked and will be passed directly to the underlying
7//! websocket library.
8
9use std::borrow::Cow;
10
11/// Information about a close message.
12///
13/// A close frame can be constructed via [`CloseFrame::new`]. A default close
14/// frame for causing a [full session disconnect] and for
15/// [causing a session resume] are provided.
16///
17/// [causing a session resume]: CloseFrame::RESUME
18/// [full session disconnect]: CloseFrame::NORMAL
19#[derive(Clone, Debug, Eq, PartialEq)]
20pub struct CloseFrame<'a> {
21    /// Reason for the close.
22    pub code: u16,
23    /// Textual representation of the reason the connection is being closed.
24    pub reason: Cow<'a, str>,
25}
26
27impl<'a> CloseFrame<'a> {
28    /// Normal close code indicating the shard will not be reconnecting soon.
29    ///
30    /// This frame will cause Discord to invalidate your session. If you intend
31    /// to resume your session soon, use [`RESUME`].
32    ///
33    /// [`RESUME`]: Self::RESUME
34    pub const NORMAL: Self = Self::new(1000, "closing connection");
35
36    /// Close code indicating the shard will be reconnecting soon.
37    ///
38    /// This frame will cause Discord to keep your session alive. If you
39    /// **don't** intend to resume your session soon, use [`NORMAL`].
40    ///
41    /// [`NORMAL`]: Self::NORMAL
42    pub const RESUME: Self = Self::new(4000, "resuming connection");
43
44    /// Construct a close frame from a code and a reason why.
45    ///
46    /// # Examples
47    ///
48    /// ```
49    /// use twilight_model::gateway::CloseFrame;
50    ///
51    /// let frame = CloseFrame::new(1000, "reason here");
52    ///
53    /// assert_eq!(1000, frame.code);
54    /// assert_eq!("reason here", frame.reason);
55    /// ```
56    pub const fn new(code: u16, reason: &'a str) -> Self {
57        Self {
58            code,
59            reason: Cow::Borrowed(reason),
60        }
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::CloseFrame;
67    use static_assertions::assert_impl_all;
68    use std::fmt::Debug;
69
70    assert_impl_all!(
71        CloseFrame<'_>:
72        Clone,
73        Debug,
74        Eq,
75        PartialEq,
76    );
77}