subspace_networking/protocols/reserved_peers/
handler.rs

1use libp2p::core::upgrade::DeniedUpgrade;
2use libp2p::swarm::handler::ConnectionEvent;
3use libp2p::swarm::{ConnectionHandler, ConnectionHandlerEvent, SubstreamProtocol};
4use std::task::{Context, Poll};
5use void::Void;
6
7/// Connection handler for managing connections within our `reserved peers` protocol.
8///
9/// This `Handler` is part of our custom protocol designed to maintain persistent connections
10/// with a set of predefined peers.
11///
12/// ## Connection Handling
13///
14/// The `Handler` manages the lifecycle of a connection to each peer. If it's connected to a
15/// reserved peer, it maintains the connection alive (`KeepAlive::Yes`). If not, it allows the
16/// connection to close (`KeepAlive::No`).
17///
18/// This behavior ensures that connections to reserved peers are maintained persistently,
19/// while connections to non-reserved peers are allowed to close.
20pub struct Handler {
21    /// A boolean flag indicating whether the handler is currently connected to a reserved peer.
22    connected_to_reserved_peer: bool,
23}
24
25impl Handler {
26    /// Builds a new [`Handler`].
27    pub fn new(connected_to_reserved_peer: bool) -> Self {
28        Handler {
29            connected_to_reserved_peer,
30        }
31    }
32}
33
34impl ConnectionHandler for Handler {
35    type FromBehaviour = Void;
36    type ToBehaviour = ();
37    type InboundProtocol = DeniedUpgrade;
38    type OutboundProtocol = DeniedUpgrade;
39    type OutboundOpenInfo = ();
40    type InboundOpenInfo = ();
41
42    fn listen_protocol(&self) -> SubstreamProtocol<DeniedUpgrade, ()> {
43        SubstreamProtocol::new(DeniedUpgrade, ())
44    }
45
46    fn on_behaviour_event(&mut self, _: Void) {}
47
48    fn connection_keep_alive(&self) -> bool {
49        self.connected_to_reserved_peer
50    }
51
52    fn poll(&mut self, _: &mut Context<'_>) -> Poll<ConnectionHandlerEvent<DeniedUpgrade, (), ()>> {
53        Poll::Pending
54    }
55
56    fn on_connection_event(
57        &mut self,
58        _: ConnectionEvent<
59            Self::InboundProtocol,
60            Self::OutboundProtocol,
61            Self::InboundOpenInfo,
62            Self::OutboundOpenInfo,
63        >,
64    ) {
65    }
66}