Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ changes go in their respective binding's NEXT_CHANGELOG.

### Changed

- HTTP retries now treat temporary DNS resolver failures as transient while
permanent unknown-host failures still fail immediately.

### Updated

### Fixed
Expand Down
158 changes: 151 additions & 7 deletions src/client/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1668,13 +1668,14 @@ lGrv15pBcePj
};
use std::collections::HashSet;
use std::sync::atomic::{AtomicU32, Ordering};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

/// Build a client pointed at the mock server with short retry waits for fast tests.
fn test_client(
mock_server: &MockServer,
fn test_client_with_http_config(
retry_config: RetryConfig,
http_config: HttpClientConfig,
) -> DatabricksHttpClient {
let mut overrides = HashMap::new();
let ovr = RetryConfigOverrides {
Expand All @@ -1691,15 +1692,20 @@ lGrv15pBcePj

let global = RetryConfig::default();
let retry_configs = build_retry_configs(&global, &overrides);

let config = HttpClientConfig::default();
let client = DatabricksHttpClient::new(config, retry_configs).unwrap();
let client = DatabricksHttpClient::new(http_config, retry_configs).unwrap();
let auth = Arc::new(PersonalAccessToken::new("test-token".to_string()));
client.set_auth_provider(auth);
client
}

/// Build a client pointed at the mock server with short retry waits for fast tests.
fn test_client(
mock_server: &MockServer,
retry_config: RetryConfig,
) -> DatabricksHttpClient {
// Override the client's base URL by using the mock_server URI directly in requests
let _ = mock_server; // used by caller to build request URLs
client
test_client_with_http_config(retry_config, HttpClientConfig::default())
}

/// Short retry config for fast tests (10ms waits instead of 1s).
Expand All @@ -1713,6 +1719,144 @@ lGrv15pBcePj
}
}

async fn read_request_head(stream: &mut TcpStream) {
let mut received = Vec::new();
let mut buffer = [0_u8; 1024];
loop {
let read = stream.read(&mut buffer).await.unwrap();
if read == 0 {
return;
}
received.extend_from_slice(&buffer[..read]);
if received.windows(4).any(|window| window == b"\r\n\r\n") {
return;
}
}
}

async fn write_ok_response(stream: &mut TcpStream) {
stream
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok")
.await
.unwrap();
}

#[tokio::test]
async fn test_connection_refused_retries_until_attempt_limit() {
// Reserve an ephemeral port and release it so every connection is
// refused. The final error records the number of attempts made.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
drop(listener);

let client =
test_client_with_http_config(fast_retry_config(2), HttpClientConfig::default());
let request = client
.inner()
.get(format!("http://{address}/test"))
.build()
.unwrap();

let error = client
.execute(request, RequestType::GetStatementStatus)
.await
.expect_err("closed port must fail");
assert!(
error.message.contains("after 3 attempts"),
"connection refusal should consume the retry budget: {error}"
);
}

#[tokio::test]
async fn test_connection_closed_before_response_is_retried() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let accepted = Arc::new(AtomicU32::new(0));
let server_accepted = Arc::clone(&accepted);

let server = tokio::spawn(async move {
for attempt in 0..2 {
let (mut stream, _) = listener.accept().await.unwrap();
server_accepted.fetch_add(1, Ordering::SeqCst);
read_request_head(&mut stream).await;
if attempt == 0 {
Comment thread
vuanhphung marked this conversation as resolved.
Resolved
// EOF before any response bytes simulates a connection
// dropped/reset after the request reached the peer.
continue;
}
write_ok_response(&mut stream).await;
}
});

let client =
test_client_with_http_config(fast_retry_config(2), HttpClientConfig::default());
let request = client
.inner()
.get(format!("http://{address}/test"))
.build()
.unwrap();

let response = client
.execute(request, RequestType::GetStatementStatus)
.await
.expect("idempotent request should recover after a dropped connection");
assert_eq!(response.text().await.unwrap(), "ok");
assert_eq!(
accepted.load(Ordering::SeqCst),
2,
"server must observe the retry before its task is awaited"
);
server.await.unwrap();
}

