Skip to main content

trillium_channels/
channel.rs

1use crate::{ChannelBroadcaster, ChannelCentral, ChannelEvent, ChannelHandler};
2use std::ops::{Deref, DerefMut};
3use trillium::{Conn, Handler, Upgrade};
4use trillium_websockets::{WebSocket, WebSocketConfig};
5
6/// Trillium handler containing a [`ChannelHandler`]
7///
8/// This is constructed from a [`ChannelHandler`] using [`Channel::new`]
9/// and dereferences to that type.
10///
11/// By default, a browser can only connect from a page on the same host as the
12/// socket. To serve pages from other origins, see [`Channel::allow_origins`].
13#[derive(Debug)]
14pub struct Channel<CH>(WebSocket<ChannelCentral<CH>>);
15
16impl<CH> Handler for Channel<CH>
17where
18    CH: ChannelHandler,
19{
20    async fn run(&self, conn: Conn) -> Conn {
21        self.0.run(conn).await
22    }
23
24    async fn init(&mut self, info: &mut trillium::Info) {
25        self.0.init(info).await;
26    }
27
28    async fn before_send(&self, conn: Conn) -> Conn {
29        self.0.before_send(conn).await
30    }
31
32    fn has_upgrade(&self, upgrade: &Upgrade) -> bool {
33        self.0.has_upgrade(upgrade)
34    }
35
36    async fn upgrade(&self, upgrade: Upgrade) {
37        self.0.upgrade(upgrade).await
38    }
39}
40
41impl<CH: ChannelHandler> Channel<CH> {
42    /// Constructs a new trillium Channel handler from the provided
43    /// [`ChannelHandler`] implementation
44    pub fn new(channel_handler: CH) -> Self {
45        Self(WebSocket::new(ChannelCentral::new(channel_handler)))
46    }
47
48    /// Accept connections only from pages on these origins.
49    ///
50    /// ```
51    /// # use trillium_channels::{Channel, ChannelConn, ChannelEvent, ChannelHandler};
52    /// # struct Chat; impl ChannelHandler for Chat {
53    /// #     async fn join_channel(&self, conn: ChannelConn<'_>, event: ChannelEvent) {}
54    /// # }
55    /// Channel::new(Chat).allow_origins(["https://app.example.com"]);
56    /// ```
57    ///
58    /// Origins are compared exactly, after normalizing default ports and idn hosts, never by
59    /// prefix or suffix. For a family of subdomains, use
60    /// [`allow_origin_fn`][Self::allow_origin_fn].
61    ///
62    /// A connection with no `Origin` header is allowed, as it did not come from a browser.
63    ///
64    /// # Panics
65    ///
66    /// Panics if any of the provided strings is not a url with a scheme and a host, or if it
67    /// carries a path, query, fragment, or userinfo.
68    pub fn allow_origins<'a>(self, origins: impl IntoIterator<Item = &'a str>) -> Self {
69        Self(self.0.allow_origins(origins))
70    }
71
72    /// Accept connections for which this predicate returns true.
73    ///
74    /// The argument is the raw `Origin` header, so `None` (a non-browser client) stays
75    /// distinguishable from `Some("null")` (a sandboxed iframe or a `file://` page, which is
76    /// attacker-reachable and should generally be rejected).
77    pub fn allow_origin_fn<F>(self, predicate: F) -> Self
78    where
79        F: Fn(Option<&str>) -> bool + Send + Sync + 'static,
80    {
81        Self(self.0.allow_origin_fn(predicate))
82    }
83
84    /// Accept connections from any origin, disabling the same-origin default.
85    ///
86    /// Any page on the web can then open a socket to this channel and act with the browser's
87    /// ambient authority — the visitor's cookies are attached to the connection. Only do this if
88    /// the socket is either unauthenticated or authenticated by something the page cannot
89    /// replay, such as a token in the socket's query string or join payload.
90    pub fn allow_any_origin(self) -> Self {
91        Self(self.0.allow_any_origin())
92    }
93
94    /// Configure the websocket protocol for every connection, such as the maximum message and
95    /// frame sizes.
96    pub fn with_protocol_config(self, config: WebSocketConfig) -> Self {
97        Self(self.0.with_protocol_config(config))
98    }
99
100    /// Retrieve a ChannelBroadcaster that can be moved elsewhere or cloned
101    /// in order to trigger channel events and listen for global events.
102    pub fn broadcaster(&self) -> ChannelBroadcaster {
103        self.0.channel_broadcaster()
104    }
105
106    /// Send a ChannelEvent to all connected clients that subscribe to the topic
107    pub fn broadcast(&self, event: impl Into<ChannelEvent>) {
108        self.0.broadcast(event);
109    }
110}
111
112impl<CH> Deref for Channel<CH> {
113    type Target = CH;
114
115    fn deref(&self) -> &Self::Target {
116        &self.0
117    }
118}
119
120impl<CH> DerefMut for Channel<CH> {
121    fn deref_mut(&mut self) -> &mut Self::Target {
122        &mut self.0
123    }
124}