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
89 changes: 87 additions & 2 deletions napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -332,6 +351,61 @@ export interface ConnectionOptions {
* `User-Agent` entry here.
*/
customHeaders?: Array<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`].
*/
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`
Expand Down Expand Up @@ -505,6 +579,17 @@ export declare class AsyncStatement {
* that only need the state name.
*/
status(): Promise<string>
/** Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE). */
numModifiedRows(): Promise<number | null>
/**
* Server-supplied user-facing message (may contain SQL fragments —
* redact before centralised logging).
*/
displayMessage(): Promise<string | null>
/** Server-supplied diagnostic detail. */
diagnosticInfo(): Promise<string | null>
/** Server-supplied structured error detail (JSON), when enabled. */
errorDetailsJson(): Promise<string | null>
/**
* Block until the server reaches a terminal state, then return
* an `AsyncResultHandle` that wraps the materialised result
Expand Down
71 changes: 68 additions & 3 deletions napi/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ use napi::bindgen_prelude::Buffer;
type Buffer = Vec<u8>;

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`.
Expand Down Expand Up @@ -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<String>,
pub password: Option<String>,
pub bypass_hosts: Option<String>,
}

/// JS-visible options for opening a Databricks SQL session.
///
/// Authentication is selected by `authMode` (default [`AuthMode::Pat`]):
Expand Down Expand Up @@ -301,6 +321,29 @@ pub struct ConnectionOptions {
/// Overall retry budget in whole seconds. Maps onto
/// [`HttpConfig::overall_timeout`].
pub retry_overall_timeout_secs: Option<u32>,
/// 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<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.
pub socket_timeout_ms: Option<u32>,
}

/// Map the JS `ConnectionOptions` auth fields onto the kernel
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -518,10 +567,24 @@ pub async fn open_session(mut options: ConnectionOptions) -> napi::Result<Connec
result.complex_types_as_json = complex_types_as_json;
builder = builder.result(result);
}
// HTTP config (pool sizing + custom headers) was built up-front
// by `build_http_config` before the transport fields moved.
// HTTP config (pool sizing + custom headers + retry knobs +
// socket-read timeout) was built up-front by `build_http_config`
// before the transport fields moved.
builder = builder.http(http_config);
builder = builder.tls(tls_config);
// Programmatic HTTP/HTTPS proxy. Only wire a `ProxyConfig` when a
// proxy is supplied; otherwise leave it unset so the kernel keeps
// reqwest's env-var behaviour (HTTPS_PROXY / NO_PROXY).
// `ProxyConfig` is `#[non_exhaustive]` — construct via `default()`
// then mutate, mapping the structured `ProxyInput` field-for-field.
if let Some(p) = options.proxy {
let mut proxy = ProxyConfig::default();
proxy.url = Some(p.url);
proxy.username = p.username;
proxy.password = p.password;
proxy.bypass_hosts = p.bypass_hosts;
builder = builder.proxy(proxy);
}
let session = builder.open().await.map_err(napi_err_from_kernel)?;
let session_id = session.session_id().to_owned();
Ok(Connection {
Expand Down Expand Up @@ -564,6 +627,8 @@ mod tests {
retry_max_wait_secs: None,
retry_max_attempts: None,
retry_overall_timeout_secs: None,
proxy: None,
socket_timeout_ms: None,
}
}

Expand Down
62 changes: 57 additions & 5 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -475,13 +475,65 @@ impl Default for HttpConfig {
}
}

// ─── HTTP proxy (reserved) ──────────────────────────────────────────────────
// ─── HTTP proxy ───────────────────────────────────────────────────────────

/// Reserved for v0.1. Fields land once the proxy story (auth, bypass,
/// system-proxy interplay) is settled.
/// Programmatic HTTP/HTTPS proxy configuration.
///
/// When [`url`](Self::url) is `None` (the default), the kernel does **not**
/// configure a proxy explicitly and `reqwest`'s standard behaviour applies —
/// the `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` environment variables are
/// honoured automatically. Setting [`url`](Self::url) **overrides** those env
/// vars with the supplied proxy, routing all (`http://` and `https://`)
/// traffic through it.
///
/// Basic-auth credentials may be embedded directly in the URL
/// (`http://user:pass@host:port`), or supplied out-of-band via
/// [`username`](Self::username) / [`password`](Self::password); the explicit
/// fields take precedence over URL-embedded credentials when both are set.
///
/// `ProxyConfig` is `#[non_exhaustive]` — construct via
/// [`ProxyConfig::default`] and assign the public fields you need:
///
/// ```no_run
/// # use databricks_sql_kernel::ProxyConfig;
/// let mut proxy = ProxyConfig::default();
/// proxy.url = Some("http://proxy.corp.example.com:8080".to_string());
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct ProxyConfig {}
#[derive(Clone, Default)]
pub struct ProxyConfig {
/// Proxy URL, e.g. `http://proxy.corp.example.com:8080` or
/// `http://user:pass@proxy:8080`. Must use the `http://` or
/// `https://` scheme. `None` ⇒ env-var behaviour (no override).
pub url: Option<String>,

/// Username for proxy basic-auth. Overrides any credentials
/// embedded in [`url`](Self::url) when set.
pub username: Option<String>,

/// Password for proxy basic-auth. Secret material — redacted in
/// `Debug`. Ignored unless [`username`](Self::username) is also set.
pub password: Option<String>,

/// 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<String>,
}

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(|_| "<set>"))
.field("username", &self.username)
.field("password", &self.password.as_ref().map(|_| "<redacted>"))
.field("bypass_hosts", &self.bypass_hosts)
.finish()
}
}

// ─── TLS ────────────────────────────────────────────────────────────────────

Expand Down
Loading
Loading