Skip to main content

twitch_irc/connection/
mod.rs

1pub mod event_loop;
2
3use crate::config::ClientConfig;
4use crate::connection::event_loop::{ConnectionLoopCommand, ConnectionLoopWorker};
5use crate::error::Error;
6use crate::login::LoginCredentials;
7use crate::message::commands::ServerMessage;
8#[cfg(feature = "metrics-collection")]
9use crate::metrics::MetricsBundle;
10use crate::transport::Transport;
11use std::sync::Arc;
12use tokio::sync::mpsc;
13
14#[derive(Debug)]
15pub enum ConnectionIncomingMessage<T: Transport, L: LoginCredentials> {
16    IncomingMessage(Box<ServerMessage>),
17    #[cfg(feature = "metrics-collection")]
18    StateOpen,
19    StateClosed {
20        cause: Error<T, L>,
21    },
22}
23
24pub(crate) struct Connection<T: Transport, L: LoginCredentials> {
25    /// sends commands to the this connection's event loop.
26    pub connection_loop_tx: Arc<mpsc::UnboundedSender<ConnectionLoopCommand<T, L>>>,
27}
28
29impl<T: Transport, L: LoginCredentials> Connection<T, L> {
30    /// makes a tuple with the incoming messages and the `Connection` handle for outgoing
31    /// messages.
32    pub fn new(
33        config: Arc<ClientConfig<L>>,
34        connection_id: usize,
35        #[cfg(feature = "metrics-collection")] metrics: Option<MetricsBundle>,
36    ) -> (
37        mpsc::UnboundedReceiver<ConnectionIncomingMessage<T, L>>,
38        Connection<T, L>,
39    ) {
40        let (connection_loop_tx, connection_loop_rx) = mpsc::unbounded_channel();
41        let (connection_incoming_tx, connection_incoming_rx) = mpsc::unbounded_channel();
42        let connection_loop_tx = Arc::new(connection_loop_tx);
43
44        ConnectionLoopWorker::spawn(
45            config,
46            connection_incoming_tx,
47            Arc::downgrade(&connection_loop_tx),
48            connection_loop_rx,
49            connection_id,
50            #[cfg(feature = "metrics-collection")]
51            metrics,
52        );
53
54        (connection_incoming_rx, Connection { connection_loop_tx })
55    }
56}