Skip to content

Commit c55bb28

Browse files
committed
feat(napi): expose HTTP proxy + per-connection socket timeout ConnectionOptions
Add two new optional napi `ConnectionOptions` fields so the Node SEA driver can configure HTTP routing programmatically instead of relying solely on the `HTTPS_PROXY` env var: - `proxy`: an HTTP/HTTPS proxy URL (e.g. `http://user:pass@host:port`) routed through `reqwest::Proxy::all`. Embedded basic-auth credentials are honoured. Omitted => current behaviour (env vars still respected). - `socketTimeoutMs`: per-connection read timeout mapped onto the kernel `HttpConfig::request_timeout` (reqwest `Client::timeout`). Plumbing: - Give the public `config::ProxyConfig` real fields (url / username / password / bypass_hosts) with a redacting `Debug`, replacing the previously-empty reserved struct. - Project `SessionConfig.proxy` onto the internal `HttpClientConfig` proxy in `build_proxy_config` (the internal http layer already supported proxy URL/auth/bypass; only the public->internal wiring was missing). Keep a destructuring binding so future field additions fail to compile rather than being silently dropped. The internal `reqwest::ClientBuilder` proxy/timeout handling is unchanged. Adds unit tests for the proxy projection and the request_timeout -> read_timeout mapping. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
1 parent c640c4e commit c55bb28

3 files changed

Lines changed: 183 additions & 20 deletions

File tree

‎napi/src/database.rs‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,11 @@ use napi::bindgen_prelude::Buffer;
3333
#[cfg(test)]
3434
type Buffer = Vec<u8>;
3535

36+
use std::time::Duration;
37+
3638
use databricks_sql_kernel::{
37-
AuthConfig, DefaultOpts, Error as KernelError, HttpConfig, ResultConfig, Session, TlsConfig,
39+
AuthConfig, DefaultOpts, Error as KernelError, HttpConfig, ProxyConfig, ResultConfig, Session,
40+
TlsConfig,
3841
};
3942

4043
/// NodeJS-driver-appropriate default for `pool_max_idle_per_host`.
@@ -210,6 +213,32 @@ pub struct ConnectionOptions {
210213
/// internal CA. Honoured regardless of `check_server_certificate`.
211214
/// Maps onto the kernel [`TlsConfig::custom_ca_cert`].
212215
pub custom_ca_cert: Option<Buffer>,
216+
/// HTTP/HTTPS proxy URL to route all kernel traffic through, e.g.
217+
/// `http://proxy.corp.example.com:8080`. Basic-auth credentials may
218+
/// be embedded in the URL (`http://user:pass@host:port`); the
219+
/// `userinfo` is parsed off and applied as a `Proxy-Authorization`
220+
/// header. Must use the `http://` or `https://` scheme.
221+
///
222+
/// Omitted ⇒ the kernel does NOT configure a proxy explicitly and
223+
/// `reqwest`'s standard behaviour applies — the `HTTPS_PROXY` /
224+
/// `HTTP_PROXY` / `NO_PROXY` environment variables are still
225+
/// honoured. Setting this **overrides** those env vars. This
226+
/// complements the env-var path: callers who cannot set process
227+
/// env vars (e.g. a long-lived Node server) can now route a single
228+
/// connection through a proxy programmatically.
229+
///
230+
/// Maps onto the kernel [`ProxyConfig::url`].
231+
pub proxy: Option<String>,
232+
/// Per-connection socket read timeout, in milliseconds. Caps how
233+
/// long a single HTTP round-trip may block waiting on the server
234+
/// before the request errors out. Maps onto the kernel
235+
/// [`HttpConfig::request_timeout`] (the internal reqwest
236+
/// `Client::timeout`).
237+
///
238+
/// Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs
239+
/// serialises `u32` as JS `number`; the largest representable value
240+
/// (~49.7 days) far exceeds any sensible socket timeout.
241+
pub socket_timeout_ms: Option<u32>,
213242
}
214243

215244
/// Map the JS `ConnectionOptions` auth fields onto the kernel
@@ -368,8 +397,24 @@ pub async fn open_session(options: ConnectionOptions) -> napi::Result<Connection
368397
.max_connections
369398
.map(|max| max as usize)
370399
.unwrap_or(NAPI_DEFAULT_POOL_MAX_IDLE_PER_HOST);
400+
// Per-connection socket read timeout. Maps onto the kernel's
401+
// `request_timeout` (the reqwest `Client::timeout`). Omitted ⇒
402+
// kernel default.
403+
if let Some(ms) = options.socket_timeout_ms {
404+
http.request_timeout = Duration::from_millis(ms as u64);
405+
}
371406
builder = builder.http(http);
372407
builder = builder.tls(tls_config);
408+
// Programmatic HTTP/HTTPS proxy. Only wire a `ProxyConfig` when a
409+
// URL is supplied; otherwise leave it unset so the kernel keeps
410+
// reqwest's env-var behaviour (HTTPS_PROXY / NO_PROXY).
411+
// `ProxyConfig` is `#[non_exhaustive]` — construct via `default()`
412+
// then mutate.
413+
if let Some(proxy_url) = options.proxy {
414+
let mut proxy = ProxyConfig::default();
415+
proxy.url = Some(proxy_url);
416+
builder = builder.proxy(proxy);
417+
}
373418
let session = builder.open().await.map_err(napi_err_from_kernel)?;
374419
let session_id = session.session_id().to_owned();
375420
Ok(Connection {
@@ -404,6 +449,8 @@ mod tests {
404449
complex_types_as_json: None,
405450
check_server_certificate: None,
406451
custom_ca_cert: None,
452+
proxy: None,
453+
socket_timeout_ms: None,
407454
}
408455
}
409456

‎src/config.rs‎

Lines changed: 57 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -467,13 +467,65 @@ impl Default for HttpConfig {
467467
}
468468
}
469469

