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
61 changes: 61 additions & 0 deletions napi/src/async_statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,67 @@ impl AsyncStatement {
.await
}

// ─── SEA extended status accessors (Thrift parity, async path) ─────
//
// Mirror the same-named accessors on the sync `Statement`. The
// underlying values come off the kernel `ExecutedAsyncStatement`'s
// latest observed `StatementStatus`; for a DML the kernel derives
// `num_modified_rows` from the result that rides on the terminal
// GetStatement poll (see `SeaRestTransport::enrich_num_modified_rows`),
// so a caller gets the count after the statement has reached a terminal
// state via `status()` / `awaitResult()` — no extra fetch. `null` until
// then, and on SELECT / warehouses that don't surface the counter.
// Throws `InvalidStatementHandle` after `close()`, matching `status()`.

/// Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE).
#[napi]
pub async fn num_modified_rows(&self) -> napi::Result<Option<i64>> {
let inner = Arc::clone(&self.inner);
guarded(async move {
let guard = inner.lock().await;
let inner_state = guard.as_ref().ok_or_else(|| closed_err("AsyncStatement"))?;
Ok(inner_state.executed_async.num_modified_rows())
})
.await
}

/// Server-supplied user-facing message (may contain SQL fragments —
/// redact before centralised logging).
#[napi]
pub async fn display_message(&self) -> napi::Result<Option<String>> {
let inner = Arc::clone(&self.inner);
guarded(async move {
let guard = inner.lock().await;
let inner_state = guard.as_ref().ok_or_else(|| closed_err("AsyncStatement"))?;
Ok(inner_state.executed_async.display_message())
})
.await
}

/// Server-supplied diagnostic detail.
#[napi]
pub async fn diagnostic_info(&self) -> napi::Result<Option<String>> {
let inner = Arc::clone(&self.inner);
guarded(async move {
let guard = inner.lock().await;
let inner_state = guard.as_ref().ok_or_else(|| closed_err("AsyncStatement"))?;
Ok(inner_state.executed_async.diagnostic_info())
})
.await
}

/// Server-supplied structured error detail (JSON), when enabled.
#[napi]
pub async fn error_details_json(&self) -> napi::Result<Option<String>> {
let inner = Arc::clone(&self.inner);
guarded(async move {
let guard = inner.lock().await;
let inner_state = guard.as_ref().ok_or_else(|| closed_err("AsyncStatement"))?;
Ok(inner_state.executed_async.error_details_json())
})
.await
}

/// Block until the server reaches a terminal state, then return
/// an `AsyncResultHandle` that wraps the materialised result
/// stream. The handle exposes `fetchNextBatch()` / `schema()`
Expand Down
78 changes: 78 additions & 0 deletions napi/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,27 @@ pub struct ConnectionOptions {
/// identity. The NodeJS driver folds its `userAgentEntry` into a
/// `User-Agent` entry here.
pub custom_headers: Option<Vec<HeaderEntry>>,

/// Retry/backoff tuning — all optional. An unset field keeps the kernel's
/// built-in policy (1s/60s exponential backoff, 6 total attempts, 900s
/// budget). Mirrors the pyo3 binding's `retry_*` kwargs so the Node.js
/// driver can forward the same retry knobs the Python connector does.
///
/// Lower bound of the exponential backoff (also clamps a server
/// `Retry-After`). Maps onto [`HttpConfig::retry_min_wait`].
pub retry_min_wait_secs: Option<u32>,
/// Upper bound of the exponential backoff. Maps onto
/// [`HttpConfig::retry_max_wait`].
pub retry_max_wait_secs: Option<u32>,
/// **Total** number of attempts (matching the connector's
/// `_retry_stop_after_attempts_count` and JDBC count semantics). The
/// kernel's [`HttpConfig::retry_max_retries`] counts retries *after* the
/// first attempt, so this is converted with `max(0, attempts - 1)` in
/// [`build_http_config`] — `0` / `1` both mean a single attempt, no retry.
pub retry_max_attempts: Option<u32>,
/// Overall retry budget in whole seconds. Maps onto
/// [`HttpConfig::overall_timeout`].
pub retry_overall_timeout_secs: Option<u32>,
}

