Skip to main content

trillium_channels/
channel.rs

1use crate::{ChannelBroadcaster, ChannelCentral, ChannelEvent, ChannelHandler};
2use std::ops::{Deref, DerefMut};
3use trillium::{async_trait, Conn, Handler, Upgrade};
4use trillium_websockets::WebSocket;
5
6/**
7Trillium handler containing a [`ChannelHandler`]
8
9This is constructed from a [`ChannelHandler`] using [`Channel::new`]
10and dereferences to that type.
11*/
12#[derive(Debug)]
13pub struct Channel<CH>(WebSocket<ChannelCentral<CH>>);
14
15#[async_trait]
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    /**
43    Constructs a new trillium Channel handler from the provided
44    [`ChannelHandler`] implementation
45     */
46    pub fn new(channel_handler: CH) -> Self {
47        Self(WebSocket::new(ChannelCentral::new(channel_handler)))
48    }
49
50    /**
51    Retrieve a ChannelBroadcaster that can be moved elsewhere or cloned
52    in order to trigger channel events and listen for global events.
53     */
54    pub fn broadcaster(&self) -> ChannelBroadcaster {
55        self.0.channel_broadcaster()
56    }
57
58    /**
59    Send a ChannelEvent to all connected clients that subscribe to the topic
60     */
61    pub fn broadcast(&self, event: impl Into<ChannelEvent>) {
62        self.0.broadcast(event);
63    }
64}
65
66impl<CH> Deref for Channel<CH> {
67    type Target = CH;
68
69    fn deref(&self) -> &Self::Target {
70        &self.0
71    }
72}
73
74impl<CH> DerefMut for Channel<CH> {
75    fn deref_mut(&mut self) -> &mut Self::Target {
76        &mut self.0
77    }
78}