470-
// ─── HTTP proxy (reserved) ──────────────────────────────────────────────────
470+
// ─── HTTP proxy ───────────────────────────────────────────────────────────
471471

472-
/// Reserved for v0.1. Fields land once the proxy story (auth, bypass,
473-
/// system-proxy interplay) is settled.
472+
/// Programmatic HTTP/HTTPS proxy configuration.
473+
///
474+
/// When [`url`](Self::url) is `None` (the default), the kernel does **not**
475+
/// configure a proxy explicitly and `reqwest`'s standard behaviour applies —
476+
/// the `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` environment variables are
477+
/// honoured automatically. Setting [`url`](Self::url) **overrides** those env
478+
/// vars with the supplied proxy, routing all (`http://` and `https://`)
479+
/// traffic through it.
480+
///
481+
/// Basic-auth credentials may be embedded directly in the URL
482+
/// (`http://user:pass@host:port`), or supplied out-of-band via
483+
/// [`username`](Self::username) / [`password`](Self::password); the explicit
484+
/// fields take precedence over URL-embedded credentials when both are set.
485+
///
486+
/// `ProxyConfig` is `#[non_exhaustive]` — construct via
487+
/// [`ProxyConfig::default`] and assign the public fields you need:
488+
///
489+
/// ```no_run
490+
/// # use databricks_sql_kernel::ProxyConfig;
491+
/// let mut proxy = ProxyConfig::default();
492+
/// proxy.url = Some("http://proxy.corp.example.com:8080".to_string());
493+
/// ```
474494
#[non_exhaustive]
475-
#[derive(Debug, Clone, Default)]
476-
pub struct ProxyConfig {}
495+
#[derive(Clone, Default)]
496+
pub struct ProxyConfig {
497+
/// Proxy URL, e.g. `http://proxy.corp.example.com:8080` or
498+
/// `http://user:pass@proxy:8080`. Must use the `http://` or
499+
/// `https://` scheme. `None` ⇒ env-var behaviour (no override).
500+
pub url: Option<String>,
501+
502+
/// Username for proxy basic-auth. Overrides any credentials
503+
/// embedded in [`url`](Self::url) when set.
504+
pub username: Option<String>,
505+
506+
/// Password for proxy basic-auth. Secret material — redacted in
507+
/// `Debug`. Ignored unless [`username`](Self::username) is also set.
508+
pub password: Option<String>,
509+
510+
/// Comma-separated list of hosts/domains to bypass the proxy
511+
/// (e.g. `"localhost,*.internal.corp,.example.com"`). Only applied
512+
/// when [`url`](Self::url) is set.
513+
pub bypass_hosts: Option<String>,
514+
}
515+
516+
impl std::fmt::Debug for ProxyConfig {
517+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
518+
// Redact the explicit `password` field. The `url` may itself
519+
// carry embedded `user:pass@` credentials, so render only its
520+
// presence rather than the raw string.
521+
f.debug_struct("ProxyConfig")
522+
.field("url", &self.url.as_ref().map(|_| "<set>"))
523+
.field("username", &self.username)
524+
.field("password", &self.password.as_ref().map(|_| "<redacted>"))
525+
.field("bypass_hosts", &self.bypass_hosts)
526+
.finish()
527+
}
528+
}
477529

478530
// ─── TLS ────────────────────────────────────────────────────────────────────
479531

‎src/session.rs‎

