diff --git a/iroh/examples/auth-hook.rs b/iroh/examples/auth-hook.rs index c091ca0510..83541c2983 100644 --- a/iroh/examples/auth-hook.rs +++ b/iroh/examples/auth-hook.rs @@ -305,7 +305,7 @@ mod auth { impl EndpointHooks for IncomingAuthHook { async fn after_handshake<'a>( &'a self, - conn: &'a iroh::endpoint::ConnectionInfo, + conn: &'a iroh::endpoint::Connection, ) -> AfterHandshakeOutcome { if conn.alpn() == ALPN || self diff --git a/iroh/examples/monitor-connections.rs b/iroh/examples/monitor-connections.rs index 89a34d2e9f..ebde20a9f8 100644 --- a/iroh/examples/monitor-connections.rs +++ b/iroh/examples/monitor-connections.rs @@ -2,7 +2,7 @@ use std::{sync::Arc, time::Duration}; use iroh::{ Endpoint, Watcher, - endpoint::{AfterHandshakeOutcome, ConnectionInfo, EndpointHooks, presets}, + endpoint::{AfterHandshakeOutcome, Connection, EndpointHooks, WeakConnectionHandle, presets}, }; use n0_error::{Result, StackResultExt, StdResultExt, ensure_any}; use n0_future::task::AbortOnDropHandle; @@ -83,13 +83,33 @@ async fn main() -> Result { /// It could also maintain a datastructure of all connections, or send the stats to some metrics service. #[derive(Clone, Debug)] struct Monitor { - tx: UnboundedSender, + tx: UnboundedSender, _task: Arc>, } +/// Static info captured at handshake time, paired with a weak handle to the connection. +/// +/// We capture `alpn` and `remote_id` at hook time because [`WeakConnectionHandle`] only +/// exposes [`upgrade`] and [`closed`], so reading these fields after the connection has +/// been dropped would otherwise be impossible. +/// +/// [`upgrade`]: WeakConnectionHandle::upgrade +/// [`closed`]: WeakConnectionHandle::closed +#[derive(Debug)] +struct MonitoredConnection { + alpn: Vec, + remote_id: iroh::EndpointId, + handle: WeakConnectionHandle, +} + impl EndpointHooks for Monitor { - async fn after_handshake(&self, conn: &ConnectionInfo) -> AfterHandshakeOutcome { - self.tx.send(conn.clone()).ok(); + async fn after_handshake(&self, conn: &Connection) -> AfterHandshakeOutcome { + let info = MonitoredConnection { + alpn: conn.alpn().to_vec(), + remote_id: conn.remote_id(), + handle: conn.weak_handle(), + }; + self.tx.send(info).ok(); AfterHandshakeOutcome::Accept } } @@ -104,17 +124,17 @@ impl Monitor { } } - async fn run(mut rx: UnboundedReceiver) { + async fn run(mut rx: UnboundedReceiver) { let mut tasks = JoinSet::new(); loop { tokio::select! { - Some(conn) = rx.recv() => { - let alpn = String::from_utf8_lossy(conn.alpn()).to_string(); - let remote = conn.remote_id().fmt_short(); - let rtt = conn.paths().peek().iter().map(|p| p.stats().expect("conn is not dropped").rtt).min(); + Some(MonitoredConnection { alpn, remote_id, handle }) = rx.recv() => { + let alpn = String::from_utf8_lossy(&alpn).to_string(); + let remote = remote_id.fmt_short(); + let rtt = handle.upgrade().and_then(|c| c.paths().peek().iter().map(|p| p.stats().expect("conn is not dropped").rtt).min()); info!(%remote, %alpn, ?rtt, "new connection"); tasks.spawn(async move { - match conn.closed().await { + match handle.closed().await { Some((close_reason, stats)) => { // We have access to the final stats of the connection! info!(%remote, %alpn, ?close_reason, udp_rx=stats.udp_rx.bytes, udp_tx=stats.udp_tx.bytes, "connection closed"); diff --git a/iroh/examples/remote-info.rs b/iroh/examples/remote-info.rs index ea0b31f5fe..deff86efaf 100644 --- a/iroh/examples/remote-info.rs +++ b/iroh/examples/remote-info.rs @@ -167,7 +167,9 @@ mod remote_map { use iroh::{ EndpointId, Watcher, - endpoint::{AfterHandshakeOutcome, ConnectionInfo, EndpointHooks, PathInfo}, + endpoint::{ + AfterHandshakeOutcome, Connection, EndpointHooks, PathInfo, WeakConnectionHandle, + }, }; use n0_future::task::AbortOnDropHandle; use tokio::{sync::mpsc, task::JoinSet}; @@ -178,7 +180,7 @@ mod remote_map { #[derive(Debug, Default)] pub struct RemoteInfo { aggregate: Aggregate, - connections: HashMap, + connections: HashMap, } /// Aggregate information about a remote info. @@ -238,6 +240,7 @@ mod remote_map { /// Returns `None` if there are no active connections. pub fn current_min_rtt(&self) -> Option { self.connections() + .flat_map(|c| c.upgrade()) .flat_map(|c| c.paths().get().into_iter()) .flat_map(|p| p.stats()) .map(|s| s.rtt) @@ -249,6 +252,7 @@ mod remote_map { /// Returns `None` if there are no active connections. pub fn has_ip_path(&self) -> Option { self.connections() + .flat_map(|c| c.upgrade()) .flat_map(|c| c.paths().get()) .filter(|path| path.is_ip()) .map(|_| true) @@ -260,6 +264,7 @@ mod remote_map { /// Returns `None` if there are no active connections. pub fn has_relay_path(&self) -> Option { self.connections() + .flat_map(|c| c.upgrade()) .flat_map(|c| c.paths().get()) .filter(|path| path.is_relay()) .map(|_| true) @@ -271,8 +276,8 @@ mod remote_map { !self.connections.is_empty() } - /// Returns an iterator over [`ConnectionInfo`] for currently active connections to this remote. - pub fn connections(&self) -> impl Iterator { + /// Returns an iterator over [`WeakConnectionHandle`] for currently active connections to this remote. + pub fn connections(&self) -> impl Iterator { self.connections.values() } } @@ -289,13 +294,31 @@ mod remote_map { /// Hook to collect information about remote endpoints from an endpoint. #[derive(Debug)] pub struct RemoteMapHook { - tx: mpsc::Sender, + tx: mpsc::Sender, + } + + /// Pairing of a connection's remote endpoint id, captured at handshake time, with a + /// weak handle to the connection. The `remote_id` is captured eagerly because + /// [`WeakConnectionHandle`] only exposes [`upgrade`] and [`closed`]. + /// + /// [`upgrade`]: WeakConnectionHandle::upgrade + /// [`closed`]: WeakConnectionHandle::closed + #[derive(Debug, Clone)] + pub struct TrackedConnection { + pub remote_id: EndpointId, + pub handle: WeakConnectionHandle, } impl EndpointHooks for RemoteMapHook { - async fn after_handshake(&self, conn: &ConnectionInfo) -> AfterHandshakeOutcome { + async fn after_handshake(&self, conn: &Connection) -> AfterHandshakeOutcome { info!(remote=%conn.remote_id().fmt_short(), "after_handshake"); - self.tx.send(conn.clone()).await.ok(); + // We track the connection via a weak handle so this map does not keep the + // connection alive past the application's last reference to it. + let tracked = TrackedConnection { + remote_id: conn.remote_id(), + handle: conn.weak_handle(), + }; + self.tx.send(tracked).await.ok(); AfterHandshakeOutcome::Accept } } @@ -332,7 +355,7 @@ mod remote_map { } async fn run( - mut rx: mpsc::Receiver, + mut rx: mpsc::Receiver, map: RemoteMapInner, retention_time: Duration, ) { @@ -375,27 +398,28 @@ mod remote_map { tasks: &mut JoinSet<()>, map: RemoteMapInner, conn_id: u64, - conn: ConnectionInfo, + conn: TrackedConnection, ) { // Store conn info for full introspection possibility. { let mut inner = map.write().expect("poisoned"); inner - .entry(conn.remote_id()) + .entry(conn.remote_id) .or_default() .connections - .insert(conn_id, conn.clone()); + .insert(conn_id, conn.handle.clone()); } // Track connection closing to clear up the map. tasks.spawn({ - let conn = conn.clone(); + let remote_id = conn.remote_id; + let handle = conn.handle.clone(); let map = map.clone(); async move { - conn.closed().await; + handle.closed().await; { let mut inner = map.write().expect("poisoned"); - let info = inner.entry(conn.remote_id()).or_default(); + let info = inner.entry(remote_id).or_default(); info.connections.remove(&conn_id); info.aggregate.last_update = SystemTime::now(); } @@ -404,21 +428,24 @@ mod remote_map { }); // Track path changes to update stats aggregate. - tasks.spawn({ - async move { - let mut path_updates = conn.paths().stream(); - while let Some(paths) = path_updates.next().await { - { - let mut inner = map.write().expect("poisoned"); - let info = inner.entry(conn.remote_id()).or_default(); - for path in paths { - info.aggregate.update(&path); + if let Some(watcher) = conn.handle.upgrade().map(|c| c.paths()) { + let remote_id = conn.remote_id; + tasks.spawn({ + async move { + let mut path_updates = watcher.stream(); + while let Some(paths) = path_updates.next().await { + { + let mut inner = map.write().expect("poisoned"); + let info = inner.entry(remote_id).or_default(); + for path in paths { + info.aggregate.update(&path); + } } } } - } - .instrument(tracing::Span::current()) - }); + .instrument(tracing::Span::current()) + }); + } } async fn clear_expired( diff --git a/iroh/examples/transfer.rs b/iroh/examples/transfer.rs index 1be123c437..01cfbcd3a5 100644 --- a/iroh/examples/transfer.rs +++ b/iroh/examples/transfer.rs @@ -714,7 +714,7 @@ async fn fetch( // Attempt to connect, over the given ALPN. Returns a connection. let start = Instant::now(); let conn = endpoint.connect(remote_addr, TRANSFER_ALPN).await?; - let conn_info = conn.to_info(); + let conn_info = conn.weak_handle(); let remote_id = conn.remote_id(); output.emit(Connected { remote_id, diff --git a/iroh/src/endpoint.rs b/iroh/src/endpoint.rs index d1baff85ed..491661c227 100644 --- a/iroh/src/endpoint.rs +++ b/iroh/src/endpoint.rs @@ -79,9 +79,9 @@ pub use self::quic::{QlogConfig, QlogFactory, QlogFileFactory}; pub use self::{ connection::{ Accept, Accepting, AlpnError, AuthenticationError, Connecting, ConnectingError, Connection, - ConnectionInfo, ConnectionState, HandshakeCompleted, Incoming, IncomingAddr, - IncomingZeroRtt, IncomingZeroRttConnection, OutgoingZeroRtt, OutgoingZeroRttConnection, - RemoteEndpointIdError, RetryError, ZeroRttStatus, + ConnectionState, HandshakeCompleted, Incoming, IncomingAddr, IncomingZeroRtt, + IncomingZeroRttConnection, OutgoingZeroRtt, OutgoingZeroRttConnection, + RemoteEndpointIdError, RetryError, WeakConnectionHandle, ZeroRttStatus, }, quic::{ AcceptBi, AcceptUni, AckFrequencyConfig, ApplicationClose, Chunk, ClosedStream, diff --git a/iroh/src/endpoint/connection.rs b/iroh/src/endpoint/connection.rs index 40974a7e80..fa7d37a54d 100644 --- a/iroh/src/endpoint/connection.rs +++ b/iroh/src/endpoint/connection.rs @@ -30,7 +30,7 @@ use futures_util::{FutureExt, future::Shared}; use iroh_base::{EndpointId, RelayUrl}; use n0_error::{e, stack_error}; use n0_future::{TryFutureExt, future::Boxed as BoxFuture, time::Duration}; -use noq::WeakConnectionHandle; +use noq::WeakConnectionHandle as NoqWeakConnectionHandle; use pin_project::pin_project; use tracing::{event, warn}; @@ -47,7 +47,7 @@ use crate::{ }, socket::{ RemoteStateActorStoppedError, - remote_map::{PathInfo, PathWatchable, PathWatcher}, + remote_map::{PathWatchable, PathWatcher}, transports, }, }; @@ -351,7 +351,7 @@ fn conn_from_noq_conn( }; if let AfterHandshakeOutcome::Reject { error_code, reason } = - inner.hooks.after_handshake(&conn.to_info()).await + inner.hooks.after_handshake(&conn).await { conn.close(error_code, &reason); return Err(e!(ConnectingError::LocallyRejected)); @@ -1104,6 +1104,10 @@ impl Connection { /// iterate over the path stats while the [`Connection`] struct is still in scope. /// /// [`PathInfoList`]: crate::endpoint::PathInfoList + /// [`PathInfo`]: crate::endpoint::PathInfo + /// [`PathInfo::is_selected`]: crate::endpoint::PathInfo::is_selected + /// [`PathInfo::is_closed`]: crate::endpoint::PathInfo::is_closed + /// [`PathInfo::stats`]: crate::endpoint::PathInfo::stats /// [`Watcher`]: crate::Watcher pub fn paths(&self) -> PathWatcher { self.data.paths.watch() @@ -1114,15 +1118,16 @@ impl Connection { self.inner.side() } - /// Returns a connection info struct. + /// Returns a [`WeakConnectionHandle`] for this connection. /// - /// A [`ConnectionInfo`] is a weak handle to the connection that does not keep the connection alive, - /// but does allow to access some information about the connection and to wait for the connection to be closed. - pub fn to_info(&self) -> ConnectionInfo { - ConnectionInfo { + /// A [`WeakConnectionHandle`] does not keep the connection alive. It can be used to + /// wait for the connection to be closed via [`WeakConnectionHandle::closed`] and to + /// attempt to upgrade back to a strong [`Connection`] via + /// [`WeakConnectionHandle::upgrade`]. + pub fn weak_handle(&self) -> WeakConnectionHandle { + WeakConnectionHandle { data: self.data.clone(), inner: self.inner.weak_handle(), - side: self.side(), } } } @@ -1204,61 +1209,52 @@ impl Connection { } } -/// Information about a connection. +/// A weak handle to a [`Connection`]. /// -/// A [`ConnectionInfo`] is a weak handle to a connection that exposes some information about the connection, -/// but does not keep the connection alive. +/// A [`WeakConnectionHandle`] does not keep the connection alive: holding one will not +/// prevent the connection from being closed when the last [`Connection`] handle is dropped. +/// +/// Use [`upgrade`] to obtain a strong [`Connection`], and [`closed`] to wait for the +/// connection to be closed without keeping it alive. +/// +/// [`upgrade`]: WeakConnectionHandle::upgrade +/// [`closed`]: WeakConnectionHandle::closed #[derive(Debug, Clone)] -pub struct ConnectionInfo { - side: Side, +pub struct WeakConnectionHandle { data: HandshakeCompletedData, - inner: WeakConnectionHandle, + inner: NoqWeakConnectionHandle, } -#[allow(missing_docs)] -impl ConnectionInfo { - pub fn alpn(&self) -> &[u8] { - &self.data.info.alpn - } - - pub fn remote_id(&self) -> EndpointId { - self.data.info.endpoint_id - } - - pub fn is_alive(&self) -> bool { - self.inner.upgrade().is_some() - } - - /// Returns a watcher for the network paths of this connection. +impl WeakConnectionHandle { + /// Attempts to upgrade this weak handle to a strong [`Connection`]. /// - /// See [`Connection::paths`] for details. - pub fn paths(&self) -> PathWatcher { - self.data.paths.watch() + /// Returns `None` if the connection has already been dropped. + pub fn upgrade(&self) -> Option { + self.inner.upgrade().map(|inner| Connection { + inner, + data: self.data.clone(), + }) } - /// Returns connection statistics. + /// Returns a future that resolves once the connection has been closed. /// - /// Returns `None` if the connection has been dropped. - pub fn stats(&self) -> Option { - self.inner.upgrade().map(|conn| conn.stats()) - } - - /// Returns the side of the connection (client or server). - pub fn side(&self) -> Side { - self.side - } - - /// Waits for the connection to be closed, and returns the close reason and final connection stats. + /// If no strong references to the [`Connection`] exist at the time this is called, + /// the future resolves to `None`. If at least one strong reference still exists at + /// the time of this call, the returned future is guaranteed to receive the close + /// event with the close reason and final connection statistics, even if all strong + /// references are dropped before the future is awaited. /// - /// Returns `None` if the connection has been dropped already before this call. - pub async fn closed(&self) -> Option<(ConnectionError, ConnectionStats)> { - let fut = self.inner.upgrade()?.on_closed(); - Some(fut.await) - } - - /// Returns the currently selected path. - pub fn selected_path(&self) -> Option { - self.paths().into_iter().find(|path| path.is_selected()) + /// The future does not keep the connection alive. + pub fn closed( + &self, + ) -> impl Future> + Send + 'static { + let registered = self.inner.upgrade().map(|conn| conn.on_closed()); + async move { + match registered { + Some(fut) => Some(fut.await), + None => None, + } + } } } diff --git a/iroh/src/endpoint/hooks.rs b/iroh/src/endpoint/hooks.rs index f0beed7944..4050446683 100644 --- a/iroh/src/endpoint/hooks.rs +++ b/iroh/src/endpoint/hooks.rs @@ -2,7 +2,7 @@ use std::pin::Pin; use iroh_base::EndpointAddr; -use crate::endpoint::{connection::ConnectionInfo, quic::VarInt}; +use crate::endpoint::{connection::Connection, quic::VarInt}; type BoxFuture<'a, T> = Pin + Send + 'a>>; @@ -89,9 +89,19 @@ pub trait EndpointHooks: std::fmt::Debug + Send + Sync { /// At this point in time, we know the remote's endpoint id and ALPN. If any hook returns /// [`AfterHandshakeOutcome::Reject`], the connection is closed with the provided error code /// and reason. + /// + /// The hook receives the [`Connection`] by reference so that implementations can read any + /// information they need synchronously. Do not clone the [`Connection`] out of the hook: + /// holding a strong [`Connection`] handle keeps the connection alive and disables + /// close-on-drop, which the primary use sites of the connection might rely on. If you need to + /// keep a reference for later (for example to wait for the connection to close, or to + /// look up the connection in a map), call [`Connection::weak_handle`] and store the + /// resulting [`WeakConnectionHandle`] instead. + /// + /// [`WeakConnectionHandle`]: crate::endpoint::WeakConnectionHandle fn after_handshake<'a>( &'a self, - _conn: &'a ConnectionInfo, + _conn: &'a Connection, ) -> impl Future + Send + 'a { async { AfterHandshakeOutcome::accept() } } @@ -103,10 +113,7 @@ pub(crate) trait DynEndpointHooks: std::fmt::Debug + Send + Sync { remote_addr: &'a EndpointAddr, alpn: &'a [u8], ) -> BoxFuture<'a, BeforeConnectOutcome>; - fn after_handshake<'a>( - &'a self, - conn: &'a ConnectionInfo, - ) -> BoxFuture<'a, AfterHandshakeOutcome>; + fn after_handshake<'a>(&'a self, conn: &'a Connection) -> BoxFuture<'a, AfterHandshakeOutcome>; } impl DynEndpointHooks for T { @@ -118,10 +125,7 @@ impl DynEndpointHooks for T { Box::pin(EndpointHooks::before_connect(self, remote_addr, alpn)) } - fn after_handshake<'a>( - &'a self, - conn: &'a ConnectionInfo, - ) -> BoxFuture<'a, AfterHandshakeOutcome> { + fn after_handshake<'a>(&'a self, conn: &'a Connection) -> BoxFuture<'a, AfterHandshakeOutcome> { Box::pin(EndpointHooks::after_handshake(self, conn)) } } @@ -153,7 +157,7 @@ impl EndpointHooksList { BeforeConnectOutcome::Accept } - pub(super) async fn after_handshake(&self, conn: &ConnectionInfo) -> AfterHandshakeOutcome { + pub(super) async fn after_handshake(&self, conn: &Connection) -> AfterHandshakeOutcome { for hook in self.inner.iter() { match hook.after_handshake(conn).await { AfterHandshakeOutcome::Accept => continue,