diff --git a/Cargo.lock b/Cargo.lock index c56bb71bba..a288dc6863 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2437,6 +2437,7 @@ dependencies = [ name = "iroh-dns" version = "0.98.0" dependencies = [ + "arc-swap", "cfg_aliases", "derive_more", "hickory-resolver", diff --git a/iroh-dns/Cargo.toml b/iroh-dns/Cargo.toml index cfff7e1e08..f84fe55239 100644 --- a/iroh-dns/Cargo.toml +++ b/iroh-dns/Cargo.toml @@ -13,6 +13,7 @@ rust-version = "1.89" workspace = true [dependencies] +arc-swap = "1.9.1" derive_more = { version = "2.0.1", features = ["debug"] } iroh-base = { version = "0.98.0", path = "../iroh-base", default-features = false, features = ["key", "relay"] } n0-error = "0.1.3" diff --git a/iroh-dns/src/dns.rs b/iroh-dns/src/dns.rs index 9518fa48de..8ae638076a 100644 --- a/iroh-dns/src/dns.rs +++ b/iroh-dns/src/dns.rs @@ -13,6 +13,7 @@ use std::{ sync::Arc, }; +use arc_swap::ArcSwap; use hickory_resolver::{ TokioResolver, config::{ConnectionConfig, ResolverConfig, ResolverOpts}, @@ -26,7 +27,7 @@ use n0_future::{ boxed::BoxFuture, time::{self, Duration}, }; -use tokio::sync::RwLock; +use tokio::sync::Notify; use tracing::debug; use url::Url; @@ -57,11 +58,14 @@ pub trait Resolver: fmt::Debug + Send + Sync + 'static { /// Clears the internal cache. fn clear_cache(&self); - /// Completely resets the DNS resolver. + /// Returns a freshly-built resolver to replace `self` after a network change. /// - /// This is called when the host's network changes majorly. Implementations should rebind all sockets - /// and refresh the nameserver configuration if read from the host system. - fn reset(&mut self); + /// The returned resolver replaces the previous one inside [`DnsResolver`] via an + /// atomic swap. Build a new instance with re-bound sockets and re-read nameserver + /// configuration rather than mutating in place. Must not perform IO: defer DNS + /// queries and socket binds until the new resolver is first used. May be called + /// concurrently, in which case all but one allocated replacement is dropped unused. + fn reset(&self) -> Box; } /// Boxed iterator alias. @@ -210,7 +214,7 @@ impl Builder { /// Builds the DNS resolver. pub fn build(self) -> DnsResolver { - DnsResolver(Arc::new(RwLock::new(HickoryResolver::new(self)))) + DnsResolver::custom(HickoryResolver::new(self)) } } @@ -221,7 +225,93 @@ impl Builder { /// Alternatively, you can create a fully custom DNS resolver by implementing the [`Resolver`] /// trait and creating the resolver with [`Self::custom`]. #[derive(Debug, Clone)] -pub struct DnsResolver(Arc>); +pub struct DnsResolver { + inner: Arc, +} + +/// Shared state behind [`DnsResolver`]. +#[derive(Debug)] +struct Inner { + /// Wakes in-flight [`Self::op`] calls when the resolver is swapped. + notify_reset: Notify, + resolver: ArcSwap>, +} + +impl Inner { + fn new(inner: Box) -> Self { + Self { + notify_reset: Notify::new(), + resolver: ArcSwap::from_pointee(inner), + } + } + + /// Atomically swaps the resolver and wakes in-flight [`Self::op`] calls. + /// + /// The swap happens before the wake. An op that observes or misses the wake is + /// then guaranteed to load the new resolver. Non-blocking. + /// + /// Under contention only the first concurrent caller's swap lands; the others + /// drop their freshly-built resolver. The winner's notification is enough since + /// every in-flight op will pick up the new resolver on its next iteration. + fn reset(&self) { + let current = self.resolver.load(); + let new = Arc::new(current.reset()); + let prev = self.resolver.compare_and_swap(¤t, new); + if Arc::ptr_eq(¤t, &prev) { + self.notify_reset.notify_waiters(); + } + } + + fn clear_cache(&self) { + self.resolver.load().clear_cache(); + } + + /// Runs `f(resolver)` with a timeout, restarting against the new resolver if + /// [`Self::reset`] fires. + /// + /// Three things race in `biased` order: the lookup completes (returned even if a + /// reset happened concurrently, since a successful result is still valid), a reset + /// is observed (drop the in-flight future and re-run `f`), or the timeout elapses. + /// + /// `timeout` is per-attempt. Each retry starts a fresh sleep, so the wall-clock + /// total can exceed it if many resets fire. This is intentional: a fresh attempt + /// against a just-changed network should not inherit the previous attempt's + /// remaining budget. + /// + /// `f` may be invoked more than once and so must be `Fn`. Captured state must be + /// reusable across calls, typically by cloning inside the closure body. + /// + /// `notified` is enabled before `load_full`. Combined with [`Self::reset`]'s + /// swap-then-notify ordering: a wake missed before `enable()` had already been + /// preceded by the swap, so the following `load_full` returns the new resolver. + async fn op(&self, timeout: Duration, f: F) -> Result + where + E: 'static + Send + Into, + R: 'static + Send, + F: 'static + Send + Fn(Arc>) -> Fut, + Fut: 'static + Send + Future>, + { + loop { + let notified = self.notify_reset.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + + let timeout = n0_future::time::sleep(timeout); + tokio::pin!(timeout); + + let resolver = self.resolver.load_full(); + let fut = f(resolver); + tokio::pin!(fut); + + tokio::select! { + biased; + res = fut => return res.map_err(Into::into), + _ = notified => continue, + _ = timeout => return Err(e!(DnsError::Timeout)), + } + } + } +} impl DnsResolver { /// Creates a new DNS resolver with sensible cross-platform defaults. @@ -251,17 +341,23 @@ impl DnsResolver { /// implement the [`Resolver`] trait on a struct and implement DNS resolution /// however you see fit. pub fn custom(resolver: impl Resolver) -> Self { - Self(Arc::new(RwLock::new(resolver))) + Self { + inner: Arc::new(Inner::new(Box::new(resolver))), + } } /// Removes all entries from the cache. - pub async fn clear_cache(&self) { - self.0.read().await.clear_cache() + pub fn clear_cache(&self) { + self.inner.clear_cache(); } - /// Recreates the inner resolver. - pub async fn reset(&self) { - self.0.write().await.reset() + /// Replaces the inner resolver with a freshly-built one. + /// + /// Call this on a major host network change to pick up the new system DNS + /// configuration and rebind sockets. The swap is atomic and non-blocking; + /// in-flight lookups retry against the new resolver. See [`Resolver::reset`]. + pub fn reset(&self) { + self.inner.reset(); } /// Looks up a TXT record. @@ -271,10 +367,10 @@ impl DnsResolver { timeout: Duration, ) -> Result, DnsError> { let host = host.to_string(); - let fut = self.0.read().await.lookup_txt(host); - let res = time::timeout(timeout, fut) - .await - .map_err(|_| e!(DnsError::Timeout))??; + let res = self + .inner + .op(timeout, move |resolver| resolver.lookup_txt(host.clone())) + .await?; Ok(res) } @@ -285,10 +381,10 @@ impl DnsResolver { timeout: Duration, ) -> Result + use, DnsError> { let host = host.to_string(); - let fut = self.0.read().await.lookup_ipv4(host); - let addrs = time::timeout(timeout, fut) - .await - .map_err(|_| e!(DnsError::Timeout))??; + let addrs = self + .inner + .op(timeout, move |resolver| resolver.lookup_ipv4(host.clone())) + .await?; Ok(addrs.into_iter().map(IpAddr::V4)) } @@ -299,10 +395,10 @@ impl DnsResolver { timeout: Duration, ) -> Result + use, DnsError> { let host = host.to_string(); - let fut = self.0.read().await.lookup_ipv6(host); - let addrs = time::timeout(timeout, fut) - .await - .map_err(|_| e!(DnsError::Timeout))??; + let addrs = self + .inner + .op(timeout, move |resolver| resolver.lookup_ipv6(host.clone())) + .await?; Ok(addrs.into_iter().map(IpAddr::V6)) } @@ -619,8 +715,12 @@ impl Resolver for HickoryResolver { self.resolver.clear_cache() } - fn reset(&mut self) { - self.resolver = Self::build_resolver(&self.builder); + fn reset(&self) -> Box { + let resolver = Self::build_resolver(&self.builder); + Box::new(Self { + resolver, + builder: self.builder.clone(), + }) } } @@ -834,7 +934,7 @@ pub(crate) mod tests { todo!() } - fn reset(&mut self) { + fn reset(&self) -> Box { todo!() } } diff --git a/iroh/src/socket.rs b/iroh/src/socket.rs index c7b66b7f78..60105aaad6 100644 --- a/iroh/src/socket.rs +++ b/iroh/src/socket.rs @@ -1557,7 +1557,7 @@ impl Actor { ); current_netmon_state = state; self.sock.metrics.socket.actor_link_change.inc(); - self.handle_network_change(is_major).await; + self.handle_network_change(is_major); } remote_id = poll_fn(|cx| self.remote_map.poll_cleanup(cx)) => { trace!(%remote_id, "cleaned up RemoteStateActor"); @@ -1607,7 +1607,7 @@ impl Actor { /// /// This is triggered when the netmon actor detects a change in the local network /// interfaces, assigned IP addresses and routes. - async fn handle_network_change(&mut self, is_major: bool) { + fn handle_network_change(&mut self, is_major: bool) { debug!(is_major, "link change detected"); if is_major { @@ -1617,7 +1617,7 @@ impl Actor { self.transports_network_change.check_relay_connection(); #[cfg(not(wasm_browser))] - self.sock.dns_resolver.reset().await; + self.sock.dns_resolver.reset(); self.re_stun(UpdateReason::LinkChangeMajor); } else { self.re_stun(UpdateReason::LinkChangeMinor); @@ -1751,7 +1751,7 @@ impl Actor { } #[cfg(all(test, with_crypto_provider))] ActorMessage::ForceNetworkChange(is_major) => { - self.handle_network_change(is_major).await; + self.handle_network_change(is_major); } } }