Lines changed: 78 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -581,32 +581,49 @@ impl SessionBuilder {
581581
/// Translate the public [`HttpConfig`] (+ proxy / TLS / org_id) into
582582
/// the internal [`HttpClientConfig`] the HTTP client expects.
583583
///
584-
/// The public [`ProxyConfig`] is still a reserved `#[non_exhaustive]`
585-
/// struct (no fields wired yet); the public [`TlsConfig`] now carries
586-
/// `custom_ca_cert` / `accept_self_signed` /
587-
/// `skip_hostname_verification` and is projected onto the internal
584+
/// The public [`ProxyConfig`] is projected onto the internal
585+
/// [`HttpProxyConfig`] (`url` set ⇒ override env vars and route all
586+
/// traffic through it; `url` unset ⇒ reqwest's env-var behaviour). The
587+
/// public [`TlsConfig`] carries `custom_ca_cert` / `accept_self_signed`
588+
/// / `skip_hostname_verification` and is projected onto the internal
588589
/// [`HttpTlsConfig`] via [`HttpTlsConfig::from_public`].
589590
fn build_http_client_config(config: &SessionConfig, org_id: Option<String>) -> HttpClientConfig {
590-
let mut hcc = HttpClientConfig {
591+
HttpClientConfig {
591592
connect_timeout: Duration::from_secs(30),
592593
// The internal `read_timeout` corresponds to the public
593594
// `request_timeout` — both gate a single HTTP round-trip.
594595
read_timeout: config.http.request_timeout,
595596
max_connections_per_host: config.http.pool_max_idle_per_host,
596-
proxy: HttpProxyConfig::default(),
597+
proxy: build_proxy_config(config.proxy.as_ref()),
597598
tls: HttpTlsConfig::from_public(&config.tls),
598599
org_id,
599600
custom_headers: config.http.custom_headers.clone(),
600601
..HttpClientConfig::default()
602+
}
603+
}
604+
605+
/// Project the public [`ProxyConfig`] onto the internal
606+
/// [`HttpProxyConfig`]. `None` (no proxy config supplied) yields the
607+
/// default internal config (`url == None`), under which the HTTP client
608+
/// keeps reqwest's standard env-var behaviour. A destructuring binding
609+
/// (NOT `..`) is used so a future public-field addition surfaces as a
610+
/// compile error here rather than being silently dropped.
611+
fn build_proxy_config(proxy: Option<&ProxyConfig>) -> HttpProxyConfig {
612+
let Some(proxy) = proxy else {
613+
return HttpProxyConfig::default();
601614
};
602-
// Touch the still-reserved proxy config so a future field addition
603-
// (without setting it through here) shows up as a compile error
604-
// rather than a silently-dropped option. Explicit `ProxyConfig {}`
605-
// (NOT `{ .. }`) — the `..` rest pattern would defeat the
606-
// tripwire by silently accepting any new field.
607-
let ProxyConfig {} = config.proxy.clone().unwrap_or_default();
608-
let _ = &mut hcc;
609-
hcc
615+
let ProxyConfig {
616+
url,
617+
username,
618+
password,
619+
bypass_hosts,
620+
} = proxy.clone();
621+
HttpProxyConfig {
622+
url,
623+
username,
624+
password,
625+
bypass_hosts,
626+
}
610627
}
611628

612629
/// Build the per-category retry config for the HTTP client.
@@ -818,4 +835,51 @@ mod retry_config_tests {
818835
assert_eq!(sea.max_retries, 5);
819836
assert_eq!(sea.overall_timeout, Duration::from_secs(900));
820837
}
838+
839+
// ─── Proxy / socket-timeout projection ─────────────────────────
840+
841+
/// `None` (no public proxy config) ⇒ internal proxy `url` stays
842+
/// unset, preserving reqwest's env-var behaviour.
843+
#[test]
844+
fn proxy_absent_keeps_env_var_behaviour() {
845+
let proxy = build_proxy_config(None);
846+
assert!(proxy.url.is_none());
847+
let cfg = config_with_http(HttpConfig::default());
848+
assert!(build_http_client_config(&cfg, None).proxy.url.is_none());
849+
}
850+
851+
/// A public `ProxyConfig` with a URL (and optional auth / bypass)
852+
/// projects field-for-field onto the internal proxy config.
853+
#[test]
854+
fn proxy_fields_project_onto_internal_config() {
855+
let mut cfg = config_with_http(HttpConfig::default());
856+
cfg.proxy = Some(crate::config::ProxyConfig {
857+
url: Some("http://proxy.corp.example.com:8080".to_string()),
858+
username: Some("alice".to_string()),
859+
password: Some("secret".to_string()),
860+
bypass_hosts: Some("localhost,*.internal".to_string()),
861+
..Default::default()
862+
});
863+
let proxy = build_http_client_config(&cfg, None).proxy;
864+
assert_eq!(
865+
proxy.url.as_deref(),
866+
Some("http://proxy.corp.example.com:8080")
867+
);
868+
assert_eq!(proxy.username.as_deref(), Some("alice"));
869+
assert_eq!(proxy.password.as_deref(), Some("secret"));
870+
assert_eq!(proxy.bypass_hosts.as_deref(), Some("localhost,*.internal"));
871+
}
872+
873+
/// The public `request_timeout` becomes the internal HTTP client's
874+
/// `read_timeout` (the per-connection socket read timeout the napi
875+
/// `socketTimeoutMs` option drives).
876+
#[test]
877+
fn request_timeout_becomes_internal_read_timeout() {
878+
let http = HttpConfig {
879+
request_timeout: Duration::from_millis(4500),
880+
..HttpConfig::default()
881+
};
882+
let hcc = build_http_client_config(&config_with_http(http), None);
883+
assert_eq!(hcc.read_timeout, Duration::from_millis(4500));
884+
}
821885
}

0 commit comments

Comments
 (0)