diff --git a/napi/index.d.ts b/napi/index.d.ts index f8105ff6..0b042121 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -33,7 +33,7 @@ * byte-identical Thrift parity, the JS adapter pre-serialises via * `serializeQueryTags` and writes the result into * `statementConf["query_tags"]` directly — see - * `SeaSessionBackend.executeStatement` in the NodeJS driver. This + * `KernelSessionBackend.executeStatement` in the NodeJS driver. This * path is the one the production code uses. */ export interface ExecuteOptions { @@ -99,7 +99,7 @@ export interface NamedTypedValueInput { /** * Authentication mode selector crossing the napi boundary. The string * literals are what napi-rs emits from this `#[napi(string_enum)]` — the - * NodeJS SEA adapter (`SeaAuth`) matches them verbatim (`'Pat'`, + * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`, * `'OAuthM2m'`, `'OAuthU2m'`). * * Mirrors the kernel [`AuthConfig`] variants this binding supports. @@ -133,6 +133,25 @@ export interface HeaderEntry { name: string value: string } +/** + * Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's + * internal [`ProxyConfig`]. Supplied as a structured object rather than a + * flattened URL so credentials never have to be percent-encoded into the URL + * and the bypass-host list can be expressed. + * + * - `url` — proxy endpoint, e.g. `"http://proxy.corp.example.com:8080"`. Must + * use the `http://` or `https://` scheme. + * - `username` / `password` — optional proxy basic-auth, applied via + * `reqwest`'s `Proxy::basic_auth` (not embedded in the URL). + * - `bypassHosts` — optional comma-separated host/domain list that should + * bypass the proxy (e.g. `"localhost,*.internal.corp"`). + */ +export interface ProxyInput { + url: string + username?: string + password?: string + bypassHosts?: string +} /** * JS-visible options for opening a Databricks SQL session. * @@ -332,6 +351,61 @@ export interface ConnectionOptions { * `User-Agent` entry here. */ customHeaders?: Array + /** + * 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`]. + */ + retryMinWaitSecs?: number + /** + * Upper bound of the exponential backoff. Maps onto + * [`HttpConfig::retry_max_wait`]. + */ + retryMaxWaitSecs?: number + /** + * **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. + */ + retryMaxAttempts?: number + /** + * Overall retry budget in whole seconds. Maps onto + * [`HttpConfig::overall_timeout`]. + */ + retryOverallTimeoutSecs?: number + /** + * Programmatic HTTP/HTTPS proxy ([`ProxyInput`]) to route all kernel + * traffic through. Carries the proxy `url`, optional basic-auth + * `username` / `password`, and an optional `bypassHosts` list — mapped + * field-for-field onto the kernel [`ProxyConfig`]. + * + * Omitted ⇒ the kernel does NOT configure a proxy explicitly and + * `reqwest`'s standard behaviour applies — the `HTTPS_PROXY` / + * `HTTP_PROXY` / `NO_PROXY` environment variables are still honoured. + * Setting this **overrides** those env vars. This complements the env-var + * path: callers who cannot set process env vars (e.g. a long-lived Node + * server) can now route a single connection through a proxy + * programmatically. + */ + proxy?: ProxyInput + /** + * Per-connection socket read timeout, in milliseconds. Caps how + * long a single HTTP round-trip may block waiting on the server + * before the request errors out. Maps onto the kernel + * [`HttpConfig::request_timeout`] (the internal reqwest + * `Client::timeout`). + * + * Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs + * serialises `u32` as JS `number`; the largest representable value + * (~49.7 days) far exceeds any sensible socket timeout. + */ + socketTimeoutMs?: number } /** * Open a Databricks SQL session and return an opaque `Connection` @@ -505,6 +579,17 @@ export declare class AsyncStatement { * that only need the state name. */ status(): Promise + /** Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE). */ + numModifiedRows(): Promise + /** + * Server-supplied user-facing message (may contain SQL fragments — + * redact before centralised logging). + */ + displayMessage(): Promise + /** Server-supplied diagnostic detail. */ + diagnosticInfo(): Promise + /** Server-supplied structured error detail (JSON), when enabled. */ + errorDetailsJson(): Promise /** * Block until the server reaches a terminal state, then return * an `AsyncResultHandle` that wraps the materialised result diff --git a/napi/src/database.rs b/napi/src/database.rs index 37149796..988f2324 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -34,7 +34,8 @@ use napi::bindgen_prelude::Buffer; type Buffer = Vec; use databricks_sql_kernel::{ - AuthConfig, DefaultOpts, Error as KernelError, HttpConfig, ResultConfig, Session, TlsConfig, + AuthConfig, DefaultOpts, Error as KernelError, HttpConfig, ProxyConfig, ResultConfig, Session, + TlsConfig, }; /// NodeJS-driver-appropriate default for `pool_max_idle_per_host`. @@ -116,6 +117,25 @@ pub struct HeaderEntry { pub value: String, } +/// Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's +/// internal [`ProxyConfig`]. Supplied as a structured object rather than a +/// flattened URL so credentials never have to be percent-encoded into the URL +/// and the bypass-host list can be expressed. +/// +/// - `url` — proxy endpoint, e.g. `"http://proxy.corp.example.com:8080"`. Must +/// use the `http://` or `https://` scheme. +/// - `username` / `password` — optional proxy basic-auth, applied via +/// `reqwest`'s `Proxy::basic_auth` (not embedded in the URL). +/// - `bypassHosts` — optional comma-separated host/domain list that should +/// bypass the proxy (e.g. `"localhost,*.internal.corp"`). +#[napi(object)] +pub struct ProxyInput { + pub url: String, + pub username: Option, + pub password: Option, + pub bypass_hosts: Option, +} + /// JS-visible options for opening a Databricks SQL session. /// /// Authentication is selected by `authMode` (default [`AuthMode::Pat`]): @@ -301,6 +321,29 @@ pub struct ConnectionOptions { /// Overall retry budget in whole seconds. Maps onto /// [`HttpConfig::overall_timeout`]. pub retry_overall_timeout_secs: Option, + /// Programmatic HTTP/HTTPS proxy ([`ProxyInput`]) to route all kernel + /// traffic through. Carries the proxy `url`, optional basic-auth + /// `username` / `password`, and an optional `bypassHosts` list — mapped + /// field-for-field onto the kernel [`ProxyConfig`]. + /// + /// Omitted ⇒ the kernel does NOT configure a proxy explicitly and + /// `reqwest`'s standard behaviour applies — the `HTTPS_PROXY` / + /// `HTTP_PROXY` / `NO_PROXY` environment variables are still honoured. + /// Setting this **overrides** those env vars. This complements the env-var + /// path: callers who cannot set process env vars (e.g. a long-lived Node + /// server) can now route a single connection through a proxy + /// programmatically. + pub proxy: Option, + /// Per-connection socket read timeout, in milliseconds. Caps how + /// long a single HTTP round-trip may block waiting on the server + /// before the request errors out. Maps onto the kernel + /// [`HttpConfig::request_timeout`] (the internal reqwest + /// `Client::timeout`). + /// + /// Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs + /// serialises `u32` as JS `number`; the largest representable value + /// (~49.7 days) far exceeds any sensible socket timeout. + pub socket_timeout_ms: Option, } /// Map the JS `ConnectionOptions` auth fields onto the kernel @@ -444,6 +487,12 @@ fn build_http_config(options: &mut ConnectionOptions) -> HttpConfig { if let Some(s) = options.retry_overall_timeout_secs { http.overall_timeout = std::time::Duration::from_secs(u64::from(s)); } + // Per-connection socket read timeout. Maps onto the kernel's + // `request_timeout` (the reqwest `Client::timeout`). Omitted ⇒ kernel + // default (120 s). + if let Some(ms) = options.socket_timeout_ms { + http.request_timeout = std::time::Duration::from_millis(u64::from(ms)); + } http } @@ -518,10 +567,24 @@ pub async fn open_session(mut options: ConnectionOptions) -> napi::Result, + + /// Username for proxy basic-auth. Overrides any credentials + /// embedded in [`url`](Self::url) when set. + pub username: Option, + + /// Password for proxy basic-auth. Secret material — redacted in + /// `Debug`. Ignored unless [`username`](Self::username) is also set. + pub password: Option, + + /// Comma-separated list of hosts/domains to bypass the proxy + /// (e.g. `"localhost,*.internal.corp,.example.com"`). Only applied + /// when [`url`](Self::url) is set. + pub bypass_hosts: Option, +} + +impl std::fmt::Debug for ProxyConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Redact the explicit `password` field. The `url` may itself + // carry embedded `user:pass@` credentials, so render only its + // presence rather than the raw string. + f.debug_struct("ProxyConfig") + .field("url", &self.url.as_ref().map(|_| "")) + .field("username", &self.username) + .field("password", &self.password.as_ref().map(|_| "")) + .field("bypass_hosts", &self.bypass_hosts) + .finish() + } +} // ─── TLS ──────────────────────────────────────────────────────────────────── diff --git a/src/session.rs b/src/session.rs index 81cda453..93641528 100644 --- a/src/session.rs +++ b/src/session.rs @@ -664,32 +664,49 @@ impl SessionBuilder { /// Translate the public [`HttpConfig`] (+ proxy / TLS / org_id) into /// the internal [`HttpClientConfig`] the HTTP client expects. /// -/// The public [`ProxyConfig`] is still a reserved `#[non_exhaustive]` -/// struct (no fields wired yet); the public [`TlsConfig`] now carries -/// `custom_ca_cert` / `accept_self_signed` / -/// `skip_hostname_verification` and is projected onto the internal +/// The public [`ProxyConfig`] is projected onto the internal +/// [`HttpProxyConfig`] (`url` set ⇒ override env vars and route all +/// traffic through it; `url` unset ⇒ reqwest's env-var behaviour). The +/// public [`TlsConfig`] carries `custom_ca_cert` / `accept_self_signed` +/// / `skip_hostname_verification` and is projected onto the internal /// [`HttpTlsConfig`] via [`HttpTlsConfig::from_public`]. fn build_http_client_config(config: &SessionConfig, org_id: Option) -> HttpClientConfig { - let mut hcc = 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. read_timeout: config.http.request_timeout, max_connections_per_host: config.http.pool_max_idle_per_host, - proxy: HttpProxyConfig::default(), + proxy: build_proxy_config(config.proxy.as_ref()), tls: HttpTlsConfig::from_public(&config.tls), org_id, custom_headers: config.http.custom_headers.clone(), ..HttpClientConfig::default() + } +} + +/// Project the public [`ProxyConfig`] onto the internal +/// [`HttpProxyConfig`]. `None` (no proxy config supplied) yields the +/// default internal config (`url == None`), under which the HTTP client +/// keeps reqwest's standard env-var behaviour. A destructuring binding +/// (NOT `..`) is used so a future public-field addition surfaces as a +/// compile error here rather than being silently dropped. +fn build_proxy_config(proxy: Option<&ProxyConfig>) -> HttpProxyConfig { + let Some(proxy) = proxy else { + return HttpProxyConfig::default(); }; - // Touch the still-reserved proxy config so a future field addition - // (without setting it through here) shows up as a compile error - // rather than a silently-dropped option. Explicit `ProxyConfig {}` - // (NOT `{ .. }`) — the `..` rest pattern would defeat the - // tripwire by silently accepting any new field. - let ProxyConfig {} = config.proxy.clone().unwrap_or_default(); - let _ = &mut hcc; - hcc + let ProxyConfig { + url, + username, + password, + bypass_hosts, + } = proxy.clone(); + HttpProxyConfig { + url, + username, + password, + bypass_hosts, + } } /// Build the per-category retry config for the HTTP client. @@ -901,4 +918,51 @@ mod retry_config_tests { assert_eq!(sea.max_retries, 5); assert_eq!(sea.overall_timeout, Duration::from_secs(900)); } + + // ─── Proxy / socket-timeout projection ───────────────────────── + + /// `None` (no public proxy config) ⇒ internal proxy `url` stays + /// unset, preserving reqwest's env-var behaviour. + #[test] + fn proxy_absent_keeps_env_var_behaviour() { + let proxy = build_proxy_config(None); + assert!(proxy.url.is_none()); + let cfg = config_with_http(HttpConfig::default()); + assert!(build_http_client_config(&cfg, None).proxy.url.is_none()); + } + + /// A public `ProxyConfig` with a URL (and optional auth / bypass) + /// projects field-for-field onto the internal proxy config. + #[test] + fn proxy_fields_project_onto_internal_config() { + let mut cfg = config_with_http(HttpConfig::default()); + cfg.proxy = Some(crate::config::ProxyConfig { + url: Some("http://proxy.corp.example.com:8080".to_string()), + username: Some("alice".to_string()), + password: Some("secret".to_string()), + bypass_hosts: Some("localhost,*.internal".to_string()), + ..Default::default() + }); + let proxy = build_http_client_config(&cfg, None).proxy; + assert_eq!( + proxy.url.as_deref(), + Some("http://proxy.corp.example.com:8080") + ); + assert_eq!(proxy.username.as_deref(), Some("alice")); + assert_eq!(proxy.password.as_deref(), Some("secret")); + assert_eq!(proxy.bypass_hosts.as_deref(), Some("localhost,*.internal")); + } + + /// The public `request_timeout` becomes the internal HTTP client's + /// `read_timeout` (the per-connection socket read timeout the napi + /// `socketTimeoutMs` option drives). + #[test] + fn request_timeout_becomes_internal_read_timeout() { + let http = HttpConfig { + request_timeout: Duration::from_millis(4500), + ..HttpConfig::default() + }; + let hcc = build_http_client_config(&config_with_http(http), None); + assert_eq!(hcc.read_timeout, Duration::from_millis(4500)); + } } diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index d4c1c8ca..b3293f00 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -184,9 +184,15 @@ async fn execute_direct_inline_failure_surfaces_eagerly() { async fn execute_direct_running_handle_is_cancellable() { let session = live_session().await; let mut stmt = session.statement(); - // A 40B-row scan reliably runs past the ~10s server inline wait. + // The `execute_direct` inline wait is the SEA server's default for an + // OMITTED `wait_timeout`, which holds up to the 50s SEA maximum — not the + // ~10s an earlier comment assumed. A ~35s scan (range(40e9)) therefore sits + // right at that boundary and flakily returns `Completed`. Use a scan that + // cannot finish within ANY inline wait (range(1e12), minutes of work) so the + // Running arm is deterministic; it is cancelled below, so its full runtime + // never elapses (execute_direct returns once the inline wait is exhausted). stmt.spec() - .sql("SELECT count(*) FROM range(40000000000) WHERE id % 7 = 3 AND rand() < 0.9999"); + .sql("SELECT count(*) FROM range(1000000000000) WHERE id % 7 = 3 AND rand() < 0.9999"); match stmt .execute_direct() .await @@ -203,7 +209,7 @@ async fn execute_direct_running_handle_is_cancellable() { } } DirectStatement::Completed(_) => { - panic!("a 40B-row scan must not finish within the inline wait") + panic!("a 1T-row scan must not finish within the inline wait") } } session.close().await.expect("session close"); @@ -216,8 +222,14 @@ async fn execute_direct_running_handle_is_cancellable() { async fn execute_direct_running_await_result_completes() { let session = live_session().await; let mut stmt = session.statement(); + // Must reliably exceed the server's inline wait (the SEA default for an + // OMITTED `wait_timeout`, observed well under the 50s SEA max) so + // `execute_direct` returns `Running`, yet still finish in bounded time since + // `await_result` drives it to completion below. range(100e9) (~90s of scan on + // the test warehouse) clears the inline-wait ceiling with comfortable margin + // — the prior ~35s range(40e9) sat right at the boundary and flaked. stmt.spec() - .sql("SELECT count(*) AS c FROM range(40000000000) WHERE id % 7 = 3 AND rand() < 0.9999"); + .sql("SELECT count(*) AS c FROM range(100000000000) WHERE id % 7 = 3 AND rand() < 0.9999"); match stmt .execute_direct() .await @@ -230,7 +242,9 @@ async fn execute_direct_running_await_result_completes() { .expect("await_result to terminal"); assert_eq!(drain_rows(&mut stream).await, 1, "count(*) returns one row"); } - DirectStatement::Completed(_) => panic!("a 40B-row scan must be Running"), + DirectStatement::Completed(_) => { + panic!("a 200B-row scan must exceed the inline wait and be Running") + } } session.close().await.expect("session close"); } diff --git a/tests/v0_query_tags_headers_e2e.rs b/tests/v0_query_tags_headers_e2e.rs index 5f7242cd..07ba7399 100644 --- a/tests/v0_query_tags_headers_e2e.rs +++ b/tests/v0_query_tags_headers_e2e.rs @@ -144,17 +144,20 @@ async fn custom_http_headers_round_trip_succeeds() { // The kernel's own Authorization is applied last and wins; the // custom headers ride alongside. A header that broke the request // would surface as a failed execute here. - // A custom User-Agent here is APPENDED to the kernel's base UA (the - // kernel keeps its disposition-gating `DatabricksJDBCDriverOSS` - // token as a prefix), so we pass just the caller entry — the kernel - // prepends its base. Replacing the UA outright would break the SEA - // result disposition (HTTP 400), which is exactly the regression - // this exercises end-to-end. + // + // A caller `User-Agent` REPLACES the kernel's base UA entirely (see + // `HttpClient::new`). The SEA gateway gates the `INLINE_OR_EXTERNAL_LINKS` + // result disposition on a `startsWith` match against its allow-list of + // known driver prefixes, so the caller UA MUST carry a real, allow-listed + // connector prefix — a made-up prefix is rejected with HTTP 400 + // ("not a supported disposition"). Use the actual Node connector UA + // (`NodejsDatabricksSqlConnector/...`), the way the NodeJS driver forwards + // its composed UA over the napi binding. let session = live_session_with_headers(vec![ ("X-Custom-E2E-Header".to_string(), "kernel-e2e".to_string()), ( "User-Agent".to_string(), - "KernelE2E/1.0 (smoke-test)".to_string(), + "NodejsDatabricksSqlConnector/1.0 (smoke-test)".to_string(), ), ]) .await;