cs_mwc_libp2p_swarm/
protocols_handler.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//! Once a connection to a remote peer is established, a `ProtocolsHandler` negotiates
22//! and handles one or more specific protocols on the connection.
23//!
24//! Protocols are negotiated and used on individual substreams of the connection.
25//! Thus a `ProtocolsHandler` defines the inbound and outbound upgrades to apply
26//! when creating a new inbound or outbound substream, respectively, and is notified
27//! by a `Swarm` when these upgrades have been successfully applied, including the
28//! final output of the upgrade. A `ProtocolsHandler` can then continue communicating
29//! with the peer over the substream using the negotiated protocol(s).
30//!
31//! Two `ProtocolsHandler`s can be composed with [`ProtocolsHandler::select()`]
32//! in order to build a new handler supporting the combined set of protocols,
33//! with methods being dispatched to the appropriate handler according to the
34//! used protocol(s) determined by the associated types of the handlers.
35//!
36//! > **Note**: A `ProtocolsHandler` handles one or more protocols in the context of a single
37//! >           connection with a remote. In order to handle a protocol that requires knowledge of
38//! >           the network as a whole, see the `NetworkBehaviour` trait.
39
40mod dummy;
41mod map_in;
42mod map_out;
43mod node_handler;
44mod one_shot;
45mod select;
46pub mod multi;
47
48pub use crate::upgrade::{
49    InboundUpgradeSend,
50    OutboundUpgradeSend,
51    UpgradeInfoSend,
52};
53
54use mwc_libp2p_core::{
55    ConnectedPoint,
56    Multiaddr,
57    PeerId,
58    upgrade::{self, UpgradeError},
59};
60use std::{cmp::Ordering, error, fmt, task::Context, task::Poll, time::Duration};
61use wasm_timer::Instant;
62
63pub use dummy::DummyProtocolsHandler;
64pub use map_in::MapInEvent;
65pub use map_out::MapOutEvent;
66pub use node_handler::{NodeHandlerWrapper, NodeHandlerWrapperBuilder, NodeHandlerWrapperError};
67pub use one_shot::{OneShotHandler, OneShotHandlerConfig};
68pub use select::{IntoProtocolsHandlerSelect, ProtocolsHandlerSelect};
69
70/// A handler for a set of protocols used on a connection with a remote.
71///
72/// This trait should be implemented for a type that maintains the state for
73/// the execution of a specific protocol with a remote.
74///
75/// # Handling a protocol
76///
77/// Communication with a remote over a set of protocols is initiated in one of two ways:
78///
79///   1. Dialing by initiating a new outbound substream. In order to do so,
80///      [`ProtocolsHandler::poll()`] must return an [`ProtocolsHandlerEvent::OutboundSubstreamRequest`],
81///      providing an instance of [`mwc_libp2p_core::upgrade::OutboundUpgrade`] that is used to negotiate the
82///      protocol(s). Upon success, [`ProtocolsHandler::inject_fully_negotiated_outbound`]
83///      is called with the final output of the upgrade.
84///
85///   2. Listening by accepting a new inbound substream. When a new inbound substream
86///      is created on a connection, [`ProtocolsHandler::listen_protocol`] is called
87///      to obtain an instance of [`mwc_libp2p_core::upgrade::InboundUpgrade`] that is used to
88///      negotiate the protocol(s). Upon success,
89///      [`ProtocolsHandler::inject_fully_negotiated_inbound`] is called with the final
90///      output of the upgrade.
91///
92/// # Connection Keep-Alive
93///
94/// A `ProtocolsHandler` can influence the lifetime of the underlying connection
95/// through [`ProtocolsHandler::connection_keep_alive`]. That is, the protocol
96/// implemented by the handler can include conditions for terminating the connection.
97/// The lifetime of successfully negotiated substreams is fully controlled by the handler.
98///
99/// Implementors of this trait should keep in mind that the connection can be closed at any time.
100/// When a connection is closed gracefully, the substreams used by the handler may still
101/// continue reading data until the remote closes its side of the connection.
102pub trait ProtocolsHandler: Send + 'static {
103    /// Custom event that can be received from the outside.
104    type InEvent: Send + 'static;
105    /// Custom event that can be produced by the handler and that will be returned to the outside.
106    type OutEvent: Send + 'static;
107    /// The type of errors returned by [`ProtocolsHandler::poll`].
108    type Error: error::Error + Send + 'static;
109    /// The inbound upgrade for the protocol(s) used by the handler.
110    type InboundProtocol: InboundUpgradeSend;
111    /// The outbound upgrade for the protocol(s) used by the handler.
112    type OutboundProtocol: OutboundUpgradeSend;
113    /// The type of additional information returned from `listen_protocol`.
114    type InboundOpenInfo: Send + 'static;
115    /// The type of additional information passed to an `OutboundSubstreamRequest`.
116    type OutboundOpenInfo: Send + 'static;
117
118    /// The [`InboundUpgrade`](mwc_libp2p_core::upgrade::InboundUpgrade) to apply on inbound
119    /// substreams to negotiate the desired protocols.
120    ///
121    /// > **Note**: The returned `InboundUpgrade` should always accept all the generally
122    /// >           supported protocols, even if in a specific context a particular one is
123    /// >           not supported, (eg. when only allowing one substream at a time for a protocol).
124    /// >           This allows a remote to put the list of supported protocols in a cache.
125    fn listen_protocol(&self) -> SubstreamProtocol<Self::InboundProtocol, Self::InboundOpenInfo>;
126
127    /// Injects the output of a successful upgrade on a new inbound substream.
128    fn inject_fully_negotiated_inbound(
129        &mut self,
130        protocol: <Self::InboundProtocol as InboundUpgradeSend>::Output,
131        info: Self::InboundOpenInfo
132    );
133
134    /// Injects the output of a successful upgrade on a new outbound substream.
135    ///
136    /// The second argument is the information that was previously passed to
137    /// [`ProtocolsHandlerEvent::OutboundSubstreamRequest`].
138    fn inject_fully_negotiated_outbound(
139        &mut self,
140        protocol: <Self::OutboundProtocol as OutboundUpgradeSend>::Output,
141        info: Self::OutboundOpenInfo
142    );
143
144    /// Injects an event coming from the outside in the handler.
145    fn inject_event(&mut self, event: Self::InEvent);
146
147    /// Notifies the handler of a change in the address of the remote.
148    fn inject_address_change(&mut self, _new_address: &Multiaddr) {}
149
150    /// Indicates to the handler that upgrading an outbound substream to the given protocol has failed.
151    fn inject_dial_upgrade_error(
152        &mut self,
153        info: Self::OutboundOpenInfo,
154        error: ProtocolsHandlerUpgrErr<
155            <Self::OutboundProtocol as OutboundUpgradeSend>::Error
156        >
157    );
158
159    /// Indicates to the handler that upgrading an inbound substream to the given protocol has failed.
160    fn inject_listen_upgrade_error(
161        &mut self,
162        _: Self::InboundOpenInfo,
163        _: ProtocolsHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>
164    ) {}
165
166    /// Returns until when the connection should be kept alive.
167    ///
168    /// This method is called by the `Swarm` after each invocation of
169    /// [`ProtocolsHandler::poll`] to determine if the connection and the associated
170    /// `ProtocolsHandler`s should be kept alive as far as this handler is concerned
171    /// and if so, for how long.
172    ///
173    /// Returning [`KeepAlive::No`] indicates that the connection should be
174    /// closed and this handler destroyed immediately.
175    ///
176    /// Returning [`KeepAlive::Until`] indicates that the connection may be closed
177    /// and this handler destroyed after the specified `Instant`.
178    ///
179    /// Returning [`KeepAlive::Yes`] indicates that the connection should
180    /// be kept alive until the next call to this method.
181    ///
182    /// > **Note**: The connection is always closed and the handler destroyed
183    /// > when [`ProtocolsHandler::poll`] returns an error. Furthermore, the
184    /// > connection may be closed for reasons outside of the control
185    /// > of the handler.
186    fn connection_keep_alive(&self) -> KeepAlive;
187
188    /// Should behave like `Stream::poll()`.
189    fn poll(&mut self, cx: &mut Context<'_>) -> Poll<
190        ProtocolsHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, Self::Error>
191    >;
192
193    /// Adds a closure that turns the input event into something else.
194    fn map_in_event<TNewIn, TMap>(self, map: TMap) -> MapInEvent<Self, TNewIn, TMap>
195    where
196        Self: Sized,
197        TMap: Fn(&TNewIn) -> Option<&Self::InEvent>,
198    {
199        MapInEvent::new(self, map)
200    }
201
202    /// Adds a closure that turns the output event into something else.
203    fn map_out_event<TMap, TNewOut>(self, map: TMap) -> MapOutEvent<Self, TMap>
204    where
205        Self: Sized,
206        TMap: FnMut(Self::OutEvent) -> TNewOut,
207    {
208        MapOutEvent::new(self, map)
209    }
210
211    /// Creates a new `ProtocolsHandler` that selects either this handler or
212    /// `other` by delegating methods calls appropriately.
213    ///
214    /// > **Note**: The largest `KeepAlive` returned by the two handlers takes precedence,
215    /// > i.e. is returned from [`ProtocolsHandler::connection_keep_alive`] by the returned
216    /// > handler.
217    fn select<TProto2>(self, other: TProto2) -> ProtocolsHandlerSelect<Self, TProto2>
218    where
219        Self: Sized,
220    {
221        ProtocolsHandlerSelect::new(self, other)
222    }
223
224    /// Creates a builder that allows creating a `NodeHandler` that handles this protocol
225    /// exclusively.
226    ///
227    /// > **Note**: This method should not be redefined in a custom `ProtocolsHandler`.
228    fn into_node_handler_builder(self) -> NodeHandlerWrapperBuilder<Self>
229    where
230        Self: Sized,
231    {
232        IntoProtocolsHandler::into_node_handler_builder(self)
233    }
234}
235
236/// Configuration of inbound or outbound substream protocol(s)
237/// for a [`ProtocolsHandler`].
238///
239/// The inbound substream protocol(s) are defined by [`ProtocolsHandler::listen_protocol`]
240/// and the outbound substream protocol(s) by [`ProtocolsHandlerEvent::OutboundSubstreamRequest`].
241#[derive(Copy, Clone, Debug, PartialEq, Eq)]
242pub struct SubstreamProtocol<TUpgrade, TInfo> {
243    upgrade: TUpgrade,
244    info: TInfo,
245    upgrade_protocol: upgrade::Version,
246    timeout: Duration,
247}
248
249impl<TUpgrade, TInfo> SubstreamProtocol<TUpgrade, TInfo> {
250    /// Create a new `SubstreamProtocol` from the given upgrade.
251    ///
252    /// The default timeout for applying the given upgrade on a substream is
253    /// 10 seconds.
254    pub fn new(upgrade: TUpgrade, info: TInfo) -> Self {
255        SubstreamProtocol {
256            upgrade,
257            info,
258            upgrade_protocol: upgrade::Version::V1,
259            timeout: Duration::from_secs(30),
260        }
261    }
262
263    /// Sets the multistream-select protocol (version) to use for negotiating
264    /// protocols upgrades on outbound substreams.
265    pub fn with_upgrade_protocol(mut self, version: upgrade::Version) -> Self {
266        self.upgrade_protocol = version;
267        self
268    }
269
270    /// Maps a function over the protocol upgrade.
271    pub fn map_upgrade<U, F>(self, f: F) -> SubstreamProtocol<U, TInfo>
272    where
273        F: FnOnce(TUpgrade) -> U,
274    {
275        SubstreamProtocol {
276            upgrade: f(self.upgrade),
277            info: self.info,
278            upgrade_protocol: self.upgrade_protocol,
279            timeout: self.timeout,
280        }
281    }
282
283    /// Maps a function over the protocol info.
284    pub fn map_info<U, F>(self, f: F) -> SubstreamProtocol<TUpgrade, U>
285    where
286        F: FnOnce(TInfo) -> U,
287    {
288        SubstreamProtocol {
289            upgrade: self.upgrade,
290            info: f(self.info),
291            upgrade_protocol: self.upgrade_protocol,
292            timeout: self.timeout,
293        }
294    }
295
296    /// Sets a new timeout for the protocol upgrade.
297    pub fn with_timeout(mut self, timeout: Duration) -> Self {
298        self.timeout = timeout;
299        self
300    }
301
302    /// Borrows the contained protocol upgrade.
303    pub fn upgrade(&self) -> &TUpgrade {
304        &self.upgrade
305    }
306
307    /// Borrows the contained protocol info.
308    pub fn info(&self) -> &TInfo {
309        &self.info
310    }
311
312    /// Borrows the timeout for the protocol upgrade.
313    pub fn timeout(&self) -> &Duration {
314        &self.timeout
315    }
316
317    /// Converts the substream protocol configuration into the contained upgrade.
318    pub fn into_upgrade(self) -> (upgrade::Version, TUpgrade, TInfo) {
319        (self.upgrade_protocol, self.upgrade, self.info)
320    }
321}
322
323/// Event produced by a handler.
324#[derive(Debug, Copy, Clone, PartialEq, Eq)]
325pub enum ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr> {
326    /// Request a new outbound substream to be opened with the remote.
327    OutboundSubstreamRequest {
328        /// The protocol(s) to apply on the substream.
329        protocol: SubstreamProtocol<TConnectionUpgrade, TOutboundOpenInfo>
330    },
331
332    /// Close the connection for the given reason.
333    Close(TErr),
334
335    /// Other event.
336    Custom(TCustom),
337}
338
339/// Event produced by a handler.
340impl<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr>
341    ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr>
342{
343    /// If this is an `OutboundSubstreamRequest`, maps the `info` member from a
344    /// `TOutboundOpenInfo` to something else.
345    pub fn map_outbound_open_info<F, I>(
346        self,
347        map: F,
348    ) -> ProtocolsHandlerEvent<TConnectionUpgrade, I, TCustom, TErr>
349    where
350        F: FnOnce(TOutboundOpenInfo) -> I,
351    {
352        match self {
353            ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => {
354                ProtocolsHandlerEvent::OutboundSubstreamRequest {
355                    protocol: protocol.map_info(map)
356                }
357            }
358            ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(val),
359            ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(val),
360        }
361    }
362
363    /// If this is an `OutboundSubstreamRequest`, maps the protocol (`TConnectionUpgrade`)
364    /// to something else.
365    pub fn map_protocol<F, I>(
366        self,
367        map: F,
368    ) -> ProtocolsHandlerEvent<I, TOutboundOpenInfo, TCustom, TErr>
369    where
370        F: FnOnce(TConnectionUpgrade) -> I,
371    {
372        match self {
373            ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => {
374                ProtocolsHandlerEvent::OutboundSubstreamRequest {
375                    protocol: protocol.map_upgrade(map)
376                }
377            }
378            ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(val),
379            ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(val),
380        }
381    }
382
383    /// If this is a `Custom` event, maps the content to something else.
384    pub fn map_custom<F, I>(
385        self,
386        map: F,
387    ) -> ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, I, TErr>
388    where
389        F: FnOnce(TCustom) -> I,
390    {
391        match self {
392            ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => {
393                ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol }
394            }
395            ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(map(val)),
396            ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(val),
397        }
398    }
399
400    /// If this is a `Close` event, maps the content to something else.
401    pub fn map_close<F, I>(
402        self,
403        map: F,
404    ) -> ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, I>
405    where
406        F: FnOnce(TErr) -> I,
407    {
408        match self {
409            ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => {
410                ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol }
411            }
412            ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(val),
413            ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(map(val)),
414        }
415    }
416}
417
418/// Error that can happen on an outbound substream opening attempt.
419#[derive(Debug)]
420pub enum ProtocolsHandlerUpgrErr<TUpgrErr> {
421    /// The opening attempt timed out before the negotiation was fully completed.
422    Timeout,
423    /// There was an error in the timer used.
424    Timer,
425    /// Error while upgrading the substream to the protocol we want.
426    Upgrade(UpgradeError<TUpgrErr>),
427}
428
429impl<TUpgrErr> ProtocolsHandlerUpgrErr<TUpgrErr> {
430    /// Map the inner [`UpgradeError`] type.
431    pub fn map_upgrade_err<F, E>(self, f: F) -> ProtocolsHandlerUpgrErr<E>
432    where
433        F: FnOnce(UpgradeError<TUpgrErr>) -> UpgradeError<E>
434    {
435        match self {
436            ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout,
437            ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer,
438            ProtocolsHandlerUpgrErr::Upgrade(e) => ProtocolsHandlerUpgrErr::Upgrade(f(e))
439        }
440    }
441}
442
443impl<TUpgrErr> fmt::Display for ProtocolsHandlerUpgrErr<TUpgrErr>
444where
445    TUpgrErr: fmt::Display,
446{
447    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448        match self {
449            ProtocolsHandlerUpgrErr::Timeout => {
450                write!(f, "Timeout error while opening a substream")
451            },
452            ProtocolsHandlerUpgrErr::Timer => {
453                write!(f, "Timer error while opening a substream")
454            },
455            ProtocolsHandlerUpgrErr::Upgrade(err) => write!(f, "{}", err),
456        }
457    }
458}
459
460impl<TUpgrErr> error::Error for ProtocolsHandlerUpgrErr<TUpgrErr>
461where
462    TUpgrErr: error::Error + 'static
463{
464    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
465        match self {
466            ProtocolsHandlerUpgrErr::Timeout => None,
467            ProtocolsHandlerUpgrErr::Timer => None,
468            ProtocolsHandlerUpgrErr::Upgrade(err) => Some(err),
469        }
470    }
471}
472
473/// Prototype for a `ProtocolsHandler`.
474pub trait IntoProtocolsHandler: Send + 'static {
475    /// The protocols handler.
476    type Handler: ProtocolsHandler;
477
478    /// Builds the protocols handler.
479    ///
480    /// The `PeerId` is the id of the node the handler is going to handle.
481    fn into_handler(self, remote_peer_id: &PeerId, connected_point: &ConnectedPoint) -> Self::Handler;
482
483    /// Return the handler's inbound protocol.
484    fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol;
485
486    /// Builds an implementation of `IntoProtocolsHandler` that handles both this protocol and the
487    /// other one together.
488    fn select<TProto2>(self, other: TProto2) -> IntoProtocolsHandlerSelect<Self, TProto2>
489    where
490        Self: Sized,
491    {
492        IntoProtocolsHandlerSelect::new(self, other)
493    }
494
495    /// Creates a builder that will allow creating a `NodeHandler` that handles this protocol
496    /// exclusively.
497    fn into_node_handler_builder(self) -> NodeHandlerWrapperBuilder<Self>
498    where
499        Self: Sized,
500    {
501        NodeHandlerWrapperBuilder::new(self)
502    }
503}
504
505impl<T> IntoProtocolsHandler for T
506where T: ProtocolsHandler
507{
508    type Handler = Self;
509
510    fn into_handler(self, _: &PeerId, _: &ConnectedPoint) -> Self {
511        self
512    }
513
514    fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol {
515        self.listen_protocol().into_upgrade().1
516    }
517}
518
519/// How long the connection should be kept alive.
520#[derive(Debug, Copy, Clone, PartialEq, Eq)]
521pub enum KeepAlive {
522    /// If nothing new happens, the connection should be closed at the given `Instant`.
523    Until(Instant),
524    /// Keep the connection alive.
525    Yes,
526    /// Close the connection as soon as possible.
527    No,
528}
529
530impl KeepAlive {
531    /// Returns true for `Yes`, false otherwise.
532    pub fn is_yes(&self) -> bool {
533        match *self {
534            KeepAlive::Yes => true,
535            _ => false,
536        }
537    }
538}
539
540impl PartialOrd for KeepAlive {
541    fn partial_cmp(&self, other: &KeepAlive) -> Option<Ordering> {
542        Some(self.cmp(other))
543    }
544}
545
546impl Ord for KeepAlive {
547    fn cmp(&self, other: &KeepAlive) -> Ordering {
548        use self::KeepAlive::*;
549
550        match (self, other) {
551            (No, No) | (Yes, Yes)  => Ordering::Equal,
552            (No,  _) | (_,   Yes)  => Ordering::Less,
553            (_,  No) | (Yes,   _)  => Ordering::Greater,
554            (Until(t1), Until(t2)) => t1.cmp(t2),
555        }
556    }
557}