iroh/socket/remote_map/remote_state/
path_watcher.rs1use std::{
27 pin::Pin,
28 sync::{Arc, Mutex},
29 task::{Context, Poll},
30};
31
32use iroh_base::TransportAddr;
33use n0_future::{StreamExt, time::Duration};
34use noq::WeakPathHandle;
35use noq_proto::PathId;
36use smallvec::SmallVec;
37use tokio::sync::{Notify, broadcast, futures::Notified};
38use tokio_stream::{
39 Stream,
40 wrappers::{BroadcastStream, errors::BroadcastStreamRecvError},
41};
42use tracing::warn;
43
44use crate::{
45 endpoint::PathStats,
46 socket::transports::{self, LocalTransportAddr},
47};
48
49const BROADCAST_CAPACITY: usize = 8;
51
52#[derive(Clone, Debug)]
54#[non_exhaustive]
55pub enum PathEvent {
56 #[non_exhaustive]
58 Opened {
59 id: PathId,
61 remote_addr: TransportAddr,
63 local_addr: LocalTransportAddr,
65 },
66 #[non_exhaustive]
68 Closed {
69 id: PathId,
71 remote_addr: TransportAddr,
73 local_addr: LocalTransportAddr,
75 last_stats: Box<PathStats>,
77 },
78 #[non_exhaustive]
80 Selected {
81 id: PathId,
83 remote_addr: TransportAddr,
85 local_addr: LocalTransportAddr,
87 },
88 #[non_exhaustive]
97 Lagged {
98 missed: u64,
100 },
101}
102
103#[derive(Clone, derive_more::Debug)]
104#[debug("PathData({}, {})", self.handle.id(), self.remote_addr)]
105struct PathData {
106 handle: WeakPathHandle,
107 remote_addr: TransportAddr,
108 local_addr: LocalTransportAddr,
109}
110
111impl PathData {
112 fn upgrade(&self, _conn: &noq::Connection) -> noq::Path {
118 self.handle
119 .upgrade()
120 .expect("Wrong Connection reference passed to PathData::upgrade")
121 }
122}
123
124#[derive(Default, Debug, Clone)]
125struct State {
126 list: SmallVec<[PathData; 4]>,
127 selected: Option<PathId>,
128 closed: bool,
129}
130
131#[derive(Debug)]
132struct Shared {
133 state: Mutex<State>,
134 notify: Notify,
135}
136
137#[derive(Debug)]
145pub(super) struct PathStateSender {
146 shared: Arc<Shared>,
147 events: broadcast::Sender<PathEvent>,
148}
149
150impl PathStateSender {
151 pub(super) fn new() -> (Self, PathStateReceiver) {
156 let (events, _) = broadcast::channel(BROADCAST_CAPACITY);
157 let shared = Arc::new(Shared {
158 state: Default::default(),
159 notify: Notify::new(),
160 });
161 let receiver = PathStateReceiver {
162 shared: shared.clone(),
163 events: events.downgrade(),
164 };
165 let sender = PathStateSender { shared, events };
166 (sender, receiver)
167 }
168
169 pub(super) fn record_opened(
171 &self,
172 handle: WeakPathHandle,
173 network_path: transports::FourTuple,
174 ) {
175 let id = handle.id();
176 let remote_addr: TransportAddr = network_path.remote().into();
177 let local_addr = network_path.local();
178 {
179 let mut state = self.shared.state.lock().expect("poisoned");
180 let entry = PathData {
181 handle,
182 remote_addr: remote_addr.clone(),
183 local_addr: local_addr.clone(),
184 };
185 match state.list.iter().position(|e| e.handle.id() == id) {
186 Some(idx) => state.list[idx] = entry,
187 None => state.list.push(entry),
188 }
189 }
190 self.shared.notify.notify_waiters();
191 let _ = self.events.send(PathEvent::Opened {
192 id,
193 remote_addr,
194 local_addr,
195 });
196 }
197
198 pub(super) fn record_abandoned(&self, id: PathId, conn: &noq::Connection) {
200 let removed = {
201 let mut state = self.shared.state.lock().expect("poisoned");
202 if state.selected == Some(id) {
203 state.selected = None;
204 }
205 state
206 .list
207 .iter()
208 .position(|e| e.handle.id() == id)
209 .map(|pos| state.list.remove(pos))
210 };
211 if let Some(data) = removed {
212 let stats = data.upgrade(conn).stats();
213 self.shared.notify.notify_waiters();
214 let _ = self.events.send(PathEvent::Closed {
215 id,
216 remote_addr: data.remote_addr.clone(),
217 local_addr: data.local_addr.clone(),
218 last_stats: Box::new(stats),
219 });
220 }
221 }
222
223 pub(super) fn record_selected(&self, network_path: &transports::FourTuple) {
225 let remote_addr: TransportAddr = network_path.remote().into();
226 let local_addr = network_path.local();
227 let event = {
228 let mut state = self.shared.state.lock().expect("poisoned");
229 let selected_path_id = state
230 .list
231 .iter()
232 .find(|p| p.remote_addr == remote_addr && p.local_addr == local_addr)
233 .map(|p| p.handle.id());
234 if selected_path_id != state.selected {
235 state.selected = selected_path_id;
236 selected_path_id.map(|path_id| PathEvent::Selected {
237 id: path_id,
238 remote_addr: remote_addr.clone(),
239 local_addr: local_addr.clone(),
240 })
241 } else {
242 None
243 }
244 };
245 if let Some(event) = event {
246 let _ = self.events.send(event);
247 self.shared.notify.notify_waiters();
248 }
249 }
250
251 pub(super) fn close(self, closed: noq::Closed) {
259 let mut state = self.shared.state.lock().expect("poisoned");
260 if !state.closed {
261 for path in state.list.iter() {
262 if let Some(stats) = closed
263 .path_stats
264 .iter()
265 .find(|(id, _stats)| *id == path.handle.id())
266 .map(|(_id, stats)| stats)
267 {
268 let _ = self.events.send(PathEvent::Closed {
269 id: path.handle.id(),
270 remote_addr: path.remote_addr.clone(),
271 local_addr: path.local_addr.clone(),
272 last_stats: Box::new(*stats),
273 });
274 } else {
275 warn!(
276 "Connection close event is missing path stats for path {}",
277 path.handle.id()
278 );
279 }
280 }
281 state.closed = true;
282 self.shared.notify.notify_waiters();
283 }
284 }
285}
286
287impl Drop for PathStateSender {
288 fn drop(&mut self) {
289 let mut state = self.shared.state.lock().expect("poisoned");
290 if !state.closed {
291 state.closed = true;
292 self.shared.notify.notify_waiters();
293 }
294 }
295}
296
297#[derive(Clone, Debug)]
303pub(crate) struct PathStateReceiver {
304 shared: Arc<Shared>,
305 events: broadcast::WeakSender<PathEvent>,
306}
307
308impl PathStateReceiver {
309 pub(crate) fn get<'a>(&self, conn: &'a noq::Connection) -> PathList<'a> {
311 PathList {
312 snapshot: self.shared.state.lock().expect("poisoned").clone(),
313 conn,
314 }
315 }
316
317 pub(crate) fn events(&self) -> PathEventStream {
321 let receiver = if let Some(sender) = self.events.upgrade() {
322 sender.subscribe()
323 } else {
324 let (_tx, rx) = broadcast::channel(1);
325 rx
326 };
327 PathEventStream {
328 inner: BroadcastStream::new(receiver),
329 }
330 }
331
332 pub(crate) fn stream<'a>(&'a self, conn: &'a noq::Connection) -> PathListStream<'a> {
338 PathListStream {
339 shared: &self.shared,
340 conn,
341 notified: Box::pin(self.shared.notify.notified()),
342 first_poll: true,
343 }
344 }
345}
346
347#[derive(Clone, derive_more::Debug)]
356pub struct PathList<'conn> {
357 snapshot: State,
358 #[debug(skip)]
359 conn: &'conn noq::Connection,
360}
361
362impl<'conn> PathList<'conn> {
363 pub fn len(&self) -> usize {
365 self.snapshot.list.len()
366 }
367
368 pub fn is_empty(&self) -> bool {
370 self.snapshot.list.is_empty()
371 }
372
373 pub fn iter(&self) -> PathListIter<'_> {
375 PathListIter {
376 inner: self.snapshot.list.iter(),
377 selected: self.snapshot.selected,
378 conn: self.conn,
379 }
380 }
381
382 pub fn get(&self, id: PathId) -> Option<Path<'_>> {
387 self.iter().find(|p| p.id() == id)
388 }
389}
390
391impl<'a> IntoIterator for &'a PathList<'a> {
392 type IntoIter = PathListIter<'a>;
393 type Item = Path<'a>;
394 fn into_iter(self) -> Self::IntoIter {
395 self.iter()
396 }
397}
398
399#[derive(Debug)]
401pub struct PathListIter<'a> {
402 inner: std::slice::Iter<'a, PathData>,
403 selected: Option<PathId>,
404 conn: &'a noq::Connection,
405}
406
407impl<'a> PathListIter<'a> {
408 fn item(&self, data: &'a PathData) -> Path<'a> {
409 Path {
410 data,
411 is_selected: self.selected == Some(data.handle.id()),
412 conn: self.conn,
413 }
414 }
415}
416
417impl<'a> Iterator for PathListIter<'a> {
418 type Item = Path<'a>;
419
420 fn next(&mut self) -> Option<Self::Item> {
421 self.inner.next().map(|d| self.item(d))
422 }
423
424 fn size_hint(&self) -> (usize, Option<usize>) {
425 self.inner.size_hint()
426 }
427}
428
429impl<'a> DoubleEndedIterator for PathListIter<'a> {
430 fn next_back(&mut self) -> Option<Self::Item> {
431 self.inner.next_back().map(|d| self.item(d))
432 }
433}
434
435impl ExactSizeIterator for PathListIter<'_> {}
436
437#[derive(Clone, Debug)]
446pub struct Path<'a> {
447 data: &'a PathData,
448 is_selected: bool,
449 conn: &'a noq::Connection,
451}
452
453impl<'conn> Path<'conn> {
454 pub fn id(&self) -> PathId {
456 self.data.handle.id()
457 }
458
459 pub fn remote_addr(&self) -> &TransportAddr {
461 &self.data.remote_addr
462 }
463
464 pub fn local_addr(&self) -> &LocalTransportAddr {
466 &self.data.local_addr
467 }
468
469 pub fn is_selected(&self) -> bool {
471 self.is_selected
472 }
473
474 pub fn is_ip(&self) -> bool {
476 self.data.remote_addr.is_ip()
477 }
478
479 pub fn is_relay(&self) -> bool {
481 self.data.remote_addr.is_relay()
482 }
483
484 pub fn stats(&self) -> PathStats {
490 self.data.upgrade(self.conn).stats()
491 }
492
493 pub fn rtt(&self) -> Duration {
495 self.stats().rtt
496 }
497}
498
499#[derive(Debug)]
507pub struct PathListStream<'conn> {
508 shared: &'conn Shared,
509 conn: &'conn noq::Connection,
510 notified: Pin<Box<Notified<'conn>>>,
511 first_poll: bool,
512}
513
514impl<'conn> Stream for PathListStream<'conn> {
515 type Item = PathList<'conn>;
516
517 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
518 let this = self.get_mut();
519 if this.first_poll {
520 this.first_poll = false;
521 } else {
522 std::task::ready!(this.notified.as_mut().poll(cx));
523 this.notified.set(this.shared.notify.notified());
524 }
525 this.notified.as_mut().enable();
526 let snapshot = this.shared.state.lock().expect("poisoned").clone();
527 if snapshot.closed {
528 Poll::Ready(None)
529 } else {
530 Poll::Ready(Some(PathList {
531 snapshot,
532 conn: this.conn,
533 }))
534 }
535 }
536}
537
538#[derive(Debug)]
544pub struct PathEventStream {
545 inner: BroadcastStream<PathEvent>,
546}
547
548impl Stream for PathEventStream {
549 type Item = PathEvent;
550 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
551 self.inner.poll_next(cx).map(|event| match event? {
552 Ok(event) => Some(event),
553 Err(BroadcastStreamRecvError::Lagged(missed)) => Some(PathEvent::Lagged { missed }),
554 })
555 }
556}