libp2p_core/muxing.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//! Muxing is the process of splitting a connection into multiple substreams.
22//!
23//! The main item of this module is the `StreamMuxer` trait. An implementation of `StreamMuxer`
24//! has ownership of a connection, lets you open and close substreams.
25//!
26//! > **Note**: You normally don't need to use the methods of the `StreamMuxer` directly, as this
27//! > is managed by the library's internals.
28//!
29//! Each substream of a connection is an isolated stream of data. All the substreams are muxed
30//! together so that the data read from or written to each substream doesn't influence the other
31//! substreams.
32//!
33//! In the context of libp2p, each substream can use a different protocol. Contrary to opening a
34//! connection, opening a substream is almost free in terms of resources. This means that you
35//! shouldn't hesitate to rapidly open and close substreams, and to design protocols that don't
36//! require maintaining long-lived channels of communication.
37//!
38//! > **Example**: The Kademlia protocol opens a new substream for each request it wants to
39//! > perform. Multiple requests can be performed simultaneously by opening multiple
40//! > substreams, without having to worry about associating responses with the
41//! > right request.
42//!
43//! # Implementing a muxing protocol
44//!
45//! In order to implement a muxing protocol, create an object that implements the `UpgradeInfo`,
46//! `InboundUpgrade` and `OutboundUpgrade` traits. See the `upgrade` module for more information.
47//! The `Output` associated type of the `InboundUpgrade` and `OutboundUpgrade` traits should be
48//! identical, and should be an object that implements the `StreamMuxer` trait.
49//!
50//! The upgrade process will take ownership of the connection, which makes it possible for the
51//! implementation of `StreamMuxer` to control everything that happens on the wire.
52
53use futures::{task::Context, task::Poll, AsyncRead, AsyncWrite};
54use multiaddr::Multiaddr;
55use std::future::Future;
56use std::pin::Pin;
57
58pub use self::boxed::StreamMuxerBox;
59pub use self::boxed::SubstreamBox;
60
61mod boxed;
62
63/// Provides multiplexing for a connection by allowing users to open substreams.
64///
65/// A substream created by a [`StreamMuxer`] is a type that implements [`AsyncRead`] and [`AsyncWrite`].
66/// The [`StreamMuxer`] itself is modelled closely after [`AsyncWrite`]. It features `poll`-style
67/// functions that allow the implementation to make progress on various tasks.
68pub trait StreamMuxer {
69 /// Type of the object that represents the raw substream where data can be read and written.
70 type Substream: AsyncRead + AsyncWrite;
71
72 /// Error type of the muxer
73 type Error: std::error::Error;
74
75 /// Poll for new inbound substreams.
76 ///
77 /// This function should be called whenever callers are ready to accept more inbound streams. In
78 /// other words, callers may exercise back-pressure on incoming streams by not calling this
79 /// function if a certain limit is hit.
80 fn poll_inbound(
81 self: Pin<&mut Self>,
82 cx: &mut Context<'_>,
83 ) -> Poll<Result<Self::Substream, Self::Error>>;
84
85 /// Poll for a new, outbound substream.
86 fn poll_outbound(
87 self: Pin<&mut Self>,
88 cx: &mut Context<'_>,
89 ) -> Poll<Result<Self::Substream, Self::Error>>;
90
91 /// Poll to close this [`StreamMuxer`].
92 ///
93 /// After this has returned `Poll::Ready(Ok(()))`, the muxer has become useless and may be safely
94 /// dropped.
95 ///
96 /// > **Note**: You are encouraged to call this method and wait for it to return `Ready`, so
97 /// > that the remote is properly informed of the shutdown. However, apart from
98 /// > properly informing the remote, there is no difference between this and
99 /// > immediately dropping the muxer.
100 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
101
102 /// Poll to allow the underlying connection to make progress.
103 ///
104 /// In contrast to all other `poll`-functions on [`StreamMuxer`], this function MUST be called
105 /// unconditionally. Because it will be called regardless, this function can be used by
106 /// implementations to return events about the underlying connection that the caller MUST deal
107 /// with.
108 fn poll(
109 self: Pin<&mut Self>,
110 cx: &mut Context<'_>,
111 ) -> Poll<Result<StreamMuxerEvent, Self::Error>>;
112}
113
114/// An event produced by a [`StreamMuxer`].
115#[derive(Debug)]
116pub enum StreamMuxerEvent {
117 /// The address of the remote has changed.
118 AddressChange(Multiaddr),
119}
120
121/// Extension trait for [`StreamMuxer`].
122pub trait StreamMuxerExt: StreamMuxer + Sized {
123 /// Convenience function for calling [`StreamMuxer::poll_inbound`] for [`StreamMuxer`]s that are `Unpin`.
124 fn poll_inbound_unpin(
125 &mut self,
126 cx: &mut Context<'_>,
127 ) -> Poll<Result<Self::Substream, Self::Error>>
128 where
129 Self: Unpin,
130 {
131 Pin::new(self).poll_inbound(cx)
132 }
133
134 /// Convenience function for calling [`StreamMuxer::poll_outbound`] for [`StreamMuxer`]s that are `Unpin`.
135 fn poll_outbound_unpin(
136 &mut self,
137 cx: &mut Context<'_>,
138 ) -> Poll<Result<Self::Substream, Self::Error>>
139 where
140 Self: Unpin,
141 {
142 Pin::new(self).poll_outbound(cx)
143 }
144
145 /// Convenience function for calling [`StreamMuxer::poll`] for [`StreamMuxer`]s that are `Unpin`.
146 fn poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Result<StreamMuxerEvent, Self::Error>>
147 where
148 Self: Unpin,
149 {
150 Pin::new(self).poll(cx)
151 }
152
153 /// Convenience function for calling [`StreamMuxer::poll_close`] for [`StreamMuxer`]s that are `Unpin`.
154 fn poll_close_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>
155 where
156 Self: Unpin,
157 {
158 Pin::new(self).poll_close(cx)
159 }
160
161 /// Returns a future for closing this [`StreamMuxer`].
162 fn close(self) -> Close<Self> {
163 Close(self)
164 }
165}
166
167impl<S> StreamMuxerExt for S where S: StreamMuxer {}
168
169pub struct Close<S>(S);
170
171impl<S> Future for Close<S>
172where
173 S: StreamMuxer + Unpin,
174{
175 type Output = Result<(), S::Error>;
176
177 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
178 self.0.poll_close_unpin(cx)
179 }
180}