mwc_libp2p_core/network/
event.rs

1// Copyright 2018 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21//! Network events and associated information.
22
23use crate::{
24    Multiaddr,
25    connection::{
26        ConnectionId,
27        ConnectedPoint,
28        ConnectionError,
29        ConnectionHandler,
30        Connected,
31        EstablishedConnection,
32        IntoConnectionHandler,
33        ListenerId,
34        PendingConnectionError,
35    },
36    transport::Transport,
37    PeerId
38};
39use std::{fmt, num::NonZeroU32};
40
41/// Event that can happen on the `Network`.
42pub enum NetworkEvent<'a, TTrans, TInEvent, TOutEvent, THandler>
43where
44    TTrans: Transport,
45    THandler: IntoConnectionHandler,
46{
47    /// One of the listeners gracefully closed.
48    ListenerClosed {
49        /// The listener ID that closed.
50        listener_id: ListenerId,
51        /// The addresses that the listener was listening on.
52        addresses: Vec<Multiaddr>,
53        /// Reason for the closure. Contains `Ok(())` if the stream produced `None`, or `Err`
54        /// if the stream produced an error.
55        reason: Result<(), TTrans::Error>,
56    },
57
58    /// One of the listeners reported a non-fatal error.
59    ListenerError {
60        /// The listener that errored.
61        listener_id: ListenerId,
62        /// The listener error.
63        error: TTrans::Error
64    },
65
66    /// One of the listeners is now listening on an additional address.
67    NewListenerAddress {
68        /// The listener that is listening on the new address.
69        listener_id: ListenerId,
70        /// The new address the listener is now also listening on.
71        listen_addr: Multiaddr
72    },
73
74    /// One of the listeners is no longer listening on some address.
75    ExpiredListenerAddress {
76        /// The listener that is no longer listening on some address.
77        listener_id: ListenerId,
78        /// The expired address.
79        listen_addr: Multiaddr
80    },
81
82    /// A new connection arrived on a listener.
83    ///
84    /// To accept the connection, see [`Network::accept`](crate::Network::accept).
85    IncomingConnection {
86        /// The listener who received the connection.
87        listener_id: ListenerId,
88        /// The pending incoming connection.
89        connection: IncomingConnection<TTrans::ListenerUpgrade>,
90    },
91
92    /// An error happened on a connection during its initial handshake.
93    ///
94    /// This can include, for example, an error during the handshake of the encryption layer, or
95    /// the connection unexpectedly closed.
96    IncomingConnectionError {
97        /// Local connection address.
98        local_addr: Multiaddr,
99        /// Address used to send back data to the remote.
100        send_back_addr: Multiaddr,
101        /// The error that happened.
102        error: PendingConnectionError<TTrans::Error>,
103    },
104
105    /// A new connection to a peer has been established.
106    ConnectionEstablished {
107        /// The newly established connection.
108        connection: EstablishedConnection<'a, TInEvent>,
109        /// The total number of established connections to the same peer,
110        /// including the one that has just been opened.
111        num_established: NonZeroU32,
112    },
113
114    /// An established connection to a peer has been closed.
115    ///
116    /// A connection may close if
117    ///
118    ///   * it encounters an error, which includes the connection being
119    ///     closed by the remote. In this case `error` is `Some`.
120    ///   * it was actively closed by [`EstablishedConnection::start_close`],
121    ///     i.e. a successful, orderly close. In this case `error` is `None`.
122    ///   * it was actively closed by [`super::peer::ConnectedPeer::disconnect`] or
123    ///     [`super::peer::DialingPeer::disconnect`], i.e. dropped without an
124    ///     orderly close. In this case `error` is `None`.
125    ///
126    ConnectionClosed {
127        /// The ID of the connection that encountered an error.
128        id: ConnectionId,
129        /// Information about the connection that encountered the error.
130        connected: Connected,
131        /// The error that occurred.
132        error: Option<ConnectionError<<THandler::Handler as ConnectionHandler>::Error>>,
133        /// The remaining number of established connections to the same peer.
134        num_established: u32,
135    },
136
137    /// A dialing attempt to an address of a peer failed.
138    DialError {
139        /// The number of remaining dialing attempts.
140        attempts_remaining: u32,
141
142        /// Id of the peer we were trying to dial.
143        peer_id: PeerId,
144
145        /// The multiaddr we failed to reach.
146        multiaddr: Multiaddr,
147
148        /// The error that happened.
149        error: PendingConnectionError<TTrans::Error>,
150    },
151
152    /// Failed to reach a peer that we were trying to dial.
153    UnknownPeerDialError {
154        /// The multiaddr we failed to reach.
155        multiaddr: Multiaddr,
156
157        /// The error that happened.
158        error: PendingConnectionError<TTrans::Error>,
159    },
160
161    /// An established connection produced an event.
162    ConnectionEvent {
163        /// The connection on which the event occurred.
164        connection: EstablishedConnection<'a, TInEvent>,
165        /// Event that was produced by the node.
166        event: TOutEvent,
167    },
168
169    /// An established connection has changed its address.
170    AddressChange {
171        /// The connection whose address has changed.
172        connection: EstablishedConnection<'a, TInEvent>,
173        /// New endpoint of this connection.
174        new_endpoint: ConnectedPoint,
175        /// Old endpoint of this connection.
176        old_endpoint: ConnectedPoint,
177    },
178}
179
180impl<TTrans, TInEvent, TOutEvent, THandler> fmt::Debug for
181    NetworkEvent<'_, TTrans, TInEvent, TOutEvent, THandler>
182where
183    TInEvent: fmt::Debug,
184    TOutEvent: fmt::Debug,
185    TTrans: Transport,
186    TTrans::Error: fmt::Debug,
187    THandler: IntoConnectionHandler,
188    <THandler::Handler as ConnectionHandler>::Error: fmt::Debug,
189{
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
191        match self {
192            NetworkEvent::NewListenerAddress { listener_id, listen_addr } => {
193                f.debug_struct("NewListenerAddress")
194                    .field("listener_id", listener_id)
195                    .field("listen_addr", listen_addr)
196                    .finish()
197            }
198            NetworkEvent::ExpiredListenerAddress { listener_id, listen_addr } => {
199                f.debug_struct("ExpiredListenerAddress")
200                    .field("listener_id", listener_id)
201                    .field("listen_addr", listen_addr)
202                    .finish()
203            }
204            NetworkEvent::ListenerClosed { listener_id, addresses, reason } => {
205                f.debug_struct("ListenerClosed")
206                    .field("listener_id", listener_id)
207                    .field("addresses", addresses)
208                    .field("reason", reason)
209                    .finish()
210            }
211            NetworkEvent::ListenerError { listener_id, error } => {
212                f.debug_struct("ListenerError")
213                    .field("listener_id", listener_id)
214                    .field("error", error)
215                    .finish()
216            }
217            NetworkEvent::IncomingConnection { connection, .. } => {
218                f.debug_struct("IncomingConnection")
219                    .field("local_addr", &connection.local_addr)
220                    .field("send_back_addr", &connection.send_back_addr)
221                    .finish()
222            }
223            NetworkEvent::IncomingConnectionError { local_addr, send_back_addr, error } => {
224                f.debug_struct("IncomingConnectionError")
225                    .field("local_addr", local_addr)
226                    .field("send_back_addr", send_back_addr)
227                    .field("error", error)
228                    .finish()
229            }
230            NetworkEvent::ConnectionEstablished { connection, .. } => {
231                f.debug_struct("ConnectionEstablished")
232                    .field("connection", connection)
233                    .finish()
234            }
235            NetworkEvent::ConnectionClosed { id, connected, error, .. } => {
236                f.debug_struct("ConnectionClosed")
237                    .field("id", id)
238                    .field("connected", connected)
239                    .field("error", error)
240                    .finish()
241            }
242            NetworkEvent::DialError { attempts_remaining, peer_id, multiaddr, error } => {
243                f.debug_struct("DialError")
244                    .field("attempts_remaining", attempts_remaining)
245                    .field("peer_id", peer_id)
246                    .field("multiaddr", multiaddr)
247                    .field("error", error)
248                    .finish()
249            }
250            NetworkEvent::UnknownPeerDialError { multiaddr, error, .. } => {
251                f.debug_struct("UnknownPeerDialError")
252                    .field("multiaddr", multiaddr)
253                    .field("error", error)
254                    .finish()
255            }
256            NetworkEvent::ConnectionEvent { connection, event } => {
257                f.debug_struct("ConnectionEvent")
258                    .field("connection", connection)
259                    .field("event", event)
260                    .finish()
261            }
262            NetworkEvent::AddressChange { connection, new_endpoint, old_endpoint } => {
263                f.debug_struct("AddressChange")
264                    .field("connection", connection)
265                    .field("new_endpoint", new_endpoint)
266                    .field("old_endpoint", old_endpoint)
267                    .finish()
268            }
269        }
270    }
271}
272
273/// A pending incoming connection produced by a listener.
274pub struct IncomingConnection<TUpgrade> {
275    /// The connection upgrade.
276    pub(crate) upgrade: TUpgrade,
277    /// Local connection address.
278    pub local_addr: Multiaddr,
279    /// Address used to send back data to the remote.
280    pub send_back_addr: Multiaddr,
281}