libp2p_swarm/handler/
select.rs

1// Copyright 2019 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
21use crate::handler::{
22    AddressChange, ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, DialUpgradeError,
23    FullyNegotiatedInbound, FullyNegotiatedOutbound, InboundUpgradeSend, ListenUpgradeError,
24    OutboundUpgradeSend, StreamUpgradeError, SubstreamProtocol,
25};
26use crate::upgrade::SendWrapper;
27use either::Either;
28use futures::{future, ready};
29use libp2p_core::upgrade::SelectUpgrade;
30use std::{cmp, task::Context, task::Poll};
31
32/// Implementation of [`ConnectionHandler`] that combines two protocols into one.
33#[derive(Debug, Clone)]
34pub struct ConnectionHandlerSelect<TProto1, TProto2> {
35    /// The first protocol.
36    proto1: TProto1,
37    /// The second protocol.
38    proto2: TProto2,
39}
40
41impl<TProto1, TProto2> ConnectionHandlerSelect<TProto1, TProto2> {
42    /// Builds a [`ConnectionHandlerSelect`].
43    pub(crate) fn new(proto1: TProto1, proto2: TProto2) -> Self {
44        ConnectionHandlerSelect { proto1, proto2 }
45    }
46
47    pub fn into_inner(self) -> (TProto1, TProto2) {
48        (self.proto1, self.proto2)
49    }
50}
51
52impl<S1OOI, S2OOI, S1OP, S2OP>
53    FullyNegotiatedOutbound<Either<SendWrapper<S1OP>, SendWrapper<S2OP>>, Either<S1OOI, S2OOI>>
54where
55    S1OP: OutboundUpgradeSend,
56    S2OP: OutboundUpgradeSend,
57    S1OOI: Send + 'static,
58    S2OOI: Send + 'static,
59{
60    pub(crate) fn transpose(
61        self,
62    ) -> Either<FullyNegotiatedOutbound<S1OP, S1OOI>, FullyNegotiatedOutbound<S2OP, S2OOI>> {
63        match self {
64            FullyNegotiatedOutbound {
65                protocol: future::Either::Left(protocol),
66                info: Either::Left(info),
67            } => Either::Left(FullyNegotiatedOutbound { protocol, info }),
68            FullyNegotiatedOutbound {
69                protocol: future::Either::Right(protocol),
70                info: Either::Right(info),
71            } => Either::Right(FullyNegotiatedOutbound { protocol, info }),
72            _ => panic!("wrong API usage: the protocol doesn't match the upgrade info"),
73        }
74    }
75}
76
77impl<S1IP, S1IOI, S2IP, S2IOI>
78    FullyNegotiatedInbound<SelectUpgrade<SendWrapper<S1IP>, SendWrapper<S2IP>>, (S1IOI, S2IOI)>
79where
80    S1IP: InboundUpgradeSend,
81    S2IP: InboundUpgradeSend,
82{
83    pub(crate) fn transpose(
84        self,
85    ) -> Either<FullyNegotiatedInbound<S1IP, S1IOI>, FullyNegotiatedInbound<S2IP, S2IOI>> {
86        match self {
87            FullyNegotiatedInbound {
88                protocol: future::Either::Left(protocol),
89                info: (i1, _i2),
90            } => Either::Left(FullyNegotiatedInbound { protocol, info: i1 }),
91            FullyNegotiatedInbound {
92                protocol: future::Either::Right(protocol),
93                info: (_i1, i2),
94            } => Either::Right(FullyNegotiatedInbound { protocol, info: i2 }),
95        }
96    }
97}
98
99impl<S1OOI, S2OOI, S1OP, S2OP>
100    DialUpgradeError<Either<S1OOI, S2OOI>, Either<SendWrapper<S1OP>, SendWrapper<S2OP>>>
101where
102    S1OP: OutboundUpgradeSend,
103    S2OP: OutboundUpgradeSend,
104    S1OOI: Send + 'static,
105    S2OOI: Send + 'static,
106{
107    pub(crate) fn transpose(
108        self,
109    ) -> Either<DialUpgradeError<S1OOI, S1OP>, DialUpgradeError<S2OOI, S2OP>> {
110        match self {
111            DialUpgradeError {
112                info: Either::Left(info),
113                error: StreamUpgradeError::Apply(Either::Left(err)),
114            } => Either::Left(DialUpgradeError {
115                info,
116                error: StreamUpgradeError::Apply(err),
117            }),
118            DialUpgradeError {
119                info: Either::Right(info),
120                error: StreamUpgradeError::Apply(Either::Right(err)),
121            } => Either::Right(DialUpgradeError {
122                info,
123                error: StreamUpgradeError::Apply(err),
124            }),
125            DialUpgradeError {
126                info: Either::Left(info),
127                error: e,
128            } => Either::Left(DialUpgradeError {
129                info,
130                error: e.map_upgrade_err(|_| panic!("already handled above")),
131            }),
132            DialUpgradeError {
133                info: Either::Right(info),
134                error: e,
135            } => Either::Right(DialUpgradeError {
136                info,
137                error: e.map_upgrade_err(|_| panic!("already handled above")),
138            }),
139        }
140    }
141}
142
143impl<TProto1, TProto2> ConnectionHandlerSelect<TProto1, TProto2>
144where
145    TProto1: ConnectionHandler,
146    TProto2: ConnectionHandler,
147{
148    fn on_listen_upgrade_error(
149        &mut self,
150        ListenUpgradeError {
151            info: (i1, i2),
152            error,
153        }: ListenUpgradeError<
154            <Self as ConnectionHandler>::InboundOpenInfo,
155            <Self as ConnectionHandler>::InboundProtocol,
156        >,
157    ) {
158        match error {
159            Either::Left(error) => {
160                self.proto1
161                    .on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError {
162                        info: i1,
163                        error,
164                    }));
165            }
166            Either::Right(error) => {
167                self.proto2
168                    .on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError {
169                        info: i2,
170                        error,
171                    }));
172            }
173        }
174    }
175}
176
177impl<TProto1, TProto2> ConnectionHandler for ConnectionHandlerSelect<TProto1, TProto2>
178where
179    TProto1: ConnectionHandler,
180    TProto2: ConnectionHandler,
181{
182    type FromBehaviour = Either<TProto1::FromBehaviour, TProto2::FromBehaviour>;
183    type ToBehaviour = Either<TProto1::ToBehaviour, TProto2::ToBehaviour>;
184    type InboundProtocol = SelectUpgrade<
185        SendWrapper<<TProto1 as ConnectionHandler>::InboundProtocol>,
186        SendWrapper<<TProto2 as ConnectionHandler>::InboundProtocol>,
187    >;
188    type OutboundProtocol =
189        Either<SendWrapper<TProto1::OutboundProtocol>, SendWrapper<TProto2::OutboundProtocol>>;
190    type OutboundOpenInfo = Either<TProto1::OutboundOpenInfo, TProto2::OutboundOpenInfo>;
191    type InboundOpenInfo = (TProto1::InboundOpenInfo, TProto2::InboundOpenInfo);
192
193    fn listen_protocol(&self) -> SubstreamProtocol<Self::InboundProtocol, Self::InboundOpenInfo> {
194        let proto1 = self.proto1.listen_protocol();
195        let proto2 = self.proto2.listen_protocol();
196        let timeout = *std::cmp::max(proto1.timeout(), proto2.timeout());
197        let (u1, i1) = proto1.into_upgrade();
198        let (u2, i2) = proto2.into_upgrade();
199        let choice = SelectUpgrade::new(SendWrapper(u1), SendWrapper(u2));
200        SubstreamProtocol::new(choice, (i1, i2)).with_timeout(timeout)
201    }
202
203    fn on_behaviour_event(&mut self, event: Self::FromBehaviour) {
204        match event {
205            Either::Left(event) => self.proto1.on_behaviour_event(event),
206            Either::Right(event) => self.proto2.on_behaviour_event(event),
207        }
208    }
209
210    fn connection_keep_alive(&self) -> bool {
211        cmp::max(
212            self.proto1.connection_keep_alive(),
213            self.proto2.connection_keep_alive(),
214        )
215    }
216
217    fn poll(
218        &mut self,
219        cx: &mut Context<'_>,
220    ) -> Poll<
221        ConnectionHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Self::ToBehaviour>,
222    > {
223        match self.proto1.poll(cx) {
224            Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(event)) => {
225                return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(Either::Left(event)));
226            }
227            Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol }) => {
228                return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest {
229                    protocol: protocol
230                        .map_upgrade(|u| Either::Left(SendWrapper(u)))
231                        .map_info(Either::Left),
232                });
233            }
234            Poll::Ready(ConnectionHandlerEvent::ReportRemoteProtocols(support)) => {
235                return Poll::Ready(ConnectionHandlerEvent::ReportRemoteProtocols(support));
236            }
237            Poll::Pending => (),
238        };
239
240        match self.proto2.poll(cx) {
241            Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(event)) => {
242                return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(Either::Right(
243                    event,
244                )));
245            }
246            Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol }) => {
247                return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest {
248                    protocol: protocol
249                        .map_upgrade(|u| Either::Right(SendWrapper(u)))
250                        .map_info(Either::Right),
251                });
252            }
253            Poll::Ready(ConnectionHandlerEvent::ReportRemoteProtocols(support)) => {
254                return Poll::Ready(ConnectionHandlerEvent::ReportRemoteProtocols(support));
255            }
256            Poll::Pending => (),
257        };
258
259        Poll::Pending
260    }
261
262    fn poll_close(&mut self, cx: &mut Context<'_>) -> Poll<Option<Self::ToBehaviour>> {
263        if let Some(e) = ready!(self.proto1.poll_close(cx)) {
264            return Poll::Ready(Some(Either::Left(e)));
265        }
266
267        if let Some(e) = ready!(self.proto2.poll_close(cx)) {
268            return Poll::Ready(Some(Either::Right(e)));
269        }
270
271        Poll::Ready(None)
272    }
273
274    fn on_connection_event(
275        &mut self,
276        event: ConnectionEvent<
277            Self::InboundProtocol,
278            Self::OutboundProtocol,
279            Self::InboundOpenInfo,
280            Self::OutboundOpenInfo,
281        >,
282    ) {
283        match event {
284            ConnectionEvent::FullyNegotiatedOutbound(fully_negotiated_outbound) => {
285                match fully_negotiated_outbound.transpose() {
286                    Either::Left(f) => self
287                        .proto1
288                        .on_connection_event(ConnectionEvent::FullyNegotiatedOutbound(f)),
289                    Either::Right(f) => self
290                        .proto2
291                        .on_connection_event(ConnectionEvent::FullyNegotiatedOutbound(f)),
292                }
293            }
294            ConnectionEvent::FullyNegotiatedInbound(fully_negotiated_inbound) => {
295                match fully_negotiated_inbound.transpose() {
296                    Either::Left(f) => self
297                        .proto1
298                        .on_connection_event(ConnectionEvent::FullyNegotiatedInbound(f)),
299                    Either::Right(f) => self
300                        .proto2
301                        .on_connection_event(ConnectionEvent::FullyNegotiatedInbound(f)),
302                }
303            }
304            ConnectionEvent::AddressChange(address) => {
305                self.proto1
306                    .on_connection_event(ConnectionEvent::AddressChange(AddressChange {
307                        new_address: address.new_address,
308                    }));
309
310                self.proto2
311                    .on_connection_event(ConnectionEvent::AddressChange(AddressChange {
312                        new_address: address.new_address,
313                    }));
314            }
315            ConnectionEvent::DialUpgradeError(dial_upgrade_error) => {
316                match dial_upgrade_error.transpose() {
317                    Either::Left(err) => self
318                        .proto1
319                        .on_connection_event(ConnectionEvent::DialUpgradeError(err)),
320                    Either::Right(err) => self
321                        .proto2
322                        .on_connection_event(ConnectionEvent::DialUpgradeError(err)),
323                }
324            }
325            ConnectionEvent::ListenUpgradeError(listen_upgrade_error) => {
326                self.on_listen_upgrade_error(listen_upgrade_error)
327            }
328            ConnectionEvent::LocalProtocolsChange(supported_protocols) => {
329                self.proto1
330                    .on_connection_event(ConnectionEvent::LocalProtocolsChange(
331                        supported_protocols.clone(),
332                    ));
333                self.proto2
334                    .on_connection_event(ConnectionEvent::LocalProtocolsChange(
335                        supported_protocols,
336                    ));
337            }
338            ConnectionEvent::RemoteProtocolsChange(supported_protocols) => {
339                self.proto1
340                    .on_connection_event(ConnectionEvent::RemoteProtocolsChange(
341                        supported_protocols.clone(),
342                    ));
343                self.proto2
344                    .on_connection_event(ConnectionEvent::RemoteProtocolsChange(
345                        supported_protocols,
346                    ));
347            }
348        }
349    }
350}