From 9cf417aa9700e2dc77fc56add8bf54cdb7dadc1b Mon Sep 17 00:00:00 2001 From: ramfox Date: Thu, 19 Feb 2026 13:24:53 -0500 Subject: [PATCH] feat(iroh)!: dropping the endpoint ungracefully should log and error, but still clean up resources immediately (#3879) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Description closes https://github.com/n0-computer/iroh/issues/3867 relies on https://github.com/n0-computer/iroh/pull/3924 Alot of finagaling needed to happen to ensure that when the Endpoint is dropped, it's underlying resources are cleaned up ASAP. First, added a custom `Runtime` that wraps spawned tasks in a `CancellationToken`. This allows for both graceful shutdown (which does not use the cancel token, but instead waits for tasks to finish naturally) and ungraceful abort (which uses the cancel token to stop all running tasks) Wrote a new `Handle::abort` method that is sync and does not wait for graceful clean up after cancelling tokens, before aborting any runtime tasks. In order to ensure that the `Endpoint` is only "aborted" on the last clone of the endpoint, `StaticConfig` was moved into the `Handle`, and it was renamed to `EndpointInner` that is now wrapped in an `Arc`. When the `Arc` is finally dropped, the `Drop` impl on `EndpointInner` is called, which calls `Handle::abort`, if the `Endpoint` was not gracefully closed before dropping. This PR also makes sure that we drop any references to address lookup services on close. ## Breaking Changes New behavioral change! Then `Endpoint` does not do ANY best-effort to close connections gracefully before dropping. This makes it even more important to call `Endpoint::close` in all cases. This change (that prevents the underlying `quinn::Endpoint` to do it's best to wait/send close frames before shutting down) has already highlighted in tests how much more brittle it is to drop the endpoint without calling `close` first. ## Change checklist - [x] Self-review. - [x] Documentation updates following the [style guide](https://rust-lang.github.io/rfcs/1574-more-api-documentation-conventions.html#appendix-a-full-conventions-text), if relevant. - [x] Tests if relevant. Co-authored-by: “ramfox” <“kasey@n0.computer”> Co-authored-by: Franz Heinzmann --- Cargo.lock | 30 +-- iroh/src/address_lookup.rs | 8 +- iroh/src/endpoint.rs | 437 +++++++++++++++++++++++++------- iroh/src/endpoint/connection.rs | 6 +- iroh/src/lib.rs | 3 +- iroh/src/runtime.rs | 138 ++++++++++ iroh/src/socket.rs | 217 +++++++++++----- iroh/src/web_runtime.rs | 33 --- 8 files changed, 668 insertions(+), 204 deletions(-) create mode 100644 iroh/src/runtime.rs delete mode 100644 iroh/src/web_runtime.rs diff --git a/Cargo.lock b/Cargo.lock index 5abc4959b7..1e7e9201b7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1157,7 +1157,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -1736,7 +1736,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2 0.6.2", + "socket2 0.5.10", "tokio", "tower-service", "tracing", @@ -2157,7 +2157,7 @@ dependencies = [ [[package]] name = "iroh-quinn" version = "0.16.1" -source = "git+https://github.com/n0-computer/quinn?branch=main#d5580a52928327a16ca9c0901d88cc9396f1b284" +source = "git+https://github.com/n0-computer/quinn?branch=main#ebbd7654658415a3c5e627f0c0113e6abc2ac020" dependencies = [ "bytes", "cfg_aliases", @@ -2166,7 +2166,7 @@ dependencies = [ "pin-project-lite", "rustc-hash", "rustls", - "socket2 0.6.2", + "socket2 0.5.10", "thiserror 2.0.18", "tokio", "tokio-stream", @@ -2177,7 +2177,7 @@ dependencies = [ [[package]] name = "iroh-quinn-proto" version = "0.15.1" -source = "git+https://github.com/n0-computer/quinn?branch=main#d5580a52928327a16ca9c0901d88cc9396f1b284" +source = "git+https://github.com/n0-computer/quinn?branch=main#ebbd7654658415a3c5e627f0c0113e6abc2ac020" dependencies = [ "bytes", "derive_more", @@ -2204,11 +2204,11 @@ dependencies = [ [[package]] name = "iroh-quinn-udp" version = "0.8.0" -source = "git+https://github.com/n0-computer/quinn?branch=main#d5580a52928327a16ca9c0901d88cc9396f1b284" +source = "git+https://github.com/n0-computer/quinn?branch=main#ebbd7654658415a3c5e627f0c0113e6abc2ac020" dependencies = [ "cfg_aliases", "libc", - "socket2 0.6.2", + "socket2 0.5.10", "tracing", "windows-sys 0.61.2", ] @@ -2770,7 +2770,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -3315,7 +3315,7 @@ dependencies = [ "quinn-udp", "rustc-hash", "rustls", - "socket2 0.6.2", + "socket2 0.5.10", "thiserror 2.0.18", "tokio", "tracing", @@ -3352,9 +3352,9 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2 0.6.2", + "socket2 0.5.10", "tracing", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -3624,7 +3624,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -3716,7 +3716,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -3820,7 +3820,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b55fb86dfd3a2f5f76ea78310a88f96c4ea21a3031f8d212443d56123fd0521" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -4270,7 +4270,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] diff --git a/iroh/src/address_lookup.rs b/iroh/src/address_lookup.rs index 30164fa3e3..69eb86693b 100644 --- a/iroh/src/address_lookup.rs +++ b/iroh/src/address_lookup.rs @@ -451,7 +451,7 @@ impl ConcurrentAddressLookup { self.services.write().expect("poisoned").push(service); } - /// Is there any services configured? + /// Are there any services configured? pub fn is_empty(&self) -> bool { self.services.read().expect("poisoned").is_empty() } @@ -460,6 +460,12 @@ impl ConcurrentAddressLookup { pub fn len(&self) -> usize { self.services.read().expect("poisoned").len() } + + /// Removes all configured services. + pub fn clear(&self) { + let mut services = self.services.write().expect("poisoned"); + services.clear(); + } } impl From for ConcurrentAddressLookup diff --git a/iroh/src/endpoint.rs b/iroh/src/endpoint.rs index 836184b314..751cd12ffd 100644 --- a/iroh/src/endpoint.rs +++ b/iroh/src/endpoint.rs @@ -13,7 +13,7 @@ #[cfg(not(wasm_browser))] use std::net::SocketAddr; -use std::sync::Arc; +use std::{pin::Pin, sync::Arc}; use iroh_base::{EndpointAddr, EndpointId, RelayUrl, SecretKey, TransportAddr}; use iroh_relay::{RelayConfig, RelayMap}; @@ -23,6 +23,8 @@ use n0_error::{e, ensure, stack_error}; use n0_watcher::Watcher; #[cfg(not(wasm_browser))] use netdev::ipnet::{Ipv4Net, Ipv6Net}; +use pin_project::pin_project; +use tokio_util::sync::WaitForCancellationFutureOwned; use tracing::{debug, instrument, trace, warn}; use url::Url; @@ -43,7 +45,9 @@ use crate::{ }, endpoint::presets::Preset, metrics::EndpointMetrics, - socket::{self, Handle, RemoteStateActorStoppedError, mapped_addrs::MappedAddr}, + socket::{ + self, EndpointInner, RemoteStateActorStoppedError, StaticConfig, mapped_addrs::MappedAddr, + }, tls::{self, DEFAULT_MAX_TLS_TICKETS}, }; @@ -208,15 +212,15 @@ impl Builder { insecure_skip_relay_cert_verify: self.insecure_skip_relay_cert_verify, metrics, hooks: self.hooks, + static_config, }; - let sock = socket::Socket::spawn(sock_opts).await?; + let inner = socket::Socket::spawn(sock_opts).await?; trace!("created socket"); debug!(version = env!("CARGO_PKG_VERSION"), "iroh Endpoint created"); let ep = Endpoint { - sock, - static_config: Arc::new(static_config), + inner: Arc::new(inner), }; // Add Address Lookup mechanisms @@ -633,26 +637,6 @@ impl Builder { } } -/// Configuration for a [`quinn::Endpoint`] that cannot be changed at runtime. -#[derive(Debug)] -struct StaticConfig { - tls_config: tls::TlsConfig, - transport_config: QuicTransportConfig, - keylog: bool, -} - -impl StaticConfig { - /// Create a [`ServerConfig`] with the specified ALPN protocols. - fn create_server_config(&self, alpn_protocols: Vec>) -> quinn_proto::ServerConfig { - let quic_server_config = self - .tls_config - .make_server_config(alpn_protocols, self.keylog); - let mut inner = quinn::ServerConfig::with_crypto(Arc::new(quic_server_config)); - inner.transport_config(self.transport_config.to_inner_arc()); - inner - } -} - #[allow(missing_docs)] #[stack_error(derive, add_meta)] #[non_exhaustive] @@ -688,10 +672,7 @@ pub enum EndpointError { /// [QUIC]: https://quicwg.org #[derive(Clone, Debug)] pub struct Endpoint { - /// Handle to the socket/actor - pub(crate) sock: Handle, - /// Configuration structs for quinn, holds the transport config, certificate setup, secret key etc. - static_config: Arc, + inner: Arc, } #[allow(missing_docs)] @@ -774,8 +755,10 @@ impl Endpoint { warn!("Attempting to set ALPNs for a closed endpoint. Ignoring."); return; } - let server_config = self.static_config.create_server_config(alpns); - self.sock.endpoint().set_server_config(Some(server_config)); + let server_config = self.inner.static_config.create_server_config(alpns); + self.inner + .quinn_endpoint() + .set_server_config(Some(server_config)); } /// Adds the provided configuration to the [`RelayMap`]. @@ -791,7 +774,7 @@ impl Endpoint { if self.is_closed() { return None; } - self.sock.insert_relay(relay, config).await + self.inner.insert_relay(relay, config).await } /// Removes the configuration from the [`RelayMap`] for the provided [`RelayUrl`]. @@ -801,7 +784,7 @@ impl Endpoint { if self.is_closed() { return None; } - self.sock.remove_relay(relay).await + self.inner.remove_relay(relay).await } // # Methods for establishing connectivity. @@ -880,7 +863,7 @@ impl Endpoint { } let endpoint_addr: EndpointAddr = endpoint_addr.into(); if let BeforeConnectOutcome::Reject = - self.sock.hooks.before_connect(&endpoint_addr, alpn).await + self.inner.hooks.before_connect(&endpoint_addr, alpn).await { return Err(e!(ConnectWithOptsError::LocallyRejected)); } @@ -898,12 +881,12 @@ impl Endpoint { "connecting", ); - let mapped_addr = self.sock.resolve_remote(endpoint_addr).await??; + let mapped_addr = self.inner.resolve_remote(endpoint_addr).await??; let transport_config = options .transport_config .map(|cfg| cfg.to_inner_arc()) - .unwrap_or(self.static_config.transport_config.to_inner_arc()); + .unwrap_or(self.inner.static_config.transport_config.to_inner_arc()); // Start connecting via quinn. This will time out after 10 seconds if no reachable // address is available. @@ -912,9 +895,10 @@ impl Endpoint { let mut alpn_protocols = vec![alpn.to_vec()]; alpn_protocols.extend(options.additional_alpns); let quic_client_config = self + .inner .static_config .tls_config - .make_client_config(alpn_protocols, self.static_config.keylog); + .make_client_config(alpn_protocols, self.inner.static_config.keylog); let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); client_config.transport_config(transport_config.clone()); client_config @@ -922,10 +906,10 @@ impl Endpoint { let dest_addr = mapped_addr.private_socket_addr(); let server_name = &tls::name::encode(endpoint_id); - let connect = self - .sock - .endpoint() - .connect_with(client_config, dest_addr, server_name)?; + let connect = + self.inner + .quinn_endpoint() + .connect_with(client_config, dest_addr, server_name)?; Ok(Connecting::new(connect, self.clone(), endpoint_id)) } @@ -940,7 +924,7 @@ impl Endpoint { /// [`Endpoint::close`]. pub fn accept(&self) -> Accept<'_> { Accept { - inner: self.sock.endpoint().accept(), + inner: self.inner.quinn_endpoint().accept(), ep: self.clone(), } } @@ -949,7 +933,7 @@ impl Endpoint { /// Returns the secret_key of this endpoint. pub fn secret_key(&self) -> &SecretKey { - &self.static_config.tls_config.secret_key + &self.inner.static_config.tls_config.secret_key } /// Returns the endpoint id of this endpoint. @@ -957,7 +941,7 @@ impl Endpoint { /// This ID is the unique addressing information of this endpoint and other peers must know /// it to be able to connect to this endpoint. pub fn id(&self) -> EndpointId { - self.static_config.tls_config.secret_key.public() + self.inner.static_config.tls_config.secret_key.public() } /// Returns the current [`EndpointAddr`]. @@ -1002,18 +986,47 @@ impl Endpoint { /// If there are no `addrs`in the [`EndpointAddr`], you may not be dialable by other endpoints /// on the internet. /// - /// /// The `EndpointAddr` will change as: /// - network conditions change /// - the endpoint connects to a relay server /// - the endpoint changes its preferred relay server /// - more addresses are discovered for this endpoint /// + /// ## Closing behavior + /// + /// The returned watcher only becomes disconnected once the last clone of the [`Endpoint`] + /// is dropped. Closing the endpoint does not disconnect the watcher. Thus, a stream created + /// via [`Watcher::stream`] only terminates once the endpoint is fully dropped. To stop a task + /// that loops over a watcher stream once the endpoint stops, combine with [`Self::closed`]: + /// + /// ``` + /// # use iroh::{Watcher, Endpoint}; + /// # use n0_future::StreamExt; + /// # use tracing::info; + /// # async fn wrapper() -> n0_error::Result<()> { + /// let endpoint = Endpoint::bind().await?; + /// // We want to watch address changes in a different task, and stop our task + /// // once the endpoint stops. + /// let mut addr_stream = endpoint.watch_addr().stream(); + /// let endpoint_closed = endpoint.closed(); + /// tokio::spawn(endpoint_closed.run_until(async move { + /// while let Some(addr) = addr_stream.next().await { + /// info!("our address changed: {addr:?}"); + /// } + /// info!("endpoint closed"); + /// })); + /// // Do fancy things, then close the endpoint. + /// // Our task above will stop even if there are still clones of `Endpoint` alive somewhere. + /// endpoint.close().await; + /// # Ok(()) + /// # } + /// ``` + /// /// [`RelayUrl`]: crate::RelayUrl #[cfg(not(wasm_browser))] pub fn watch_addr(&self) -> impl n0_watcher::Watcher + use<> { - let watch_addrs = self.sock.ip_addrs(); - let watch_relay = self.sock.home_relay(); + let watch_addrs = self.inner.ip_addrs(); + let watch_relay = self.inner.home_relay(); let endpoint_id = self.id(); watch_addrs.or(watch_relay).map(move |(addrs, relays)| { @@ -1032,12 +1045,17 @@ impl Endpoint { /// When compiled to Wasm, this function returns a watcher that initializes /// with an [`EndpointAddr`] that only contains a relay URL, but no direct addresses, /// as there are no APIs for directly using sockets in browsers. + /// + /// The returned watcher only becomes disconnected once the last clone of the [`Endpoint`] + /// is dropped. Closing the endpoint does not disconnect the watcher. Thus, a stream created + /// via [`Watcher::stream`] only terminates once the endpoint stops. If you want to stop a + /// task once the endpoint stops combine with [`Self::closed`]. #[cfg(wasm_browser)] pub fn watch_addr(&self) -> impl n0_watcher::Watcher + use<> { // In browsers, there will never be any direct addresses, so we wait // for the home relay instead. This makes the `EndpointAddr` have *some* way // of connecting to us. - let watch_relay = self.sock.home_relay(); + let watch_relay = self.inner.home_relay(); let endpoint_id = self.id(); watch_relay.map(move |mut relays| { EndpointAddr::from_parts(endpoint_id, relays.into_iter().map(TransportAddr::Relay)) @@ -1090,7 +1108,7 @@ impl Endpoint { /// } /// ``` pub async fn online(&self) { - self.sock.home_relay().initialized().await; + self.inner.home_relay().initialized().await; } /// Returns a [`Watcher`] for any net-reports run from this [`Endpoint`]. @@ -1109,6 +1127,11 @@ impl Endpoint { /// run, the [`Watcher`] will always return [`Some`] report immediately, which /// is the most recently run `net-report`. /// + /// The returned watcher only becomes disconnected once the last clone of the [`Endpoint`] + /// is dropped. Closing the endpoint does not disconnect the watcher. Thus, a stream created + /// via [`Watcher::stream`] only terminates once the endpoint stops. If you want to stop a + /// task once the endpoint stops combine with [`Self::closed`]. + /// /// # Examples /// /// To get the first report use [`Watcher::initialized`]: @@ -1123,7 +1146,7 @@ impl Endpoint { /// ``` #[doc(hidden)] pub fn net_report(&self) -> impl Watcher> + use<> { - self.sock.net_report() + self.inner.net_report() } /// Returns the last [`NetReport`] generated by this endpoint. @@ -1133,7 +1156,7 @@ impl Endpoint { /// This method is hidden in the docs because it is not part of the public api #[doc(hidden)] pub fn last_net_report(&self) -> Option { - self.sock.net_report().get() + self.inner.net_report().get() } /// Returns the local socket addresses on which the underlying sockets are bound. @@ -1142,7 +1165,7 @@ impl Endpoint { /// address if available. #[cfg(not(wasm_browser))] pub fn bound_sockets(&self) -> Vec { - self.sock + self.inner .local_addr() .into_iter() .filter_map(|addr| addr.into_socket_addr()) @@ -1165,7 +1188,7 @@ impl Endpoint { if self.is_closed() { return Err(e!(EndpointError::Closed)); } - Ok(self.sock.dns_resolver()) + Ok(self.inner.dns_resolver()) } /// Returns the Address Lookup service, if configured. @@ -1179,7 +1202,7 @@ impl Endpoint { if self.is_closed() { return Err(e!(EndpointError::Closed)); } - Ok(self.sock.address_lookup()) + Ok(self.inner.address_lookup()) } /// Returns metrics collected for this endpoint. @@ -1298,7 +1321,7 @@ impl Endpoint { /// [`MetricsGroupSet`]: iroh_metrics::MetricsGroupSet #[cfg(feature = "metrics")] pub fn metrics(&self) -> &EndpointMetrics { - &self.sock.metrics + &self.inner.metrics } /// Returns addressing information about a recently used remote endpoint. @@ -1313,7 +1336,7 @@ impl Endpoint { if self.is_closed() { return None; } - self.sock.remote_info(endpoint_id).await + self.inner.remote_info(endpoint_id).await } // # Methods for less common state updates. @@ -1335,7 +1358,7 @@ impl Endpoint { debug!("Attempting to notify a closed endpoint about a network change. Ignoring."); return; } - self.sock.network_change().await; + self.inner.network_change().await; } // # Methods to update internal state. @@ -1355,7 +1378,7 @@ impl Endpoint { warn!("Attempting to set user data for a closed endpoint. Ignoring."); return; } - self.sock.set_user_data_for_address_lookup(user_data); + self.inner.set_user_data_for_address_lookup(user_data); } // # Methods for terminating the endpoint. @@ -1393,12 +1416,35 @@ impl Endpoint { /// Be aware however that the underlying UDP sockets are only closed once all clones of /// the the respective [`Endpoint`] are dropped. pub async fn close(&self) { - self.sock.close().await; + self.inner.close().await; } /// Check if this endpoint is still alive, or already closed. pub fn is_closed(&self) -> bool { - self.sock.is_closed() + self.inner.is_closed() + } + + /// Returns a future that resolves once the endpoint closes. + /// + /// The returned future does not contain a clone or reference to the [`Endpoint`], + /// so keeping the returned future alive does not prevent the endpoint from being dropped. + /// + /// To run a task and stop it once the endpoint closes, you can use + /// [`EndpointClosed::run_until`]: + /// ``` + /// # use iroh::endpoint::Endpoint; + /// # async fn wrapper() -> n0_error::Result<()> { + /// let endpoint = Endpoint::bind().await?; + /// tokio::spawn(endpoint.closed().run_until(async move { + /// // the future will be aborted once the endpoint closes. + /// })); + /// # Ok(()) + /// # } + /// ``` + pub fn closed(&self) -> EndpointClosed { + EndpointClosed { + inner: self.inner.closed(), + } } /// Create a [`ServerConfigBuilder`] for this endpoint that includes the given alpns. @@ -1406,25 +1452,18 @@ impl Endpoint { /// Use the [`ServerConfigBuilder`] to customize the [`ServerConfig`] connection configuration /// for a connection accepted using the [`Incoming::accept_with`] method. pub fn create_server_config_builder(&self, alpns: Vec>) -> ServerConfigBuilder { - let inner = self.static_config.create_server_config(alpns); - ServerConfigBuilder::new(inner, self.static_config.transport_config.clone()) + let inner = self.inner.static_config.create_server_config(alpns); + ServerConfigBuilder::new(inner, self.inner.static_config.transport_config.clone()) } // # Remaining private methods #[cfg(test)] - pub(crate) fn socket(&self) -> Result { + pub(crate) fn inner(&self) -> Result, EndpointError> { if self.is_closed() { return Err(e!(EndpointError::Closed)); } - Ok(self.sock.clone()) - } - #[cfg(test)] - pub(crate) fn endpoint(&self) -> Result<&quinn::Endpoint, EndpointError> { - if self.is_closed() { - return Err(e!(EndpointError::Closed)); - } - Ok(self.sock.endpoint()) + Ok(self.inner.clone()) } } @@ -1476,6 +1515,41 @@ impl ConnectOptions { } } +/// Future returned from [`Endpoint::closed`]. +#[derive(derive_more::Debug)] +#[pin_project] +#[debug("EndpointClosed")] +pub struct EndpointClosed { + #[pin] + inner: WaitForCancellationFutureOwned, +} + +impl Future for EndpointClosed { + type Output = (); + + fn poll( + self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll { + let this = self.project(); + this.inner.poll(cx) + } +} + +impl EndpointClosed { + /// Runs a future to completion, or until the [`Endpoint`] is closed. + /// + /// Returns the output of `fut` if it completes before the endpoint closes, + /// or `None` otherwise. + pub async fn run_until(self, fut: F) -> Option { + n0_future::future::or(async { Some(fut.await) }, async { + self.await; + None + }) + .await + } +} + /// Read a proxy url from the environment, in this order /// /// - `HTTP_PROXY` @@ -1601,11 +1675,15 @@ mod tests { }; use iroh_base::{EndpointAddr, EndpointId, RelayUrl, SecretKey, TransportAddr}; + use iroh_relay::endpoint_info::UserData; use n0_error::{AnyError as Error, Result, StdResultExt}; - use n0_future::{BufferedStreamExt, StreamExt, stream, task::AbortOnDropHandle, time}; + use n0_future::{ + BufferedStreamExt, StreamExt, future::now_or_never, stream, task::AbortOnDropHandle, time, + }; use n0_tracing_test::traced_test; use n0_watcher::Watcher; use rand::SeedableRng; + use rand_chacha::ChaCha8Rng; use tokio::sync::oneshot; use tracing::{Instrument, debug_span, info, info_span, instrument}; @@ -1614,8 +1692,8 @@ mod tests { RelayMap, RelayMode, address_lookup::memory::MemoryLookup, endpoint::{ - ApplicationClose, BindError, BindOpts, ConnectOptions, Connection, ConnectionError, - PathInfo, + ApplicationClose, BindError, BindOpts, ConnectError, ConnectOptions, + ConnectWithOptsError, Connection, ConnectionError, PathInfo, }, protocol::{AcceptError, ProtocolHandler, Router}, test_utils::{QlogFileGroup, run_relay_server, run_relay_server_with}, @@ -1683,6 +1761,8 @@ mod tests { ConnectionError::LocallyClosed )) ); + info!("Closing the endpoint"); + ep.close().await; info!("server test completed"); Ok::<_, Error>(()) } @@ -1720,6 +1800,8 @@ mod tests { info!("opening new - expect it to fail"); let res = conn.open_uni().await; assert_eq!(res.unwrap_err(), expected_err); + info!("Closing the client"); + ep.close().await; info!("client test completed"); Ok::<_, Error>(()) } @@ -1768,7 +1850,7 @@ mod tests { info!(me = %ep.id().fmt_short(), eps = ?eps, "server listening on"); for i in 0..n_clients { - tokio::time::timeout(Duration::from_secs(5), async { + let res = tokio::time::timeout(Duration::from_secs(5), async { let round_start = Instant::now(); info!("[server] round {i}"); let incoming = ep.accept().await.anyerr()?; @@ -1789,8 +1871,21 @@ mod tests { Ok::<_, Error>(()) }) .await - .std_context("timeout")??; + .std_context("timeout"); + match res { + Err(err) | Ok(Err(err)) => { + // ensure we close the endpoint before returning early + // on error + ep.close().await; + return Err(err); + } + _ => { + // if this round went `Ok` don't close the endpoint yet + } + } } + // close the endpoint before dropping the server task + ep.close().await; Ok::<_, Error>(()) } .instrument(debug_span!("server")), @@ -1801,16 +1896,17 @@ mod tests { let round_start = Instant::now(); info!("[client] round {i}"); let client_secret_key = SecretKey::generate(&mut rng); - tokio::time::timeout( + let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) + .alpns(vec![TEST_ALPN.to_vec()]) + .insecure_skip_relay_cert_verify(true) + .secret_key(client_secret_key) + .bind() + .await?; + let ep_1 = ep.clone(); + let res = tokio::time::timeout( Duration::from_secs(5), async { info!("client binding"); - let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) - .alpns(vec![TEST_ALPN.to_vec()]) - .insecure_skip_relay_cert_verify(true) - .secret_key(client_secret_key) - .bind() - .await?; let eps = ep.bound_sockets(); info!(me = %ep.id().fmt_short(), eps=?eps, "client bound"); @@ -1830,15 +1926,15 @@ mod tests { // we're the last to receive data, so we close conn.close(0u32.into(), b"bye!"); info!("client finished"); - ep.close().await; - info!("client closed"); - Ok::<_, Error>(()) } .instrument(debug_span!("client", %i)), ) .await - .std_context("timeout")??; + .std_context("timeout"); + ep_1.close().await; + info!("client endpoint closed"); + res??; info!("[client] round {i} done in {:?}", round_start.elapsed()); } Ok::<_, Error>(()) @@ -2007,7 +2103,9 @@ mod tests { send.write_all(b"close please").await.anyerr()?; send.finish().anyerr()?; - Ok(conn.closed().await) + let res = conn.closed().await; + ep.close().await; + Ok(res) } #[instrument(name = "server", skip_all)] @@ -2043,7 +2141,8 @@ mod tests { let msg = recv.read_to_end(100).await.anyerr()?; assert_eq!(msg, b"close please"); info!("received 'close please'"); - // Dropping the connection closes it just fine. + // Closing the endpoint closes all connections. + ep.close().await; Ok(()) } @@ -2106,7 +2205,9 @@ mod tests { info!("Have relay connection"); send.write_all(b"close please").await.anyerr()?; send.finish().anyerr()?; - Ok(conn.closed().await) + let res = conn.closed().await; + ep.close().await; + Ok(res) } #[instrument(name = "server", skip_all)] @@ -2140,7 +2241,8 @@ mod tests { let msg = recv.read_to_end(100).await.anyerr()?; assert_eq!(msg, b"close please"); info!("received 'close please'"); - // Dropping the connection closes it just fine. + // Closing the endpoint closes all connections. + ep.close().await; Ok(()) } @@ -3134,4 +3236,157 @@ mod tests { Ok(()) } + + #[tokio::test] + #[traced_test] + async fn test_closed_endpoint_behaviour() -> Result { + // create endpoint + // call endpoint.close + // ensure methods behave in the expected way + info!("Creating endpoint"); + let ep = Endpoint::builder().bind().await?; + let closed = ep.closed(); + info!("Closing endpoint"); + let now = Instant::now(); + ep.close().await; + info!("Endpoint closed in {:?}", now.elapsed()); + + // Assert that the `closed` cancellation token is now cancelled + assert_eq!(now_or_never(closed), Some(())); + + info!("Set ALPNS fails silently"); + ep.set_alpns(vec![b"test".into()]); + + info!("Insert Relay returns None"); + let relay_config = crate::defaults::staging::default_na_east_relay(); + assert!( + ep.insert_relay("localhost:300".parse()?, Arc::new(relay_config)) + .await + .is_none() + ); + + info!("Remove Relay returns None"); + assert!(ep.remove_relay(&"localhost:300".parse()?).await.is_none()); + + info!("Connecting"); + let mut rng = ChaCha8Rng::seed_from_u64(41); + let ep_id = SecretKey::generate(&mut rng).public(); + + // should likely be an error that states that the + // endpoint is closed instead: + if let ConnectError::Connect { source, .. } = ep.connect(ep_id, b"test").await.unwrap_err() + { + assert!(matches!( + source, + ConnectWithOptsError::EndpointClosed { .. } + )); + } else { + panic!("unexpected error for connect"); + } + + info!("Accepting!"); + assert!(ep.accept().await.is_none()); + + // this should work + info!("Addr: {:?}", ep.addr()); + + // create watchers to verify they terminate after the endpoint is dropped. + let mut addrs = ep.watch_addr().stream(); + let mut net_reports = ep.net_report().stream(); + + // returns None + let net_report = ep.last_net_report(); + info!("last Net report {net_report:?}"); + + // this should work + let sockets = ep.bound_sockets(); + info!("Sockets: {sockets:?}"); + + // these should return errors + assert!(ep.dns_resolver().is_err()); + assert!(ep.address_lookup().is_err()); + + // this should work + let metrics = ep.metrics(); + info!("Metrics: {metrics:?}"); + + // this should return none + assert!(ep.remote_info(ep_id).await.is_none()); + + // this should fail silently + ep.network_change().await; + + // this should fail silently + ep.set_user_data_for_address_lookup(Some( + UserData::try_from("TEST".to_string()).expect("valid string"), + )); + drop(ep); + // now that the endpoint is dropped, all watchers should terminate. + tokio::time::timeout(Duration::from_secs(1), async { + while let Some(addr) = addrs.next().await { + info!("Addrs stream: {addr:?}"); + } + while let Some(net_report) = net_reports.next().await { + info!("Net report stream: {net_report:?}"); + } + }) + .await + .expect("watchers not closed"); + + info!("Done!"); + Ok(()) + } + + #[tokio::test] + #[traced_test] + async fn test_closed_endpoint_unpolled_accept_fut() -> Result { + info!("Creating endpoint"); + let ep = Endpoint::builder().bind().await?; + + info!("Get accept future"); + let accept_fut = ep.accept(); + + info!("Closing endpoint"); + let now = Instant::now(); + tokio::time::timeout(Duration::from_secs(5), ep.close()) + .await + .expect("Endpoint closes in a reasonable time"); + info!("Endpoint closed in {:?}", now.elapsed()); + + info!("Accept future returns None after the endpoint has closed"); + let incoming = accept_fut.await; + assert!(incoming.is_none()); + Ok(()) + } + + #[tokio::test] + #[traced_test] + async fn test_closed_endpoint_polled_accept_fut() -> Result { + info!("Creating endpoint"); + let ep = Endpoint::builder().bind().await?; + + info!("Run an accept task"); + let ep2 = ep.clone(); + let accept_task = tokio::spawn(async move { + info!("Waiting on Accept"); + let res = ep2.accept().await; + info!("Accept await has returned"); + res + }); + + // Try to ensure the accept future is polled at least once. + tokio::time::sleep(Duration::from_millis(10)).await; + + info!("Closing the endpoint"); + tokio::time::timeout(Duration::from_secs(5), ep.close()) + .await + .expect("Endpoint closes in a reasonable time"); + info!("Endpoint closed"); + + info!("Await the accept task"); + let incoming = accept_task.await.expect("accept task panicked"); + assert!(incoming.is_none()); + + Ok(()) + } } diff --git a/iroh/src/endpoint/connection.rs b/iroh/src/endpoint/connection.rs index fc67555483..a6fafcdb0c 100644 --- a/iroh/src/endpoint/connection.rs +++ b/iroh/src/endpoint/connection.rs @@ -270,11 +270,11 @@ fn conn_from_quinn_conn( // Register this connection with the socket. let fut = ep - .sock + .inner .register_connection(info.endpoint_id, conn.weak_handle()); // Check hooks - let sock = ep.sock.clone(); + let inner = ep.inner.clone(); Ok(async move { let paths = fut.await?; let conn = Connection { @@ -283,7 +283,7 @@ fn conn_from_quinn_conn( }; if let AfterHandshakeOutcome::Reject { error_code, reason } = - sock.hooks.after_handshake(&conn.to_info()).await + inner.hooks.after_handshake(&conn.to_info()).await { conn.close(error_code, &reason); return Err(e!(ConnectingError::LocallyRejected)); diff --git a/iroh/src/lib.rs b/iroh/src/lib.rs index c9b93cd298..5ec6c25bd0 100644 --- a/iroh/src/lib.rs +++ b/iroh/src/lib.rs @@ -256,9 +256,8 @@ mod socket; mod tls; +pub(crate) mod runtime; pub(crate) mod util; -#[cfg(wasm_browser)] -pub(crate) mod web_runtime; pub mod address_lookup; pub mod defaults; diff --git a/iroh/src/runtime.rs b/iroh/src/runtime.rs new file mode 100644 index 0000000000..7e5dab7e62 --- /dev/null +++ b/iroh/src/runtime.rs @@ -0,0 +1,138 @@ +use std::{ + pin::Pin, + sync::atomic::{AtomicU64, Ordering}, +}; + +use iroh_base::EndpointId; +use tokio_util::sync::CancellationToken; +#[cfg(not(wasm_browser))] +use tokio_util::task::TaskTracker; + +#[derive(Debug)] +pub struct Runtime { + id: EndpointId, + #[cfg(not(wasm_browser))] + tasks: TaskTracker, + #[cfg(not(wasm_browser))] + cancel: CancellationToken, + #[cfg(not(wasm_browser))] + task_counter: AtomicU64, +} + +impl Runtime { + /// Create a new [`Runtime`] that manages shutting down tasks properly, + /// whether gracefully or un-gracefully. + pub fn new(id: EndpointId) -> Self { + Self { + id, + #[cfg(not(wasm_browser))] + tasks: TaskTracker::new(), + #[cfg(not(wasm_browser))] + cancel: CancellationToken::new(), + #[cfg(not(wasm_browser))] + task_counter: AtomicU64::new(0), + } + } + + /// Shutdown the runtime gracefully. + /// + /// Closes the task tracker and waits for all spawned tasks to finish naturally. + /// + /// If the tasks were already closed, it assumes the tasks have already been + /// awaited. + #[cfg(not(wasm_browser))] + pub async fn shutdown(&self) { + if self.tasks.close() { + self.tasks.wait().await + } + } + + /// Shutdown the runtime ASAP, not waiting for any graceful closing of tasks. + #[cfg(not(wasm_browser))] + pub fn abort(&self) { + // Drop the running futures. + self.cancel.cancel(); + // Signal that the runtime should be closed. + self.tasks.close(); + // Does not wait for the tasks to return. + } + + /// No-op on wasm. There is no task tracker to close or wait on. + #[cfg(wasm_browser)] + pub async fn shutdown(&self) {} + + /// No-op on wasm. There is no task tracker or cancellation to perform. + #[cfg(wasm_browser)] + pub fn abort(&self) {} +} + +impl quinn::Runtime for Runtime { + #[cfg(not(wasm_browser))] + fn new_timer(&self, i: std::time::Instant) -> Pin> { + quinn::TokioRuntime.new_timer(i) + } + + #[cfg(wasm_browser)] + fn new_timer(&self, deadline: n0_future::time::Instant) -> Pin> { + Box::pin(web::Timer(n0_future::time::sleep_until(deadline))) + } + + #[cfg(not(wasm_browser))] + fn spawn(&self, future: Pin + Send>>) { + // Do not allow spawning more tasks if the runtime should be closed. + if self.tasks.is_closed() { + tracing::debug!(me = %self.id.fmt_short(), "runtime closed, dropping spawned task"); + return; + } + + use tracing::{Instrument, trace_span}; + + let task_id = self.task_counter.fetch_add(1, Ordering::Relaxed); + let cancel = self.cancel.clone(); + let span = trace_span!("runtime", me = %self.id.fmt_short(), task_id); + self.tasks.spawn(async move { + // wrapping the future in a cancellation token is what allows + // us to "abort" tasks in the event the runtime is meant to + // close quickly and ungracefully + cancel.run_until_cancelled(future.instrument(span)).await; + }); + } + + #[cfg(wasm_browser)] + fn spawn(&self, future: Pin + Send>>) { + wasm_bindgen_futures::spawn_local(future); + } + + // We're not actually using this function in iroh + #[cfg(not(wasm_browser))] + fn wrap_udp_socket( + &self, + t: std::net::UdpSocket, + ) -> std::io::Result> { + quinn::TokioRuntime.wrap_udp_socket(t) + } +} + +#[cfg(wasm_browser)] +mod web { + use std::{ + future::Future, + pin::Pin, + task::{Context, Poll}, + }; + + use n0_future::time; + + #[derive(Debug)] + pub(crate) struct Timer(pub(crate) time::Sleep); + + impl quinn::AsyncTimer for Timer { + fn reset(mut self: Pin<&mut Self>, deadline: time::Instant) { + Pin::new(&mut self.0).reset(deadline) + } + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + Pin::new(&mut self.0).poll(cx) + } + } +} diff --git a/iroh/src/socket.rs b/iroh/src/socket.rs index c0c4fd64b6..eccc93d5e4 100644 --- a/iroh/src/socket.rs +++ b/iroh/src/socket.rs @@ -44,7 +44,7 @@ use tokio::sync::{ mpsc::{self}, oneshot, }; -use tokio_util::sync::CancellationToken; +use tokio_util::sync::{CancellationToken, WaitForCancellationFutureOwned}; use tracing::{Instrument, Level, debug, event, info_span, instrument, trace, warn}; use transports::{LocalAddrsWatch, Transport, TransportConfig}; use url::Url; @@ -60,13 +60,15 @@ use crate::net_report::QuicConfig; use crate::{ address_lookup::{self, AddressLookup, EndpointData, Error as AddressLookupError, UserData}, defaults::timeouts::NET_REPORT_TIMEOUT, - endpoint::hooks::EndpointHooksList, + endpoint::{hooks::EndpointHooksList, quic::QuicTransportConfig}, metrics::EndpointMetrics, net_report::{self, IfStateDetails, Report}, + runtime::Runtime, socket::{ concurrent_read_map::ReadOnlyMap, remote_map::{MappedAddrs, PathsWatcher, RemoteInfo}, }, + tls, }; mod metrics; @@ -146,21 +148,63 @@ pub(crate) struct Options { pub(crate) insecure_skip_relay_cert_verify: bool, pub(crate) metrics: EndpointMetrics, pub(crate) hooks: EndpointHooksList, + + /// Static configuration for the endpoint. + pub(crate) static_config: StaticConfig, } -/// Handle for [`Socket`]. +/// Inner state for an iroh [`crate::Endpoint`]. /// /// Dereferences to [`Socket`], and handles closing. -#[derive(Clone, Debug, derive_more::Deref)] -pub(crate) struct Handle { +#[derive(Debug, derive_more::Deref)] +pub(crate) struct EndpointInner { #[deref(forward)] sock: Arc, // empty when shutdown - actor_task: Arc>>>, + actor_task: Mutex>>, /// Channel to send to the internal actor. actor_sender: mpsc::Sender, // quinn endpoint endpoint: quinn::Endpoint, + // Runtime used by quinn + runtime: Arc, + /// Static configuration for the endpoint. + pub(crate) static_config: StaticConfig, +} + +impl Drop for EndpointInner { + fn drop(&mut self) { + if self.sock.is_closed() { + return; + } + tracing::error!( + "Endpoint dropped without calling `Endpoint::close`. Aborting ungracefully." + ); + self.abort(); + } +} + +/// Configuration for a [`quinn::Endpoint`] that cannot be changed at runtime. +#[derive(Debug)] +pub(crate) struct StaticConfig { + pub(crate) tls_config: tls::TlsConfig, + pub(crate) transport_config: QuicTransportConfig, + pub(crate) keylog: bool, +} + +impl StaticConfig { + /// Create a [`quinn_proto::ServerConfig`] with the specified ALPN protocols. + pub(crate) fn create_server_config( + &self, + alpn_protocols: Vec>, + ) -> quinn_proto::ServerConfig { + let quic_server_config = self + .tls_config + .make_server_config(alpn_protocols, self.keylog); + let mut inner = quinn::ServerConfig::with_crypto(Arc::new(quic_server_config)); + inner.transport_config(self.transport_config.to_inner_arc()); + inner + } } #[derive(Debug)] @@ -245,8 +289,8 @@ pub(crate) struct Socket { impl Socket { /// Creates a [`Socket`] listening. - pub(crate) async fn spawn(opts: Options) -> Result { - Handle::new(opts).await + pub(crate) async fn spawn(opts: Options) -> Result { + EndpointInner::new(opts).await } /// Returns the relay endpoint we are connected to, that has the best latency. @@ -270,6 +314,11 @@ impl Socket { self.shutdown.is_closing() } + /// Returns a future that resolves once endpoint shutdown has started. + pub(crate) fn closed(&self) -> WaitForCancellationFutureOwned { + self.shutdown.at_close_start.clone().cancelled_owned() + } + /// Get the cached version of addresses. pub(crate) fn local_addr(&self) -> Vec { self.local_addrs_watch.clone().get() @@ -661,7 +710,7 @@ pub enum BindError { }, } -impl Handle { +impl EndpointInner { /// Creates a [`Socket`]. async fn new(opts: Options) -> Result { let Options { @@ -676,6 +725,7 @@ impl Handle { insecure_skip_relay_cert_verify, metrics, hooks, + static_config, } = opts; let address_lookup = address_lookup::ConcurrentAddressLookup::default(); @@ -804,14 +854,13 @@ impl Handle { let local_addrs_watch = transports.local_addrs_watch(); let network_change_sender = transports.create_network_change_sender(); + let runtime = Arc::new(Runtime::new(secret_key.public())); + let endpoint = quinn::Endpoint::new_with_abstract_socket( endpoint_config, Some(server_config), Box::new(Transport::new(sock.clone(), transports)), - #[cfg(not(wasm_browser))] - Arc::new(quinn::TokioRuntime), - #[cfg(wasm_browser)] - Arc::new(crate::web_runtime::WebRuntime), + runtime.clone(), ) .map_err(|err| e!(BindError::CreateQuicEndpoint, err))?; @@ -897,18 +946,20 @@ impl Handle { .instrument(info_span!("actor")), ); - let actor_task = Arc::new(Mutex::new(Some(AbortOnDropHandle::new(actor_task)))); + let actor_task = Mutex::new(Some(AbortOnDropHandle::new(actor_task))); - Ok(Handle { + Ok(EndpointInner { sock, actor_sender, actor_task, endpoint, + runtime, + static_config, }) } - /// The underlying [`quinn::Endpoint`] - pub fn endpoint(&self) -> &quinn::Endpoint { + /// Returns a reference to the underlying [`quinn::Endpoint`]. + pub(crate) fn quinn_endpoint(&self) -> &quinn::Endpoint { &self.endpoint } @@ -929,8 +980,11 @@ impl Handle { // Cancel at_close_start token, which cancels running netreports. self.sock.shutdown.at_close_start.cancel(); + // Remove address lookup services + self.sock.address_lookup().clear(); + // Initiate closing all connections, and refuse future connections. - self.endpoint.close(0u16.into(), b""); + self.quinn_endpoint().close(0u16.into(), b""); // In the history of this code, this call had been // - removed: https://github.com/n0-computer/iroh/pull/1753 @@ -948,10 +1002,10 @@ impl Handle { // If this call is skipped, then connections that protocols close just shortly before the // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. trace!("wait_idle start"); - self.endpoint.wait_idle().await; + self.quinn_endpoint().wait_idle().await; trace!("wait_idle done"); - // Start cancellation of all actors + // Start cancellation of all actors. self.sock.shutdown.at_endpoint_closed.cancel(); // MutexGuard is not held across await points @@ -967,17 +1021,59 @@ impl Handle { match shutdown_done { Ok(_) => trace!("tasks finished in time, shutdown complete"), Err(time::Elapsed { .. }) => { - // Dropping the task will abort itt + // Dropping the task will abort it warn!("tasks didn't finish in time, aborting"); } } } + // Waits for the EndpointDriver and all ConnectionDrivers to shut down + // Expects that the `quinn::Endpoint` has been closed before this call, + // otherwise, the runtime will never shutdown. + self.runtime.shutdown().await; + self.sock.shutdown.closed.store(true, Ordering::SeqCst); trace!("socket closed"); } + /// Aborts the endpoint ungracefully: + /// + /// - Calls cancellation token that stops running net reports + /// - Removes all address lookup services + /// - Calls cancellation token that stops all the Socket actors + /// - Aborts the runtime + /// - Drops the actor task + /// - Sets the `Socket::is_closed` state to true + /// + /// This does not wait for any current connections or tasks to close gracefully. + /// + /// This should only be called in the `iroh::Endpoint` `Drop` impl when the + /// `iroh::Endpoint` is dropped without first calling `Endpoint::close`. + #[instrument(skip_all)] + pub(crate) fn abort(&self) { + if self.sock.is_closed() || self.sock.is_closing() { + return; + } + trace!(me = ?self.public_key, "aborting socket..."); + + // Cancel at_close_start token, which cancels running netreports. + self.sock.shutdown.at_close_start.cancel(); + + self.sock.address_lookup().clear(); + + // Cancel all actors. + self.sock.shutdown.at_endpoint_closed.cancel(); + + // Aborts all tasks, not waiting for any to close gracefully. + self.runtime.abort(); + + self.actor_task.lock().expect("poisoned").take(); + + self.sock.shutdown.closed.store(true, Ordering::SeqCst); + trace!("socket closed"); + } + pub(crate) async fn insert_relay( &self, relay: RelayUrl, @@ -1016,7 +1112,7 @@ impl Handle { .ok(); } - /// Resolves an [`EndpointAddr`] to an [`EndpointIdMappedAddr`] to connect to via [`Handle::endpoint`]. + /// Resolves an [`EndpointAddr`] to an [`EndpointIdMappedAddr`] to connect to via [`EndpointInner::endpoint`]. /// /// This starts a `RemoteStateActor` for the remote if not running already, and then checks /// if the actor has any known paths to the remote. If not, it starts address lookup and waits for @@ -1625,7 +1721,7 @@ mod tests { dns::DnsResolver, endpoint::QuicTransportConfig, socket::{ - Handle, Socket, TransportConfig, + EndpointInner, Socket, StaticConfig, TransportConfig, mapped_addrs::{EndpointIdMappedAddr, MappedAddr}, }, tls::{self, DEFAULT_MAX_TLS_TICKETS}, @@ -1635,7 +1731,12 @@ mod tests { fn default_options(rng: &mut R) -> Options { let secret_key = SecretKey::generate(rng); - let server_config = make_default_server_config(&secret_key); + let static_config = StaticConfig { + tls_config: tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS), + transport_config: QuicTransportConfig::default(), + keylog: false, + }; + let server_config = static_config.create_server_config(vec![]); Options { transports: vec![ TransportConfig::default_ipv4(), @@ -1651,20 +1752,10 @@ mod tests { address_lookup_user_data: None, metrics: Default::default(), hooks: Default::default(), + static_config, } } - /// Generate a server config with no ALPNS and a default transport configuration - fn make_default_server_config(secret_key: &SecretKey) -> quinn::ServerConfig { - let quic_server_config = - crate::tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) - .make_server_config(vec![], false); - let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(quic_server_config)); - let transport = QuicTransportConfig::default(); - server_config.transport_config(transport.to_inner_arc()); - server_config - } - #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] async fn echo_receiver(ep: Endpoint, loss: ExpectedLoss) -> Result { info!("accepting conn"); @@ -1704,7 +1795,7 @@ mod tests { conn.closed().await; info!("closed"); - ep.endpoint()?.wait_idle().await; + ep.inner()?.quinn_endpoint().wait_idle().await; info!("idle"); Ok(()) @@ -1758,7 +1849,7 @@ mod tests { conn.close(0u32.into(), b"done"); info!("closed"); - ep.endpoint()?.wait_idle().await; + ep.inner()?.quinn_endpoint().wait_idle().await; info!("idle"); Ok(()) } @@ -1889,7 +1980,7 @@ mod tests { let (_guard, m1, m2) = endpoint_pair().await; println!("Net change"); - m1.socket()?.force_network_change(true).await; + m1.inner()?.force_network_change(true).await; tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding let _handle = AbortOnDropHandle::new(tokio::spawn({ @@ -1935,7 +2026,7 @@ mod tests { let task = tokio::spawn(async move { loop { info!("[m1] network change"); - m1.socket() + m1.inner() .expect("haven't closed the endpoint yet") .force_network_change(true) .await; @@ -1966,12 +2057,12 @@ mod tests { let mut rng = rng.clone(); let task = tokio::spawn(async move { info!("-- [m1] network change"); - m1.socket() + m1.inner() .expect("haven't closed the endpoint yet") .force_network_change(true) .await; info!("-- [m2] network change"); - m2.socket() + m2.inner() .expect("haven't closed the endpoint yet") .force_network_change(true) .await; @@ -1997,13 +2088,13 @@ mod tests { let (_guard, m1, m2) = endpoint_pair().await; info!("closing endpoints"); - let sock1 = m1.socket()?; - let sock2 = m2.socket()?; + let sock1 = m1.inner()?; + let sock2 = m2.inner()?; m1.close().await; m2.close().await; - assert!(sock1.sock.is_closed()); - assert!(sock2.sock.is_closed()); + assert!(sock1.is_closed()); + assert!(sock2.is_closed()); } Ok(()) } @@ -2012,7 +2103,7 @@ mod tests { #[traced_test] async fn test_direct_addresses() { let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); - let sock = Handle::new(default_options(&mut rng)).await.unwrap(); + let sock = EndpointInner::new(default_options(&mut rng)).await.unwrap(); // See if we can get endpoints. let eps0 = sock.ip_addrs().get(); @@ -2032,11 +2123,13 @@ mod tests { /// /// Use [`socket_connect`] to establish connections. #[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))] - async fn socket_ep(secret_key: SecretKey) -> Result { - let quic_server_config = tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) - .make_server_config(vec![ALPN.to_vec()], true); - let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(quic_server_config)); - server_config.transport_config(Arc::new(quinn::TransportConfig::default())); + async fn socket_ep(secret_key: SecretKey) -> Result { + let static_config = StaticConfig { + tls_config: tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS), + transport_config: QuicTransportConfig::default(), + keylog: true, + }; + let server_config = static_config.create_server_config(vec![ALPN.to_vec()]); let dns_resolver = DnsResolver::new(); let opts = Options { @@ -2052,6 +2145,7 @@ mod tests { insecure_skip_relay_cert_verify: false, metrics: Default::default(), hooks: Default::default(), + static_config, }; let sock = Socket::spawn(opts).await?; Ok(sock) @@ -2062,7 +2156,7 @@ mod tests { /// Uses [`ALPN`], `endpoint_id`, must match `addr`. #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] async fn socket_connect( - ep: &quinn::Endpoint, + ep: quinn::Endpoint, ep_secret_key: SecretKey, addr: EndpointIdMappedAddr, endpoint_id: EndpointId, @@ -2088,7 +2182,7 @@ mod tests { /// Uses [`ALPN`], `endpoint_id`, must match `addr`. #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] async fn socket_connect_with_transport_config( - ep: &quinn::Endpoint, + ep: quinn::Endpoint, ep_secret_key: SecretKey, mapped_addr: EndpointIdMappedAddr, endpoint_id: EndpointId, @@ -2135,7 +2229,7 @@ mod tests { let res = tokio::time::timeout( Duration::from_millis(500), socket_connect( - sock_1.endpoint(), + sock_1.quinn_endpoint().clone(), secret_key_1.clone(), bad_addr, endpoint_id_missing_endpoint, @@ -2162,7 +2256,7 @@ mod tests { info!("accept finished"); Ok(()) } - let ep = sock_2.endpoint().clone(); + let ep = sock_2.quinn_endpoint().clone(); async move { if let Err(err) = accept(ep).await { error!("{err:#}"); @@ -2185,7 +2279,12 @@ mod tests { .unwrap(); let res = tokio::time::timeout( Duration::from_secs(10), - socket_connect(sock_1.endpoint(), secret_key_1.clone(), addr, endpoint_id_2), + socket_connect( + sock_1.quinn_endpoint().clone(), + secret_key_1.clone(), + addr, + endpoint_id_2, + ), ) .await .expect("timeout while connecting"); @@ -2209,7 +2308,7 @@ mod tests { let sock_1 = socket_ep(secret_key_1.clone()).await.unwrap(); let sock_2 = socket_ep(secret_key_2.clone()).await.unwrap(); - let ep_2 = sock_2.endpoint().clone(); + let ep_2 = sock_2.quinn_endpoint().clone(); // We need a task to accept the connection. let accept_task = tokio::spawn({ @@ -2260,7 +2359,7 @@ mod tests { let mut transport_config = quinn::TransportConfig::default(); transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); let res = socket_connect_with_transport_config( - sock_1.endpoint(), + sock_1.quinn_endpoint().clone(), secret_key_1.clone(), addr_2, endpoint_id_2, @@ -2290,7 +2389,7 @@ mod tests { tokio::time::timeout(Duration::from_secs(10), async move { info!("establishing new connection"); let conn = socket_connect( - sock_1.endpoint(), + sock_1.quinn_endpoint().clone(), secret_key_1.clone(), addr_2, endpoint_id_2, diff --git a/iroh/src/web_runtime.rs b/iroh/src/web_runtime.rs deleted file mode 100644 index 4e69ea5d06..0000000000 --- a/iroh/src/web_runtime.rs +++ /dev/null @@ -1,33 +0,0 @@ -use std::{ - future::Future, - pin::Pin, - task::{Context, Poll}, -}; - -use n0_future::time; - -#[derive(Debug, Clone)] -pub struct WebRuntime; - -#[derive(Debug)] -struct Timer(time::Sleep); - -impl quinn::Runtime for WebRuntime { - fn new_timer(&self, deadline: time::Instant) -> Pin> { - Box::pin(Timer(time::sleep_until(deadline))) - } - - fn spawn(&self, future: Pin + Send>>) { - wasm_bindgen_futures::spawn_local(future); - } -} - -impl quinn::AsyncTimer for Timer { - fn reset(mut self: Pin<&mut Self>, deadline: time::Instant) { - Pin::new(&mut self.0).reset(deadline) - } - - fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { - Pin::new(&mut self.0).poll(cx) - } -}