restructure modules

This commit is contained in:
Frando
2026-06-16 15:30:26 +02:00
parent f6668921a2
commit 96cd8ebf4c
6 changed files with 127 additions and 96 deletions
-6
View File
@@ -6,16 +6,10 @@
//! See the [`crate::endpoint_info`] module documentation for details on how iroh endpoint records
//! are structured.
#[cfg(not(wasm_browser))]
mod cache;
#[cfg(not(wasm_browser))]
mod query;
#[cfg(not(wasm_browser))]
mod resolver;
#[cfg(not(wasm_browser))]
mod system_config;
#[cfg(not(wasm_browser))]
mod transport;
#[cfg(target_os = "android")]
pub use system_config::install_android_jni_context;
+23 -87
View File
@@ -1,10 +1,12 @@
//! Built-in DNS resolver using `simple-dns` for packet construction/parsing
//! and tokio for transport.
#[cfg(with_crypto_provider)]
use std::sync::Mutex;
use std::{
future::Future,
net::{Ipv4Addr, Ipv6Addr},
sync::{Arc, Mutex},
sync::Arc,
time::Instant,
};
@@ -17,14 +19,18 @@ use n0_future::{
use simple_dns::TYPE;
use tracing::{debug, trace};
use super::{
BoxIter, Builder, DnsError, DnsProtocol, Nameserver, TxtRecordData,
cache::{CachedRecord, DnsCache, QueryType},
query::{self, MAX_CNAME_DEPTH},
transport,
};
use super::{BoxIter, Builder, DnsError, DnsProtocol, Nameserver, TxtRecordData};
use crate::dns::{Resolver, system_config::DnsConfig};
mod cache;
mod query;
mod rtt_map;
mod transport;
use self::cache::{CachedRecord, DnsCache, QueryType};
use self::query::MAX_CNAME_DEPTH;
use self::rtt_map::RttMap;
/// Per-nameserver timeout for a single attempt.
const NAMESERVER_TIMEOUT: Duration = Duration::from_secs(2);
@@ -43,68 +49,6 @@ const QUERY_ATTEMPT_DELAY: Duration = Duration::from_millis(100);
/// UDP is unreliable, so a single dropped packet shouldn't be fatal.
const UDP_ATTEMPTS: usize = 2;
/// EWMA weight for folding a new RTT sample into a nameserver's smoothed RTT.
const SRTT_ALPHA: f64 = 0.3;
/// Neutral smoothed-RTT baseline (microseconds) for a never-probed nameserver,
/// and the value the estimate decays toward. Measured-fast servers sit below it
/// and are preferred; failed servers sit above it and are demoted. Decaying
/// toward this (rather than toward zero) keeps a measured-fast server ahead of
/// an idle or recovering one instead of the other way round.
const SRTT_BASELINE_MICROS: f64 = 50_000.0;
/// Penalty added to a nameserver's smoothed RTT on a failed attempt, in
/// microseconds. Large enough to demote it below currently-healthy servers.
const SRTT_FAILURE_PENALTY_MICROS: f64 = 150_000.0;
/// Upper bound on a nameserver's smoothed RTT, in microseconds.
const SRTT_MAX_MICROS: f64 = 5_000_000.0;
/// Time constant (seconds) of the read-time decay of the smoothed RTT toward
/// the baseline, so demoted servers recover and idle estimates lapse to neutral.
const SRTT_DECAY_SECS: f64 = 180.0;
/// Smoothed round-trip time estimate for one nameserver.
///
/// Used to order nameservers fastest-first and to demote ones that fail. A
/// read-time exponential decay pulls the estimate back toward zero so that a
/// demoted server eventually gets re-probed, and a once-fast server that has
/// gone away does not stay preferred forever.
#[derive(Debug)]
struct Srtt {
/// Smoothed estimate in microseconds, as of `updated`.
micros: f64,
/// When `micros` was last written.
updated: Instant,
}
impl Srtt {
fn new() -> Self {
Self {
micros: SRTT_BASELINE_MICROS,
updated: Instant::now(),
}
}
/// The decayed estimate at `now`, used for ordering. Relaxes toward
/// [`SRTT_BASELINE_MICROS`] as the estimate ages.
fn decayed(&self, now: Instant) -> f64 {
let dt = now.saturating_duration_since(self.updated).as_secs_f64();
SRTT_BASELINE_MICROS + (self.micros - SRTT_BASELINE_MICROS) * (-dt / SRTT_DECAY_SECS).exp()
}
/// Folds a successful round-trip time into the estimate.
fn record_success(&mut self, rtt: Duration, now: Instant) {
let sample = rtt.as_micros() as f64;
let base = self.decayed(now);
self.micros = (SRTT_ALPHA * sample + (1.0 - SRTT_ALPHA) * base).min(SRTT_MAX_MICROS);
self.updated = now;
}
/// Penalizes the estimate after a failed attempt.
fn record_failure(&mut self, now: Instant) {
let base = self.decayed(now);
self.micros = (base + SRTT_FAILURE_PENALTY_MICROS).min(SRTT_MAX_MICROS);
self.updated = now;
}
}
/// Default value for `ndots` per resolv.conf(5).
///
/// Names with at least this many dots are tried as absolute names first,
@@ -130,7 +74,7 @@ pub(super) struct SimpleDnsResolver {
https_client: Mutex<Option<reqwest::Client>>,
/// Smoothed RTT per nameserver (parallel to `nameservers`), used to order
/// servers and re-probe demoted ones.
health: Mutex<Vec<Srtt>>,
rtt_map: RttMap,
cache: DnsCache,
builder: Builder,
}
@@ -149,7 +93,7 @@ impl SimpleDnsResolver {
.tls_client_config
.as_ref()
.map(|c| Arc::new(c.clone()));
let health = Mutex::new((0..config.nameservers.len()).map(|_| Srtt::new()).collect());
let health = RttMap::new(config.nameservers.len());
Self {
nameservers: config.nameservers,
search_domains: config.search_domains,
@@ -158,7 +102,7 @@ impl SimpleDnsResolver {
tls_config,
#[cfg(with_crypto_provider)]
https_client: Mutex::new(None),
health,
rtt_map: health,
cache: DnsCache::new(),
builder,
}
@@ -317,23 +261,15 @@ impl SimpleDnsResolver {
/// Returns nameserver indices ordered fastest-first by smoothed RTT.
fn nameserver_order(&self) -> Vec<usize> {
let now = Instant::now();
let health = self.health.lock().expect("poisoned");
let mut order: Vec<usize> = (0..self.nameservers.len()).collect();
order.sort_by(|&a, &b| health[a].decayed(now).total_cmp(&health[b].decayed(now)));
order.sort_by(|&a, &b| {
self.rtt_map
.get_decayed(a)
.total_cmp(&self.rtt_map.get_decayed(b))
});
order
}
/// Records a successful query against nameserver `idx`.
fn record_success(&self, idx: usize, rtt: Duration) {
self.health.lock().expect("poisoned")[idx].record_success(rtt, Instant::now());
}
/// Records a failed query against nameserver `idx`.
fn record_failure(&self, idx: usize) {
self.health.lock().expect("poisoned")[idx].record_failure(Instant::now());
}
/// Sends a query to the configured nameservers, racing them happy-eyeballs
/// style: tries the historically fastest first, starts the next either
/// [`QUERY_ATTEMPT_DELAY`] later or as soon as the in-flight attempt fails
@@ -386,11 +322,11 @@ impl SimpleDnsResolver {
// A dial attempt completed.
Some((idx, start, res)) = dials.next(), if !dials.is_empty() => match res {
Ok(resp) => {
self.record_success(idx, start.elapsed());
self.rtt_map.record_success(idx, start.elapsed());
return Ok(resp);
}
Err(e) => {
self.record_failure(idx);
self.rtt_map.record_failure(idx);
last_err = Some(e);
// Fail fast: start the next attempt now rather than waiting.
next_attempt.as_mut().set_none();
@@ -9,7 +9,7 @@ use std::{
use lru::LruCache;
use super::TxtRecordData;
use crate::dns::TxtRecordData;
/// Maximum number of entries in the DNS cache.
const MAX_CACHE_ENTRIES: usize = 512;
@@ -8,7 +8,7 @@ use simple_dns::{
rdata::{A, AAAA, RData},
};
use super::{DnsError, TxtRecordData};
use crate::dns::{DnsError, TxtRecordData};
/// EDNS(0) advertised UDP payload size.
///
+101
View File
@@ -0,0 +1,101 @@
//! Smoothed round-trip-time tracking used to order nameservers fastest-first.
use std::{sync::Mutex, time::Instant};
use n0_future::time::Duration;
/// EWMA weight for folding a new RTT sample into a nameserver's smoothed RTT.
const SRTT_ALPHA: f64 = 0.3;
/// Neutral smoothed-RTT baseline (microseconds) for a never-probed nameserver,
/// and the value the estimate decays toward. Measured-fast servers sit below it
/// and are preferred; failed servers sit above it and are demoted. Decaying
/// toward this (rather than toward zero) keeps a measured-fast server ahead of
/// an idle or recovering one instead of the other way round.
const SRTT_BASELINE_MICROS: f64 = 50_000.0;
/// Penalty added to a nameserver's smoothed RTT on a failed attempt, in
/// microseconds. Large enough to demote it below currently-healthy servers.
const SRTT_FAILURE_PENALTY_MICROS: f64 = 150_000.0;
/// Upper bound on a nameserver's smoothed RTT, in microseconds.
const SRTT_MAX_MICROS: f64 = 5_000_000.0;
/// Time constant (seconds) of the read-time decay of the smoothed RTT toward
/// the baseline, so demoted servers recover and idle estimates lapse to neutral.
const SRTT_DECAY_SECS: f64 = 180.0;
/// Smoothed round-trip time estimate for one nameserver.
///
/// Used to order nameservers fastest-first and to demote ones that fail. A
/// read-time exponential decay pulls the estimate back toward zero so that a
/// demoted server eventually gets re-probed, and a once-fast server that has
/// gone away does not stay preferred forever.
#[derive(Debug)]
struct Srtt {
/// Smoothed estimate in microseconds, as of `updated`.
micros: f64,
/// When `micros` was last written.
updated: Instant,
}
impl Srtt {
fn new() -> Self {
Self {
micros: SRTT_BASELINE_MICROS,
updated: Instant::now(),
}
}
/// The decayed estimate at `now`, used for ordering. Relaxes toward
/// [`SRTT_BASELINE_MICROS`] as the estimate ages.
fn decayed(&self, now: Instant) -> f64 {
let dt = now.saturating_duration_since(self.updated).as_secs_f64();
SRTT_BASELINE_MICROS + (self.micros - SRTT_BASELINE_MICROS) * (-dt / SRTT_DECAY_SECS).exp()
}
/// Folds a successful round-trip time into the estimate.
fn record_success(&mut self, rtt: Duration, now: Instant) {
let sample = rtt.as_micros() as f64;
let base = self.decayed(now);
self.micros = (SRTT_ALPHA * sample + (1.0 - SRTT_ALPHA) * base).min(SRTT_MAX_MICROS);
self.updated = now;
}
/// Penalizes the estimate after a failed attempt.
fn record_failure(&mut self, now: Instant) {
let base = self.decayed(now);
self.micros = (base + SRTT_FAILURE_PENALTY_MICROS).min(SRTT_MAX_MICROS);
self.updated = now;
}
}
/// Smoothed-RTT estimates for a fixed set of nameservers, indexed in parallel
/// to the resolver's nameserver list.
///
/// Behind a single mutex so the resolver can read and update health from
/// concurrent queries without threading a lock through the call sites.
#[derive(Debug)]
pub(super) struct RttMap {
entries: Mutex<Vec<Srtt>>,
}
impl RttMap {
/// Creates a map with `len` nameservers, each at the neutral baseline.
pub(super) fn new(len: usize) -> Self {
Self {
entries: Mutex::new((0..len).map(|_| Srtt::new()).collect()),
}
}
/// Returns the decayed smoothed RTT for nameserver `idx`, used for ordering.
pub(super) fn get_decayed(&self, idx: usize) -> f64 {
self.entries.lock().expect("poisoned")[idx].decayed(Instant::now())
}
/// Folds a successful round-trip time for nameserver `idx` into its estimate.
pub(super) fn record_success(&self, idx: usize, rtt: Duration) {
self.entries.lock().expect("poisoned")[idx].record_success(rtt, Instant::now());
}
/// Penalizes nameserver `idx` after a failed attempt.
pub(super) fn record_failure(&self, idx: usize) {
self.entries.lock().expect("poisoned")[idx].record_failure(Instant::now());
}
}
@@ -9,7 +9,7 @@ use n0_error::{AnyError, StdResultExt};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[cfg(with_crypto_provider)]
use super::DnsError;
use crate::dns::DnsError;
// Known limitation: TCP and TLS connections are not reused across queries.
// Each query opens a fresh connection, which means a full TLS handshake per