#[tokio::test]
async fn test_per_request_timeout_is_retried() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let accepted = Arc::new(AtomicU32::new(0));
let server_accepted = Arc::clone(&accepted);

let server = tokio::spawn(async move {
for attempt in 0..2 {
let (mut stream, _) = listener.accept().await.unwrap();
server_accepted.fetch_add(1, Ordering::SeqCst);
if attempt == 0 {
tokio::spawn(async move {
read_request_head(&mut stream).await;
tokio::time::sleep(Duration::from_millis(300)).await;
});
} else {
read_request_head(&mut stream).await;
write_ok_response(&mut stream).await;
}
}
});

let http_config = HttpClientConfig {
connect_timeout: Duration::from_millis(100),
read_timeout: Duration::from_millis(75),
..HttpClientConfig::default()
};
let client = test_client_with_http_config(fast_retry_config(2), http_config);
let request = client
.inner()
.get(format!("http://{address}/test"))
.build()
.unwrap();

let response = client
.execute(request, RequestType::GetStatementStatus)
.await
.expect("idempotent request should recover after its deadline");
assert_eq!(response.text().await.unwrap(), "ok");
assert_eq!(
accepted.load(Ordering::SeqCst),
2,
"server must observe the retry before its task is awaited"
);
server.await.unwrap();
}

