[edge] Upstreams: 3 s deadline on name lookups, 502 on timeout

This commit is contained in:
2026-11-07 16:39:29 +01:00
parent ee8c304740
commit 8c04b0f4bd
+88 -10
View File
@@ -10,6 +10,7 @@ use std::net::SocketAddr;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize}; use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::time::Duration;
use http::{HeaderName, HeaderValue}; use http::{HeaderName, HeaderValue};
use ianitor_core::edge_config::{ use ianitor_core::edge_config::{
@@ -127,23 +128,100 @@ fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
}) })
} }
/// How long a name lookup may take before the request fails with 502. Matches the 3 s dial
/// timeout (Caddy's default), which in Go also bounds the lookup.
pub const RESOLVE_TIMEOUT: Duration = Duration::from_secs(3);
impl UpstreamRt { impl UpstreamRt {
/// Addresses to try, in resolver order. Names are resolved at connect time (like Caddy's /// 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. /// dialer), so DNS changes and unresolvable names only affect requests, not startup.
/// A lookup that takes longer than [`RESOLVE_TIMEOUT`] is an error.
pub async fn resolve(&self) -> std::io::Result<Vec<SocketAddr>> { pub async fn resolve(&self) -> std::io::Result<Vec<SocketAddr>> {
if let Ok(ip) = self.host.parse::<std::net::IpAddr>() { resolve_with(
return Ok(vec![SocketAddr::new(ip, self.port)]); &self.host,
} self.port,
let addrs: Vec<SocketAddr> = tokio::net::lookup_host((self.host.as_str(), self.port)) RESOLVE_TIMEOUT,
.await? |host, port| async move {
.collect(); tokio::net::lookup_host((host.as_str(), port))
if addrs.is_empty() { .await
.map(Iterator::collect)
},
)
.await
}
}
/// [`UpstreamRt::resolve`] with the lookup passed in, so the deadline can be tested.
pub async fn resolve_with<F, Fut>(
host: &str,
port: u16,
deadline: Duration,
lookup: F,
) -> std::io::Result<Vec<SocketAddr>>
where
F: FnOnce(String, u16) -> Fut,
Fut: Future<Output = std::io::Result<Vec<SocketAddr>>>,
{
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
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( return Err(std::io::Error::new(
std::io::ErrorKind::NotFound, std::io::ErrorKind::TimedOut,
"name resolves to no address", format!("name lookup took longer than {deadline:?}"),
)); ));
} }
Ok(addrs) };
if addrs.is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
"name resolves to no address",
));
}
Ok(addrs)
}
#[cfg(test)]
mod resolve_tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[tokio::test(start_paused = true)]
async fn a_slow_resolver_times_out() {
let t = tokio::time::Instant::now();
let err = resolve_with("slow.test", 80, RESOLVE_TIMEOUT, |_, _| async {
tokio::time::sleep(Duration::from_secs(10)).await;
Ok(vec!["127.0.0.1:80".parse().unwrap()])
})
.await
.unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
assert_eq!(t.elapsed(), RESOLVE_TIMEOUT);
}
#[tokio::test(start_paused = true)]
async fn a_prompt_resolver_and_ip_literals_pass() {
let a: SocketAddr = "127.0.0.1:80".parse().unwrap();
let got = resolve_with(
"ok.test",
80,
RESOLVE_TIMEOUT,
|_, _| async move { Ok(vec![a]) },
)
.await;
assert_eq!(got.unwrap(), vec![a]);
let got = resolve_with("::1", 8080, RESOLVE_TIMEOUT, |_, _| async {
unreachable!("IP literals are not looked up")
})
.await;
assert_eq!(got.unwrap(), vec!["[::1]:8080".parse().unwrap()]);
let got = resolve_with("empty.test", 80, RESOLVE_TIMEOUT, |_, _| async {
Ok(vec![])
})
.await;
assert_eq!(got.unwrap_err().kind(), std::io::ErrorKind::NotFound);
} }
} }