|
| 1 | +// Copyright 2024 litep2p developers |
| 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 | +//! Limits for the transport manager. |
| 22 | +
|
| 23 | +use crate::types::ConnectionId; |
| 24 | + |
| 25 | +use std::collections::HashSet; |
| 26 | + |
| 27 | +/// Configuration for the connection limits. |
| 28 | +#[derive(Debug, Clone, Default)] |
| 29 | +pub struct ConnectionLimitsConfig { |
| 30 | + /// Maximum number of incoming connections that can be established. |
| 31 | + max_incoming_connections: Option<usize>, |
| 32 | + /// Maximum number of outgoing connections that can be established. |
| 33 | + max_outgoing_connections: Option<usize>, |
| 34 | +} |
| 35 | + |
| 36 | +impl ConnectionLimitsConfig { |
| 37 | + /// Configures the maximum number of incoming connections that can be established. |
| 38 | + pub fn max_incoming_connections(mut self, limit: Option<usize>) -> Self { |
| 39 | + self.max_incoming_connections = limit; |
| 40 | + self |
| 41 | + } |
| 42 | + |
| 43 | + /// Configures the maximum number of outgoing connections that can be established. |
| 44 | + pub fn max_outgoing_connections(mut self, limit: Option<usize>) -> Self { |
| 45 | + self.max_outgoing_connections = limit; |
| 46 | + self |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/// Error type for connection limits. |
| 51 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 52 | +pub enum ConnectionLimitsError { |
| 53 | + /// Maximum number of incoming connections exceeded. |
| 54 | + MaxIncomingConnectionsExceeded, |
| 55 | + /// Maximum number of outgoing connections exceeded. |
| 56 | + MaxOutgoingConnectionsExceeded, |
| 57 | +} |
| 58 | + |
| 59 | +/// Connection limits. |
| 60 | +#[derive(Debug, Clone)] |
| 61 | +pub struct ConnectionLimits { |
| 62 | + /// Configuration for the connection limits. |
| 63 | + config: ConnectionLimitsConfig, |
| 64 | + |
| 65 | + /// Established incoming connections. |
| 66 | + incoming_connections: HashSet<ConnectionId>, |
| 67 | + /// Established outgoing connections. |
| 68 | + outgoing_connections: HashSet<ConnectionId>, |
| 69 | +} |
| 70 | + |
| 71 | +impl ConnectionLimits { |
| 72 | + /// Creates a new connection limits instance. |
| 73 | + pub fn new(config: ConnectionLimitsConfig) -> Self { |
| 74 | + let max_incoming_connections = config.max_incoming_connections.unwrap_or(0); |
| 75 | + let max_outgoing_connections = config.max_outgoing_connections.unwrap_or(0); |
| 76 | + |
| 77 | + Self { |
| 78 | + config, |
| 79 | + incoming_connections: HashSet::with_capacity(max_incoming_connections), |
| 80 | + outgoing_connections: HashSet::with_capacity(max_outgoing_connections), |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + /// Called when dialing an address. |
| 85 | + /// |
| 86 | + /// Returns the number of outgoing connections permitted to be established. |
| 87 | + /// It is guaranteed that at least one connection can be established if the method returns `Ok`. |
| 88 | + /// The number of available outgoing connections can influence the maximum parallel dials to a |
| 89 | + /// single address. |
| 90 | + /// |
| 91 | + /// If the maximum number of outgoing connections is not set, `Ok(usize::MAX)` is returned. |
| 92 | + pub fn on_dial_address(&mut self) -> Result<usize, ConnectionLimitsError> { |
| 93 | + if let Some(max_outgoing_connections) = self.config.max_outgoing_connections { |
| 94 | + if self.outgoing_connections.len() >= max_outgoing_connections { |
| 95 | + return Err(ConnectionLimitsError::MaxOutgoingConnectionsExceeded); |
| 96 | + } |
| 97 | + |
| 98 | + return Ok(max_outgoing_connections - self.outgoing_connections.len()); |
| 99 | + } |
| 100 | + |
| 101 | + Ok(usize::MAX) |
| 102 | + } |
| 103 | + |
| 104 | + /// Called when a new connection is established. |
| 105 | + pub fn on_connection_established( |
| 106 | + &mut self, |
| 107 | + connection_id: ConnectionId, |
| 108 | + is_listener: bool, |
| 109 | + ) -> Result<(), ConnectionLimitsError> { |
| 110 | + // Check connection limits. |
| 111 | + if is_listener { |
| 112 | + if let Some(max_incoming_connections) = self.config.max_incoming_connections { |
| 113 | + if self.incoming_connections.len() >= max_incoming_connections { |
| 114 | + return Err(ConnectionLimitsError::MaxIncomingConnectionsExceeded); |
| 115 | + } |
| 116 | + } |
| 117 | + } else { |
| 118 | + if let Some(max_outgoing_connections) = self.config.max_outgoing_connections { |
| 119 | + if self.outgoing_connections.len() >= max_outgoing_connections { |
| 120 | + return Err(ConnectionLimitsError::MaxOutgoingConnectionsExceeded); |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + // Keep track of the connection. |
| 126 | + if is_listener { |
| 127 | + if self.config.max_incoming_connections.is_some() { |
| 128 | + self.incoming_connections.insert(connection_id); |
| 129 | + } |
| 130 | + } else { |
| 131 | + if self.config.max_outgoing_connections.is_some() { |
| 132 | + self.outgoing_connections.insert(connection_id); |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + Ok(()) |
| 137 | + } |
| 138 | + |
| 139 | + /// Called when a connection is closed. |
| 140 | + pub fn on_connection_closed(&mut self, connection_id: ConnectionId) { |
| 141 | + self.incoming_connections.remove(&connection_id); |
| 142 | + self.outgoing_connections.remove(&connection_id); |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +#[cfg(test)] |
| 147 | +mod tests { |
| 148 | + use super::*; |
| 149 | + use crate::types::ConnectionId; |
| 150 | + |
| 151 | + #[test] |
| 152 | + fn connection_limits() { |
| 153 | + let config = ConnectionLimitsConfig::default() |
| 154 | + .max_incoming_connections(Some(3)) |
| 155 | + .max_outgoing_connections(Some(2)); |
| 156 | + let mut limits = ConnectionLimits::new(config); |
| 157 | + |
| 158 | + let connection_id_in_1 = ConnectionId::random(); |
| 159 | + let connection_id_in_2 = ConnectionId::random(); |
| 160 | + let connection_id_out_1 = ConnectionId::random(); |
| 161 | + let connection_id_out_2 = ConnectionId::random(); |
| 162 | + let connection_id_in_3 = ConnectionId::random(); |
| 163 | + let connection_id_out_3 = ConnectionId::random(); |
| 164 | + |
| 165 | + // Establish incoming connection. |
| 166 | + assert!(limits.on_connection_established(connection_id_in_1, true).is_ok()); |
| 167 | + assert_eq!(limits.incoming_connections.len(), 1); |
| 168 | + |
| 169 | + assert!(limits.on_connection_established(connection_id_in_2, true).is_ok()); |
| 170 | + assert_eq!(limits.incoming_connections.len(), 2); |
| 171 | + |
| 172 | + assert!(limits.on_connection_established(connection_id_in_3, true).is_ok()); |
| 173 | + assert_eq!(limits.incoming_connections.len(), 3); |
| 174 | + |
| 175 | + assert_eq!( |
| 176 | + limits.on_connection_established(ConnectionId::random(), true).unwrap_err(), |
| 177 | + ConnectionLimitsError::MaxIncomingConnectionsExceeded |
| 178 | + ); |
| 179 | + assert_eq!(limits.incoming_connections.len(), 3); |
| 180 | + |
| 181 | + // Establish outgoing connection. |
| 182 | + assert!(limits.on_connection_established(connection_id_out_1, false).is_ok()); |
| 183 | + assert_eq!(limits.incoming_connections.len(), 3); |
| 184 | + assert_eq!(limits.outgoing_connections.len(), 1); |
| 185 | + |
| 186 | + assert!(limits.on_connection_established(connection_id_out_2, false).is_ok()); |
| 187 | + assert_eq!(limits.incoming_connections.len(), 3); |
| 188 | + assert_eq!(limits.outgoing_connections.len(), 2); |
| 189 | + |
| 190 | + assert_eq!( |
| 191 | + limits.on_connection_established(connection_id_out_3, false).unwrap_err(), |
| 192 | + ConnectionLimitsError::MaxOutgoingConnectionsExceeded |
| 193 | + ); |
| 194 | + |
| 195 | + // Close connections with peer a. |
| 196 | + limits.on_connection_closed(connection_id_in_1); |
| 197 | + assert_eq!(limits.incoming_connections.len(), 2); |
| 198 | + assert_eq!(limits.outgoing_connections.len(), 2); |
| 199 | + |
| 200 | + limits.on_connection_closed(connection_id_out_1); |
| 201 | + assert_eq!(limits.incoming_connections.len(), 2); |
| 202 | + assert_eq!(limits.outgoing_connections.len(), 1); |
| 203 | + } |
| 204 | +} |
0 commit comments