\ No newline at end of file
diff --git a/pr/3539/docs/src/iroh/magicsock.rs.html b/pr/3539/docs/src/iroh/magicsock.rs.html
index 42558b349b..fee7770bd8 100644
--- a/pr/3539/docs/src/iroh/magicsock.rs.html
+++ b/pr/3539/docs/src/iroh/magicsock.rs.html
@@ -68,7 +68,7 @@
68use crate::net_report::{IpMappedAddr, QuicConfig};
69use crate::{
70 defaults::timeouts::NET_REPORT_TIMEOUT,
-
71 disco::{
self, SendAddr},
+
71 disco::{
self, SendAddr, TransactionId},
72 discovery::{
73 ConcurrentDiscovery, Discovery, DiscoveryContext, DynIntoDiscovery, EndpointData,
74 IntoDiscoveryError, UserData,
@@ -1809,7 +1809,7 @@
1809
1810#[derive(Debug)]
1811enum ActorMessage {
-
1812 EndpointPingExpired(usize, stun_rs::TransactionId),
+
1812 EndpointPingExpired(usize, TransactionId),
1813 NetworkChange,
1814 ScheduleDirectAddrUpdate(UpdateReason,
Option<(EndpointId, RelayUrl)>),
1815 RelayMapChange,
diff --git a/pr/3539/docs/src/iroh/magicsock/endpoint_map.rs.html b/pr/3539/docs/src/iroh/magicsock/endpoint_map.rs.html
index 1a2c8bf296..57bc822a0c 100644
--- a/pr/3539/docs/src/iroh/magicsock/endpoint_map.rs.html
+++ b/pr/3539/docs/src/iroh/magicsock/endpoint_map.rs.html
@@ -9,957 +9,951 @@
9use iroh_base::{EndpointAddr, EndpointId, PublicKey, RelayUrl};
10use n0_future::time::Instant;
11use serde::{Deserialize, Serialize};
-
12use stun_rs::TransactionId;
-
13use tracing::{debug, info, instrument, trace, warn};
-
14
-
15use self::endpoint_state::{EndpointState, Options, PingHandled};
-
16use super::{ActorMessage, EndpointIdMappedAddr, metrics::Metrics, transports};
-
17use crate::disco::{CallMeMaybe, Pong, SendAddr};
-
18#[cfg(any(test, feature = "test-utils"))]
-19use crate::endpoint::PathSelection;
-
20
-
21mod endpoint_state;
-
22mod path_state;
-
23mod path_validity;
-
24mod udp_paths;
-
25
-
26pub use endpoint_state::{ConnectionType, ControlMsg, DirectAddrInfo};
-
27pub(
super)
use endpoint_state::{DiscoPingPurpose, PingAction, PingRole, RemoteInfo, SendPing};
-
28
-
29const MAX_INACTIVE_ENDPOINTS: usize =
30;
-
32
-
33#[derive(Debug, Default)]
-51pub(
super)
struct EndpointMap {
-
52 inner: Mutex<EndpointMapInner>,
-
53}
-
54
-
55#[derive(Default, Debug)]
-56pub(
super)
struct EndpointMapInner {
-
57 by_endpoint_key: HashMap<EndpointId, usize>,
-
58 by_ip_port: HashMap<IpPort, usize>,
-
59 by_quic_mapped_addr: HashMap<EndpointIdMappedAddr, usize>,
-
60 by_id: HashMap<usize, EndpointState>,
-
61 next_id: usize,
-
62 #[cfg(any(test, feature = "test-utils"))]
-63 path_selection: PathSelection,
-
64}
-
65
-
66#[derive(Debug, Clone)]
-71enum EndpointStateKey {
-
72 Idx(usize),
-
73 EndpointId(EndpointId),
-
74 EndpointIdMappedAddr(EndpointIdMappedAddr),
-
75 IpPort(IpPort),
-
76}
-
77
-
78#[derive(Serialize, Deserialize, strum::Display, Debug, Clone, Eq, PartialEq, Hash)]
-96#[strum(serialize_all = "kebab-case")]
-97pub enum Source {
-
98 Saved,
-
100 Udp,
-
102 Relay,
-
104 App,
-
106 #[strum(serialize = "{name}")]
-108 Discovery {
-
109 name: String,
-
111 },
-
112 #[strum(serialize = "{name}")]
-114 NamedApp {
-
115 name: String,
-
117 },
-
118}
-
119
-
120impl EndpointMap {
-
121 pub(
super)
fn load_from_vec(
-
123 endpoints: Vec<EndpointAddr>,
-
124 #[cfg(any(test, feature = "test-utils"))] path_selection: PathSelection,
-
125 have_ipv6: bool,
-
126 metrics:
&Metrics,
-
127 ) ->
Self {
-
128 Self::from_inner(EndpointMapInner::load_from_vec(
-
129 endpoints,
-
130 #[cfg(any(test, feature = "test-utils"))]
-131 path_selection,
-
132 have_ipv6,
-
133 metrics,
-
134 ))
-
135 }
-
136
-
137 fn from_inner(inner: EndpointMapInner) ->
Self {
-
138 Self {
-
139 inner: Mutex::new(inner),
-
140 }
-
141 }
-
142
-
143 pub(
super)
fn add_endpoint_addr(
-
145 &self,
-
146 endpoint_addr: EndpointAddr,
-
147 source: Source,
-
148 have_v6: bool,
-
149 metrics:
&Metrics,
-
150 ) {
-
151 self.inner.lock().expect(
"poisoned").add_endpoint_addr(
-
152 endpoint_addr,
-
153 source,
-
154 have_v6,
-
155 metrics,
-
156 )
-
157 }
-
158
-
159 pub(
super)
fn endpoint_count(
&self) -> usize {
-
161 self.inner.lock().expect(
"poisoned").endpoint_count()
-
162 }
-
163
-
164 #[cfg(not(wasm_browser))]
-165 pub(
super)
fn receive_udp(
-
166 &self,
-
167 udp_addr: SocketAddr,
-
168 ) ->
Option<(PublicKey, EndpointIdMappedAddr)> {
-
169 self.inner.lock().expect(
"poisoned").receive_udp(udp_addr)
-
170 }
-
171
-
172 pub(
super)
fn receive_relay(
-
173 &self,
-
174 relay_url:
&RelayUrl,
-
175 src: EndpointId,
-
176 ) -> EndpointIdMappedAddr {
-
177 self.inner
-
178 .lock()
-
179 .expect(
"poisoned")
-
180 .receive_relay(relay_url, src)
-
181 }
-
182
-
183 pub(
super)
fn notify_ping_sent(
-
184 &self,
-
185 id: usize,
-
186 dst: SendAddr,
-
187 tx_id: stun_rs::TransactionId,
-
188 purpose: DiscoPingPurpose,
-
189 msg_sender: tokio::sync::mpsc::Sender<ActorMessage>,
-
190 ) {
-
191 if let Some(ep) =
self
-192 .inner
-
193 .lock()
-
194 .expect(
"poisoned")
-
195 .get_mut(EndpointStateKey::Idx(id))
-
196 {
-
197 ep.ping_sent(dst, tx_id, purpose, msg_sender);
-
198 }
-
199 }
-
200
-
201 pub(
super)
fn notify_ping_timeout(
-
202 &self,
-
203 id: usize,
-
204 tx_id: stun_rs::TransactionId,
-
205 metrics:
&Metrics,
-
206 ) {
-
207 if let Some(ep) =
self
-208 .inner
-
209 .lock()
-
210 .expect(
"poisoned")
-
211 .get_mut(EndpointStateKey::Idx(id))
-
212 {
-
213 ep.ping_timeout(tx_id, Instant::now(), metrics);
-
214 }
-
215 }
-
216
-
217 pub(
super)
fn get_quic_mapped_addr_for_endpoint_key(
-
218 &self,
-
219 endpoint_key: EndpointId,
-
220 ) ->
Option<EndpointIdMappedAddr> {
-
221 self.inner
-
222 .lock()
-
223 .expect(
"poisoned")
-
224 .get(EndpointStateKey::EndpointId(endpoint_key))
-
225 .map(|ep|
*ep.quic_mapped_addr())
-
226 }
-
227
-
228 pub(
super)
fn handle_ping(
-
231 &self,
-
232 sender: PublicKey,
-
233 src: SendAddr,
-
234 tx_id: TransactionId,
-
235 ) -> PingHandled {
-
236 self.inner
-
237 .lock()
-
238 .expect(
"poisoned")
-
239 .handle_ping(sender, src, tx_id)
-
240 }
-
241
-
242 pub(
super)
fn handle_pong(
-
243 &self,
-
244 sender: PublicKey,
-
245 src:
&transports::Addr,
-
246 pong: Pong,
-
247 metrics:
&Metrics,
-
248 ) {
-
249 self.inner
-
250 .lock()
-
251 .expect(
"poisoned")
-
252 .handle_pong(sender, src, pong, metrics)
-
253 }
-
254
-
255 #[must_use = "actions must be handled"]
-256 pub(
super)
fn handle_call_me_maybe(
-
257 &self,
-
258 sender: PublicKey,
-
259 cm: CallMeMaybe,
-
260 metrics:
&Metrics,
-
261 ) -> Vec<PingAction> {
-
262 self.inner
-
263 .lock()
-
264 .expect(
"poisoned")
-
265 .handle_call_me_maybe(sender, cm, metrics)
-
266 }
-
267
-
268 #[allow(clippy::type_complexity)]
-269 pub(
super)
fn get_send_addrs(
-
270 &self,
-
271 addr: EndpointIdMappedAddr,
-
272 have_ipv6: bool,
-
273 metrics:
&Metrics,
-
274 ) ->
Option<(
-
275 PublicKey,
-
276 Option<SocketAddr>,
-
277 Option<RelayUrl>,
-
278 Vec<PingAction>,
-
279 )> {
-
280 let mut inner =
self.inner.lock().expect(
"poisoned");
-
281 let ep = inner.get_mut(EndpointStateKey::EndpointIdMappedAddr(addr))
?;
-
282 let public_key =
*ep.public_key();
-
283 trace!(dest = %addr, endpoint_id = %public_key.fmt_short(),
"dst mapped to EndpointId");
-
284 let (udp_addr, relay_url, ping_actions) = ep.get_send_addrs(have_ipv6, metrics);
-
285 Some((public_key, udp_addr, relay_url, ping_actions))
-
286 }
-
287
-
288 pub(
super)
fn reset_endpoint_states(
&self, metrics:
&Metrics) {
-
289 let now = Instant::now();
-
290 let mut inner =
self.inner.lock().expect(
"poisoned");
-
291 for (
_, ep)
in inner.endpoint_states_mut() {
-
292 ep.note_connectivity_change(now, metrics);
-
293 }
-
294 }
-
295
-
296 pub(
super)
fn endpoints_stayin_alive(
&self, have_ipv6: bool) -> Vec<PingAction> {
-
297 let mut inner =
self.inner.lock().expect(
"poisoned");
-
298 inner
-
299 .endpoint_states_mut()
-
300 .flat_map(|(_idx, endpoint_state)| endpoint_state.stayin_alive(have_ipv6))
-
301 .collect()
-
302 }
-
303
-
304 #[cfg(test)]
-306 pub(
super)
fn list_remote_infos(
&self, now: Instant) -> Vec<RemoteInfo> {
-
307 self.inner
-
312 .lock()
-
313 .expect(
"poisoned")
-
314 .remote_infos_iter(now)
-
315 .collect()
-
316 }
-
317
-
318 pub(
super)
fn conn_type(
-
325 &self,
-
326 endpoint_id: EndpointId,
-
327 ) ->
Option<n0_watcher::Direct<ConnectionType>> {
-
328 self.inner.lock().expect(
"poisoned").conn_type(endpoint_id)
-
329 }
-
330
-
331 pub(
super)
fn latency(
&self, endpoint_id: EndpointId) ->
Option<Duration> {
-
332 self.inner.lock().expect(
"poisoned").latency(endpoint_id)
-
333 }
-
334
-
335 pub(
super)
fn remote_info(
&self, endpoint_id: EndpointId) ->
Option<RemoteInfo> {
-
337 self.inner
-
338 .lock()
-
339 .expect(
"poisoned")
-
340 .remote_info(endpoint_id)
-
341 }
-
342
-
343 pub(
super)
fn prune_inactive(
&self) {
-
345 self.inner.lock().expect(
"poisoned").prune_inactive();
-
346 }
-
347
-
348 pub(
crate)
fn on_direct_addr_discovered(
&self, discovered: BTreeSet<SocketAddr>) {
-
349 self.inner
-
350 .lock()
-
351 .expect(
"poisoned")
-
352 .on_direct_addr_discovered(discovered, Instant::now());
-
353 }
-
354}
-
355
-
356impl EndpointMapInner {
-
357 fn load_from_vec(
-
359 endpoints: Vec<EndpointAddr>,
-
360 #[cfg(any(test, feature = "test-utils"))] path_selection: PathSelection,
-
361 have_ipv6: bool,
-
362 metrics:
&Metrics,
-
363 ) ->
Self {
-
364 let mut me =
Self {
-
365 #[cfg(any(test, feature = "test-utils"))]
-366 path_selection,
-
367 ..Default::default()
-
368 };
-
369 for endpoint_addr
in endpoints {
-
370 me.add_endpoint_addr(endpoint_addr, Source::Saved, have_ipv6, metrics);
-
371 }
-
372 me
-
373 }
-
374
-
375 #[instrument(skip_all, fields(endpoint = %endpoint_addr.endpoint_id.fmt_short()))]
-377 fn add_endpoint_addr(
-
378 &mut self,
-
379 endpoint_addr: EndpointAddr,
-
380 source: Source,
-
381 have_ipv6: bool,
-
382 metrics:
&Metrics,
-
383 ) {
-
384 let source0 = source.clone();
-
385 let endpoint_id = endpoint_addr.endpoint_id;
-
386 let relay_url = endpoint_addr.relay_url.clone();
-
387 #[cfg(any(test, feature = "test-utils"))]
-388 let path_selection =
self.path_selection;
-
389 let endpoint_state =
-
390 self.get_or_insert_with(EndpointStateKey::EndpointId(endpoint_id), || Options {
-
391 endpoint_id,
-
392 relay_url,
-
393 active:
false,
-
394 source,
-
395 #[cfg(any(test, feature = "test-utils"))]
-396 path_selection,
-
397 });
-
398 endpoint_state.update_from_endpoint_addr(
-
399 endpoint_addr.relay_url.as_ref(),
-
400 &endpoint_addr.direct_addresses,
-
401 source0,
-
402 have_ipv6,
-
403 metrics,
-
404 );
-
405 let id = endpoint_state.id();
-
406 for addr
in endpoint_addr.direct_addresses() {
-
407 self.set_endpoint_state_for_ip_port(
*addr, id);
-
408 }
-
409 }
-
410
-
411 pub(
super)
fn on_direct_addr_discovered(
-
413 &mut self,
-
414 discovered: BTreeSet<SocketAddr>,
-
415 now: Instant,
-
416 ) {
-
417 for addr
in discovered {
-
418 self.remove_by_ipp(addr.into(), now,
"matches our local addr")
-
419 }
-
420 }
-
421
-
422 fn remove_by_ipp(
&mut self, ipp: IpPort, now: Instant, why:
&'static str) {
-
424 if let Some(id) =
self.by_ip_port.remove(
&ipp) {
-
425 if let Entry::Occupied(
mut entry) =
self.by_id.entry(id) {
-
426 let endpoint = entry.get_mut();
-
427 endpoint.remove_direct_addr(
&ipp, now, why);
-
428 if endpoint.direct_addresses().count() ==
0 {
-
429 let endpoint_id = endpoint.public_key();
-
430 let mapped_addr = endpoint.quic_mapped_addr();
-
431 self.by_endpoint_key.remove(endpoint_id);
-
432 self.by_quic_mapped_addr.remove(mapped_addr);
-
433 debug!(endpoint_id=%endpoint_id.fmt_short(), why,
"removing endpoint");
-
434 entry.remove();
-
435 }
-
436 }
-
437 }
-
438 }
-
439
-
440 fn get_id(
&self, id: EndpointStateKey) ->
Option<usize> {
-
441 match id {
-
442 EndpointStateKey::Idx(id) =>
Some(id),
-
443 EndpointStateKey::EndpointId(endpoint_key) => {
-
444 self.by_endpoint_key.get(
&endpoint_key).copied()
-
445 }
-
446 EndpointStateKey::EndpointIdMappedAddr(addr) => {
-
447 self.by_quic_mapped_addr.get(
&addr).copied()
-
448 }
-
449 EndpointStateKey::IpPort(ipp) =>
self.by_ip_port.get(
&ipp).copied(),
-
450 }
-
451 }
-
452
-
453 fn get_mut(
&mut self, id: EndpointStateKey) ->
Option<
&mut EndpointState> {
-
454 self.get_id(id).and_then(|id|
self.by_id.get_mut(
&id))
-
455 }
-
456
-
457 fn get(
&self, id: EndpointStateKey) ->
Option<
&EndpointState> {
-
458 self.get_id(id).and_then(|id|
self.by_id.get(
&id))
-
459 }
-
460
-
461 fn get_or_insert_with(
-
462 &mut self,
-
463 id: EndpointStateKey,
-
464 f:
impl FnOnce() -> Options,
-
465 ) ->
&mut EndpointState {
-
466 let id =
self.get_id(id);
-
467 match id {
-
468 None =>
self.insert_endpoint(f()),
-
469 Some(id) =>
self.by_id.get_mut(
&id).expect(
"is not empty"),
-
470 }
-
471 }
-
472
-
473 fn endpoint_count(
&self) -> usize {
-
475 self.by_id.len()
-
476 }
-
477
-
478 #[cfg(not(wasm_browser))]
-480 fn receive_udp(
&mut self, udp_addr: SocketAddr) ->
Option<(EndpointId, EndpointIdMappedAddr)> {
-
481 let ip_port: IpPort = udp_addr.into();
-
482 let Some(endpoint_state) =
self.get_mut(EndpointStateKey::IpPort(ip_port))
else {
-
483 trace!(src=%udp_addr,
"receive_udp: no endpoint_state found for addr, ignore");
-
484 return None;
-
485 };
-
486 endpoint_state.receive_udp(ip_port, Instant::now());
-
487 Some((
-
488 *endpoint_state.public_key(),
-
489 *endpoint_state.quic_mapped_addr(),
-
490 ))
-
491 }
-
492
-
493 #[instrument(skip_all, fields(src = %src.fmt_short()))]
-494 fn receive_relay(
&mut self, relay_url:
&RelayUrl, src: EndpointId) -> EndpointIdMappedAddr {
-
495 #[cfg(any(test, feature = "test-utils"))]
-496 let path_selection =
self.path_selection;
-
497 let endpoint_state =
self.get_or_insert_with(EndpointStateKey::EndpointId(src), || {
-
498 trace!(
"packets from unknown endpoint, insert into endpoint map");
-
499 Options {
-
500 endpoint_id: src,
-
501 relay_url:
Some(relay_url.clone()),
-
502 active:
true,
-
503 source: Source::Relay,
-
504 #[cfg(any(test, feature = "test-utils"))]
-505 path_selection,
-
506 }
-
507 });
-
508 endpoint_state.receive_relay(relay_url, src, Instant::now());
-
509 *endpoint_state.quic_mapped_addr()
-
510 }
-
511
-
512 #[cfg(test)]
-513 fn endpoint_states(
&self) ->
impl Iterator<Item = (
&usize,
&EndpointState)> {
-
514 self.by_id.iter()
-
515 }
-
516
-
517 fn endpoint_states_mut(
&mut self) ->
impl Iterator<Item = (
&usize,
&mut EndpointState)> {
-
518 self.by_id.iter_mut()
+
12use tracing::{debug, info, instrument, trace, warn};
+
13
+
14use self::endpoint_state::{EndpointState, Options, PingHandled};
+
15use super::{ActorMessage, EndpointIdMappedAddr, metrics::Metrics, transports};
+
16use crate::disco::{CallMeMaybe, Pong, SendAddr, TransactionId};
+
17#[cfg(any(test, feature = "test-utils"))]
+18use crate::endpoint::PathSelection;
+
19
+
20mod endpoint_state;
+
21mod path_state;
+
22mod path_validity;
+
23mod udp_paths;
+
24
+
25pub use endpoint_state::{ConnectionType, ControlMsg, DirectAddrInfo};
+
26pub(
super)
use endpoint_state::{DiscoPingPurpose, PingAction, PingRole, RemoteInfo, SendPing};
+
27
+
28const MAX_INACTIVE_ENDPOINTS: usize =
30;
+
31
+
32#[derive(Debug, Default)]
+50pub(
super)
struct EndpointMap {
+
51 inner: Mutex<EndpointMapInner>,
+
52}
+
53
+
54#[derive(Default, Debug)]
+55pub(
super)
struct EndpointMapInner {
+
56 by_endpoint_key: HashMap<EndpointId, usize>,
+
57 by_ip_port: HashMap<IpPort, usize>,
+
58 by_quic_mapped_addr: HashMap<EndpointIdMappedAddr, usize>,
+
59 by_id: HashMap<usize, EndpointState>,
+
60 next_id: usize,
+
61 #[cfg(any(test, feature = "test-utils"))]
+62 path_selection: PathSelection,
+
63}
+
64
+
65#[derive(Debug, Clone)]
+70enum EndpointStateKey {
+
71 Idx(usize),
+
72 EndpointId(EndpointId),
+
73 EndpointIdMappedAddr(EndpointIdMappedAddr),
+
74 IpPort(IpPort),
+
75}
+
76
+
77#[derive(Serialize, Deserialize, strum::Display, Debug, Clone, Eq, PartialEq, Hash)]
+95#[strum(serialize_all = "kebab-case")]
+96pub enum Source {
+
97 Saved,
+
99 Udp,
+
101 Relay,
+
103 App,
+
105 #[strum(serialize = "{name}")]
+107 Discovery {
+
108 name: String,
+
110 },
+
111 #[strum(serialize = "{name}")]
+113 NamedApp {
+
114 name: String,
+
116 },
+
117}
+
118
+
119impl EndpointMap {
+
120 pub(
super)
fn load_from_vec(
+
122 endpoints: Vec<EndpointAddr>,
+
123 #[cfg(any(test, feature = "test-utils"))] path_selection: PathSelection,
+
124 have_ipv6: bool,
+
125 metrics:
&Metrics,
+
126 ) ->
Self {
+
127 Self::from_inner(EndpointMapInner::load_from_vec(
+
128 endpoints,
+
129 #[cfg(any(test, feature = "test-utils"))]
+130 path_selection,
+
131 have_ipv6,
+
132 metrics,
+
133 ))
+
134 }
+
135
+
136 fn from_inner(inner: EndpointMapInner) ->
Self {
+
137 Self {
+
138 inner: Mutex::new(inner),
+
139 }
+
140 }
+
141
+
142 pub(
super)
fn add_endpoint_addr(
+
144 &self,
+
145 endpoint_addr: EndpointAddr,
+
146 source: Source,
+
147 have_v6: bool,
+
148 metrics:
&Metrics,
+
149 ) {
+
150 self.inner.lock().expect(
"poisoned").add_endpoint_addr(
+
151 endpoint_addr,
+
152 source,
+
153 have_v6,
+
154 metrics,
+
155 )
+
156 }
+
157
+
158 pub(
super)
fn endpoint_count(
&self) -> usize {
+
160 self.inner.lock().expect(
"poisoned").endpoint_count()
+
161 }
+
162
+
163 #[cfg(not(wasm_browser))]
+164 pub(
super)
fn receive_udp(
+
165 &self,
+
166 udp_addr: SocketAddr,
+
167 ) ->
Option<(PublicKey, EndpointIdMappedAddr)> {
+
168 self.inner.lock().expect(
"poisoned").receive_udp(udp_addr)
+
169 }
+
170
+
171 pub(
super)
fn receive_relay(
+
172 &self,
+
173 relay_url:
&RelayUrl,
+
174 src: EndpointId,
+
175 ) -> EndpointIdMappedAddr {
+
176 self.inner
+
177 .lock()
+
178 .expect(
"poisoned")
+
179 .receive_relay(relay_url, src)
+
180 }
+
181
+
182 pub(
super)
fn notify_ping_sent(
+
183 &self,
+
184 id: usize,
+
185 dst: SendAddr,
+
186 tx_id: TransactionId,
+
187 purpose: DiscoPingPurpose,
+
188 msg_sender: tokio::sync::mpsc::Sender<ActorMessage>,
+
189 ) {
+
190 if let Some(ep) =
self
+191 .inner
+
192 .lock()
+
193 .expect(
"poisoned")
+
194 .get_mut(EndpointStateKey::Idx(id))
+
195 {
+
196 ep.ping_sent(dst, tx_id, purpose, msg_sender);
+
197 }
+
198 }
+
199
+
200 pub(
super)
fn notify_ping_timeout(
&self, id: usize, tx_id: TransactionId, metrics:
&Metrics) {
+
201 if let Some(ep) =
self
+202 .inner
+
203 .lock()
+
204 .expect(
"poisoned")
+
205 .get_mut(EndpointStateKey::Idx(id))
+
206 {
+
207 ep.ping_timeout(tx_id, Instant::now(), metrics);
+
208 }
+
209 }
+
210
+
211 pub(
super)
fn get_quic_mapped_addr_for_endpoint_key(
+
212 &self,
+
213 endpoint_key: EndpointId,
+
214 ) ->
Option<EndpointIdMappedAddr> {
+
215 self.inner
+
216 .lock()
+
217 .expect(
"poisoned")
+
218 .get(EndpointStateKey::EndpointId(endpoint_key))
+
219 .map(|ep|
*ep.quic_mapped_addr())
+
220 }
+
221
+
222 pub(
super)
fn handle_ping(
+
225 &self,
+
226 sender: PublicKey,
+
227 src: SendAddr,
+
228 tx_id: TransactionId,
+
229 ) -> PingHandled {
+
230 self.inner
+
231 .lock()
+
232 .expect(
"poisoned")
+
233 .handle_ping(sender, src, tx_id)
+
234 }
+
235
+
236 pub(
super)
fn handle_pong(
+
237 &self,
+
238 sender: PublicKey,
+
239 src:
&transports::Addr,
+
240 pong: Pong,
+
241 metrics:
&Metrics,
+
242 ) {
+
243 self.inner
+
244 .lock()
+
245 .expect(
"poisoned")
+
246 .handle_pong(sender, src, pong, metrics)
+
247 }
+
248
+
249 #[must_use = "actions must be handled"]
+250 pub(
super)
fn handle_call_me_maybe(
+
251 &self,
+
252 sender: PublicKey,
+
253 cm: CallMeMaybe,
+
254 metrics:
&Metrics,
+
255 ) -> Vec<PingAction> {
+
256 self.inner
+
257 .lock()
+
258 .expect(
"poisoned")
+
259 .handle_call_me_maybe(sender, cm, metrics)
+
260 }
+
261
+
262 #[allow(clippy::type_complexity)]
+263 pub(
super)
fn get_send_addrs(
+
264 &self,
+
265 addr: EndpointIdMappedAddr,
+
266 have_ipv6: bool,
+
267 metrics:
&Metrics,
+
268 ) ->
Option<(
+
269 PublicKey,
+
270 Option<SocketAddr>,
+
271 Option<RelayUrl>,
+
272 Vec<PingAction>,
+
273 )> {
+
274 let mut inner =
self.inner.lock().expect(
"poisoned");
+
275 let ep = inner.get_mut(EndpointStateKey::EndpointIdMappedAddr(addr))
?;
+
276 let public_key =
*ep.public_key();
+
277 trace!(dest = %addr, endpoint_id = %public_key.fmt_short(),
"dst mapped to EndpointId");
+
278 let (udp_addr, relay_url, ping_actions) = ep.get_send_addrs(have_ipv6, metrics);
+
279 Some((public_key, udp_addr, relay_url, ping_actions))
+
280 }
+
281
+
282 pub(
super)
fn reset_endpoint_states(
&self, metrics:
&Metrics) {
+
283 let now = Instant::now();
+
284 let mut inner =
self.inner.lock().expect(
"poisoned");
+
285 for (
_, ep)
in inner.endpoint_states_mut() {
+
286 ep.note_connectivity_change(now, metrics);
+
287 }
+
288 }
+
289
+
290 pub(
super)
fn endpoints_stayin_alive(
&self, have_ipv6: bool) -> Vec<PingAction> {
+
291 let mut inner =
self.inner.lock().expect(
"poisoned");
+
292 inner
+
293 .endpoint_states_mut()
+
294 .flat_map(|(_idx, endpoint_state)| endpoint_state.stayin_alive(have_ipv6))
+
295 .collect()
+
296 }
+
297
+
298 #[cfg(test)]
+300 pub(
super)
fn list_remote_infos(
&self, now: Instant) -> Vec<RemoteInfo> {
+
301 self.inner
+
306 .lock()
+
307 .expect(
"poisoned")
+
308 .remote_infos_iter(now)
+
309 .collect()
+
310 }
+
311
+
312 pub(
super)
fn conn_type(
+
319 &self,
+
320 endpoint_id: EndpointId,
+
321 ) ->
Option<n0_watcher::Direct<ConnectionType>> {
+
322 self.inner.lock().expect(
"poisoned").conn_type(endpoint_id)
+
323 }
+
324
+
325 pub(
super)
fn latency(
&self, endpoint_id: EndpointId) ->
Option<Duration> {
+
326 self.inner.lock().expect(
"poisoned").latency(endpoint_id)
+
327 }
+
328
+
329 pub(
super)
fn remote_info(
&self, endpoint_id: EndpointId) ->
Option<RemoteInfo> {
+
331 self.inner
+
332 .lock()
+
333 .expect(
"poisoned")
+
334 .remote_info(endpoint_id)
+
335 }
+
336
+
337 pub(
super)
fn prune_inactive(
&self) {
+
339 self.inner.lock().expect(
"poisoned").prune_inactive();
+
340 }
+
341
+
342 pub(
crate)
fn on_direct_addr_discovered(
&self, discovered: BTreeSet<SocketAddr>) {
+
343 self.inner
+
344 .lock()
+
345 .expect(
"poisoned")
+
346 .on_direct_addr_discovered(discovered, Instant::now());
+
347 }
+
348}
+
349
+
350impl EndpointMapInner {
+
351 fn load_from_vec(
+
353 endpoints: Vec<EndpointAddr>,
+
354 #[cfg(any(test, feature = "test-utils"))] path_selection: PathSelection,
+
355 have_ipv6: bool,
+
356 metrics:
&Metrics,
+
357 ) ->
Self {
+
358 let mut me =
Self {
+
359 #[cfg(any(test, feature = "test-utils"))]
+360 path_selection,
+
361 ..Default::default()
+
362 };
+
363 for endpoint_addr
in endpoints {
+
364 me.add_endpoint_addr(endpoint_addr, Source::Saved, have_ipv6, metrics);
+
365 }
+
366 me
+
367 }
+
368
+
369 #[instrument(skip_all, fields(endpoint = %endpoint_addr.endpoint_id.fmt_short()))]
+371 fn add_endpoint_addr(
+
372 &mut self,
+
373 endpoint_addr: EndpointAddr,
+
374 source: Source,
+
375 have_ipv6: bool,
+
376 metrics:
&Metrics,
+
377 ) {
+
378 let source0 = source.clone();
+
379 let endpoint_id = endpoint_addr.endpoint_id;
+
380 let relay_url = endpoint_addr.relay_url.clone();
+
381 #[cfg(any(test, feature = "test-utils"))]
+382 let path_selection =
self.path_selection;
+
383 let endpoint_state =
+
384 self.get_or_insert_with(EndpointStateKey::EndpointId(endpoint_id), || Options {
+
385 endpoint_id,
+
386 relay_url,
+
387 active:
false,
+
388 source,
+
389 #[cfg(any(test, feature = "test-utils"))]
+390 path_selection,
+
391 });
+
392 endpoint_state.update_from_endpoint_addr(
+
393 endpoint_addr.relay_url.as_ref(),
+
394 &endpoint_addr.direct_addresses,
+
395 source0,
+
396 have_ipv6,
+
397 metrics,
+
398 );
+
399 let id = endpoint_state.id();
+
400 for addr
in endpoint_addr.direct_addresses() {
+
401 self.set_endpoint_state_for_ip_port(
*addr, id);
+
402 }
+
403 }
+
404
+
405 pub(
super)
fn on_direct_addr_discovered(
+
407 &mut self,
+
408 discovered: BTreeSet<SocketAddr>,
+
409 now: Instant,
+
410 ) {
+
411 for addr
in discovered {
+
412 self.remove_by_ipp(addr.into(), now,
"matches our local addr")
+
413 }
+
414 }
+
415
+
416 fn remove_by_ipp(
&mut self, ipp: IpPort, now: Instant, why:
&'static str) {
+
418 if let Some(id) =
self.by_ip_port.remove(
&ipp) {
+
419 if let Entry::Occupied(
mut entry) =
self.by_id.entry(id) {
+
420 let endpoint = entry.get_mut();
+
421 endpoint.remove_direct_addr(
&ipp, now, why);
+
422 if endpoint.direct_addresses().count() ==
0 {
+
423 let endpoint_id = endpoint.public_key();
+
424 let mapped_addr = endpoint.quic_mapped_addr();
+
425 self.by_endpoint_key.remove(endpoint_id);
+
426 self.by_quic_mapped_addr.remove(mapped_addr);
+
427 debug!(endpoint_id=%endpoint_id.fmt_short(), why,
"removing endpoint");
+
428 entry.remove();
+
429 }
+
430 }
+
431 }
+
432 }
+
433
+
434 fn get_id(
&self, id: EndpointStateKey) ->
Option<usize> {
+
435 match id {
+
436 EndpointStateKey::Idx(id) =>
Some(id),
+
437 EndpointStateKey::EndpointId(endpoint_key) => {
+
438 self.by_endpoint_key.get(
&endpoint_key).copied()
+
439 }
+
440 EndpointStateKey::EndpointIdMappedAddr(addr) => {
+
441 self.by_quic_mapped_addr.get(
&addr).copied()
+
442 }
+
443 EndpointStateKey::IpPort(ipp) =>
self.by_ip_port.get(
&ipp).copied(),
+
444 }
+
445 }
+
446
+
447 fn get_mut(
&mut self, id: EndpointStateKey) ->
Option<
&mut EndpointState> {
+
448 self.get_id(id).and_then(|id|
self.by_id.get_mut(
&id))
+
449 }
+
450
+
451 fn get(
&self, id: EndpointStateKey) ->
Option<
&EndpointState> {
+
452 self.get_id(id).and_then(|id|
self.by_id.get(
&id))
+
453 }
+
454
+
455 fn get_or_insert_with(
+
456 &mut self,
+
457 id: EndpointStateKey,
+
458 f:
impl FnOnce() -> Options,
+
459 ) ->
&mut EndpointState {
+
460 let id =
self.get_id(id);
+
461 match id {
+
462 None =>
self.insert_endpoint(f()),
+
463 Some(id) =>
self.by_id.get_mut(
&id).expect(
"is not empty"),
+
464 }
+
465 }
+
466
+
467 fn endpoint_count(
&self) -> usize {
+
469 self.by_id.len()
+
470 }
+
471
+
472 #[cfg(not(wasm_browser))]
+474 fn receive_udp(
&mut self, udp_addr: SocketAddr) ->
Option<(EndpointId, EndpointIdMappedAddr)> {
+
475 let ip_port: IpPort = udp_addr.into();
+
476 let Some(endpoint_state) =
self.get_mut(EndpointStateKey::IpPort(ip_port))
else {
+
477 trace!(src=%udp_addr,
"receive_udp: no endpoint_state found for addr, ignore");
+
478 return None;
+
479 };
+
480 endpoint_state.receive_udp(ip_port, Instant::now());
+
481 Some((
+
482 *endpoint_state.public_key(),
+
483 *endpoint_state.quic_mapped_addr(),
+
484 ))
+
485 }
+
486
+
487 #[instrument(skip_all, fields(src = %src.fmt_short()))]
+488 fn receive_relay(
&mut self, relay_url:
&RelayUrl, src: EndpointId) -> EndpointIdMappedAddr {
+
489 #[cfg(any(test, feature = "test-utils"))]
+490 let path_selection =
self.path_selection;
+
491 let endpoint_state =
self.get_or_insert_with(EndpointStateKey::EndpointId(src), || {
+
492 trace!(
"packets from unknown endpoint, insert into endpoint map");
+
493 Options {
+
494 endpoint_id: src,
+
495 relay_url:
Some(relay_url.clone()),
+
496 active:
true,
+
497 source: Source::Relay,
+
498 #[cfg(any(test, feature = "test-utils"))]
+499 path_selection,
+
500 }
+
501 });
+
502 endpoint_state.receive_relay(relay_url, src, Instant::now());
+
503 *endpoint_state.quic_mapped_addr()
+
504 }
+
505
+
506 #[cfg(test)]
+507 fn endpoint_states(
&self) ->
impl Iterator<Item = (
&usize,
&EndpointState)> {
+
508 self.by_id.iter()
+
509 }
+
510
+
511 fn endpoint_states_mut(
&mut self) ->
impl Iterator<Item = (
&usize,
&mut EndpointState)> {
+
512 self.by_id.iter_mut()
+
513 }
+
514
+
515 #[cfg(test)]
+517 fn remote_infos_iter(
&self, now: Instant) ->
impl Iterator<Item = RemoteInfo> +
'_ {
+
518 self.endpoint_states().map(
move |(
_, ep)| ep.info(now))
519 }
520
-
521 #[cfg(test)]
-523 fn remote_infos_iter(
&self, now: Instant) ->
impl Iterator<Item = RemoteInfo> +
'_ {
-
524 self.endpoint_states().map(
move |(
_, ep)| ep.info(now))
+
521 fn remote_info(
&self, endpoint_id: EndpointId) ->
Option<RemoteInfo> {
+
523 self.get(EndpointStateKey::EndpointId(endpoint_id))
+
524 .map(|ep| ep.info(Instant::now()))
525 }
526
-
527 fn remote_info(
&self, endpoint_id: EndpointId) ->
Option<RemoteInfo> {
-
529 self.get(EndpointStateKey::EndpointId(endpoint_id))
-
530 .map(|ep| ep.info(Instant::now()))
-
531 }
-
532
-
533 fn conn_type(
&self, endpoint_id: EndpointId) ->
Option<n0_watcher::Direct<ConnectionType>> {
-
543 self.get(EndpointStateKey::EndpointId(endpoint_id))
-
544 .map(|ep| ep.conn_type())
-
545 }
-
546
-
547 fn latency(
&self, endpoint_id: EndpointId) ->
Option<Duration> {
-
548 self.get(EndpointStateKey::EndpointId(endpoint_id))
-
549 .and_then(|ep| ep.latency())
-
550 }
-
551
-
552 fn handle_pong(
-
553 &mut self,
-
554 sender: EndpointId,
-
555 src:
&transports::Addr,
-
556 pong: Pong,
-
557 metrics:
&Metrics,
-
558 ) {
-
559 if let Some(ns) =
self.get_mut(EndpointStateKey::EndpointId(sender)).as_mut() {
-
560 let insert = ns.handle_pong(
&pong, src.clone().into(), metrics);
-
561 if let Some((src, key)) = insert {
-
562 self.set_endpoint_key_for_ip_port(src,
&key);
-
563 }
-
564 trace!(
?insert,
"received pong")
-
565 }
else {
-
566 warn!(
"received pong: endpoint unknown, ignore")
-
567 }
-
568 }
-
569
-
570 #[must_use = "actions must be handled"]
-571 fn handle_call_me_maybe(
-
572 &mut self,
-
573 sender: EndpointId,
-
574 cm: CallMeMaybe,
-
575 metrics:
&Metrics,
-
576 ) -> Vec<PingAction> {
-
577 let ns_id = EndpointStateKey::EndpointId(sender);
-
578 if let Some(id) =
self.get_id(ns_id.clone()) {
-
579 for number
in &cm.my_numbers {
-
580 self.set_endpoint_state_for_ip_port(
*number, id);
-
582 }
-
583 }
-
584 match self.get_mut(ns_id) {
-
585 None => {
-
586 debug!(
"received call-me-maybe: ignore, endpoint is unknown");
-
587 metrics.recv_disco_call_me_maybe_bad_disco.inc();
-
588 vec![]
-
589 }
-
590 Some(ns) => {
-
591 debug!(endpoints =
?cm.my_numbers,
"received call-me-maybe");
-
592
-
593 ns.handle_call_me_maybe(cm, metrics)
-
594 }
-
595 }
-
596 }
-
597
-
598 fn handle_ping(
-
599 &mut self,
-
600 sender: EndpointId,
-
601 src: SendAddr,
-
602 tx_id: TransactionId,
-
603 ) -> PingHandled {
-
604 #[cfg(any(test, feature = "test-utils"))]
-605 let path_selection =
self.path_selection;
-
606 let endpoint_state =
self.get_or_insert_with(EndpointStateKey::EndpointId(sender), || {
-
607 debug!(
"received ping: endpoint unknown, add to endpoint map");
-
608 let source =
if src.is_relay() {
-
609 Source::Relay
-
610 }
else {
-
611 Source::Udp
-
612 };
-
613 Options {
-
614 endpoint_id: sender,
-
615 relay_url: src.relay_url(),
-
616 active:
true,
-
617 source,
-
618 #[cfg(any(test, feature = "test-utils"))]
-619 path_selection,
-
620 }
-
621 });
-
622
-
623 let handled = endpoint_state.handle_ping(src.clone(), tx_id);
-
624 if let SendAddr::Udp(
ref addr) = src {
-
625 if matches!(handled.role, PingRole::NewPath) {
-
626 self.set_endpoint_key_for_ip_port(
*addr,
&sender);
-
627 }
-
628 }
-
629 handled
-
630 }
-
631
-
632 fn insert_endpoint(
&mut self, options: Options) ->
&mut EndpointState {
-
634 info!(
-
635 endpoint = %options.endpoint_id.fmt_short(),
-
636 relay_url =
?options.relay_url,
-
637 source = %options.source,
-
638 "inserting new endpoint in EndpointMap",
-
639 );
-
640 let id =
self.next_id;
-
641 self.next_id =
self.next_id.wrapping_add(
1);
-
642 let endpoint_state = EndpointState::new(id, options);
+
527 fn conn_type(
&self, endpoint_id: EndpointId) ->
Option<n0_watcher::Direct<ConnectionType>> {
+
537 self.get(EndpointStateKey::EndpointId(endpoint_id))
+
538 .map(|ep| ep.conn_type())
+
539 }
+
540
+
541 fn latency(
&self, endpoint_id: EndpointId) ->
Option<Duration> {
+
542 self.get(EndpointStateKey::EndpointId(endpoint_id))
+
543 .and_then(|ep| ep.latency())
+
544 }
+
545
+
546 fn handle_pong(
+
547 &mut self,
+
548 sender: EndpointId,
+
549 src:
&transports::Addr,
+
550 pong: Pong,
+
551 metrics:
&Metrics,
+
552 ) {
+
553 if let Some(ns) =
self.get_mut(EndpointStateKey::EndpointId(sender)).as_mut() {
+
554 let insert = ns.handle_pong(
&pong, src.clone().into(), metrics);
+
555 if let Some((src, key)) = insert {
+
556 self.set_endpoint_key_for_ip_port(src,
&key);
+
557 }
+
558 trace!(
?insert,
"received pong")
+
559 }
else {
+
560 warn!(
"received pong: endpoint unknown, ignore")
+
561 }
+
562 }
+
563
+
564 #[must_use = "actions must be handled"]
+565 fn handle_call_me_maybe(
+
566 &mut self,
+
567 sender: EndpointId,
+
568 cm: CallMeMaybe,
+
569 metrics:
&Metrics,
+
570 ) -> Vec<PingAction> {
+
571 let ns_id = EndpointStateKey::EndpointId(sender);
+
572 if let Some(id) =
self.get_id(ns_id.clone()) {
+
573 for number
in &cm.my_numbers {
+
574 self.set_endpoint_state_for_ip_port(
*number, id);
+
576 }
+
577 }
+
578 match self.get_mut(ns_id) {
+
579 None => {
+
580 debug!(
"received call-me-maybe: ignore, endpoint is unknown");
+
581 metrics.recv_disco_call_me_maybe_bad_disco.inc();
+
582 vec![]
+
583 }
+
584 Some(ns) => {
+
585 debug!(endpoints =
?cm.my_numbers,
"received call-me-maybe");
+
586
+
587 ns.handle_call_me_maybe(cm, metrics)
+
588 }
+
589 }
+
590 }
+
591
+
592 fn handle_ping(
+
593 &mut self,
+
594 sender: EndpointId,
+
595 src: SendAddr,
+
596 tx_id: TransactionId,
+
597 ) -> PingHandled {
+
598 #[cfg(any(test, feature = "test-utils"))]
+599 let path_selection =
self.path_selection;
+
600 let endpoint_state =
self.get_or_insert_with(EndpointStateKey::EndpointId(sender), || {
+
601 debug!(
"received ping: endpoint unknown, add to endpoint map");
+
602 let source =
if src.is_relay() {
+
603 Source::Relay
+
604 }
else {
+
605 Source::Udp
+
606 };
+
607 Options {
+
608 endpoint_id: sender,
+
609 relay_url: src.relay_url(),
+
610 active:
true,
+
611 source,
+
612 #[cfg(any(test, feature = "test-utils"))]
+613 path_selection,
+
614 }
+
615 });
+
616
+
617 let handled = endpoint_state.handle_ping(src.clone(), tx_id);
+
618 if let SendAddr::Udp(
ref addr) = src {
+
619 if matches!(handled.role, PingRole::NewPath) {
+
620 self.set_endpoint_key_for_ip_port(
*addr,
&sender);
+
621 }
+
622 }
+
623 handled
+
624 }
+
625
+
626 fn insert_endpoint(
&mut self, options: Options) ->
&mut EndpointState {
+
628 info!(
+
629 endpoint = %options.endpoint_id.fmt_short(),
+
630 relay_url =
?options.relay_url,
+
631 source = %options.source,
+
632 "inserting new endpoint in EndpointMap",
+
633 );
+
634 let id =
self.next_id;
+
635 self.next_id =
self.next_id.wrapping_add(
1);
+
636 let endpoint_state = EndpointState::new(id, options);
+
637
+
638 self.by_quic_mapped_addr
+
640 .insert(
*endpoint_state.quic_mapped_addr(), id);
+
641 self.by_endpoint_key
+
642 .insert(
*endpoint_state.public_key(), id);
643
-
644 self.by_quic_mapped_addr
-
646 .insert(
*endpoint_state.quic_mapped_addr(), id);
-
647 self.by_endpoint_key
-
648 .insert(
*endpoint_state.public_key(), id);
-
649
-
650 self.by_id.insert(id, endpoint_state);
-
651 self.by_id.get_mut(
&id).expect(
"just inserted")
-
652 }
-
653
-
654 fn set_endpoint_key_for_ip_port(
&mut self, ipp:
impl Into<IpPort>, nk:
&PublicKey) {
-
660 let ipp = ipp.into();
-
661 if let Some(id) =
self.by_ip_port.get(
&ipp) {
-
662 if !
self.by_endpoint_key.contains_key(nk) {
-
663 self.by_endpoint_key.insert(
*nk,
*id);
-
664 }
-
665 self.by_ip_port.remove(
&ipp);
-
666 }
-
667 if let Some(id) =
self.by_endpoint_key.get(nk) {
-
668 trace!(
"insert ip -> id: {:?} -> {}", ipp, id);
-
669 self.by_ip_port.insert(ipp,
*id);
-
670 }
+
644 self.by_id.insert(id, endpoint_state);
+
645 self.by_id.get_mut(
&id).expect(
"just inserted")
+
646 }
+
647
+
648 fn set_endpoint_key_for_ip_port(
&mut self, ipp:
impl Into<IpPort>, nk:
&PublicKey) {
+
654 let ipp = ipp.into();
+
655 if let Some(id) =
self.by_ip_port.get(
&ipp) {
+
656 if !
self.by_endpoint_key.contains_key(nk) {
+
657 self.by_endpoint_key.insert(
*nk,
*id);
+
658 }
+
659 self.by_ip_port.remove(
&ipp);
+
660 }
+
661 if let Some(id) =
self.by_endpoint_key.get(nk) {
+
662 trace!(
"insert ip -> id: {:?} -> {}", ipp, id);
+
663 self.by_ip_port.insert(ipp,
*id);
+
664 }
+
665 }
+
666
+
667 fn set_endpoint_state_for_ip_port(
&mut self, ipp:
impl Into<IpPort>, id: usize) {
+
668 let ipp = ipp.into();
+
669 trace!(
?ipp,
?id,
"set endpoint for ip:port");
+
670 self.by_ip_port.insert(ipp, id);
671 }
672
-
673 fn set_endpoint_state_for_ip_port(
&mut self, ipp:
impl Into<IpPort>, id: usize) {
-
674 let ipp = ipp.into();
-
675 trace!(
?ipp,
?id,
"set endpoint for ip:port");
-
676 self.by_ip_port.insert(ipp, id);
-
677 }
-
678
-
679 fn prune_inactive(
&mut self) {
-
681 let now = Instant::now();
-
682 let mut prune_candidates: Vec<
_> =
self
-683 .by_id
-
684 .values()
-
685 .filter(|endpoint| !endpoint.is_active(
&now))
-
686 .map(|endpoint| (
*endpoint.public_key(), endpoint.last_used()))
-
687 .collect();
-
688
-
689 let prune_count = prune_candidates
-
690 .len()
-
691 .saturating_sub(MAX_INACTIVE_ENDPOINTS);
-
692 if prune_count ==
0 {
-
693 return;
-
695 }
-
696
-
697 prune_candidates.sort_unstable_by_key(|(_pk, last_used)|
*last_used);
-
698 prune_candidates.truncate(prune_count);
-
699 for (public_key, last_used)
in prune_candidates.into_iter() {
-
700 let endpoint = public_key.fmt_short();
-
701 match last_used.map(|instant| instant.elapsed()) {
-
702 Some(last_used) =>
trace!(%endpoint,
?last_used,
"pruning inactive"),
-
703 None =>
trace!(%endpoint, last_used=%
"never",
"pruning inactive"),
-
704 }
-
705
-
706 let Some(id) =
self.by_endpoint_key.remove(
&public_key)
else {
-
707 debug_assert!(
false,
"missing by_endpoint_key entry for pk in by_id");
-
708 continue;
-
709 };
-
710
-
711 let Some(ep) =
self.by_id.remove(
&id)
else {
-
712 debug_assert!(
false,
"missing by_id entry for id in by_endpoint_key");
-
713 continue;
-
714 };
-
715
-
716 for ip_port
in ep.direct_addresses() {
-
717 self.by_ip_port.remove(
&ip_port);
-
718 }
-
719
-
720 self.by_quic_mapped_addr.remove(ep.quic_mapped_addr());
-
721 }
-
722 }
-
723}
-
724
-
725#[derive(Debug, derive_more::Display, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
-730#[display("{}", SocketAddr::from(*self))]
-731pub struct IpPort {
-
732 ip: IpAddr,
-
733 port: u16,
-
734}
-
735
-
736impl From<SocketAddr>
for IpPort {
-
737 fn from(socket_addr: SocketAddr) ->
Self {
-
738 Self {
-
739 ip: socket_addr.ip(),
-
740 port: socket_addr.port(),
-
741 }
-
742 }
-
743}
-
744
-
745impl From<IpPort>
for SocketAddr {
-
746 fn from(ip_port: IpPort) ->
Self {
-
747 let IpPort { ip, port } = ip_port;
-
748 (ip, port).into()
+
673 fn prune_inactive(
&mut self) {
+
675 let now = Instant::now();
+
676 let mut prune_candidates: Vec<
_> =
self
+677 .by_id
+
678 .values()
+
679 .filter(|endpoint| !endpoint.is_active(
&now))
+
680 .map(|endpoint| (
*endpoint.public_key(), endpoint.last_used()))
+
681 .collect();
+
682
+
683 let prune_count = prune_candidates
+
684 .len()
+
685 .saturating_sub(MAX_INACTIVE_ENDPOINTS);
+
686 if prune_count ==
0 {
+
687 return;
+
689 }
+
690
+
691 prune_candidates.sort_unstable_by_key(|(_pk, last_used)|
*last_used);
+
692 prune_candidates.truncate(prune_count);
+
693 for (public_key, last_used)
in prune_candidates.into_iter() {
+
694 let endpoint = public_key.fmt_short();
+
695 match last_used.map(|instant| instant.elapsed()) {
+
696 Some(last_used) =>
trace!(%endpoint,
?last_used,
"pruning inactive"),
+
697 None =>
trace!(%endpoint, last_used=%
"never",
"pruning inactive"),
+
698 }
+
699
+
700 let Some(id) =
self.by_endpoint_key.remove(
&public_key)
else {
+
701 debug_assert!(
false,
"missing by_endpoint_key entry for pk in by_id");
+
702 continue;
+
703 };
+
704
+
705 let Some(ep) =
self.by_id.remove(
&id)
else {
+
706 debug_assert!(
false,
"missing by_id entry for id in by_endpoint_key");
+
707 continue;
+
708 };
+
709
+
710 for ip_port
in ep.direct_addresses() {
+
711 self.by_ip_port.remove(
&ip_port);
+
712 }
+
713
+
714 self.by_quic_mapped_addr.remove(ep.quic_mapped_addr());
+
715 }
+
716 }
+
717}
+
718
+
719#[derive(Debug, derive_more::Display, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
+724#[display("{}", SocketAddr::from(*self))]
+725pub struct IpPort {
+
726 ip: IpAddr,
+
727 port: u16,
+
728}
+
729
+
730impl From<SocketAddr>
for IpPort {
+
731 fn from(socket_addr: SocketAddr) ->
Self {
+
732 Self {
+
733 ip: socket_addr.ip(),
+
734 port: socket_addr.port(),
+
735 }
+
736 }
+
737}
+
738
+
739impl From<IpPort>
for SocketAddr {
+
740 fn from(ip_port: IpPort) ->
Self {
+
741 let IpPort { ip, port } = ip_port;
+
742 (ip, port).into()
+
743 }
+
744}
+
745
+
746impl IpPort {
+
747 pub fn ip(
&self) ->
&IpAddr {
+
748 &self.ip
749 }
-
750}
-
751
-
752impl IpPort {
-
753 pub fn ip(
&self) ->
&IpAddr {
-
754 &self.ip
-
755 }
-
756
-
757 pub fn port(
&self) -> u16 {
-
758 self.port
-
759 }
-
760}
-
761
-
762#[cfg(test)]
-763mod tests {
-
764 use std::net::Ipv4Addr;
+
750
+
751 pub fn port(
&self) -> u16 {
+
752 self.port
+
753 }
+
754}
+
755
+
756#[cfg(test)]
+757mod tests {
+
758 use std::net::Ipv4Addr;
+
759
+
760 use iroh_base::SecretKey;
+
761 use rand::SeedableRng;
+
762 use tracing_test::traced_test;
+
763
+
764 use super::{endpoint_state::MAX_INACTIVE_DIRECT_ADDRESSES,
*};
765
-
766 use iroh_base::SecretKey;
-
767 use rand::SeedableRng;
-
768 use tracing_test::traced_test;
-
769
-
770 use super::{endpoint_state::MAX_INACTIVE_DIRECT_ADDRESSES,
*};
-
771
-
772 impl EndpointMap {
-
773 #[track_caller]
-774 fn add_test_addr(
&self, endpoint_addr: EndpointAddr) {
-
775 self.add_endpoint_addr(
-
776 endpoint_addr,
-
777 Source::NamedApp {
-
778 name:
"test".into(),
-
779 },
-
780 true,
-
781 &Default::default(),
-
782 )
-
783 }
-
784 }
+
766 impl EndpointMap {
+
767 #[track_caller]
+768 fn add_test_addr(
&self, endpoint_addr: EndpointAddr) {
+
769 self.add_endpoint_addr(
+
770 endpoint_addr,
+
771 Source::NamedApp {
+
772 name:
"test".into(),
+
773 },
+
774 true,
+
775 &Default::default(),
+
776 )
+
777 }
+
778 }
+
779
+
780 #[tokio::test]
+782 #[traced_test]
+783 async fn restore_from_vec() {
+
784 let endpoint_map = EndpointMap::default();
785
-
786 #[tokio::test]
-788 #[traced_test]
-789 async fn restore_from_vec() {
-
790 let endpoint_map = EndpointMap::default();
+
786 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(
0u64);
+
787 let endpoint_a = SecretKey::generate(
&mut rng).public();
+
788 let endpoint_b = SecretKey::generate(
&mut rng).public();
+
789 let endpoint_c = SecretKey::generate(
&mut rng).public();
+
790 let endpoint_d = SecretKey::generate(
&mut rng).public();
791
-
792 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(
0u64);
-
793 let endpoint_a = SecretKey::generate(
&mut rng).public();
-
794 let endpoint_b = SecretKey::generate(
&mut rng).public();
-
795 let endpoint_c = SecretKey::generate(
&mut rng).public();
-
796 let endpoint_d = SecretKey::generate(
&mut rng).public();
+
792 let relay_x: RelayUrl =
"https://my-relay-1.com".parse().unwrap();
+
793 let relay_y: RelayUrl =
"https://my-relay-2.com".parse().unwrap();
+
794
+
795 let direct_addresses_a = [addr(
4000), addr(
4001)];
+
796 let direct_addresses_c = [addr(
5000)];
797
-
798 let relay_x: RelayUrl =
"https://my-relay-1.com".parse().unwrap();
-
799 let relay_y: RelayUrl =
"https://my-relay-2.com".parse().unwrap();
-
800
-
801 let direct_addresses_a = [addr(
4000), addr(
4001)];
-
802 let direct_addresses_c = [addr(
5000)];
-
803
-
804 let endpoint_addr_a = EndpointAddr::new(endpoint_a)
-
805 .with_relay_url(relay_x)
-
806 .with_direct_addresses(direct_addresses_a);
-
807 let endpoint_addr_b = EndpointAddr::new(endpoint_b).with_relay_url(relay_y);
-
808 let endpoint_addr_c =
-
809 EndpointAddr::new(endpoint_c).with_direct_addresses(direct_addresses_c);
-
810 let endpoint_addr_d = EndpointAddr::new(endpoint_d);
-
811
-
812 endpoint_map.add_test_addr(endpoint_addr_a);
-
813 endpoint_map.add_test_addr(endpoint_addr_b);
-
814 endpoint_map.add_test_addr(endpoint_addr_c);
-
815 endpoint_map.add_test_addr(endpoint_addr_d);
-
816
-
817 let mut addrs: Vec<EndpointAddr> = endpoint_map
-
818 .list_remote_infos(Instant::now())
-
819 .into_iter()
-
820 .filter_map(|info| {
-
821 let addr: EndpointAddr = info.into();
-
822 if addr.is_empty() {
-
823 return None;
-
824 }
-
825 Some(addr)
-
826 })
-
827 .collect();
-
828 let loaded_endpoint_map = EndpointMap::load_from_vec(
-
829 addrs.clone(),
-
830 PathSelection::default(),
-
831 true,
-
832 &Default::default(),
-
833 );
-
834
-
835 let mut loaded: Vec<EndpointAddr> = loaded_endpoint_map
-
836 .list_remote_infos(Instant::now())
-
837 .into_iter()
-
838 .filter_map(|info| {
-
839 let addr: EndpointAddr = info.into();
-
840 if addr.is_empty() {
-
841 return None;
-
842 }
-
843 Some(addr)
-
844 })
-
845 .collect();
-
846
-
847 loaded.sort_unstable();
-
848 addrs.sort_unstable();
-
849
-
850 assert_eq!(addrs, loaded);
-
852 }
-
853
-
854 fn addr(port: u16) -> SocketAddr {
-
855 (std::net::IpAddr::V4(Ipv4Addr::LOCALHOST), port).into()
-
856 }
-
857
-
858 #[test]
-859 #[traced_test]
-860 fn test_prune_direct_addresses() {
-
861 let endpoint_map = EndpointMap::default();
-
862 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(
0u64);
-
863 let public_key = SecretKey::generate(
&mut rng).public();
-
864 let id = endpoint_map
-
865 .inner
-
866 .lock()
-
867 .unwrap()
-
868 .insert_endpoint(Options {
-
869 endpoint_id: public_key,
-
870 relay_url:
None,
-
871 active:
false,
-
872 source: Source::NamedApp {
-
873 name:
"test".into(),
-
874 },
-
875 path_selection: PathSelection::default(),
-
876 })
-
877 .id();
-
878
-
879 const LOCALHOST: IpAddr = IpAddr::V4(std::net::Ipv4Addr::LOCALHOST);
-
880
-
881 info!(
"Adding active addresses");
-
885 for i
in 0..MAX_INACTIVE_DIRECT_ADDRESSES {
-
886 let addr = SocketAddr::new(LOCALHOST,
5000 + i
as u16);
-
887 let endpoint_addr = EndpointAddr::new(public_key).with_direct_addresses([addr]);
-
888 endpoint_map.add_test_addr(endpoint_addr);
-
890 endpoint_map.inner.lock().unwrap().receive_udp(addr);
-
892 }
-
893
-
894 info!(
"Adding offline/inactive addresses");
-
895 for i
in 0..MAX_INACTIVE_DIRECT_ADDRESSES *
2 {
-
896 let addr = SocketAddr::new(LOCALHOST,
6000 + i
as u16);
-
897 let endpoint_addr = EndpointAddr::new(public_key).with_direct_addresses([addr]);
-
898 endpoint_map.add_test_addr(endpoint_addr);
-
899 }
-
900
-
901 let mut endpoint_map_inner = endpoint_map.inner.lock().unwrap();
-
902 let endpoint = endpoint_map_inner.by_id.get_mut(
&id).unwrap();
-
903
-
904 info!(
"Adding alive addresses");
-
905 for i
in 0..MAX_INACTIVE_DIRECT_ADDRESSES {
-
906 let addr = SendAddr::Udp(SocketAddr::new(LOCALHOST,
7000 + i
as u16));
-
907 let txid = stun_rs::TransactionId::from([i
as u8;
12]);
-
908 endpoint.handle_ping(addr, txid);
-
911 }
-
912
-
913 info!(
"Pruning addresses");
-
914 endpoint.prune_direct_addresses(Instant::now());
-
915
-
916
\ No newline at end of file
+