#[tokio::test]
async fn test_idempotent_request_succeeds_on_retry_after_503() {
let mock_server = MockServer::start().await;
Expand Down
76 changes: 44 additions & 32 deletions src/client/retry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,12 +241,10 @@ impl RetryStrategy {

/// Whether the given network/client error is retryable.
pub fn is_retryable_error(&self, error: &reqwest::Error) -> bool {
// A DNS *resolution* failure (the host name does not resolve) is
// permanent — retrying it just burns the whole retry budget on a host
// that will never come back. reqwest reports it as a "connect" error,
// which the branches below would otherwise treat as retryable, so
// short-circuit it here regardless of idempotency.
if is_dns_resolution_failure(error) {
// A permanent DNS lookup failure (for example NXDOMAIN) cannot recover
// through retry. Temporary resolver failures remain ordinary connect
// errors and follow the request's idempotency policy below.
if is_permanent_dns_resolution_failure(error) {
return false;
}
match self.idempotency {
Expand All @@ -260,35 +258,31 @@ impl RetryStrategy {
}
}

/// Heuristic: is this network error a DNS *resolution* failure (the host name
/// does not resolve), as opposed to a transient connect/timeout error?
/// Heuristic: is this network error a permanent DNS lookup failure (the host
/// name does not exist), as opposed to a temporary resolver/connect error?
///
/// A non-existent host (NXDOMAIN) will never resolve, so it must not be
/// retried. reqwest does not expose a typed DNS-error variant, so we walk the
/// error's source chain and match the resolver's message. Matching is broad
/// and lowercased to cover the common phrasings across platforms/resolvers:
/// libc/getaddrinfo (`Name or service not known`), macOS
/// (`nodename nor servname provided`), and hyper/hickory
/// (`dns error`, `failed to lookup address information`).
fn is_dns_resolution_failure(error: &reqwest::Error) -> bool {
error_chain_indicates_dns_failure(error)
/// error's source chain and match only messages that identify an unknown host.
/// Generic markers such as `dns error` and `name resolution` are deliberately
/// excluded because they also describe temporary resolver failures.
fn is_permanent_dns_resolution_failure(error: &reqwest::Error) -> bool {
error_chain_indicates_permanent_dns_failure(error)
}

/// Walk an error's `source()` chain looking for a DNS-resolution marker.
/// Walk an error's `source()` chain looking for a permanent DNS marker.
///
/// Split out from [`is_dns_resolution_failure`] so it can be unit-tested with a
/// synthetic error chain — `reqwest::Error` has no public constructor, so the
/// matching logic can't be exercised through the typed wrapper directly.
fn error_chain_indicates_dns_failure(error: &(dyn std::error::Error + 'static)) -> bool {
/// Split out from [`is_permanent_dns_resolution_failure`] so it can be tested
/// with a synthetic error chain; `reqwest::Error` has no public constructor.
fn error_chain_indicates_permanent_dns_failure(error: &(dyn std::error::Error + 'static)) -> bool {
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(error);
while let Some(err) = source {
let msg = err.to_string().to_ascii_lowercase();
if msg.contains("dns error")
|| msg.contains("failed to lookup address")
|| msg.contains("name or service not known")
if msg.contains("name or service not known")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low — The narrowed marker set is tied to specific resolver phrasings — glibc Name or service not known, macOS nodename nor servname, Windows No such host, plus hickory-only nxdomain/non-existent domain. Because the generic fallbacks (dns error, failed to lookup address, name resolution) were removed, a permanent NXDOMAIN whose error string doesn't contain one of the retained phrases is now classified transient and retried until the full retry budget is exhausted — a regression from the previous fail-fast behavior for that host.

This is fine on glibc/macOS/Windows with the default getaddrinfo resolver, but musl (Alpine) returns a different EAI_NONAME string that matches none of the retained markers, so an NXDOMAIN there would consume all six attempts. If musl targets are in scope, consider keeping a permanent-only fallback (e.g. matching EAI_NONAME/not resolve phrasings) or add a musl-phrasing case to the marker list. Non-blocking — flagging the trade-off since the PR intentionally reclassifies DNS errors.

|| msg.contains("nodename nor servname")
|| msg.contains("name resolution")
|| msg.contains("no such host")
|| msg.contains("non-existent domain")
|| msg.contains("nxdomain")
{
return true;
}
Expand Down Expand Up @@ -370,18 +364,36 @@ mod tests {
// --- DNS-resolution detection tests ---

#[test]
fn dns_marker_detected_for_common_resolver_phrasings() {
fn permanent_dns_marker_detected_for_unknown_host_phrasings() {
use std::io::Error as IoError;
for msg in [
"failed to lookup address information: Name or service not known",
"dns error: failed to lookup address information",
"nodename nor servname provided, or not known",
"No such host is known. (os error 11001)",
"dns error: NXDOMAIN",
"non-existent domain",
] {
let err = IoError::other(msg);
assert!(
error_chain_indicates_dns_failure(&err),
"expected DNS marker in: {msg}"
error_chain_indicates_permanent_dns_failure(&err),
"expected permanent DNS marker in: {msg}"
);
}
}

#[test]
fn temporary_dns_failures_are_not_classified_as_permanent() {
use std::io::Error as IoError;
for msg in [
"dns error: temporary failure in name resolution",
"failed to lookup address information: Try again",
"temporary failure in name resolution",
"server failure",
] {
let err = IoError::other(msg);
assert!(
!error_chain_indicates_permanent_dns_failure(&err),
"temporary DNS failure must not be classified as permanent: {msg}"
);
}
}
Expand All @@ -393,9 +405,9 @@ mod tests {
ErrorKind::ConnectionRefused,
"Connection refused (os error 111)",
);
assert!(!error_chain_indicates_dns_failure(&refused));
assert!(!error_chain_indicates_permanent_dns_failure(&refused));
let reset = IoError::new(ErrorKind::ConnectionReset, "connection reset by peer");
assert!(!error_chain_indicates_dns_failure(&reset));
assert!(!error_chain_indicates_permanent_dns_failure(&reset));
}

#[test]
Expand All @@ -414,8 +426,8 @@ mod tests {
Some(&self.0)
}
}
let inner = std::io::Error::other("dns error");
assert!(error_chain_indicates_dns_failure(&Wrapper(inner)));
let inner = std::io::Error::other("dns error: NXDOMAIN");
assert!(error_chain_indicates_permanent_dns_failure(&Wrapper(inner)));
}

// --- RequestType mapping tests ---
Expand Down
Loading