/// Map the JS `ConnectionOptions` auth fields onto the kernel
Expand Down Expand Up @@ -406,6 +427,23 @@ fn build_http_config(options: &mut ConnectionOptions) -> HttpConfig {
// duplicate names).
http.custom_headers = headers.into_iter().map(|h| (h.name, h.value)).collect();
}
// Retry/backoff knobs — only override the kernel default when the caller
// set one. `retry_max_attempts` is a TOTAL attempt count; the kernel's
// `retry_max_retries` counts retries *after* the first, so convert with
// `saturating_sub(1)` (0/1 ⇒ no retries). Centralises the off-by-one here,
// mirroring the pyo3 binding's `Session::new`.
if let Some(s) = options.retry_min_wait_secs {
http.retry_min_wait = std::time::Duration::from_secs(u64::from(s));
}
if let Some(s) = options.retry_max_wait_secs {
http.retry_max_wait = std::time::Duration::from_secs(u64::from(s));
}
if let Some(attempts) = options.retry_max_attempts {
http.retry_max_retries = attempts.saturating_sub(1);
}
if let Some(s) = options.retry_overall_timeout_secs {
http.overall_timeout = std::time::Duration::from_secs(u64::from(s));
}
http
}

Expand Down Expand Up @@ -522,6 +560,10 @@ mod tests {
client_cert_pem: None,
client_key_pem: None,
custom_headers: None,
retry_min_wait_secs: None,
retry_max_wait_secs: None,
retry_max_attempts: None,
retry_overall_timeout_secs: None,
}
}

Expand Down Expand Up @@ -876,4 +918,40 @@ mod tests {
assert_eq!(http.custom_headers[0].1, "Caller/1.0");
assert_eq!(http.custom_headers[1].1, "Connector/2.0");
}

#[test]
fn http_retry_knobs_map_onto_http_config() {
let mut o = base();
o.retry_min_wait_secs = Some(2);
o.retry_max_wait_secs = Some(45);
o.retry_max_attempts = Some(4); // total attempts → 3 retries
o.retry_overall_timeout_secs = Some(120);
let http = build_http_config(&mut o);
assert_eq!(http.retry_min_wait, std::time::Duration::from_secs(2));
assert_eq!(http.retry_max_wait, std::time::Duration::from_secs(45));
// total attempts (4) → retries after the first (3): the off-by-one.
assert_eq!(http.retry_max_retries, 3);
assert_eq!(http.overall_timeout, std::time::Duration::from_secs(120));
}

#[test]
fn http_retry_attempts_zero_or_one_means_no_retries() {
for attempts in [0u32, 1] {
let mut o = base();
o.retry_max_attempts = Some(attempts);
let http = build_http_config(&mut o);
assert_eq!(http.retry_max_retries, 0, "attempts={attempts}");
}
}

#[test]
fn http_retry_unset_keeps_kernel_defaults() {
let mut o = base();
let http = build_http_config(&mut o);
let def = HttpConfig::default();
assert_eq!(http.retry_min_wait, def.retry_min_wait);
assert_eq!(http.retry_max_wait, def.retry_max_wait);
assert_eq!(http.retry_max_retries, def.retry_max_retries);
assert_eq!(http.overall_timeout, def.overall_timeout);
}
}
96 changes: 96 additions & 0 deletions src/client/retry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,14 @@ 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) {
return false;
}
match self.idempotency {
// Idempotent: all network errors are retryable
RequestIdempotency::Idempotent => {
Expand All @@ -246,6 +254,43 @@ 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?
///
/// 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)
}

/// Walk an error's `source()` chain looking for a DNS-resolution 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 {
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")
|| msg.contains("nodename nor servname")
|| msg.contains("name resolution")
|| msg.contains("no such host")
{
return true;
}
source = err.source();
}
false
}

