Skip to content

Commit e5435fc

Browse files
feat(swarm): improve PeerAddresses configurability
1 parent e63975d commit e5435fc

File tree

11 files changed

+71
-42
lines changed

11 files changed

+71
-42
lines changed

Cargo.lock

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ libp2p-dcutr = { version = "0.12.0", path = "protocols/dcutr" }
8484
libp2p-dns = { version = "0.42.0", path = "transports/dns" }
8585
libp2p-floodsub = { version = "0.45.0", path = "protocols/floodsub" }
8686
libp2p-gossipsub = { version = "0.47.0", path = "protocols/gossipsub" }
87-
libp2p-identify = { version = "0.45.0", path = "protocols/identify" }
87+
libp2p-identify = { version = "0.46.0", path = "protocols/identify" }
8888
libp2p-identity = { version = "0.2.9" }
8989
libp2p-kad = { version = "0.47.0", path = "protocols/kad" }
9090
libp2p-mdns = { version = "0.46.0", path = "protocols/mdns" }
@@ -102,7 +102,7 @@ libp2p-rendezvous = { version = "0.15.0", path = "protocols/rendezvous" }
102102
libp2p-request-response = { version = "0.27.0", path = "protocols/request-response" }
103103
libp2p-server = { version = "0.12.7", path = "misc/server" }
104104
libp2p-stream = { version = "0.2.0-alpha", path = "protocols/stream" }
105-
libp2p-swarm = { version = "0.45.1", path = "swarm" }
105+
libp2p-swarm = { version = "0.45.2", path = "swarm" }
106106
libp2p-swarm-derive = { version = "=0.35.0", path = "swarm-derive" } # `libp2p-swarm-derive` may not be compatible with different `libp2p-swarm` non-breaking releases. E.g. `libp2p-swarm` might introduce a new enum variant `FromSwarm` (which is `#[non-exhaustive]`) in a non-breaking release. Older versions of `libp2p-swarm-derive` would not forward this enum variant within the `NetworkBehaviour` hierarchy. Thus the version pinning is required.
107107
libp2p-swarm-test = { version = "0.4.0", path = "swarm-test" }
108108
libp2p-tcp = { version = "0.42.0", path = "transports/tcp" }

protocols/identify/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
## 0.46.0
2+
3+
- Update to the new `PeerAddresses` API with `PeerAddressesConfig`, changing `with_cache_size` to `with_cache_config`.
4+
See [PR 5574](https://github.com/libp2p/rust-libp2p/pull/5574).
5+
16
## 0.45.0
27

38
- Address translation is moved here from `libp2p-core`.

protocols/identify/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ name = "libp2p-identify"
33
edition = "2021"
44
rust-version = { workspace = true }
55
description = "Nodes identification protocol for libp2p"
6-
version = "0.45.0"
6+
version = "0.46.0"
77
authors = ["Parity Technologies <[email protected]>"]
88
license = "MIT"
99
repository = "https://github.com/libp2p/rust-libp2p"

protocols/identify/src/behaviour.rs

Lines changed: 13 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,12 @@ use libp2p_identity::PublicKey;
2828
use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm};
2929
use libp2p_swarm::{
3030
ConnectionDenied, DialError, ExternalAddresses, ListenAddresses, NetworkBehaviour,
31-
NotifyHandler, PeerAddresses, StreamUpgradeError, THandlerInEvent, ToSwarm,
32-
_address_translation,
31+
NotifyHandler, PeerAddresses, PeerAddressesConfig, StreamUpgradeError, THandlerInEvent,
32+
ToSwarm, _address_translation,
3333
};
3434
use libp2p_swarm::{ConnectionId, THandler, THandlerOutEvent};
3535

