[edge] Resolver, tests first: hung name lookups pin at most a bounded number of their own threads, concurrent lookups of one name share one, and the rest fail at once (red: one blocking-pool task per request, as before)

This commit is contained in:
2026-11-10 20:50:26 +01:00
parent 39dd8f0f47
commit 66dcf75fea
3 changed files with 258 additions and 81 deletions
+251
View File
@@ -0,0 +1,251 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Upstream name lookups with a bounded cost.
//!
//! The system resolver (`getaddrinfo`, which honours nsswitch and /etc/hosts like every other
//! program on the machine) blocks a thread, and a lookup cannot be cancelled: when a request
//! gives up after [`crate::runtime::RESOLVE_TIMEOUT`], the thread stays busy until glibc gives
//! up (by default 5 s × 2 attempts × each name server). Through tokio's blocking pool, a dead
//! name server and enough requests would pin every thread of that pool, which the rest of edge
//! shares (file reads, the admin socket).
//!
//! So lookups run on their own threads, at most [`MAX_LOOKUP_THREADS`] at a time, never on
//! tokio's pool; concurrent requests for one name share one lookup; and a request that would
//! need a thread past the limit fails at once (a 502, like a lookup that timed out) instead of
//! queueing. Nothing is cached: like Caddy, every connect resolves again.
use std::collections::HashMap;
use std::io;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
use tokio::sync::{OwnedSemaphorePermit, Semaphore, watch};
/// How many lookups may hold a thread at once.
pub const MAX_LOOKUP_THREADS: usize = 8;
type Lookup = dyn Fn(&str, u16) -> io::Result<Vec<SocketAddr>> + Send + Sync;
type Answer = Result<Arc<Vec<SocketAddr>>, (io::ErrorKind, String)>;
type Inflight = Mutex<HashMap<(String, u16), watch::Receiver<Option<Answer>>>>;
pub struct Resolver {
permits: Arc<Semaphore>,
inflight: Arc<Inflight>,
lookup: Arc<Lookup>,
}
fn lock(m: &Inflight) -> MutexGuard<'_, HashMap<(String, u16), watch::Receiver<Option<Answer>>>> {
m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// The process-wide resolver over the system's `getaddrinfo`.
pub fn system() -> &'static Resolver {
static SYSTEM: std::sync::LazyLock<Resolver> = std::sync::LazyLock::new(|| {
Resolver::new(MAX_LOOKUP_THREADS, |host, port| {
use std::net::ToSocketAddrs;
(host, port).to_socket_addrs().map(Iterator::collect)
})
});
&SYSTEM
}
impl Resolver {
pub fn new(
threads: usize,
lookup: impl Fn(&str, u16) -> io::Result<Vec<SocketAddr>> + Send + Sync + 'static,
) -> Resolver {
Resolver {
permits: Arc::new(Semaphore::new(threads)),
inflight: Arc::default(),
lookup: Arc::new(lookup),
}
}
/// Addresses for `host:port` in resolver order, within `deadline`. IP literals are not
/// looked up. Errors: `TimedOut` (the lookup may go on in the background, holding its
/// thread), `ResourceBusy` (every lookup thread is taken), `NotFound` (no address), or the
/// resolver's own error.
pub async fn resolve(
&self,
host: &str,
port: u16,
deadline: Duration,
) -> io::Result<Vec<SocketAddr>> {
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
return Ok(vec![SocketAddr::new(ip, port)]);
}
let mut rx = self.start_or_join(host, port)?;
let answer = match tokio::time::timeout(deadline, rx.wait_for(Option::is_some)).await {
Ok(Ok(v)) => v.clone(),
Ok(Err(_)) => {
return Err(io::Error::other(
"the name lookup thread ended without an answer",
));
}
Err(_) => {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
format!("name lookup took longer than {deadline:?}"),
));
}
};
match answer {
Some(Ok(addrs)) if addrs.is_empty() => Err(io::Error::new(
io::ErrorKind::NotFound,
"name resolves to no address",
)),
Some(Ok(addrs)) => Ok(addrs.as_ref().clone()),
Some(Err((kind, msg))) => Err(io::Error::new(kind, msg)),
None => Err(io::Error::other("no answer")),
}
}
/// The lookup in flight for this name, or a new one on its own thread.
fn start_or_join(&self, host: &str, port: u16) -> io::Result<watch::Receiver<Option<Answer>>> {
// Not built yet (the red commit): one blocking-pool task per request, as before.
let _ = (&self.permits, &self.inflight);
let (tx, rx) = watch::channel(None);
let lookup = self.lookup.clone();
let host = host.to_owned();
tokio::task::spawn_blocking(move || {
let answer = lookup(&host, port)
.map(Arc::new)
.map_err(|e| (e.kind(), e.to_string()));
let _ = tx.send(Some(answer));
});
Ok(rx)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use std::sync::Condvar;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
/// A resolver whose lookups hang until the gate opens; counts the lookups started.
struct Hung {
started: Arc<AtomicUsize>,
gate: Arc<(Mutex<bool>, Condvar)>,
}
impl Hung {
fn resolver(threads: usize) -> (Resolver, Hung) {
let started = Arc::new(AtomicUsize::new(0));
let gate = Arc::new((Mutex::new(false), Condvar::new()));
let (s, g) = (started.clone(), gate.clone());
let r = Resolver::new(threads, move |_, port| {
s.fetch_add(1, Ordering::SeqCst);
let (m, cv) = &*g;
let mut open = m.lock().unwrap();
while !*open {
open = cv.wait(open).unwrap();
}
Ok(vec![SocketAddr::from(([127, 0, 0, 1], port))])
});
(r, Hung { started, gate })
}
fn open(&self) {
let (m, cv) = &*self.gate;
*m.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true;
cv.notify_all();
}
}
/// A failed assertion must not leave lookups hung (the runtime waits for them on drop).
impl Drop for Hung {
fn drop(&mut self) {
self.open();
}
}
const SHORT: Duration = Duration::from_millis(100);
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn hung_lookups_pin_at_most_the_limit_and_the_rest_fail_at_once() {
let (r, hung) = Hung::resolver(2);
for name in ["a.test", "b.test"] {
let e = r.resolve(name, 80, SHORT).await.unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::TimedOut, "{e}");
}
// Both threads are still stuck in the resolver: a third name fails without waiting.
let t = Instant::now();
let e = r
.resolve("c.test", 80, Duration::from_secs(5))
.await
.unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::ResourceBusy, "{e}");
assert!(t.elapsed() < Duration::from_secs(1), "{:?}", t.elapsed());
// A name already being looked up joins that lookup instead of taking a thread.
let e = r.resolve("A.test", 80, SHORT).await.unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::TimedOut);
assert_eq!(hung.started.load(Ordering::SeqCst), 2);
// Once the resolver answers, the threads come back.
hung.open();
let mut ok = None;
for _ in 0..100 {
match r.resolve("c.test", 81, SHORT).await {
Ok(a) => {
ok = Some(a);
break;
}
Err(e) if e.kind() == io::ErrorKind::ResourceBusy => {
tokio::time::sleep(Duration::from_millis(20)).await;
}
Err(e) => panic!("{e}"),
}
}
assert_eq!(ok.unwrap(), vec![SocketAddr::from(([127, 0, 0, 1], 81))]);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn concurrent_requests_for_one_name_share_one_lookup() {
let started = Arc::new(AtomicUsize::new(0));
let s = started.clone();
let r = Arc::new(Resolver::new(2, move |_, port| {
s.fetch_add(1, Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(200));
Ok(vec![SocketAddr::from(([192, 0, 2, 1], port))])
}));
let mut tasks = Vec::new();
for _ in 0..20 {
let r = r.clone();
tasks.push(tokio::spawn(async move {
r.resolve("shared.test", 443, Duration::from_secs(5)).await
}));
}
for t in tasks {
assert_eq!(
t.await.unwrap().unwrap(),
vec![SocketAddr::from(([192, 0, 2, 1], 443))]
);
}
assert_eq!(started.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn literals_empty_answers_and_errors() {
let r = Resolver::new(1, |host, _| match host {
"empty.test" => Ok(vec![]),
_ => Err(io::Error::new(io::ErrorKind::NotFound, "no such host")),
});
assert_eq!(
r.resolve("::1", 8080, SHORT).await.unwrap(),
vec!["[::1]:8080".parse().unwrap()]
);
assert_eq!(
r.resolve("empty.test", 80, SHORT).await.unwrap_err().kind(),
io::ErrorKind::NotFound
);
let e = r.resolve("gone.test", 80, SHORT).await.unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::NotFound);
assert!(e.to_string().contains("no such host"));
}
}