// --- Backoff Calculator ---

/// Calculate the backoff duration for a retry attempt.
Expand Down Expand Up @@ -307,6 +352,57 @@ fn parse_retry_after(value: &str) -> Option<Duration> {
mod tests {
use super::*;

// --- DNS-resolution detection tests ---

#[test]
fn dns_marker_detected_for_common_resolver_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)",
] {
let err = IoError::other(msg);
assert!(
error_chain_indicates_dns_failure(&err),
"expected DNS marker in: {msg}"
);
}
}

#[test]
fn non_dns_connect_errors_are_not_flagged() {
use std::io::{Error as IoError, ErrorKind};
let refused = IoError::new(
ErrorKind::ConnectionRefused,
"Connection refused (os error 111)",
);
assert!(!error_chain_indicates_dns_failure(&refused));
let reset = IoError::new(ErrorKind::ConnectionReset, "connection reset by peer");
assert!(!error_chain_indicates_dns_failure(&reset));
}

#[test]
fn dns_marker_detected_through_nested_source() {
#[derive(Debug)]
struct Wrapper(std::io::Error);
impl std::fmt::Display for Wrapper {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Top-level message has no DNS marker — the marker is only on
// the inner source, mirroring the reqwest → connector chain.
write!(f, "error sending request for url (https://bogus.invalid/)")
}
}
impl std::error::Error for Wrapper {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.0)
}
}
let inner = std::io::Error::other("dns error");
assert!(error_chain_indicates_dns_failure(&Wrapper(inner)));
}

// --- RequestType mapping tests ---

#[test]
Expand Down
47 changes: 46 additions & 1 deletion src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,52 @@ impl SeaRestTransport {
sea_response.statement_id, sea_response.status.state
);

Self::convert_response(sea_response)
let mut response = Self::convert_response(sea_response)?;
self.enrich_num_modified_rows(&mut response).await;
Ok(response)
}

/// SEA omits the DML row count from the status envelope — for an
/// INSERT/UPDATE/DELETE/MERGE it rides in the result set instead (a single
/// row of `num_*_rows` counters). Thrift, by contrast, reports it on the
/// operation status. When a terminal GetStatement response carries a
/// DML-count result inline, derive `num_affected_rows` (the total) and set
/// it on the status so the extended-status accessors reach Thrift parity —
/// crucially on the async path, where the count would otherwise require an
/// explicit result fetch. No extra round-trip: the count rides on the status
/// poll the caller already made.
///
/// Gated on the manifest's column signature so SELECTs (real columns) never
/// hit the decode path; a DML-count result is always tiny and inline.
async fn enrich_num_modified_rows(&self, response: &mut ExecuteResponse) {
if response.status.num_modified_rows.is_some() {
return;
}
match response.manifest.as_ref() {
Some(m) if crate::statement::dml_count::manifest_is_dml_count(m) => {}
_ => return,
}
let Ok(factory) = self.reader_factory() else {
return;
};
// Decode the inline count via a throwaway reader; this is independent of
// any later fetch the caller makes (a fresh GetStatement builds its own
// reader), so result consumption is unaffected.
let reader = match factory
.create_reader(&response.statement_id, response)
.await
{
Ok(r) => r,
Err(_) => return,
};
let mut stream = match crate::result_stream::ResultStream::from_reader(reader).await {
Ok(s) => s,
Err(_) => return,
};
if let Ok(Some(n)) = crate::statement::dml_count::read_dml_affected_rows(&mut stream).await
{
response.status.num_modified_rows = Some(n);
}
}

/// Decode a single SEA `ExecuteResponse` into a terminal outcome.
Expand Down
Loading
Loading