diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs index 64d66f5..e6b9e76 100644 --- a/crates/edge/src/lib.rs +++ b/crates/edge/src/lib.rs @@ -22,6 +22,7 @@ pub mod http_app; pub mod logging; pub mod pages; pub mod proxy; +pub mod resolver; pub mod runtime; pub mod secrets; pub mod share; diff --git a/crates/edge/src/resolver.rs b/crates/edge/src/resolver.rs new file mode 100644 index 0000000..a044538 --- /dev/null +++ b/crates/edge/src/resolver.rs @@ -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> + Send + Sync; +type Answer = Result>, (io::ErrorKind, String)>; +type Inflight = Mutex>>>; + +pub struct Resolver { + permits: Arc, + inflight: Arc, + lookup: Arc, +} + +fn lock(m: &Inflight) -> MutexGuard<'_, HashMap<(String, u16), watch::Receiver>>> { + 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 = 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> + 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> { + if let Ok(ip) = host.parse::() { + 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>> { + // 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, + gate: Arc<(Mutex, 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")); + } +} diff --git a/crates/edge/src/runtime.rs b/crates/edge/src/runtime.rs index c6e0416..1c5ca57 100644 --- a/crates/edge/src/runtime.rs +++ b/crates/edge/src/runtime.rs @@ -235,54 +235,15 @@ pub const RESOLVE_TIMEOUT: Duration = Duration::from_secs(3); impl UpstreamRt { /// Addresses to try, in resolver order. Names are resolved at connect time (like Caddy's /// dialer), so DNS changes and unresolvable names only affect requests, not startup. - /// A lookup that takes longer than [`RESOLVE_TIMEOUT`] is an error. + /// A lookup that takes longer than [`RESOLVE_TIMEOUT`] is an error; lookups run on their + /// own bounded threads ([`crate::resolver`]). pub async fn resolve(&self) -> std::io::Result> { - resolve_with( - &self.host, - self.port, - RESOLVE_TIMEOUT, - |host, port| async move { - tokio::net::lookup_host((host.as_str(), port)) - .await - .map(Iterator::collect) - }, - ) - .await + crate::resolver::system() + .resolve(&self.host, self.port, RESOLVE_TIMEOUT) + .await } } -/// [`UpstreamRt::resolve`] with the lookup passed in, so the deadline can be tested. -pub async fn resolve_with( - host: &str, - port: u16, - deadline: Duration, - lookup: F, -) -> std::io::Result> -where - F: FnOnce(String, u16) -> Fut, - Fut: Future>>, -{ - if let Ok(ip) = host.parse::() { - return Ok(vec![SocketAddr::new(ip, port)]); - } - let addrs = match tokio::time::timeout(deadline, lookup(host.to_owned(), port)).await { - Ok(r) => r?, - Err(_) => { - return Err(std::io::Error::new( - std::io::ErrorKind::TimedOut, - format!("name lookup took longer than {deadline:?}"), - )); - } - }; - if addrs.is_empty() { - return Err(std::io::Error::new( - std::io::ErrorKind::NotFound, - "name resolves to no address", - )); - } - Ok(addrs) -} - fn header_name(name: &str) -> Result { HeaderName::from_bytes(name.as_bytes()).map_err(|_| EdgeError::Header { name: name.to_owned(), @@ -498,46 +459,10 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result