3636
use std::collections::hash_map::Entry;
37-
use std::num::NonZeroUsize;
3837
use std::{
3938
collections::{HashMap, HashSet, VecDeque},
4039
task::Context,
@@ -142,11 +141,8 @@ pub struct Config {
142141
/// Disabled by default.
143142
pub push_listen_addr_updates: bool,
144143

145-
/// How many entries of discovered peers to keep before we discard
146-
/// the least-recently used one.
147-
///
148-
/// Disabled by default.
149-
pub cache_size: usize,
144+
/// Configuration for the LRU cache of discovered peers.
145+
pub cache_config: Option<PeerAddressesConfig>,
150146
}
151147

152148
impl Config {
@@ -159,7 +155,7 @@ impl Config {
159155
local_public_key,
160156
interval: Duration::from_secs(5 * 60),
161157
push_listen_addr_updates: false,
162-
cache_size: 100,
158+
cache_config: Some(Default::default()),
163159
}
164160
}
165161

@@ -184,20 +180,19 @@ impl Config {
184180
self
185181
}
186182

187-
/// Configures the size of the LRU cache, caching addresses of discovered peers.
188-
pub fn with_cache_size(mut self, cache_size: usize) -> Self {
189-
self.cache_size = cache_size;
183+
/// Configuration for the LRU cache responsible for caching addresses of discovered peers.
184+
///
185+
/// If set to [`None`], caching is disabled.
186+
pub fn with_cache_config(mut self, cache_config: Option<PeerAddressesConfig>) -> Self {
187+
self.cache_config = cache_config;
190188
self
191189
}
192190
}
193191

194192
impl Behaviour {
195193
/// Creates a new identify [`Behaviour`].
196194
pub fn new(config: Config) -> Self {
197-
let discovered_peers = match NonZeroUsize::new(config.cache_size) {
198-
None => PeerCache::disabled(),
199-
Some(size) => PeerCache::enabled(size),
200-
};
195+
let discovered_peers = PeerCache::new(config.cache_config.clone());
201196

202197
Self {
203198
config,
@@ -602,12 +597,8 @@ fn multiaddr_matches_peer_id(addr: &Multiaddr, peer_id: &PeerId) -> bool {
602597
struct PeerCache(Option<PeerAddresses>);
603598

604599
impl PeerCache {
605-
fn disabled() -> Self {
606-
Self(None)
607-
}
608-
609-
fn enabled(size: NonZeroUsize) -> Self {
610-
Self(Some(PeerAddresses::new(size)))
600+
fn new(cache_config: Option<PeerAddressesConfig>) -> Self {
601+
Self(cache_config.map(PeerAddresses::new))
611602
}
612603

613604
fn get(&mut self, peer: &PeerId) -> Vec<Multiaddr> {

protocols/identify/tests/smoke.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
use futures::StreamExt;
22
use libp2p_identify as identify;
3-
use libp2p_swarm::{Swarm, SwarmEvent};
3+
use libp2p_swarm::{PeerAddressesConfig, Swarm, SwarmEvent};
44
use libp2p_swarm_test::SwarmExt;
55
use std::collections::HashSet;
66
use std::iter;
7+
use std::num::NonZeroUsize;
78
use std::time::{Duration, Instant};
89
use tracing_subscriber::EnvFilter;
910

@@ -161,7 +162,10 @@ async fn emits_unique_listen_addresses() {
161162
identify::Config::new("a".to_string(), identity.public())
162163
.with_agent_version("b".to_string())
163164
.with_interval(Duration::from_secs(1))
164-
.with_cache_size(10),
165+
.with_cache_config(Some(PeerAddressesConfig {
166+
number_of_peers: NonZeroUsize::new(10).expect("10 != 0"),
167+
..Default::default()
168+
})),
165169
)
166170
});
167171
let mut swarm2 = Swarm::new_ephemeral(|identity| {

swarm/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
## 0.45.2
2+
3+
- Add `PeerAddressesConfig` and the possibility to configure the number of addresses cached per peer.
4+
See [PR 5574](https://github.com/libp2p/rust-libp2p/pull/5574).
5+
16
## 0.45.1
27

38
- Update `libp2p-swarm-derive` to version `0.35.0`, see [PR 5545]

swarm/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ name = "libp2p-swarm"
33
edition = "2021"
44
rust-version = { workspace = true }
55
description = "The libp2p swarm"
6-
version = "0.45.1"
6+
version = "0.45.2"
77
authors = ["Parity Technologies <[email protected]>"]
88
license = "MIT"
99
repository = "https://github.com/libp2p/rust-libp2p"

swarm/src/behaviour.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ pub mod toggle;
2626

2727
pub use external_addresses::ExternalAddresses;
2828
pub use listen_addresses::ListenAddresses;
29-
pub use peer_addresses::PeerAddresses;
29+
pub use peer_addresses::{PeerAddresses, PeerAddressesConfig};
3030

3131
use crate::connection::ConnectionId;
3232
use crate::dial_opts::DialOpts;

swarm/src/behaviour/peer_addresses.rs

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,39 @@ use lru::LruCache;
88

99
use std::num::NonZeroUsize;
1010

11+
#[derive(Debug, Clone)]
12+
/// Configuration of a [`PeerAddresses`] instance.
13+
pub struct PeerAddressesConfig {
14+
/// Capacity of the [`PeerAddresses`] cache.
15+
pub number_of_peers: NonZeroUsize,
16+
17+
/// Maximum number of cached addresses per peer.
18+
pub number_of_addresses_by_peer: NonZeroUsize,
19+
}
20+
21+
impl Default for PeerAddressesConfig {
22+
fn default() -> Self {
23+
Self {
24+
number_of_peers: NonZeroUsize::new(100).expect("100 != 0"),
25+
number_of_addresses_by_peer: NonZeroUsize::new(10).expect("10 != 0"),
26+
}
27+
}
28+
}
29+
1130
/// Struct for tracking peers' external addresses of the [`Swarm`](crate::Swarm).
1231
#[derive(Debug)]
13-
pub struct PeerAddresses(LruCache<PeerId, LruCache<Multiaddr, ()>>);
32+
pub struct PeerAddresses {
33+
config: PeerAddressesConfig,
34+
inner: LruCache<PeerId, LruCache<Multiaddr, ()>>,
35+
}
1436

1537
impl PeerAddresses {
1638
/// Creates a [`PeerAddresses`] cache with capacity for the given number of peers.
1739
///
18-
/// For each peer, we will at most store 10 addresses.
19-
pub fn new(number_of_peers: NonZeroUsize) -> Self {
20-
Self(LruCache::new(number_of_peers))
40+
/// For each peer, we will at most store `config.number_of_addresses_by_peer` addresses.
41+
pub fn new(config: PeerAddressesConfig) -> Self {
42+
let inner = LruCache::new(config.number_of_peers);
43+
Self { config, inner }
2144
}
2245

2346
/// Feed a [`FromSwarm`] event to this struct.
@@ -50,12 +73,12 @@ impl PeerAddresses {
5073
pub fn add(&mut self, peer: PeerId, address: Multiaddr) -> bool {
5174
match prepare_addr(&peer, &address) {
5275
Ok(address) => {
53-
if let Some(cached) = self.0.get_mut(&peer) {
76+
if let Some(cached) = self.inner.get_mut(&peer) {
5477
cached.put(address, ()).is_none()
5578
} else {
56-
let mut set = LruCache::new(NonZeroUsize::new(10).expect("10 > 0"));
79+
let mut set = LruCache::new(self.config.number_of_addresses_by_peer);
5780
set.put(address, ());
58-
self.0.put(peer, set);
81+
self.inner.put(peer, set);
5982

6083
true
6184
}
@@ -66,7 +89,7 @@ impl PeerAddresses {
6689

6790
/// Returns peer's external addresses.
6891
pub fn get(&mut self, peer: &PeerId) -> impl Iterator<Item = Multiaddr> + '_ {
69-
self.0
92+
self.inner
7093
.get(peer)
7194
.into_iter()
7295
.flat_map(|c| c.iter().map(|(m, ())| m))
@@ -76,7 +99,7 @@ impl PeerAddresses {
7699
/// Removes address from peer addresses cache.
77100
/// Returns true if the address was removed.
78101
pub fn remove(&mut self, peer: &PeerId, address: &Multiaddr) -> bool {
79-
match self.0.get_mut(peer) {
102+
match self.inner.get_mut(peer) {
80103
Some(addrs) => match prepare_addr(peer, address) {
81104
Ok(address) => addrs.pop(&address).is_some(),
82105
Err(_) => false,
@@ -92,7 +115,7 @@ fn prepare_addr(peer: &PeerId, addr: &Multiaddr) -> Result<Multiaddr, Multiaddr>
92115

93116
impl Default for PeerAddresses {
94117
fn default() -> Self {
95-
Self(LruCache::new(NonZeroUsize::new(100).unwrap()))
118+
Self::new(Default::default())
96119
}
97120
}
98121

0 commit comments

Comments
 (0)