diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 9bce7163..185cc6e1 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -17,6 +17,11 @@ changes go in their respective binding's NEXT_CHANGELOG. certificate and private key are supplied atomically and must both be non-empty. +- C ABI: `kernel_session_config_set_request_timeout()` configures the total + timeout for one HTTP request in milliseconds; `0` keeps the kernel's + 120-second default. This enables Go and other C-ABI consumers to expose + request-timeout configuration. + ### Changed ### Updated diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 47a3af5a..001f4c17 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -336,6 +336,13 @@ KernelStatusCode kernel_session_config_set_session_conf(KernelSessionConfig* con KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* config, const char* name, const char* value); +/* Configure the total timeout for one HTTP request, from connection start + * through response-body completion. A separate 30s connection timeout also + * applies, so connection establishment is bounded by the shorter limit. + * `request_timeout_ms == 0` keeps the kernel default (120s). */ +KernelStatusCode kernel_session_config_set_request_timeout(KernelSessionConfig* config, + uint64_t request_timeout_ms); + /* Initialize kernel logging, process-wide and ONCE (first non-OFF call wins; * later calls are no-ops). `level` is OFF/ERROR/WARN/INFO/DEBUG/TRACE * (NULL → RUST_LOG, default warn); `file_path` NULL → stderr. Not tied to diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml index 56d30a18..d4aa1c33 100644 --- a/pyo3/Cargo.toml +++ b/pyo3/Cargo.toml @@ -39,6 +39,11 @@ license = "Apache-2.0" description = "PyO3 Python bindings for the Databricks SQL Kernel" repository = "https://github.com/databricks/databricks-sql-kernel" +[features] +# Unit-test binaries must link libpython. Maturin enables this feature only +# when building the extension module, where Python provides the symbols. +extension-module = ["pyo3/extension-module"] + # Built as a Python extension module by maturin. The lib basename here # only affects the intermediate `.so` cargo produces; maturin renames # the wheel artifact to `databricks_sql_kernel..so` per @@ -72,7 +77,7 @@ databricks-sql-kernel = { path = "..", default-features = false, features = ["tl # step with `requires-python = ">=3.9"` in pyproject.toml; bumping # both together avoids shipping a wheel whose ABI tag advertises an # interpreter the package no longer claims to support. -pyo3 = { version = "0.29", features = ["extension-module", "abi3-py39"] } +pyo3 = { version = "0.29", features = ["abi3-py39"] } # Multi-thread runtime — one per Session, owned on the Rust side. tokio = { version = "1", features = ["rt-multi-thread"] } diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index 5fd72c40..ad41d30d 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -14,6 +14,9 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added +- `Session(..., request_timeout_secs=...)` configures the total timeout for one + HTTP request; unset or `0` keeps the kernel's 120-second default. + ### Changed ### Updated diff --git a/pyo3/pyproject.toml b/pyo3/pyproject.toml index 2070cad8..ae8bb2d5 100644 --- a/pyo3/pyproject.toml +++ b/pyo3/pyproject.toml @@ -57,3 +57,4 @@ dev = [ [tool.maturin] module-name = "databricks_sql_kernel" +features = ["extension-module"] diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 7d95dabe..8bc04bd0 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -95,6 +95,71 @@ fn build_telemetry_config( Ok(telemetry) } +#[allow(clippy::too_many_arguments)] +fn build_http_config( + request_timeout_secs: Option, + retry_min_wait_secs: Option, + retry_max_wait_secs: Option, + retry_max_attempts: Option, + retry_overall_timeout_secs: Option, + http_headers: Option>, +) -> PyResult> { + // Zero means "keep the kernel default", matching the C ABI setter. Use a + // float because databricks-sql-python's existing `_socket_timeout` accepts + // fractional seconds. + let request_timeout = match request_timeout_secs { + None => None, + Some(s) => { + if s == 0.0 { + None + } else { + let timeout = std::time::Duration::try_from_secs_f64(s).map_err(|_| { + pyo3::exceptions::PyValueError::new_err( + "request_timeout_secs must be finite and >= 0", + ) + })?; + if timeout.is_zero() { + return Err(pyo3::exceptions::PyValueError::new_err( + "positive request_timeout_secs must round to at least 1 nanosecond", + )); + } + Some(timeout) + } + } + }; + let has_http_headers = http_headers.as_ref().is_some_and(|h| !h.is_empty()); + if request_timeout.is_none() + && retry_min_wait_secs.is_none() + && retry_max_wait_secs.is_none() + && retry_max_attempts.is_none() + && retry_overall_timeout_secs.is_none() + && !has_http_headers + { + return Ok(None); + } + + let mut http = databricks_sql_kernel::HttpConfig::default(); + if let Some(timeout) = request_timeout { + http.request_timeout = timeout; + } + if let Some(s) = retry_min_wait_secs { + http.retry_min_wait = std::time::Duration::from_secs(s); + } + if let Some(s) = retry_max_wait_secs { + http.retry_max_wait = std::time::Duration::from_secs(s); + } + if let Some(attempts) = retry_max_attempts { + http.retry_max_retries = attempts.saturating_sub(1); + } + if let Some(s) = retry_overall_timeout_secs { + http.overall_timeout = std::time::Duration::from_secs(s); + } + if let Some(headers) = http_headers { + http.custom_headers = headers; + } + Ok(Some(http)) +} + #[allow(clippy::too_many_arguments)] fn build_driver_system_configuration( driver_name: Option, @@ -183,6 +248,12 @@ impl Session { /// CloudFetch requests; token-endpoint (auth) calls keep a fixed /// fast-fail policy. /// + /// `request_timeout_secs` sets the total timeout for one HTTP request, + /// from connection start through response-body completion. A separate + /// 30-second connection timeout also applies, so connection establishment + /// is bounded by the shorter limit. Unset or `0` keeps the kernel default + /// (120 seconds). + /// /// `http_headers` is a list of `(name, value)` pairs sent on every /// request — used to forward the connector's caller headers (which /// also carry the composed `User-Agent`). The kernel applies them @@ -223,6 +294,7 @@ impl Session { tls_skip_hostname_verify=false, tls_client_cert=None, tls_client_key=None, + request_timeout_secs=None, retry_min_wait_secs=None, retry_max_wait_secs=None, retry_max_attempts=None, @@ -279,6 +351,7 @@ impl Session { tls_skip_hostname_verify: bool, tls_client_cert: Option>, tls_client_key: Option>, + request_timeout_secs: Option, retry_min_wait_secs: Option, retry_max_wait_secs: Option, retry_max_attempts: Option, @@ -371,9 +444,10 @@ impl Session { None }; - // Build an HttpConfig only when the caller tuned retry/backoff - // or supplied custom headers; otherwise leave the builder on its - // defaults (1s/60s/5-retries, no extra headers). + // Build an HttpConfig only when the caller tuned the request timeout, + // retry/backoff, or supplied custom headers; otherwise leave the + // builder on its defaults (120s request timeout, + // 1s/60s/5-retries, no extra headers). // // `retry_max_attempts` is the **total** number of attempts // (matching the connector's `_retry_stop_after_attempts_count` @@ -387,33 +461,14 @@ impl Session { // connector forwards its `http_headers`, which also carries the // composed `User-Agent`). The kernel applies them before its own // `Authorization` / `x-databricks-org-id`, which always win. - let has_http_headers = http_headers.as_ref().is_some_and(|h| !h.is_empty()); - let http_config = if retry_min_wait_secs.is_some() - || retry_max_wait_secs.is_some() - || retry_max_attempts.is_some() - || retry_overall_timeout_secs.is_some() - || has_http_headers - { - let mut http = databricks_sql_kernel::HttpConfig::default(); - if let Some(s) = retry_min_wait_secs { - http.retry_min_wait = std::time::Duration::from_secs(s); - } - if let Some(s) = retry_max_wait_secs { - http.retry_max_wait = std::time::Duration::from_secs(s); - } - if let Some(attempts) = retry_max_attempts { - http.retry_max_retries = attempts.saturating_sub(1); - } - if let Some(s) = retry_overall_timeout_secs { - http.overall_timeout = std::time::Duration::from_secs(s); - } - if let Some(headers) = http_headers { - http.custom_headers = headers; - } - Some(http) - } else { - None - }; + let http_config = build_http_config( + request_timeout_secs, + retry_min_wait_secs, + retry_max_wait_secs, + retry_max_attempts, + retry_overall_timeout_secs, + http_headers, + )?; let driver_system_configuration = build_driver_system_configuration( driver_name, @@ -635,6 +690,34 @@ mod send_sync_tests { assert!(build_telemetry_config(false, None, None, None, None, Some(0)).is_err()); } + #[test] + fn request_timeout_kwarg_maps_to_http_config() { + let default = databricks_sql_kernel::HttpConfig::default(); + assert!(build_http_config(None, None, None, None, None, None) + .unwrap() + .is_none()); + assert!(build_http_config(Some(0.0), None, None, None, None, None) + .unwrap() + .is_none()); + + let http = build_http_config(Some(0.5), None, None, None, None, None) + .unwrap() + .expect("positive request timeout should build an HTTP config"); + assert_eq!(http.request_timeout, std::time::Duration::from_millis(500)); + assert_eq!(http.retry_min_wait, default.retry_min_wait); + assert_eq!(http.overall_timeout, default.overall_timeout); + + let one_ns = std::time::Duration::from_nanos(1).as_secs_f64(); + assert!(build_http_config(Some(one_ns / 1_000.0), None, None, None, None, None).is_err()); + let http = build_http_config(Some(one_ns), None, None, None, None, None) + .unwrap() + .expect("one-nanosecond request timeout should be accepted"); + assert_eq!(http.request_timeout, std::time::Duration::from_nanos(1)); + + assert!(build_http_config(Some(-1.0), None, None, None, None, None).is_err()); + assert!(build_http_config(Some(f64::NAN), None, None, None, None, None).is_err()); + } + #[test] fn driver_system_kwargs_map_to_kernel_config() { assert!(build_driver_system_configuration( diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index cb8fdf55..a1944c9b 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -131,6 +131,9 @@ pub struct KernelSessionConfig { /// Extra HTTP headers sent on every request (accumulated by /// `..._set_custom_header`, one `(name, value)` pair per call). custom_headers: Vec<(String, String)>, + /// Total request timeout (populated by `..._set_request_timeout`). `None` + /// keeps [`HttpConfig::default`]'s 120-second timeout. + request_timeout: Option, /// HTTP retry / backoff knobs (populated by `..._set_retry_config`). /// `None` keeps the kernel default policy (exponential backoff with /// jitter; see [`HttpConfig::default`] for the concrete values); `Some` @@ -193,7 +196,7 @@ struct ProxySpec { /// C-side HTTP retry config captured from /// `kernel_session_config_set_retry_config`. The JDBC-style backoff/attempt /// knobs a host tunes, plus the cumulative retry budget (`overall_timeout`); -/// every other `HttpConfig` field (per-request timeout, pool size) keeps its +/// every other `HttpConfig` field (request timeout, pool size) keeps its /// default when a retry spec is set. `overall_timeout` is `None` when the host /// left it 0, so [`HttpConfig::default`]'s budget is preserved. struct RetrySpec { @@ -259,6 +262,7 @@ pub unsafe extern "C" fn kernel_session_config_new( proxy: None, tls: TlsSpec::default(), custom_headers: Vec::new(), + request_timeout: None, retry: None, // Default to ignoring transactions, matching IgnoreTransactions=1. ignore_transactions: true, @@ -579,6 +583,26 @@ pub unsafe extern "C" fn kernel_session_config_set_custom_header( }) } +/// Configure the total timeout for one HTTP request, from connection start +/// through response-body completion. A separate 30-second connection timeout +/// also applies, so connection establishment is bounded by the shorter limit. +/// `request_timeout_ms == 0` clears an earlier override and keeps the kernel +/// default (120 seconds); a positive value overrides it. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_request_timeout( + config: *mut KernelSessionConfig, + request_timeout_ms: u64, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.request_timeout = + (request_timeout_ms != 0).then(|| Duration::from_millis(request_timeout_ms)); + Ok(()) + }) +} + /// Configure the HTTP retry / backoff policy: the minimum and maximum /// backoff wait between attempts (milliseconds), the maximum number of /// retries after the initial attempt (so a request is tried at most @@ -1316,23 +1340,25 @@ fn parse_scopes(s: &str) -> Option> { (!v.is_empty()).then_some(v) } -/// Fold the C-side custom headers and optional [`RetrySpec`] onto a fresh -/// [`HttpConfig`]. Both live on `HttpConfig`, so we start from defaults and set -/// only the fields a setter populated — every other HTTP default (per-request -/// timeout, pool size, and the retry knobs when no `RetrySpec` was set) is -/// preserved. +/// Fold the C-side HTTP overrides onto a fresh [`HttpConfig`]. We start from +/// defaults and set only the fields a setter populated, preserving pool size +/// and any untouched retry or timeout knobs. /// -/// This is the code that actually configures live retries (called from -/// `build_session` whenever headers or a retry spec were set), so it is a pure -/// helper kept unit-testable without a live session. +/// This is the code that actually configures live HTTP behavior (called from +/// `build_session` whenever an HTTP override was set), so it is a pure helper +/// kept unit-testable without a live session. fn merge_http_config( custom_headers: Vec<(String, String)>, + request_timeout: Option, retry: Option, ) -> HttpConfig { let mut http = HttpConfig { custom_headers, ..HttpConfig::default() }; + if let Some(t) = request_timeout { + http.request_timeout = t; + } if let Some(r) = retry { http.retry_min_wait = r.min_wait; http.retry_max_wait = r.max_wait; @@ -1456,6 +1482,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result Result { let mut builder = Client::builder() .connect_timeout(config.connect_timeout) + // `read_timeout` is a historical name; reqwest applies this as + // the total deadline from connect through response-body completion. .timeout(config.read_timeout) .pool_max_idle_per_host(config.max_connections_per_host) .user_agent(&config.user_agent) diff --git a/src/config.rs b/src/config.rs index 5d00859f..21e35bdc 100644 --- a/src/config.rs +++ b/src/config.rs @@ -741,7 +741,9 @@ impl std::fmt::Debug for AuthConfig { #[non_exhaustive] #[derive(Debug, Clone)] pub struct HttpConfig { - /// Per-request timeout. Includes connect + body. + /// Total timeout for one HTTP request, from connection start through + /// response-body completion. A separate 30-second connection timeout also + /// applies, so connection establishment is bounded by the shorter limit. pub request_timeout: Duration, /// Maximum total time across retries for a single logical RPC. diff --git a/src/session.rs b/src/session.rs index 5801182a..1f990c85 100644 --- a/src/session.rs +++ b/src/session.rs @@ -942,8 +942,8 @@ impl SessionBuilder { fn build_http_client_config(config: &SessionConfig, org_id: Option) -> HttpClientConfig { HttpClientConfig { connect_timeout: Duration::from_secs(30), - // The internal `read_timeout` corresponds to the public - // `request_timeout` — both gate a single HTTP round-trip. + // The historical internal `read_timeout` field is passed to reqwest's + // total request `.timeout()` and corresponds to public `request_timeout`. read_timeout: config.http.request_timeout, max_connections_per_host: config.http.pool_max_idle_per_host, proxy: build_proxy_config(config.proxy.as_ref()), @@ -1611,10 +1611,10 @@ mod retry_config_tests { } /// The public `request_timeout` becomes the internal HTTP client's - /// `read_timeout` (the per-connection socket read timeout the napi - /// `socketTimeoutMs` option drives). + /// historically named `read_timeout`, which is applied as reqwest's total + /// request timeout. #[test] - fn request_timeout_becomes_internal_read_timeout() { + fn request_timeout_becomes_internal_total_request_timeout() { let http = HttpConfig { request_timeout: Duration::from_millis(4500), ..HttpConfig::default() diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index ea9520a1..8faa675e 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -187,6 +187,11 @@ static void test_proxy_and_tls_setters(void) { CHECK(rc == KernelStatusCode_InvalidArgument, "set_tls_client_certificate(NULL key) → InvalidArgument"); + rc = kernel_session_config_set_request_timeout(config, 45000); + CHECK(rc == KernelStatusCode_Success, "set_request_timeout (45s) succeeds"); + rc = kernel_session_config_set_request_timeout(config, 0); + CHECK(rc == KernelStatusCode_Success, "set_request_timeout (default) succeeds"); + /* Retry config: a valid range (incl. max_retries=0 to disable, overall * timeout 0 = keep default) succeeds; a non-zero overall timeout also * succeeds; a zero min_wait is rejected; an inverted range (max