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;
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#[derive(Debug)]
11pub struct Channel<CH>(WebSocket<ChannelCentral<CH>>);
12
13impl<CH> Handler for Channel<CH>
14where
15    CH: ChannelHandler,
16{
17    async fn run(&self, conn: Conn) -> Conn {
18        self.0.run(conn).await
19    }
20
21    async fn init(&mut self, info: &mut trillium::Info) {
22        self.0.init(info).await;
23    }
24
25    async fn before_send(&self, conn: Conn) -> Conn {
26        self.0.before_send(conn).await
27    }
28
29    fn has_upgrade(&self, upgrade: &Upgrade) -> bool {
30        self.0.has_upgrade(upgrade)
31    }
32
33    async fn upgrade(&self, upgrade: Upgrade) {
34        self.0.upgrade(upgrade).await
35    }
36}
37
38impl<CH: ChannelHandler> Channel<CH> {
39    /// Constructs a new trillium Channel handler from the provided
40    /// [`ChannelHandler`] implementation
41    pub fn new(channel_handler: CH) -> Self {
42        Self(WebSocket::new(ChannelCentral::new(channel_handler)))
43    }
44
45    /// Retrieve a ChannelBroadcaster that can be moved elsewhere or cloned
46    /// in order to trigger channel events and listen for global events.
47    pub fn broadcaster(&self) -> ChannelBroadcaster {
48        self.0.channel_broadcaster()
49    }
50
51    /// Send a ChannelEvent to all connected clients that subscribe to the topic
52    pub fn broadcast(&self, event: impl Into<ChannelEvent>) {
53        self.0.broadcast(event);
54    }
55}
56
57impl<CH> Deref for Channel<CH> {
58    type Target = CH;
59
60    fn deref(&self) -> &Self::Target {
61        &self.0
62    }
63}
64
65impl<CH> DerefMut for Channel<CH> {
66    fn deref_mut(&mut self) -> &mut Self::Target {
67        &mut self.0
68    }
69}