mirror of
https://github.com/n0-computer/iroh.git
synced 2026-11-30 00:01:16 +00:00
refactor(iroh)!: use ArcSwap in DnsResolver for synchronous reset (#4141)
## Description `DnsResolver::reset` was `async` and awaited a write lock on the inner `RwLock<dyn Resolver>`. The socket actor's network-change handler awaited it, blocking the actor for the duration of the reset. This means we would potentially block the main actor loop for network IO because the write lock can only be acquired once all reads are done, and the reads are blocked for the duration of a DNS lookup (limited to `2s` usually). This change stores the resolver in `ArcSwap<Box<dyn Resolver>>` instead of `RwLock`. The `reset` call can now become synchronous - we build a fresh resolver and atomically swap it in via `compare_and_swap`. A `tokio::sync::Notify` wakes any in-flight lookup so it retries against the new resolver. Lookups go through an internal `op` helper that races the lookup future, the reset notification, and a per-attempt timeout in a biased `select!`. The `notified` future is enabled before the resolver is loaded, which together with the swap-then-notify ordering in `reset` ensures that in case of a reset all running futures are aborted and restarted against the new resolver. Under concurrent `reset` calls only the first CAS lands and only the winner notifies. Losers drop their freshly-built resolver. This is fine, and won't happen in practice because `reset` calls are serialized through the socket actor loop. ## Breaking Changes - changed: `iroh_relay::dns::Resolver::reset` signature changed from `fn reset(&mut self)` to `fn reset(&self) -> Box<dyn Resolver>`. Implementations now return a fresh resolver rather than mutating in place. - changed: `iroh_relay::dns::DnsResolver::reset` and `DnsResolver::clear_cache` are no longer `async`. - changed: `DnsError::Timeout` no longer carries a `tokio::time::error::Elapsed` source. The `From<tokio::time::error::Elapsed>` impl is removed. ## Notes & open questions The `op` timeout is per-attempt: a reset-triggered retry starts a fresh `sleep(timeout)`. This is intentional, since a fresh attempt against a just-changed network should not inherit the previous attempt's remaining time, but it does mean the wall-clock total can exceed `timeout`. I think this is fine and preferable. ## Change checklist - [x] Self-review. - [x] Documentation updates. - [ ] Tests if relevant. - [x] All breaking changes documented. --------- Co-authored-by: Friedel Ziegelmayer <me@dignifiedquire.com>
This commit is contained in:
co-authored by
Friedel Ziegelmayer
parent
c08ccf80af
commit
f904fc3db5
Generated
+1
@@ -2437,6 +2437,7 @@ dependencies = [
|
||||
name = "iroh-dns"
|
||||
version = "0.98.0"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"cfg_aliases",
|
||||
"derive_more",
|
||||
"hickory-resolver",
|
||||
|
||||
@@ -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"
|
||||
|
||||
+128
-28
@@ -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<dyn Resolver>;
|
||||
}
|
||||
|
||||
/// 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<RwLock<dyn Resolver>>);
|
||||
pub struct DnsResolver {
|
||||
inner: Arc<Inner>,
|
||||
}
|
||||
|
||||
/// Shared state behind [`DnsResolver`].
|
||||
#[derive(Debug)]
|
||||
struct Inner {
|
||||
/// Wakes in-flight [`Self::op`] calls when the resolver is swapped.
|
||||
notify_reset: Notify,
|
||||
resolver: ArcSwap<Box<dyn Resolver>>,
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
fn new(inner: Box<dyn Resolver>) -> 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<F, Fut, R, E>(&self, timeout: Duration, f: F) -> Result<R, DnsError>
|
||||
where
|
||||
E: 'static + Send + Into<DnsError>,
|
||||
R: 'static + Send,
|
||||
F: 'static + Send + Fn(Arc<Box<dyn Resolver>>) -> Fut,
|
||||
Fut: 'static + Send + Future<Output = Result<R, E>>,
|
||||
{
|
||||
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<impl Iterator<Item = TxtRecordData>, 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<impl Iterator<Item = IpAddr> + use<T>, 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<impl Iterator<Item = IpAddr> + use<T>, 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<dyn Resolver> {
|
||||
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<dyn Resolver> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
+4
-4
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user