aboutsummaryrefslogtreecommitdiff
path: root/p2p/src/listener.rs
blob: 347099dee88afccd445e8b2cea67ee926ab49e02 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
use std::{future::Future, sync::Arc};

use log::{debug, error, info};

use karyon_core::{
    async_runtime::Executor,
    async_util::{TaskGroup, TaskResult},
    crypto::KeyPair,
};

use karyon_net::{tcp, tls, Conn, Endpoint};

use crate::{
    codec::NetMsgCodec,
    message::NetMsg,
    monitor::{ConnEvent, Monitor},
    slots::ConnectionSlots,
    tls_config::tls_server_config,
    Error, Result,
};

/// Responsible for creating inbound connections with other peers.
pub struct Listener {
    /// Identity Key pair
    key_pair: KeyPair,

    /// Managing spawned tasks.
    task_group: TaskGroup,

    /// Manages available inbound slots.
    connection_slots: Arc<ConnectionSlots>,

    /// Enables secure connection.
    enable_tls: bool,

    /// Responsible for network and system monitoring.
    monitor: Arc<Monitor>,
}

impl Listener {
    /// Creates a new Listener
    pub fn new(
        key_pair: &KeyPair,
        connection_slots: Arc<ConnectionSlots>,
        enable_tls: bool,
        monitor: Arc<Monitor>,
        ex: Executor,
    ) -> Arc<Self> {
        Arc::new(Self {
            key_pair: key_pair.clone(),
            connection_slots,
            task_group: TaskGroup::with_executor(ex),
            enable_tls,
            monitor,
        })
    }

    /// Starts a listener on the given `endpoint`. For each incoming connection
    /// that is accepted, it invokes the provided `callback`, and pass the
    /// connection to the callback.
    ///
    /// Returns the resloved listening endpoint.
    pub async fn start<Fut>(
        self: &Arc<Self>,
        endpoint: Endpoint,
        // https://github.com/rust-lang/rfcs/pull/2132
        callback: impl FnOnce(Conn<NetMsg>) -> Fut + Clone + Send + 'static,
    ) -> Result<Endpoint>
    where
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        let listener = match self.listen(&endpoint).await {
            Ok(listener) => {
                self.monitor
                    .notify(ConnEvent::Listening(endpoint.clone()))
                    .await;
                listener
            }
            Err(err) => {
                error!("Failed to listen on {endpoint}: {err}");
                self.monitor.notify(ConnEvent::ListenFailed(endpoint)).await;
                return Err(err);
            }
        };

        let resolved_endpoint = listener.local_endpoint().map_err(Error::from)?;

        info!("Start listening on {resolved_endpoint}");

        self.task_group.spawn(
            {
                let this = self.clone();
                async move { this.listen_loop(listener, callback).await }
            },
            |_| async {},
        );
        Ok(resolved_endpoint)
    }

    /// Shuts down the listener
    pub async fn shutdown(&self) {
        self.task_group.cancel().await;
    }

    async fn listen_loop<Fut>(
        self: Arc<Self>,
        listener: karyon_net::Listener<NetMsg>,
        callback: impl FnOnce(Conn<NetMsg>) -> Fut + Clone + Send + 'static,
    ) where
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        loop {
            // Wait for an available inbound slot.
            self.connection_slots.wait_for_slot().await;
            let result = listener.accept().await;

            let (conn, endpoint) = match result {
                Ok(c) => {
                    let endpoint = match c.peer_endpoint() {
                        Ok(ep) => ep,
                        Err(err) => {
                            self.monitor.notify(ConnEvent::AcceptFailed).await;
                            error!("Failed to accept a new connection: {err}");
                            continue;
                        }
                    };

                    self.monitor
                        .notify(ConnEvent::Accepted(endpoint.clone()))
                        .await;
                    (c, endpoint)
                }
                Err(err) => {
                    error!("Failed to accept a new connection: {err}");
                    self.monitor.notify(ConnEvent::AcceptFailed).await;
                    continue;
                }
            };

            self.connection_slots.add();

            let on_disconnect = {
                let this = self.clone();
                |res| async move {
                    if let TaskResult::Completed(Err(err)) = res {
                        debug!("Inbound connection dropped: {err}");
                    }
                    this.monitor.notify(ConnEvent::Disconnected(endpoint)).await;
                    this.connection_slots.remove().await;
                }
            };

            let callback = callback.clone();
            self.task_group.spawn(callback(conn), on_disconnect);
        }
    }

    async fn listen(&self, endpoint: &Endpoint) -> Result<karyon_net::Listener<NetMsg>> {
        if self.enable_tls {
            if !endpoint.is_tcp() && !endpoint.is_tls() {
                return Err(Error::UnsupportedEndpoint(endpoint.to_string()));
            }

            let tls_config = tls::ServerTlsConfig {
                tcp_config: Default::default(),
                server_config: tls_server_config(&self.key_pair)?,
            };
            tls::listen(endpoint, tls_config, NetMsgCodec::new())
                .await
                .map(|l| Box::new(l) as karyon_net::Listener<NetMsg>)
        } else {
            if !endpoint.is_tcp() {
                return Err(Error::UnsupportedEndpoint(endpoint.to_string()));
            }

            tcp::listen(endpoint, tcp::TcpConfig::default(), NetMsgCodec::new())
                .await
                .map(|l| Box::new(l) as karyon_net::Listener<NetMsg>)
        }
        .map_err(Error::KaryonNet)
    }
}