From 79aca5f5ec4a6cb2e2a538d4c95d0600de692918 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Fri, 21 Aug 2026 18:56:36 -0700 Subject: [PATCH 01/10] feat(auth): injectable TokenPersistence for U2M token caching (PECOBLR-4146) Introduce a TokenPersistence trait so callers can supply a custom OAuth U2M token store (DB, keychain, in-memory) instead of the kernel's built-in encrypted disk cache. The built-in cache becomes the default impl (DiskTokenCache), so behavior is unchanged when no store is supplied. - New src/auth/oauth/persistence.rs: TokenPersistence (async load/save) + DiskTokenCache default impl wrapping the existing TokenCache. - AuthConfig::OAuthU2M gains token_store: Option>; when Some it overrides the token_cache disk policy. Threaded through the oauth_u2m constructor (bindings must use it -- AuthConfig is non_exhaustive). - AuthorizationCodeProvider swaps cache_passphrase for the store; load errors are treated as a cache miss, save errors logged and swallowed. - session.rs resolves the effective store: caller store wins, else derive DiskTokenCache from the token_cache policy. - C-ABI passes None (no callback surface; out of scope for Go). Kernel-only enabler; napi/pyo3 binding hooks follow in later commits. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- src/auth/oauth/mod.rs | 2 + src/auth/oauth/persistence.rs | 196 +++++++++++++++++++++++++++++++++ src/auth/oauth/u2m.rs | 161 ++++++++++++++++----------- src/c_abi/session.rs | 3 + src/config.rs | 26 ++++- src/session.rs | 25 +++-- tests/oauth_u2m_integration.rs | 21 +++- tests/v0_session_e2e.rs | 2 + 8 files changed, 357 insertions(+), 79 deletions(-) create mode 100644 src/auth/oauth/persistence.rs diff --git a/src/auth/oauth/mod.rs b/src/auth/oauth/mod.rs index 68053ada..98f93400 100644 --- a/src/auth/oauth/mod.rs +++ b/src/auth/oauth/mod.rs @@ -31,6 +31,7 @@ pub(crate) mod jwt_key; pub mod jwt_m2m; pub mod m2m; pub mod oidc; +pub mod persistence; #[cfg(test)] pub(crate) mod test_keys; pub mod token; @@ -44,5 +45,6 @@ pub use federation::FederationProvider; pub use jwt_m2m::JwtClientCredentialsProvider; pub use m2m::ClientCredentialsProvider; pub use oidc::OidcEndpoints; +pub use persistence::{DiskTokenCache, TokenPersistence}; pub use token::OAuthToken; pub use u2m::AuthorizationCodeProvider; diff --git a/src/auth/oauth/persistence.rs b/src/auth/oauth/persistence.rs new file mode 100644 index 00000000..23205efb --- /dev/null +++ b/src/auth/oauth/persistence.rs @@ -0,0 +1,196 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Pluggable OAuth token persistence. +//! +//! The U2M flow caches its refresh token so a browser login survives process +//! restarts. By default that is an encrypted on-disk cache ([`DiskTokenCache`], +//! under `~/.config/databricks-sql-kernel/oauth/`), but a caller can inject any +//! [`TokenPersistence`] — a database, an OS keychain, an in-memory store — via +//! the `token_store` field of +//! [`AuthConfig::OAuthU2M`](crate::config::AuthConfig). This is the kernel-side +//! contract the driver bindings map their `OAuthPersistence` (Node) / +//! `experimental_oauth_persistence` (Python) objects onto. + +use crate::auth::oauth::cache::TokenCache; +use crate::auth::oauth::token::OAuthToken; +use crate::kernel_error::Result; + +/// A store for U2M OAuth tokens, keyed by the `{host, client_id, scopes}` +/// triple. +/// +/// The kernel calls [`load`](TokenPersistence::load) before deciding whether to +/// open a browser — a returned token carrying a refresh token is reused and +/// refreshed instead of prompting — and [`save`](TokenPersistence::save) after +/// every acquisition or refresh. +/// +/// **Error handling is lenient by contract:** a `load` error is treated as a +/// cache miss (the kernel falls back to a fresh browser login and never fails +/// the connection on it), and a `save` error is logged and swallowed (a failed +/// cache write must not fail an otherwise-successful authentication). So +/// implementations may surface store/transport errors freely. +#[async_trait::async_trait] +pub trait TokenPersistence: Send + Sync + std::fmt::Debug { + /// Load the cached token for this `{host, client_id, scopes}` key, or + /// `Ok(None)` on a miss. + async fn load( + &self, + host: &str, + client_id: &str, + scopes: &[String], + ) -> Result>; + + /// Persist `token` under this `{host, client_id, scopes}` key. + async fn save( + &self, + host: &str, + client_id: &str, + scopes: &[String], + token: &OAuthToken, + ) -> Result<()>; +} + +/// The default [`TokenPersistence`]: the built-in encrypted on-disk cache. +/// +/// Wraps [`TokenCache`] with the resolved passphrase, preserving the kernel's +/// historical caching behavior exactly. [`Session::open`](crate::Session::open) +/// installs this when the caller supplies no custom `token_store` and on-disk +/// caching is enabled. +#[derive(Debug, Clone)] +pub struct DiskTokenCache { + passphrase: String, +} + +impl DiskTokenCache { + /// Create a disk cache that encrypts entries under `passphrase`. + pub fn new(passphrase: String) -> Self { + Self { passphrase } + } +} + +#[async_trait::async_trait] +impl TokenPersistence for DiskTokenCache { + async fn load( + &self, + host: &str, + client_id: &str, + scopes: &[String], + ) -> Result> { + // `TokenCache::load` is synchronous, local, and fast (one small + // encrypted file). The U2M paths that call this already run inside a + // `block_in_place` region, so invoking it directly preserves the exact + // prior behavior without an extra `spawn_blocking` hop. + Ok(TokenCache::load(host, client_id, scopes, &self.passphrase)) + } + + async fn save( + &self, + host: &str, + client_id: &str, + scopes: &[String], + token: &OAuthToken, + ) -> Result<()> { + TokenCache::save(host, client_id, scopes, token, &self.passphrase); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + + /// In-memory [`TokenPersistence`] test double: records calls and serves + /// tokens from a map keyed by `{host}|{client_id}|{scopes}`. + #[derive(Debug, Default)] + pub(crate) struct InMemoryTokenStore { + pub tokens: Mutex>, + pub loads: Mutex>, + pub saves: Mutex>, + } + + fn key(host: &str, client_id: &str, scopes: &[String]) -> String { + format!("{host}|{client_id}|{}", scopes.join(" ")) + } + + #[async_trait::async_trait] + impl TokenPersistence for InMemoryTokenStore { + async fn load( + &self, + host: &str, + client_id: &str, + scopes: &[String], + ) -> Result> { + let k = key(host, client_id, scopes); + self.loads.lock().unwrap().push(k.clone()); + Ok(self.tokens.lock().unwrap().get(&k).cloned()) + } + + async fn save( + &self, + host: &str, + client_id: &str, + scopes: &[String], + token: &OAuthToken, + ) -> Result<()> { + let k = key(host, client_id, scopes); + self.saves.lock().unwrap().push(k.clone()); + self.tokens.lock().unwrap().insert(k, token.clone()); + Ok(()) + } + } + + #[tokio::test] + async fn in_memory_store_roundtrips() { + let store = InMemoryTokenStore::default(); + let scopes = vec!["sql".to_string(), "offline_access".to_string()]; + assert!(store + .load("https://h", "cid", &scopes) + .await + .unwrap() + .is_none()); + + let token = OAuthToken::new( + "access".to_string(), + "Bearer".to_string(), + 3600, + Some("refresh".to_string()), + scopes.clone(), + ); + store + .save("https://h", "cid", &scopes, &token) + .await + .unwrap(); + + let got = store.load("https://h", "cid", &scopes).await.unwrap(); + assert_eq!(got.unwrap().access_token, "access"); + assert_eq!(store.loads.lock().unwrap().len(), 2); + assert_eq!(store.saves.lock().unwrap().len(), 1); + } + + #[test] + fn disk_token_cache_is_debug_and_clone() { + // Guards the `Debug` bound that `AuthorizationCodeProvider`'s derived + // `Debug` and `AuthConfig`'s manual `Debug` rely on. + let c = DiskTokenCache::new("pass".to_string()); + let _ = format!("{c:?}"); + let _ = c.clone(); + } + + /// The trait must stay object-safe (`Arc` is how it + /// is threaded through `AuthConfig` and the provider). + #[allow(dead_code)] + fn assert_object_safe(_: Arc) {} +} diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 5a27d3b3..12522fd9 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -36,9 +36,9 @@ //! the cache IS enabled the payload is always encrypted under the //! configured passphrase, because it carries that long-lived refresh token. -use crate::auth::oauth::cache::TokenCache; use crate::auth::oauth::callback::CallbackServer; use crate::auth::oauth::oidc::OidcEndpoints; +use crate::auth::oauth::persistence::TokenPersistence; use crate::auth::oauth::token::OAuthToken; use crate::auth::oauth::token_store::TokenStore; use crate::auth::AuthProvider; @@ -62,23 +62,27 @@ const DEFAULT_CALLBACK_PORT: u16 = 8030; /// Default timeout for waiting for the OAuth callback. const DEFAULT_CALLBACK_TIMEOUT: Duration = Duration::from_secs(120); -/// Persist `token` to the on-disk cache, or do nothing when disk caching -/// is disabled (`passphrase` is `None`). +/// Persist `token` via the configured [`TokenPersistence`] store, or do +/// nothing when no store is configured (`store` is `None`). /// /// Exists so the two save sites in the token-acquisition flow (post-refresh -/// and post-browser-flow) cannot drift apart, in particular so neither can -/// accidentally write an unencrypted token or write one when the user asked -/// for no cache at all. -fn save_to_cache( - passphrase: Option<&str>, +/// and post-browser-flow) cannot drift apart. Per the [`TokenPersistence`] +/// contract a save error is logged and swallowed — a failed cache write must +/// not fail an otherwise-successful authentication. +async fn persist_token( + store: &Option>, host: &str, client_id: &str, scopes: &[String], token: &OAuthToken, ) { - match passphrase { - Some(passphrase) => TokenCache::save(host, client_id, scopes, token, passphrase), - None => crate::klog::debug!("Token cache disabled; not persisting token to disk"), + match store { + Some(store) => { + if let Err(e) = store.save(host, client_id, scopes, token).await { + crate::klog::warn!("Failed to persist OAuth token to store: {}", e); + } + } + None => crate::klog::debug!("Token persistence disabled; not saving token"), } } @@ -142,12 +146,13 @@ pub struct AuthorizationCodeProvider { callback_timeout: Duration, /// Whether to open browser automatically (set to false in tests) open_browser: bool, - /// Passphrase for the on-disk token cache, or `None` when disk - /// caching is disabled. `Some` implies the cache is enabled: the - /// enabled-without-passphrase combination is rejected upstream in - /// [`crate::config::TokenCacheConfig::resolve`], so this field carries - /// both the "should I cache?" and "with what key?" decisions. - cache_passphrase: Option, + /// Token store used to load a cached token before opening a browser and to + /// persist after every acquisition/refresh, or `None` when persistence is + /// disabled. `Session::open` installs the built-in encrypted disk cache + /// ([`DiskTokenCache`](crate::auth::oauth::persistence::DiskTokenCache)) + /// here by default, or a caller-supplied store. See + /// [`crate::auth::oauth::persistence`]. + token_persistence: Option>, /// Tokio runtime handle captured from the constructing context; /// used to drive the async token exchange from the sync /// `get_auth_header` trait method safely whether or not the @@ -242,7 +247,7 @@ impl AuthorizationCodeProvider { vec![callback_port], callback_timeout, None, // No token_endpoint override - None, // On-disk cache disabled: no passphrase available here + None, // No token store: persistence disabled ) .await } @@ -252,9 +257,10 @@ impl AuthorizationCodeProvider { /// This is used by Database when a custom token endpoint is configured. /// Most users should use `new()` or `new_with_config()` which use OIDC discovery. /// - /// `cache_passphrase` is `Some` to enable the encrypted on-disk token - /// cache and `None` to disable it; the enabled-but-passphraseless case is - /// rejected upstream by [`crate::config::TokenCacheConfig::resolve`]. + /// `token_persistence` is `Some` to enable token caching (the built-in + /// encrypted disk cache or a caller-supplied store) and `None` to disable + /// it. `Session::open` resolves it from the `token_store` / `token_cache` + /// policy — see [`crate::auth::oauth::persistence`]. // The "full config" constructor is a flat parameter list by design — it is // the single place every U2M knob is threaded in from `Session::open`. #[allow(clippy::too_many_arguments)] @@ -266,7 +272,7 @@ impl AuthorizationCodeProvider { callback_ports: Vec, callback_timeout: Duration, token_endpoint_override: Option, - cache_passphrase: Option, + token_persistence: Option>, ) -> Result { // Discover OIDC endpoints (unless token_endpoint is overridden, we still need auth endpoint) let endpoints = OidcEndpoints::discover(host, &http_client).await?; @@ -277,27 +283,37 @@ impl AuthorizationCodeProvider { // Create token store let token_store = TokenStore::new(); - // Try loading cached token. A `None` passphrase means the on-disk - // cache is disabled, so the file is never even read — the in-memory - // TokenStore above still reuses and refreshes within this process. - if let Some(cached_token) = cache_passphrase - .as_deref() - .and_then(|passphrase| TokenCache::load(host, client_id, &scopes, passphrase)) - { - // Check if the cached token has a refresh token - if cached_token.refresh_token.is_some() { - crate::klog::debug!("Loaded cached token with refresh_token for U2M flow"); - // Store the cached token - TokenStore will handle refresh if needed - // We need to manually insert it since get_or_refresh expects to call the closure - // Let's trigger a get_or_refresh with a closure that returns the cached token - let _ = token_store.get_or_refresh(move || Ok(cached_token.clone())); - } else { - crate::klog::debug!("Cached token has no refresh_token, will trigger browser flow"); + // Try loading a cached token. A `None` store means persistence is + // disabled, so nothing is read — the in-memory TokenStore above still + // reuses and refreshes within this process. Per the TokenPersistence + // contract a load error is treated as a cache miss (browser flow on + // first auth), never fatal. + if let Some(store) = &token_persistence { + match store.load(host, client_id, &scopes).await { + Ok(Some(cached_token)) if cached_token.refresh_token.is_some() => { + crate::klog::debug!("Loaded cached token with refresh_token for U2M flow"); + // Seed the in-memory TokenStore; it will refresh if needed. + let _ = token_store.get_or_refresh(move || Ok(cached_token.clone())); + } + Ok(Some(_)) => { + crate::klog::debug!( + "Cached token has no refresh_token, will trigger browser flow" + ); + } + Ok(None) => { + crate::klog::debug!( + "No cached token found for U2M flow, will trigger browser flow on first auth" + ); + } + Err(e) => { + crate::klog::warn!( + "Failed to load cached OAuth token (treating as cache miss): {}", + e + ); + } } } else { - crate::klog::debug!( - "No cached token found for U2M flow, will trigger browser flow on first auth" - ); + crate::klog::debug!("Token persistence disabled; browser flow on first auth"); } Ok(Self { @@ -311,7 +327,7 @@ impl AuthorizationCodeProvider { callback_ports, callback_timeout, open_browser: true, - cache_passphrase, + token_persistence, // `new_with_full_config` is `async`, so we're guaranteed // to be inside a tokio runtime here. Capture that handle // so `get_auth_header` can dispatch correctly later via @@ -363,7 +379,7 @@ impl AuthProvider for AuthorizationCodeProvider { let callback_timeout = self.callback_timeout; let open_browser = self.open_browser; let http_client = self.http_client.clone(); - let cache_passphrase = self.cache_passphrase.clone(); + let token_persistence = self.token_persistence.clone(); // Get or refresh token via TokenStore let runtime_handle = self.runtime_handle.clone(); @@ -374,12 +390,23 @@ impl AuthProvider for AuthorizationCodeProvider { // inside a runtime, direct `block_on` otherwise. See // `crate::util::runtime`. block_on_in_runtime(&runtime_handle, async { - // Try loading from cache first (skipped entirely when - // on-disk caching is disabled). - if let Some(cached_token) = cache_passphrase - .as_deref() - .and_then(|p| TokenCache::load(&host, &client_id, &scopes, p)) - { + // Try loading from the store first (skipped when + // persistence is disabled; a load error is treated as a + // miss and falls through to the browser flow). + let cached_token = match &token_persistence { + Some(store) => match store.load(&host, &client_id, &scopes).await { + Ok(cached) => cached, + Err(e) => { + crate::klog::warn!( + "Failed to load cached OAuth token (treating as miss): {}", + e + ); + None + } + }, + None => None, + }; + if let Some(cached_token) = cached_token { if let Some(ref refresh_token_str) = cached_token.refresh_token { // Try refreshing the token crate::klog::debug!("Attempting to refresh token via refresh_token"); @@ -437,14 +464,15 @@ impl AuthProvider for AuthorizationCodeProvider { scopes_result, ); - // Save to cache (no-op when disabled) - save_to_cache( - cache_passphrase.as_deref(), + // Save via the store (no-op when disabled) + persist_token( + &token_persistence, &host, &client_id, &scopes, &token, - ); + ) + .await; return Ok(token); } Err(e) => { @@ -565,14 +593,8 @@ impl AuthProvider for AuthorizationCodeProvider { scopes_result, ); - // Save to cache (no-op when disabled) - save_to_cache( - cache_passphrase.as_deref(), - &host, - &client_id, - &scopes, - &token, - ); + // Save via the store (no-op when disabled) + persist_token(&token_persistence, &host, &client_id, &scopes, &token).await; Ok(token) }) @@ -586,6 +608,8 @@ impl AuthProvider for AuthorizationCodeProvider { #[cfg(test)] mod tests { use super::*; + use crate::auth::oauth::cache::TokenCache; + use crate::auth::oauth::persistence::DiskTokenCache; use crate::client::http::HttpClientConfig; use wiremock::matchers::{body_string_contains, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -662,7 +686,10 @@ mod tests { vec![8020], Duration::from_secs(120), None, - Some(TEST_CACHE_PASSPHRASE.to_string()), + Some( + Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) + as Arc, + ), ) .await .expect("Failed to create provider"); @@ -715,7 +742,10 @@ mod tests { vec![8020], Duration::from_secs(120), None, - Some(TEST_CACHE_PASSPHRASE.to_string()), + Some( + Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) + as Arc, + ), ) .await .expect("Failed to create provider"); @@ -784,7 +814,10 @@ mod tests { vec![0], // Use port 0 to avoid conflicts Duration::from_secs(5), // Short timeout for test None, - Some(TEST_CACHE_PASSPHRASE.to_string()), + Some( + Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) + as Arc, + ), ) .await .expect("Failed to create provider"); diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 9467c97b..891d03ac 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -1265,6 +1265,9 @@ fn auth_spec_to_config( None, Some(token_cache), identity_federation_client_id, + // No caller token store over the C ABI (no callback surface); the + // disk cache above is the only U2M persistence path here. + None, ), AuthSpec::AzureServicePrincipal { azure_client_id, diff --git a/src/config.rs b/src/config.rs index 5d00859f..d05d531c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -354,7 +354,17 @@ pub enum AuthConfig { callback_timeout: Option, /// On-disk token-cache policy. `None` → [`TokenCacheConfig::default`] /// (enabled, which then requires a passphrase — see that type). + /// Ignored when `token_store` is `Some` (a caller store fully + /// replaces the built-in disk cache). token_cache: Option, + /// Caller-supplied token store. When `Some`, it fully overrides the + /// built-in [`token_cache`](Self::OAuthU2M::token_cache) disk policy: + /// the kernel calls it to load/persist the U2M token instead of the + /// encrypted disk cache. `None` → use the `token_cache` policy. This is + /// the injection point the bindings map their `OAuthPersistence` / + /// `experimental_oauth_persistence` objects onto. See + /// [`crate::auth::oauth::persistence`]. + token_store: Option>, /// SP-wide Workload Identity Federation client id. `None` selects /// BYOT / account-wide WIF behavior when token exchange is needed. identity_federation_client_id: Option, @@ -507,6 +517,15 @@ impl AuthConfig { /// (first free binds). Single-port callers pass a one-element list /// (`Some(vec![port])`); `None`/empty falls back to the /// `[8030, 8031, 8032, 8033, 8034]` default window. + /// + /// `token_store` optionally injects a caller-supplied + /// [`TokenPersistence`](crate::auth::oauth::persistence::TokenPersistence) + /// (a DB / keychain / in-memory store); when `Some` it fully overrides the + /// `token_cache` disk policy. Bindings forward it as the last argument + /// because [`AuthConfig`] is `#[non_exhaustive]` — cross-crate wrappers + /// cannot build the `OAuthU2M` struct literal directly and must go through + /// this constructor. + #[allow(clippy::too_many_arguments)] pub fn oauth_u2m( client_id: Option, redirect_ports: Option>, @@ -515,6 +534,7 @@ impl AuthConfig { callback_timeout: Option, token_cache: Option, identity_federation_client_id: Option, + token_store: Option>, ) -> Self { AuthConfig::OAuthU2M { client_id, @@ -523,6 +543,7 @@ impl AuthConfig { token_url_override, callback_timeout, token_cache, + token_store, identity_federation_client_id, } } @@ -2049,6 +2070,7 @@ mod tests { None, None, Some("federation-client".to_string()), + None, ); assert_eq!( @@ -2060,7 +2082,7 @@ mod tests { #[test] fn oauth_u2m_none_ports_stays_none() { // No ports supplied → redirect_ports is None (session fills the default). - let auth = AuthConfig::oauth_u2m(None, None, None, None, None, None, None); + let auth = AuthConfig::oauth_u2m(None, None, None, None, None, None, None, None); match auth { AuthConfig::OAuthU2M { redirect_ports, .. } => assert_eq!(redirect_ports, None), other => panic!("expected OAuthU2M, got {other:?}"), @@ -2079,6 +2101,7 @@ mod tests { None, None, None, + None, ); match auth { AuthConfig::OAuthU2M { redirect_ports, .. } => { @@ -2109,6 +2132,7 @@ mod tests { token_url_override: None, callback_timeout: None, token_cache: None, + token_store: None, identity_federation_client_id: Some("federation-client".to_string()), }, ]; diff --git a/src/session.rs b/src/session.rs index 7a2f31bf..7acf64ff 100644 --- a/src/session.rs +++ b/src/session.rs @@ -45,6 +45,7 @@ //! enabled, they drive real transactions (a Private Preview feature that //! requires catalog-managed tables server-side). +use crate::auth::oauth::persistence::{DiskTokenCache, TokenPersistence}; use crate::auth::{ AuthProvider, AuthorizationCodeProvider, ClientCredentialsProvider, FederationProvider, JwtClientCredentialsProvider, PersonalAccessToken, @@ -1274,6 +1275,7 @@ async fn build_base_auth_provider( token_url_override, callback_timeout, token_cache, + token_store, .. } => { // Fill the coupled kernel default bundle for any unset field @@ -1287,15 +1289,18 @@ async fn build_base_auth_provider( scopes.as_deref(), ); let timeout = callback_timeout.unwrap_or_else(|| Duration::from_secs(120)); - // `Some(passphrase)` enables the on-disk cache, `None` disables - // it. When the cache is on but the caller supplied no passphrase, - // `resolve` substitutes a machine-local derived one rather than - // failing or writing plaintext — see `TokenCacheConfig`. - let cache_policy = token_cache - .clone() - .unwrap_or_default() - .resolve() - .map(|p| p.into_owned()); + // A caller-supplied `token_store` wins outright; otherwise derive + // the built-in encrypted disk cache from the `token_cache` policy. + // `resolve()` returns `Some(passphrase)` when caching is enabled + // (substituting a machine-local derived key when the caller gave + // none, rather than failing or writing plaintext — see + // `TokenCacheConfig`) and `None` to disable persistence entirely. + let token_persistence: Option> = + token_store.clone().or_else(|| { + token_cache.clone().unwrap_or_default().resolve().map(|p| { + Arc::new(DiskTokenCache::new(p.into_owned())) as Arc + }) + }); let provider = AuthorizationCodeProvider::new_with_full_config( host, &client_id, @@ -1304,7 +1309,7 @@ async fn build_base_auth_provider( callback_ports, timeout, token_url_override.clone(), - cache_policy, + token_persistence, ) .await?; Ok(Arc::new(provider)) diff --git a/tests/oauth_u2m_integration.rs b/tests/oauth_u2m_integration.rs index 95b83782..2a59cf56 100644 --- a/tests/oauth_u2m_integration.rs +++ b/tests/oauth_u2m_integration.rs @@ -18,6 +18,7 @@ //! allowing us to test the complete U2M refresh flow without requiring a real OAuth server //! or browser interaction. +use databricks_sql_kernel::auth::oauth::persistence::{DiskTokenCache, TokenPersistence}; use databricks_sql_kernel::auth::oauth::u2m::AuthorizationCodeProvider; use databricks_sql_kernel::auth::AuthProvider; use databricks_sql_kernel::client::http::{DatabricksHttpClient, HttpClientConfig}; @@ -121,7 +122,10 @@ async fn test_u2m_refresh_token_full_flow() { vec![8020], Duration::from_secs(120), None, - Some(TEST_CACHE_PASSPHRASE.to_string()), + Some( + Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) + as Arc, + ), ) .await .expect("Failed to create AuthorizationCodeProvider"); @@ -195,7 +199,10 @@ async fn test_u2m_refresh_token_stale_immediate_return() { vec![8021], Duration::from_secs(120), None, - Some(TEST_CACHE_PASSPHRASE.to_string()), + Some( + Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) + as Arc, + ), ) .await .expect("Failed to create provider"); @@ -275,7 +282,10 @@ async fn test_u2m_refresh_token_expired_fallback() { vec![0], // Use port 0 to avoid conflicts Duration::from_secs(5), // Short timeout for test None, - Some(TEST_CACHE_PASSPHRASE.to_string()), + Some( + Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) + as Arc, + ), ) .await .expect("Failed to create provider"); @@ -350,7 +360,10 @@ async fn test_u2m_refresh_updates_cache() { vec![8023], Duration::from_secs(120), None, - Some(TEST_CACHE_PASSPHRASE.to_string()), + Some( + Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) + as Arc, + ), ) .await .expect("Failed to create provider"); diff --git a/tests/v0_session_e2e.rs b/tests/v0_session_e2e.rs index 26489b05..fab498fc 100644 --- a/tests/v0_session_e2e.rs +++ b/tests/v0_session_e2e.rs @@ -134,6 +134,7 @@ async fn open_with_oauth_u2m_against_live_warehouse() { enabled: false, passphrase: None, }), + token_store: None, identity_federation_client_id: None, }) .open() @@ -189,6 +190,7 @@ async fn open_with_oauth_u2m_falls_back_past_busy_port() { enabled: false, passphrase: None, }), + token_store: None, identity_federation_client_id: None, }) .open() From f7b280047b8bf83140a684e06ba2dc3d664a07a8 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Fri, 21 Aug 2026 19:09:39 -0700 Subject: [PATCH 02/10] feat(napi): pluggable OAuth token store via openSession callbacks (PECOBLR-4146) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Thread the kernel's TokenPersistence through the napi binding so a Node caller can supply a custom OAuth U2M token store (its OAuthPersistence) on the kernel path, instead of the built-in disk cache. - openSession gains two optional callbacks (oauthPersistenceRead / oauthPersistencePersist). When both are supplied, a NapiTokenStore wraps them as ThreadsafeFunctions and is installed as the U2M token_store; load/save call the JS store and await its returned Promise. The token crosses as the kernel's OAuthToken JSON (lossless, same bytes the disk cache stores) via the KernelPersistArgs object. - build_auth_config takes the resolved store and forwards it in the U2M arm. - add async-trait dep (to impl the kernel's #[async_trait] TokenPersistence). Contract regeneration note: index.js/index.d.ts are regenerated with @napi-rs/cli@3.8.2 (the version bin/build-native.sh selects for the napi 3.x crate). The committed contract was stale @napi-rs/cli v2-style output, so the diff also migrates the loader to v3 (adds NAPI_RS_ENFORCE_VERSION_CHECK, the per-package version-consistency checks, WASI fallback) — same regeneration the nodejs driver landed in #505. The persistence-specific delta is KernelPersistArgs + the two openSession params. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- napi/Cargo.lock | 1 + napi/Cargo.toml | 4 + napi/index.d.ts | 1768 ++++++++++++++++++++++-------------------- napi/index.js | 918 +++++++++++++++------- napi/src/database.rs | 195 ++++- 5 files changed, 1732 insertions(+), 1154 deletions(-) diff --git a/napi/Cargo.lock b/napi/Cargo.lock index fe76a0cb..b0a7f57e 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -585,6 +585,7 @@ dependencies = [ "arrow-array", "arrow-ipc", "arrow-schema", + "async-trait", "chrono", "databricks-sql-kernel", "futures", diff --git a/napi/Cargo.toml b/napi/Cargo.toml index 8becf712..e91b440f 100644 --- a/napi/Cargo.toml +++ b/napi/Cargo.toml @@ -69,6 +69,10 @@ dyn-symbols = ["napi/dyn-symbols"] napi = { version = "3", default-features = false, features = ["napi6", "async"] } napi-derive = "3" +# Needed to implement the kernel's `#[async_trait] TokenPersistence` for the +# `ThreadsafeFunction`-backed pluggable OAuth token store (PECOBLR-4146). +async-trait = "0.1" + # Kernel — path dep on the async-public-api branch worktree. Once the # kernel is published this becomes a version dep. # diff --git a/napi/index.d.ts b/napi/index.d.ts index bc16c0d2..ca13529d 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -1,356 +1,804 @@ -/* tslint:disable */ -/* eslint-disable */ - /* auto-generated by NAPI-RS */ - +/* eslint-disable */ /** - * Per-statement options for `Connection.executeStatement`. - * - * Mirrors the kernel `StatementSpec` knobs that are safe to thread - * through napi without a kernel-side change. Today this covers: - * - `statementConf` — per-statement Spark conf overlay - * (`StatementSpec.statement_conf` → SEA `parameters` / - * Thrift `confOverlay`) - * - `queryTags` — convenience wrapper over `statementConf` with - * key `query_tags`; serialised to the same comma-separated - * `key:value` wire shape NodeJS Thrift's `serializeQueryTags` - * produces (`lib/utils/queryTags.ts`). Backslashes in keys are - * doubled; backslash/colon/comma in values are backslash-escaped. + * Opaque result-fetch handle returned by + * `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` + * directly; structurally analogous to the sync `Statement`'s + * fetch-side surface (`fetchNextBatch` / `schema` / + * `statementId`). * - * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel - * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) - * carry bound query parameters, decoded via `params::parse_typed_value`. - * (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold - * window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.) + * `cancel()` / `close()` are not exposed: the parent + * `AsyncStatement` owns server-side lifecycle. A `close()` here + * would create dual-ownership of the same statement_id with + * inconsistent close semantics. Callers `close()` the parent + * `AsyncStatement` after they're done fetching. * - * **Tag-order caveat (M4 parity note).** The napi `queryTags` field - * is a Rust `HashMap` whose iteration order is - * non-deterministic, so the serialised `query_tags` value may have - * a different key order than Thrift's `serializeQueryTags` (which - * iterates `Object.keys(...)` in insertion order) for the same - * input. The SEA server is order-insensitive on conf values, so - * the two are functionally equivalent. If a caller needs - * byte-identical Thrift parity, the JS adapter pre-serialises via - * `serializeQueryTags` and writes the result into - * `statementConf["query_tags"]` directly — see - * `KernelSessionBackend.executeStatement` in the NodeJS driver. This - * path is the one the production code uses. + * Schema is cached at construction so it survives the underlying + * stream being drained; mirrors the sync `Statement.schema()` + * post-close contract. */ -export interface ExecuteOptions { - /** - * Per-statement Spark conf overlay. Merged on top of the - * session-level `sessionConf` at execute time; this map wins - * on key collisions. Unknown keys are rejected by the server. - */ - statementConf?: Record - /** - * Query tags as key→value pairs. Serialised to a comma- - * separated `key:value` string (backslash-escaping `\`, `:`, - * `,`) and placed into `statementConf["query_tags"]`, matching - * NodeJS Thrift's `serializeQueryTags` wire shape. Passing - * both `queryTags` AND a `query_tags` key in `statementConf` - * raises `InvalidArgument` — the caller's intent is ambiguous - * so we refuse to silently pick one over the other. - * - * A **`null`** value emits a **bare key** (no colon) — e.g. - * `{ production: null }` → `"production"` — matching the - * connectors' `key`-only tag form. - * - * See the struct-level "Tag-order caveat" for the - * HashMap-iteration-order vs `Object.keys`-iteration-order - * divergence and the byte-identical-Thrift-parity workaround. - */ - queryTags?: Record +export declare class AsyncResultHandle { /** - * Server-side cap on the number of rows this statement returns - * (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to - * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. + * Server-issued statement id. Cached at construction; readable + * for log correlation. Matches the parent `AsyncStatement`'s + * `statementId`. */ - rowLimit?: number + get statementId(): string /** - * Positional parameters, in 1-based wire order. Index `i` in this - * Vec corresponds to the `i+1`-th `?` placeholder in the SQL. - * Each entry is a `{ sqlType, value }` pair — `value` is the - * string-encoded literal or `null` for SQL NULL. Mirrors - * `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. + * Pull the next batch of results. Returns `null` when the + * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a + * complete Arrow IPC stream (schema header + 1 record-batch + * message), suitable for handing to `apache-arrow`'s + * `RecordBatchReader`. Byte-identical to the sync + * `Statement.fetchNextBatch()` payload for the same query. */ - positionalParams?: Array + fetchNextBatch(): Promise /** - * Named parameters (`:name` placeholders). Each carries its `name` - * alongside the `{ sqlType, value? }` pair. Mapped to a kernel - * `TypedValue` via the same [`parse_typed_value`] codec and bound with - * `StatementSpec::param_named`. Named is the SEA-spec-required public - * param form (`StatementParameter.name` is `openapi_required`); - * positional is the documented-undocumented variant. The two are - * mutually exclusive at the SQL level (`?` vs `:name`). + * Result schema as an Arrow IPC payload (schema header only, + * no record-batch message). Available before any batches have + * been fetched. Sync because the body has no `.await` — + * `encode_ipc_stream` is pure CPU work over the cached + * `Arc`. */ - namedParams?: Array -} -/** - * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a - * distinct napi object (rather than an optional `name` on `TypedValueInput`) - * so the positional surface stays a clean ordered list with no name field. - */ -export interface NamedTypedValueInput { - name: string - sqlType: string - value?: string + schema(): ArrowSchema } + /** - * Authentication mode selector crossing the napi boundary. The string - * literals are what napi-rs emits from this `#[napi(string_enum)]` — the - * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`, - * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). + * Opaque async-statement handle. * - * Mirrors the kernel [`AuthConfig`] variants this binding supports. - * `OAuthFederation` / `External` are intentionally not exposed yet — the - * kernel marks federation as not-yet-implemented and `External` is a - * Rust-trait escape hatch with no JS-callback bridge. + * Returned by `Connection.submitStatement(...)` after the kernel + * `Statement::submit()` returns (server sent `wait_timeout=0s`, so + * the response carries a `statement_id` but the statement is still + * `Pending`/`Running`). JS drives polling via `status()` / + * `awaitResult()`. + * + * Concurrency shape: `status()`, `awaitResult()`, and `close()` take + * `inner.lock()` and hold the guard across the kernel `.await` (tokio + * `Mutex` is FIFO), so `status()` / `close()` queue behind any + * in-flight `awaitResult()` until it returns naturally. `cancel()` is + * the deliberate exception: it does **not** touch `inner` — it fires + * through the detached `AsyncStatementCanceller` (session + + * statement_id, captured at construction), so an explicit + * `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of + * queueing behind it. The server-side cancel flips the statement + * terminal, which the parked `awaitResult()` poll loop observes + * (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard` + * still covers the drop-cancel case (Promise.race / timeout) + * independently — see module docs. */ -export const enum AuthMode { - /** Personal access token (`token`). */ - Pat = 'Pat', - /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */ - OAuthM2m = 'OAuthM2m', +export declare class AsyncStatement { /** - * OAuth 2.0 machine-to-machine with a JWT private-key client - * assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. + * Server-issued statement id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate + * against kernel / server logs which key on the same id. */ - OAuthM2mJwt = 'OAuthM2mJwt', + get statementId(): string /** - * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` - * + `oauthRedirectPort`. + * One-shot status check. Returns a string enum matching the + * kernel `StatementStatus` shape: + * `'Pending' | 'Running' | 'Succeeded' | 'Failed' | + * 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the + * `#[non_exhaustive]` forward-compat catch-all that + * `StatementStatus::as_str` can return — consumers switching on + * the state must handle it.) Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. + * + * The `Failed` variant collapses to the string `'Failed'` on + * the JS side; the underlying error envelope (sql_state / + * error_code / query_id) is surfaced by `awaitResult()`'s + * rejection, which is where callers actually need the typed + * error. `status()` is intended for polling progress UIs + * that only need the state name. */ - OAuthU2m = 'OAuthU2m', + status(): Promise + /** Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE). */ + numModifiedRows(): Promise /** - * Azure Entra service-principal M2M — `azureClientId` + - * `azureClientSecret` (+ optional `azureTenantId` / - * `azureWorkspaceResourceId`). The kernel builds the Entra token - * endpoint + `.default` scope, auto-discovers the tenant from the - * workspace when `azureTenantId` is omitted, and — when - * `azureWorkspaceResourceId` is set — additionally sends the SP - * management token for an RBAC-only service principal. + * Server-supplied user-facing message (may contain SQL fragments — + * redact before centralised logging). */ - AzureSpM2m = 'AzureSpM2m' + 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 + * stream. The handle exposes `fetchNextBatch()` / `schema()` + * for consuming the result, plus `statementId` for log + * correlation. + * + * Drop-cancel safety: kernel `await_result` installs + * `AwaitResultCancelGuard` which fires a fire-and-forget + * `cancel_statement` if the future is dropped mid-poll + * (timeout, tokio::select! loser, JS-side `Promise.race` + * loser). The `util::guarded` `catch_unwind` here covers the + * V8-panic-across-boundary case on top. Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. + */ + awaitResult(): Promise + /** + * Server-side cancel. Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. Idempotent against a server + * that already reached a terminal state — the kernel's + * `cancel_statement` is a no-op there. + * + * **Lock-free by design.** Unlike `status()` / `awaitResult()` / + * `close()`, this does not take `inner.lock()` — it fires through + * the detached `AsyncStatementCanceller` captured at construction. + * That lets `stmt.cancel()` interrupt an in-flight `awaitResult()` + * (which holds the mutex for the whole poll) instead of queueing + * behind it: the server-side cancel flips the statement terminal, + * the parked `awaitResult()` poll loop observes `Cancelled` and + * returns. The closed-state check reads a lock-free flag so a + * cancel after an explicit `close()` still surfaces + * `InvalidStatementHandle`. + */ + cancel(): Promise + /** + * Explicit close. Idempotent — a second call on an + * already-closed handle returns `Ok(())`. On `Err`, the napi + * inner is already `None`, so a JS-side retry sees the + * closed-handle short-circuit and returns `Ok(())` without + * re-attempting the wire call. The kernel's own `Drop` + * fire-and-forget retry runs once in the background. + */ + close(): Promise } + /** - * A single extra HTTP header as an explicit `{ name, value }` pair. + * Handle returned by `Connection.executeStatementCancellable`. Owns the + * built-but-not-yet-executed kernel `Statement` plus a detached + * [`StatementCanceller`] captured before dispatch, so JS can fire a + * server-side cancel while the blocking `result()` is in flight. * - * An ordered list of these (`ConnectionOptions.custom_headers`) mirrors - * the kernel core's `Vec<(String, String)>` and the pyo3 binding's - * `http_headers`: order is preserved and duplicate `name`s are allowed. - * A struct (rather than a raw `[name, value]` tuple) because napi-rs - * does not marshal Rust tuples through `#[napi(object)]` fields; the - * struct is the idiomatic, self-documenting equivalent and maps to a JS - * `{ name: string, value: string }`. - */ -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"`). + * `pending` is `Arc>>` so `result()` can + * `.take()` the statement (the kernel `execute()` borrows it `&mut`, + * then it moves into the produced `Statement` wrapper to keep its + * `ValidityFlag` set — see `statement.rs`). A second `result()` call + * after the first resolved surfaces `InvalidStatementHandle`. */ -export interface ProxyInput { - url: string - username?: string - password?: string - bypassHosts?: string +export declare class CancellableExecution { + /** + * The server-issued statement id this execution targets, if the + * server has issued one yet (`null` before the initial submit + * round-trip publishes it mid-`result()`). Useful for log + * correlation while the blocking drive is in flight. + */ + get statementId(): string | null + /** + * Drive the blocking `execute()` and resolve to a `Statement` + * (identical to what `executeStatement` returns) once the kernel + * reaches a terminal state and the result stream is ready. + * + * Consumes the pending statement: a second `result()` call returns + * `KernelError(InvalidStatementHandle)`. The future is + * drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState` + * guard fires a fire-and-forget `cancel_statement` if this future is + * dropped mid-flight (`Promise.race` / timeout loser), independently + * of an explicit `cancel()`. + * + * On a server-side cancel the kernel's blocking `execute()` currently + * surfaces `InvalidArgument` (a known kernel quirk — the async path + * returns `Cancelled`). When this handle's `cancel()` actually dispatched a + * server-side cancel, we normalise that into `Cancelled` here so JS callers + * can rely on a single cancelled-status code regardless of execution path. + * + * Three outcomes can race the blocking drive: (1) a natural terminal state + * → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a + * server cancel → this `result()` rejects with a `Cancelled`-coded error + * (the normalisation above); (3) the future being **dropped** mid-flight + * (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState` + * drop-guard fires a fire-and-forget `cancel_statement`, but there is no + * `result()` left to observe a code. Only (2) yields a `Cancelled` error. + */ + result(): Promise + /** + * Server-side cancel of the in-flight statement. + * + * Lock-free: fires the detached `StatementCanceller` captured at + * construction rather than taking the mutex `result()` holds, so it + * interrupts a still-running blocking `result()` instead of queueing + * behind it. No-op (returns `Ok`) if `result()` already finished + * successfully, or if no statement id has been observed yet (query still + * in its initial submit round-trip), and idempotent against a server + * already in a terminal state. + */ + cancel(): Promise } + /** - * JS-visible options for opening a Databricks SQL session. + * Opaque connection handle wrapping a kernel `Session`. * - * Authentication is selected by `authMode` (default [`AuthMode::Pat`]): - * - `Pat` — `token` required. - * - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. - * - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional - * (defaults to the `databricks-sql-connector` client on port 8030). - * - `AzureSpM2m` — `azureClientId` + `azureClientSecret` required - * (+ optional `azureTenantId` / `azureWorkspaceResourceId`). + * `inner` is `Arc>>` so: + * - the Drop impl can clone the `Arc` and `.take()` the session on a + * background tokio task without holding `&mut self` (which Drop is + * forbidden from doing across an `await`), + * - `close()` can `.take()` the session to consume it for the kernel's + * move-by-value `Session::close(self)` signature. * - * Catalog / schema / sessionConf are applied once at session creation - * and remain in effect for every statement run on the resulting - * `Connection`. The SEA wire protocol carries them on - * `CreateSession`, not on `ExecuteStatement` — so there is no - * per-statement override path on this binding. + * **Concurrency shape** — both `executeStatement` and + * `submitStatement` build the kernel `Statement` under `inner.lock()` + * and then RELEASE the guard before the wire call + * (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()` + * is `&self`-callable and only clones the session's internal `Arc`, so + * the built statement is independent of the guard. Concurrent + * `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore + * serialise only for the microsecond statement-build, not the network + * round-trip, and `close()` never blocks behind an in-flight execute or + * submit. See + * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. */ -export interface ConnectionOptions { +export declare class Connection { /** - * Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel - * normalises this — bare hostnames get `https://` prepended. + * Server-issued session id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate + * against kernel / server logs which key on the same id. */ - hostName: string + get sessionId(): string /** - * JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The - * kernel parses out the warehouse id. + * Execute a SQL statement and return a Statement handle that + * streams batches via `fetchNextBatch()`. + * + * Catalog / schema / sessionConf are session-level + * (`openSession`). Per-statement options on `ExecuteOptions`: + * - `statementConf` — per-statement Spark conf overlay + * - `queryTags` — serialised to a comma-separated `key:value` + * string and placed in `statement_conf["query_tags"]`, + * matching NodeJS Thrift's `serializeQueryTags` wire shape + * + * `options` is omitted/`None` for the no-options path; passing + * `{ statementConf: {} }` (an empty map) is treated the same as + * omission to keep the wire shape stable for the common case. */ - httpPath: string + executeStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise /** - * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: - * existing PAT callers pass only `token`). + * directResults execute — the Thrift/JDBC model. Sends ExecuteStatement + * with no `wait_timeout` field (server applies its ~10s default inline wait + * and auto-closes on success) and returns WITHOUT polling past it: + * + * - a **`Statement`** (left arm) when the query finished within the inline + * wait — terminal, result ready inline, `close()` is a clean release; + * - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel + * handle the caller drives (`status()` / `awaitResult()` / `cancel()`). + * + * JS distinguishes the arms by feature-detecting `awaitResult` (present + * only on `AsyncStatement`). This is the path that gives mid-run cancel for + * long queries WITHOUT the eager-handle / close-drives workaround: the + * returned handle always corresponds to a server-owned statement. + * + * **Load-bearing contract:** the kernel's `DirectStatement::{Completed, + * Running}` discriminant cannot ride on these opaque `#[napi]` classes, so + * consumers MUST feature-detect via `awaitResult` (the only member unique to + * `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an + * `awaitResult` member, or every consumer silently misroutes. The pyo3 + * binding makes the same `await_result`-probe assumption. */ - authMode?: AuthMode + executeStatementDirect(sql: string, options?: ExecuteOptions | undefined | null): Promise /** - * Personal access token. Required (and non-empty) for - * [`AuthMode::Pat`]; ignored otherwise. + * Execute a SQL statement on the blocking (sync) path, but return a + * `CancellableExecution` handle so a concurrent JS task can cancel + * the query *while it is still running server-side*. + * + * `executeStatement` builds the kernel `Statement`, awaits the + * blocking `execute()`, and only then hands JS a `Statement` — so a + * query that runs for several seconds is uncancellable from JS on + * that path (there is no handle until the blocking call resolves). + * This method instead builds the statement, captures a detached + * `StatementCanceller` **before** dispatching `execute()`, and hands + * JS a `CancellableExecution` immediately. The caller drives the + * blocking execution via `result()` (resolves to the same + * `Statement` `executeStatement` returns) and can fire `cancel()` + * concurrently to interrupt a still-running query mid-COMPUTE. + * + * Option semantics are identical to `executeStatement`. + * Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` + * split (PR #121): obtain the canceller before the blocking drive. */ - token?: string + executeStatementCancellable(sql: string, options?: ExecuteOptions | undefined | null): Promise /** - * OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for - * [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). + * Submit a SQL statement and return immediately with an + * `AsyncStatement` handle, without blocking until the query + * finishes. The kernel's `Statement::submit()` sends + * `wait_timeout=0s`, so the server responds as soon as it has a + * `statement_id` (state `Pending`/`Running`); JS drives polling + * via `AsyncStatement.status()` and materialises results with + * `AsyncStatement.awaitResult()`. + * + * This is the async-execution path the Thrift backend always + * uses (`runAsync: true`): the SEA backend submits, returns a + * pending operation handle, and polls to terminal during + * fetch. Option semantics (statementConf / queryTags / + * rowLimit / positional + named params) match `executeStatement`. + * Submit always sends `wait_timeout=0s` so the call returns + * immediately; the caller drives completion via `status()` / + * `awaitResult()`. Only the blocking-vs-pending return contract + * differs from `executeStatement`. */ - oauthClientId?: string - /** OAuth client secret. Required for [`AuthMode::OAuthM2m`]. */ - oauthClientSecret?: string + submitStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise /** - * Localhost callback port for the [`AuthMode::OAuthU2m`] browser - * flow. Omitted ⇒ kernel default (8030). + * Explicit close. Awaits the server-side `DeleteSession` so the + * JS caller can observe failures (auth revoked mid-session, + * warehouse stopped, network error). Idempotent — a second call + * on an already-closed connection returns `Ok`. + * + * **Errors are terminal from the JS side.** The kernel session + * handle is consumed (`take()`) BEFORE the wire `DeleteSession` + * runs, because `Session::close` takes `self` by value. On `Err`, + * the napi `inner` is already `None`, so a JS-side retry sees a + * closed connection and returns `Ok(())` without re-attempting + * the wire call. The kernel's own `Drop` fire-and-forget retry + * runs once in the background — the JS caller can log the error + * but cannot drive a retry. If you need retry-on-failure + * semantics for `DeleteSession`, layer them above this method. */ - oauthRedirectPort?: number + close(): Promise /** - * OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults - * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). + * All catalogs visible to the session. + * + * JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. */ - oauthScopes?: Array + listCatalogs(): Promise /** - * OAuth token endpoint override. When omitted the kernel discovers the - * endpoint via the workspace's OIDC configuration. Set it to point the - * client-credentials / JWT client-assertion grant at the workspace's - * configured IdP token endpoint (e.g. Entra ID for Azure Databricks), - * which is required when that IdP — not Databricks-native OIDC — is the - * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. + * Schemas filtered by catalog (exact) and schema name pattern. + * + * JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. */ - tokenUrl?: string + listSchemas(catalog?: string | undefined | null, schemaPattern?: string | undefined | null): Promise /** - * Path to the PEM private-key file. Required for - * [`AuthMode::OAuthM2mJwt`]. + * Tables filtered by catalog (**pattern**), schema (pattern), table + * (pattern). + * + * The catalog is an ODBC/JDBC LIKE pattern (`%` / `_`), matching + * Thrift `getTables`: a wildcard catalog matches multiple catalogs; + * a literal name (or an escaped `\_` / `\%`) takes the fast exact + * path. `undefined`/omitted catalog means "all catalogs", while an + * **empty string** means "match nothing" (zero rows) — pass + * `undefined`, not `""`, for all catalogs. The catalog pattern is + * validated (whitespace-only / NUL / >255 bytes are rejected with an + * error). + * + * JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, + * filters rows by `TABLE_TYPE` kernel-side. + * + * `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does + * NOT honour the table-type filter server-side; the kernel applies + * it client-side after the result returns. Callers expecting + * server-side rejection of off-type tables should not rely on this. */ - jwtKeyFile?: string - /** JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. */ - jwtKid?: string + listTables(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, tableTypes?: Array | undefined | null): Promise /** - * Passphrase for an encrypted PKCS#8 key. Optional for - * [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). + * Columns of tables matching the filter. + * + * JDBC `getColumns` shape: 23 columns. */ - jwtPassphrase?: string + listColumns(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, columnPattern?: string | undefined | null): Promise /** - * JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, - * `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] - * (omitted ⇒ kernel default `RS256`). + * Functions visible to the session. `catalog` is exact; + * `schemaPattern` and `functionPattern` are SQL LIKE. */ - jwtAlgorithm?: string + listFunctions(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, functionPattern?: string | undefined | null): Promise /** - * SP-wide Workload Identity Federation client id used during mandatory - * token exchange. Omitted selects BYOT / account-wide WIF. + * Procedures visible to the session. `catalog` is exact; + * `schemaPattern` and `procedurePattern` are SQL LIKE. */ - identityFederationClientId?: string + listProcedures(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, procedurePattern?: string | undefined | null): Promise /** - * Azure Entra app-registration client id. Required for - * [`AuthMode::AzureSpM2m`]; ignored otherwise. + * All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). + * No wire call — static in-memory result. */ - azureClientId?: string + listTableTypes(): Promise /** - * Azure Entra app-registration client secret. Required for - * [`AuthMode::AzureSpM2m`]. + * SQL data types supported by the workspace. + * No wire call — static in-memory result. */ - azureClientSecret?: string + listTypeInfo(): Promise /** - * Azure Entra tenant id. Optional for [`AuthMode::AzureSpM2m`]; - * omitted ⇒ the kernel auto-discovers it from the workspace's - * `/aad/auth` redirect (matching the Thrift connector). + * Primary keys for the given table. All three identifiers are + * exact — ODBC `SQLPrimaryKeys` does not support patterns. */ - azureTenantId?: string + getPrimaryKeys(catalog: string, schema: string, table: string): Promise /** - * Azure workspace ARM resource id. Optional for [`AuthMode::AzureSpM2m`]; - * when set the kernel also sends the SP management token - * (`X-Databricks-Azure-SP-Management-Token`) + the - * `X-Databricks-Azure-Workspace-Resource-Id` header, so a service - * principal with an Azure RBAC role but no workspace membership can - * authenticate. Omitted ⇒ the data token authenticates alone. + * Foreign-key relationships. The foreign side must be fully + * specified (catalog + schema + table); the parent side is + * optional. All identifiers are exact — no LIKE patterns. */ - azureWorkspaceResourceId?: string + getCrossReference(parentCatalog: string | undefined | null, parentSchema: string | undefined | null, parentTable: string | undefined | null, foreignCatalog: string, foreignSchema: string, foreignTable: string): Promise +} + +/** + * Opaque executed-statement handle. + * + * **Current concurrency shape** — every method takes `inner.lock()` + * and holds the guard across the kernel `.await`. tokio `Mutex` is + * FIFO, so cancel/close queue behind any in-flight `fetchNextBatch` + * until it returns naturally. This is a known limitation that exists + * because the napi shape has not yet been split into an + * `Arc` (for cancel/close, which the + * kernel exposes as `&self`-callable) plus a `Mutex>` only + * for the borrowed-mut fetch path. The lock-shape refactor needs a + * small kernel-side accessor and lands in a follow-up PR — see + * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. + * + * `schema` and `statement_id` are cached at construction so they + * survive `close()` — JS callers building error reports against a + * disposed statement can still read them. + */ +export declare class Statement { /** - * Default catalog for statements executed on this session. - * Routed through the kernel's `DefaultOpts` and onto the SEA - * `CreateSession.catalog` wire field. + * Server-issued statement id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate against + * kernel / server logs which key on the same id. */ - catalog?: string + get statementId(): string /** - * Default schema for statements executed on this session. - * Routed through the kernel's `DefaultOpts` and onto the SEA - * `CreateSession.schema` wire field. + * Number of rows modified by the statement (UPDATE / INSERT / + * DELETE / MERGE). `null` for SELECT and on warehouses that don't + * surface the counter. Mirrors Thrift's + * `TGetOperationStatusResp.numModifiedRows`. */ - schema?: string + numModifiedRows(): Promise /** - * Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`, - * query-tag presets, …). Forwarded verbatim to SEA - * `session_confs`. Unknown keys are rejected server-side. + * Server-supplied user-facing message. Mirrors Thrift's + * `TGetOperationStatusResp.displayMessage`. **PII / sensitive- + * data note:** may contain SQL fragments or parameter values — + * redact before centralised logging. + * + * Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`). + * On terminal-error states (`Failed` / `Cancelled`) the kernel returns + * an Error instead of a `Statement`, and the same field rides on the JS + * Error envelope under the same `displayMessage` key. */ - sessionConf?: Record + displayMessage(): Promise /** - * Driver name reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Server-supplied diagnostic detail — multi-line operator / + * stack context. Mirrors Thrift's + * `TGetOperationStatusResp.diagnosticInfo`. For support surfaces, + * not user-facing. Same reachability + PII caveats as + * `displayMessage`. */ - driverName?: string + diagnosticInfo(): Promise /** - * Driver version reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Server-supplied JSON blob with extended error details. Mirrors + * Thrift's `TGetOperationStatusResp.errorDetailsJson`. + * Pass-through string — JS callers parse with `JSON.parse` if + * they need structured access. + * + * **Server-side gating:** populated only when the workspace has + * `spark.databricks.sql.errorDetailsJson.enabled = true` on the + * underlying SQL cluster. The flag is internal-only / default- + * false in the Databricks runtime, so for most JS callers this + * will return `null`. Admin-enabled workspaces return content + * shaped like `{"errorClass": "...", "messageTemplate": "..."}`. + * + * **Unbounded:** when populated, server can return a multi-MB + * blob; size before logging. */ - driverVersion?: string + errorDetailsJson(): Promise /** - * Runtime name reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Pull the next batch of results. Returns `null` when the stream + * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete + * Arrow IPC stream (schema header + 1 record-batch message) + * suitable for handing to `apache-arrow`'s `RecordBatchReader`. + * + * On `Err`, the stream is in an unspecified state — call + * `close()` and discard the `Statement`. Subsequent + * `fetchNextBatch()` calls after an error are not guaranteed to + * succeed or fail consistently. */ - runtimeName?: string + fetchNextBatch(): Promise /** - * Runtime version reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Result schema as an Arrow IPC payload (schema header only, no + * record-batch message). Available before any batches have been + * fetched, and remains available after `close()` — the kernel + * materialises the schema eagerly so JS callers can build error + * reports against a disposed statement. + * + * Sync because the body has no `.await` — `encode_ipc_stream` is + * pure CPU work over an `Arc` already cached on the + * wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync). + * napi-rs converts a panic in a sync `#[napi]` entry point into a + * thrown JS error via its own macro-expanded boundary, so the + * `util::guarded` `catch_unwind` wrapper that the `async fn` + * entry points use is not required for this method. */ - runtimeVersion?: string + schema(): ArrowSchema /** - * Runtime vendor reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Server-side cancel. + * + * For executed statements: short-circuits to `Ok(())` if + * `fetchNextBatch` has already returned `null` (stream + * naturally exhausted) — matches the JDBC `Statement.cancel()` + * no-op-after-completion contract, so JS callers can fire cancel + * defensively without distinguishing "real cancel" from "raced + * with natural completion." + * + * For metadata streams: no-op (the kernel has no in-flight + * cancellation surface for metadata calls today). + * + * Returns `KernelError(InvalidStatementHandle)` if the statement + * has been explicitly `close()`d. */ - runtimeVendor?: string + cancel(): Promise /** - * Operating system name reported in telemetry system configuration. - * Omitted ⇒ kernel default. + * Explicit close. + * + * For executed statements: awaits the server-side `CloseStatement` + * so the JS caller can observe failures (auth revoked mid-session, + * network error, server-side error). Idempotent — a second call + * on an already-closed statement returns `Ok`. + * + * **Errors are terminal from the JS side.** The kernel executed + * handle is taken out of `inner` BEFORE the wire `CloseStatement` + * runs (so `Drop` knows there's nothing left to clean up). On + * `Err`, the napi `inner` is already `None`, so a JS-side retry + * sees a closed statement and returns `Ok(())` without re- + * attempting the wire call. The kernel-level `ExecutedStatement` + * has been consumed at that point and the value is dropped on + * the way out of the closure — the kernel's `ExecutedStatement:: + * Drop` then fires-and-forgets a single retry on the captured + * runtime. The JS caller can log the error but cannot drive a + * further retry. If you need retry-on-failure semantics for + * `CloseStatement`, layer them above this method. + * + * For metadata streams: drops the stream (no server round-trip + * needed — metadata results have no in-flight server-side + * resource to release). */ - osName?: string + close(): Promise +} + +/** + * A single Arrow IPC stream payload encoding one record batch (plus + * the schema header so the JS-side reader is stateless). + */ +export interface ArrowBatch { /** - * Operating system version reported in telemetry system configuration. - * Omitted ⇒ kernel default. + * Arrow IPC stream payload (schema header + 1 record-batch + * message). Decode with `apache-arrow`'s `RecordBatchReader`. */ - osVersion?: string + ipcBytes: Buffer +} + +/** + * An Arrow IPC stream payload encoding just the result schema (no + * record-batch messages). Returned by `Statement.schema()`. + */ +export interface ArrowSchema { /** - * Operating system architecture reported in telemetry system - * configuration. Omitted ⇒ kernel default. + * Arrow IPC stream payload (schema header only, no record-batch + * messages). Decode with `apache-arrow`'s `RecordBatchReader` — + * the reader will expose the schema and immediately end. */ - osArch?: string + ipcBytes: Buffer +} + +/** + * Authentication mode selector crossing the napi boundary. The string + * literals are what napi-rs emits from this `#[napi(string_enum)]` — the + * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`, + * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). + * + * Mirrors the kernel [`AuthConfig`] variants this binding supports. + * `OAuthFederation` / `External` are intentionally not exposed yet — the + * kernel marks federation as not-yet-implemented and `External` is a + * Rust-trait escape hatch with no JS-callback bridge. + */ +export declare const enum AuthMode { + /** Personal access token (`token`). */ + Pat = 'Pat', + /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */ + OAuthM2m = 'OAuthM2m', /** - * Client application name reported in telemetry system configuration. - * Omitted ⇒ absent unless the kernel can infer a default. + * OAuth 2.0 machine-to-machine with a JWT private-key client + * assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. */ - clientAppName?: string + OAuthM2mJwt = 'OAuthM2mJwt', /** - * Locale name reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` + * + `oauthRedirectPort`. */ - localeName?: string + OAuthU2m = 'OAuthU2m', /** - * Character-set encoding reported in telemetry system configuration. - * Omitted ⇒ kernel default. - */ + * Azure Entra service-principal M2M — `azureClientId` + + * `azureClientSecret` (+ optional `azureTenantId` / + * `azureWorkspaceResourceId`). The kernel builds the Entra token + * endpoint + `.default` scope, auto-discovers the tenant from the + * workspace when `azureTenantId` is omitted, and — when + * `azureWorkspaceResourceId` is set — additionally sends the SP + * management token for an RBAC-only service principal. + */ + AzureSpM2m = 'AzureSpM2m' +} + +/** + * JS-visible options for opening a Databricks SQL session. + * + * Authentication is selected by `authMode` (default [`AuthMode::Pat`]): + * - `Pat` — `token` required. + * - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. + * - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional + * (defaults to the `databricks-sql-connector` client on port 8030). + * - `AzureSpM2m` — `azureClientId` + `azureClientSecret` required + * (+ optional `azureTenantId` / `azureWorkspaceResourceId`). + * + * Catalog / schema / sessionConf are applied once at session creation + * and remain in effect for every statement run on the resulting + * `Connection`. The SEA wire protocol carries them on + * `CreateSession`, not on `ExecuteStatement` — so there is no + * per-statement override path on this binding. + */ +export interface ConnectionOptions { + /** + * Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel + * normalises this — bare hostnames get `https://` prepended. + */ + hostName: string + /** + * JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The + * kernel parses out the warehouse id. + */ + httpPath: string + /** + * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: + * existing PAT callers pass only `token`). + */ + authMode?: AuthMode + /** + * Personal access token. Required (and non-empty) for + * [`AuthMode::Pat`]; ignored otherwise. + */ + token?: string + /** + * OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for + * [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). + */ + oauthClientId?: string + /** OAuth client secret. Required for [`AuthMode::OAuthM2m`]. */ + oauthClientSecret?: string + /** + * Localhost callback port for the [`AuthMode::OAuthU2m`] browser + * flow. Omitted ⇒ kernel default (8030). + */ + oauthRedirectPort?: number + /** + * OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults + * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). + */ + oauthScopes?: Array + /** + * OAuth token endpoint override. When omitted the kernel discovers the + * endpoint via the workspace's OIDC configuration. Set it to point the + * client-credentials / JWT client-assertion grant at the workspace's + * configured IdP token endpoint (e.g. Entra ID for Azure Databricks), + * which is required when that IdP — not Databricks-native OIDC — is the + * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. + */ + tokenUrl?: string + /** + * Path to the PEM private-key file. Required for + * [`AuthMode::OAuthM2mJwt`]. + */ + jwtKeyFile?: string + /** JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. */ + jwtKid?: string + /** + * Passphrase for an encrypted PKCS#8 key. Optional for + * [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). + */ + jwtPassphrase?: string + /** + * JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, + * `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] + * (omitted ⇒ kernel default `RS256`). + */ + jwtAlgorithm?: string + /** + * SP-wide Workload Identity Federation client id used during mandatory + * token exchange. Omitted selects BYOT / account-wide WIF. + */ + identityFederationClientId?: string + /** + * Azure Entra app-registration client id. Required for + * [`AuthMode::AzureSpM2m`]; ignored otherwise. + */ + azureClientId?: string + /** + * Azure Entra app-registration client secret. Required for + * [`AuthMode::AzureSpM2m`]. + */ + azureClientSecret?: string + /** + * Azure Entra tenant id. Optional for [`AuthMode::AzureSpM2m`]; + * omitted ⇒ the kernel auto-discovers it from the workspace's + * `/aad/auth` redirect (matching the Thrift connector). + */ + azureTenantId?: string + /** + * Azure workspace ARM resource id. Optional for [`AuthMode::AzureSpM2m`]; + * when set the kernel also sends the SP management token + * (`X-Databricks-Azure-SP-Management-Token`) + the + * `X-Databricks-Azure-Workspace-Resource-Id` header, so a service + * principal with an Azure RBAC role but no workspace membership can + * authenticate. Omitted ⇒ the data token authenticates alone. + */ + azureWorkspaceResourceId?: string + /** + * Default catalog for statements executed on this session. + * Routed through the kernel's `DefaultOpts` and onto the SEA + * `CreateSession.catalog` wire field. + */ + catalog?: string + /** + * Default schema for statements executed on this session. + * Routed through the kernel's `DefaultOpts` and onto the SEA + * `CreateSession.schema` wire field. + */ + schema?: string + /** + * Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`, + * query-tag presets, …). Forwarded verbatim to SEA + * `session_confs`. Unknown keys are rejected server-side. + */ + sessionConf?: Record + /** + * Driver name reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + driverName?: string + /** + * Driver version reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + driverVersion?: string + /** + * Runtime name reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + runtimeName?: string + /** + * Runtime version reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + runtimeVersion?: string + /** + * Runtime vendor reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + runtimeVendor?: string + /** + * Operating system name reported in telemetry system configuration. + * Omitted ⇒ kernel default. + */ + osName?: string + /** + * Operating system version reported in telemetry system configuration. + * Omitted ⇒ kernel default. + */ + osVersion?: string + /** + * Operating system architecture reported in telemetry system + * configuration. Omitted ⇒ kernel default. + */ + osArch?: string + /** + * Client application name reported in telemetry system configuration. + * Omitted ⇒ absent unless the kernel can infer a default. + */ + clientAppName?: string + /** + * Locale name reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + localeName?: string + /** + * Character-set encoding reported in telemetry system configuration. + * Omitted ⇒ kernel default. + */ charSetEncoding?: string /** * Process name reported in telemetry system configuration. Omitted ⇒ @@ -568,45 +1016,131 @@ export interface ConnectionOptions { */ socketTimeoutMs?: number } + /** - * Open a Databricks SQL session and return an opaque `Connection` - * wrapping the kernel `Session`. Authentication is selected by - * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see - * [`build_auth_config`]. + * Per-statement options for `Connection.executeStatement`. * - * The JS-visible name is `openSession` (napi-rs converts snake_case - * to camelCase for free functions). - */ -export declare function openSession(options: ConnectionOptions): Promise -/** - * One kernel log event, as handed to JS. `level` is a lower-case string - * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its - * `LogLevel`; `target` is the originating `tracing` target (e.g. - * `databricks::sql::kernel`); `message` is the rendered event plus any - * structured `key=value` fields. - */ -export interface LogRecord { - level: string - target: string - message: string -} -/** - * Install (idempotently) the kernel→JS log bridge and set its level. + * Mirrors the kernel `StatementSpec` knobs that are safe to thread + * through napi without a kernel-side change. Today this covers: + * - `statementConf` — per-statement Spark conf overlay + * (`StatementSpec.statement_conf` → SEA `parameters` / + * Thrift `confOverlay`) + * - `queryTags` — convenience wrapper over `statementConf` with + * key `query_tags`; serialised to the same comma-separated + * `key:value` wire shape NodeJS Thrift's `serializeQueryTags` + * produces (`lib/utils/queryTags.ts`). Backslashes in keys are + * doubled; backslash/colon/comma in values are backslash-escaped. * - * `callback` is invoked with **an array of [`LogRecord`]s** (`(err, records)`) - * for each forwarded batch. `level` is one of - * `off`/`error`/`warn`/`info`/`debug`/`trace` (case-insensitive); unknown - * values fall back to `warn`. + * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel + * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) + * carry bound query parameters, decoded via `params::parse_typed_value`. + * (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold + * window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.) * - * Safe to call more than once: the process-global subscriber is installed on - * the first call only, while every call refreshes the sink + level (last - * writer wins — see module docs). + * **Tag-order caveat (M4 parity note).** The napi `queryTags` field + * is a Rust `HashMap` whose iteration order is + * non-deterministic, so the serialised `query_tags` value may have + * a different key order than Thrift's `serializeQueryTags` (which + * iterates `Object.keys(...)` in insertion order) for the same + * input. The SEA server is order-insensitive on conf values, so + * the two are functionally equivalent. If a caller needs + * byte-identical Thrift parity, the JS adapter pre-serialises via + * `serializeQueryTags` and writes the result into + * `statementConf["query_tags"]` directly — see + * `KernelSessionBackend.executeStatement` in the NodeJS driver. This + * path is the one the production code uses. */ -export declare function initKernelLogging(callback: (err: Error | null, arg: Array) => any, level: string): void -/** - * Snapshot of the bridge's runtime state for observability. - * - * `installed` is `true` only when the process-global subscriber was +export interface ExecuteOptions { + /** + * Per-statement Spark conf overlay. Merged on top of the + * session-level `sessionConf` at execute time; this map wins + * on key collisions. Unknown keys are rejected by the server. + */ + statementConf?: Record + /** + * Query tags as key→value pairs. Serialised to a comma- + * separated `key:value` string (backslash-escaping `\`, `:`, + * `,`) and placed into `statementConf["query_tags"]`, matching + * NodeJS Thrift's `serializeQueryTags` wire shape. Passing + * both `queryTags` AND a `query_tags` key in `statementConf` + * raises `InvalidArgument` — the caller's intent is ambiguous + * so we refuse to silently pick one over the other. + * + * A **`null`** value emits a **bare key** (no colon) — e.g. + * `{ production: null }` → `"production"` — matching the + * connectors' `key`-only tag form. + * + * See the struct-level "Tag-order caveat" for the + * HashMap-iteration-order vs `Object.keys`-iteration-order + * divergence and the byte-identical-Thrift-parity workaround. + */ + queryTags?: Record + /** + * Server-side cap on the number of rows this statement returns + * (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to + * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. + */ + rowLimit?: number + /** + * Positional parameters, in 1-based wire order. Index `i` in this + * Vec corresponds to the `i+1`-th `?` placeholder in the SQL. + * Each entry is a `{ sqlType, value }` pair — `value` is the + * string-encoded literal or `null` for SQL NULL. Mirrors + * `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. + */ + positionalParams?: Array + /** + * Named parameters (`:name` placeholders). Each carries its `name` + * alongside the `{ sqlType, value? }` pair. Mapped to a kernel + * `TypedValue` via the same [`parse_typed_value`] codec and bound with + * `StatementSpec::param_named`. Named is the SEA-spec-required public + * param form (`StatementParameter.name` is `openapi_required`); + * positional is the documented-undocumented variant. The two are + * mutually exclusive at the SQL level (`?` vs `:name`). + */ + namedParams?: Array +} + +/** + * A single extra HTTP header as an explicit `{ name, value }` pair. + * + * An ordered list of these (`ConnectionOptions.custom_headers`) mirrors + * the kernel core's `Vec<(String, String)>` and the pyo3 binding's + * `http_headers`: order is preserved and duplicate `name`s are allowed. + * A struct (rather than a raw `[name, value]` tuple) because napi-rs + * does not marshal Rust tuples through `#[napi(object)]` fields; the + * struct is the idiomatic, self-documenting equivalent and maps to a JS + * `{ name: string, value: string }`. + */ +export interface HeaderEntry { + name: string + value: string +} + +/** + * Install (idempotently) the kernel→JS log bridge and set its level. + * + * `callback` is invoked with **an array of [`LogRecord`]s** (`(err, records)`) + * for each forwarded batch. `level` is one of + * `off`/`error`/`warn`/`info`/`debug`/`trace` (case-insensitive); unknown + * values fall back to `warn`. + * + * Safe to call more than once: the process-global subscriber is installed on + * the first call only, while every call refreshes the sink + level (last + * writer wins — see module docs). + */ +export declare function initKernelLogging(callback: ((err: Error | null, arg: Array) => any), level: string): void + +/** + * Return the bridge's [`KernelLoggingStats`]. Safe to call before + * `initKernelLogging` (reports `installed: false`, `dropped: 0`). + */ +export declare function kernelLoggingStats(): KernelLoggingStats + +/** + * Snapshot of the bridge's runtime state for observability. + * + * `installed` is `true` only when the process-global subscriber was * successfully installed by *this* bridge (and the drain thread started); * `false` means another global subscriber was already set or the drain * thread could not be spawned, so kernel logs are NOT reaching the JS sink. @@ -618,16 +1152,87 @@ export interface KernelLoggingStats { installed: boolean dropped: number } + /** - * Return the bridge's [`KernelLoggingStats`]. Safe to call before - * `initKernelLogging` (reports `installed: false`, `dropped: 0`). + * Map the JS `ConnectionOptions` auth fields onto the kernel + * [`AuthConfig`]. Per-mode required-field validation lives in the + * kernel's validating constructors ([`AuthConfig::pat`] / + * [`AuthConfig::oauth_m2m`]); this binding just forwards the JS + * optionals and maps any kernel `InvalidArgument` onto a napi error. + * `#[napi(object)]` argument for the persist callback: the workspace host + * plus the kernel's serialized `OAuthToken` (JSON). The token crosses the + * boundary as an opaque JSON string — the exact bytes the on-disk cache would + * store — so the full token (including expiry) round-trips losslessly through + * the caller's store. */ -export declare function kernelLoggingStats(): KernelLoggingStats +export interface KernelPersistArgs { + /** Workspace host the token is scoped to (the store's key). */ + host: string + /** The kernel's `OAuthToken` serialized as JSON. Opaque to the caller. */ + tokenJson: string +} + +/** + * One kernel log event, as handed to JS. `level` is a lower-case string + * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its + * `LogLevel`; `target` is the originating `tracing` target (e.g. + * `databricks::sql::kernel`); `message` is the rendered event plus any + * structured `key=value` fields. + */ +export interface LogRecord { + level: string + target: string + message: string +} + +/** + * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a + * distinct napi object (rather than an optional `name` on `TypedValueInput`) + * so the positional surface stays a clean ordered list with no name field. + */ +export interface NamedTypedValueInput { + name: string + sqlType: string + value?: string +} + +/** + * Open a Databricks SQL session and return an opaque `Connection` + * wrapping the kernel `Session`. Authentication is selected by + * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see + * [`build_auth_config`]. + * + * The JS-visible name is `openSession` (napi-rs converts snake_case + * to camelCase for free functions). + */ +export declare function openSession(options: ConnectionOptions, oauthPersistenceRead?: (((arg: string) => Promise)) | undefined | null, oauthPersistencePersist?: (((arg: KernelPersistArgs) => Promise)) | undefined | null): Promise + +/** + * 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 +} + /** * Live-retarget the bridge's level (one of * `off`/`error`/`warn`/`info`/`debug`/`trace`, case-insensitive). */ export declare function setKernelLogLevel(level: string): void + /** * JS-visible binding for a single positional parameter. * @@ -661,29 +1266,7 @@ export interface TypedValueInput { */ value?: string } -/** - * A single Arrow IPC stream payload encoding one record batch (plus - * the schema header so the JS-side reader is stateless). - */ -export interface ArrowBatch { - /** - * Arrow IPC stream payload (schema header + 1 record-batch - * message). Decode with `apache-arrow`'s `RecordBatchReader`. - */ - ipcBytes: Buffer -} -/** - * An Arrow IPC stream payload encoding just the result schema (no - * record-batch messages). Returned by `Statement.schema()`. - */ -export interface ArrowSchema { - /** - * Arrow IPC stream payload (schema header only, no record-batch - * messages). Decode with `apache-arrow`'s `RecordBatchReader` — - * the reader will expose the schema and immediately end. - */ - ipcBytes: Buffer -} + /** * Returns the native binding's crate version (`CARGO_PKG_VERSION`). * @@ -691,540 +1274,3 @@ export interface ArrowSchema { * loaded?" probe for the JS-side loader's structured diagnostics. */ export declare function version(): string -/** - * Opaque async-statement handle. - * - * Returned by `Connection.submitStatement(...)` after the kernel - * `Statement::submit()` returns (server sent `wait_timeout=0s`, so - * the response carries a `statement_id` but the statement is still - * `Pending`/`Running`). JS drives polling via `status()` / - * `awaitResult()`. - * - * Concurrency shape: `status()`, `awaitResult()`, and `close()` take - * `inner.lock()` and hold the guard across the kernel `.await` (tokio - * `Mutex` is FIFO), so `status()` / `close()` queue behind any - * in-flight `awaitResult()` until it returns naturally. `cancel()` is - * the deliberate exception: it does **not** touch `inner` — it fires - * through the detached `AsyncStatementCanceller` (session + - * statement_id, captured at construction), so an explicit - * `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of - * queueing behind it. The server-side cancel flips the statement - * terminal, which the parked `awaitResult()` poll loop observes - * (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard` - * still covers the drop-cancel case (Promise.race / timeout) - * independently — see module docs. - */ -export declare class AsyncStatement { - /** - * Server-issued statement id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate - * against kernel / server logs which key on the same id. - */ - get statementId(): string - /** - * One-shot status check. Returns a string enum matching the - * kernel `StatementStatus` shape: - * `'Pending' | 'Running' | 'Succeeded' | 'Failed' | - * 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the - * `#[non_exhaustive]` forward-compat catch-all that - * `StatementStatus::as_str` can return — consumers switching on - * the state must handle it.) Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. - * - * The `Failed` variant collapses to the string `'Failed'` on - * the JS side; the underlying error envelope (sql_state / - * error_code / query_id) is surfaced by `awaitResult()`'s - * rejection, which is where callers actually need the typed - * error. `status()` is intended for polling progress UIs - * 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 - * stream. The handle exposes `fetchNextBatch()` / `schema()` - * for consuming the result, plus `statementId` for log - * correlation. - * - * Drop-cancel safety: kernel `await_result` installs - * `AwaitResultCancelGuard` which fires a fire-and-forget - * `cancel_statement` if the future is dropped mid-poll - * (timeout, tokio::select! loser, JS-side `Promise.race` - * loser). The `util::guarded` `catch_unwind` here covers the - * V8-panic-across-boundary case on top. Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. - */ - awaitResult(): Promise - /** - * Server-side cancel. Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. Idempotent against a server - * that already reached a terminal state — the kernel's - * `cancel_statement` is a no-op there. - * - * **Lock-free by design.** Unlike `status()` / `awaitResult()` / - * `close()`, this does not take `inner.lock()` — it fires through - * the detached `AsyncStatementCanceller` captured at construction. - * That lets `stmt.cancel()` interrupt an in-flight `awaitResult()` - * (which holds the mutex for the whole poll) instead of queueing - * behind it: the server-side cancel flips the statement terminal, - * the parked `awaitResult()` poll loop observes `Cancelled` and - * returns. The closed-state check reads a lock-free flag so a - * cancel after an explicit `close()` still surfaces - * `InvalidStatementHandle`. - */ - cancel(): Promise - /** - * Explicit close. Idempotent — a second call on an - * already-closed handle returns `Ok(())`. On `Err`, the napi - * inner is already `None`, so a JS-side retry sees the - * closed-handle short-circuit and returns `Ok(())` without - * re-attempting the wire call. The kernel's own `Drop` - * fire-and-forget retry runs once in the background. - */ - close(): Promise -} -/** - * Opaque result-fetch handle returned by - * `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` - * directly; structurally analogous to the sync `Statement`'s - * fetch-side surface (`fetchNextBatch` / `schema` / - * `statementId`). - * - * `cancel()` / `close()` are not exposed: the parent - * `AsyncStatement` owns server-side lifecycle. A `close()` here - * would create dual-ownership of the same statement_id with - * inconsistent close semantics. Callers `close()` the parent - * `AsyncStatement` after they're done fetching. - * - * Schema is cached at construction so it survives the underlying - * stream being drained; mirrors the sync `Statement.schema()` - * post-close contract. - */ -export declare class AsyncResultHandle { - /** - * Server-issued statement id. Cached at construction; readable - * for log correlation. Matches the parent `AsyncStatement`'s - * `statementId`. - */ - get statementId(): string - /** - * Pull the next batch of results. Returns `null` when the - * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a - * complete Arrow IPC stream (schema header + 1 record-batch - * message), suitable for handing to `apache-arrow`'s - * `RecordBatchReader`. Byte-identical to the sync - * `Statement.fetchNextBatch()` payload for the same query. - */ - fetchNextBatch(): Promise - /** - * Result schema as an Arrow IPC payload (schema header only, - * no record-batch message). Available before any batches have - * been fetched. Sync because the body has no `.await` — - * `encode_ipc_stream` is pure CPU work over the cached - * `Arc`. - */ - schema(): ArrowSchema -} -/** - * Handle returned by `Connection.executeStatementCancellable`. Owns the - * built-but-not-yet-executed kernel `Statement` plus a detached - * [`StatementCanceller`] captured before dispatch, so JS can fire a - * server-side cancel while the blocking `result()` is in flight. - * - * `pending` is `Arc>>` so `result()` can - * `.take()` the statement (the kernel `execute()` borrows it `&mut`, - * then it moves into the produced `Statement` wrapper to keep its - * `ValidityFlag` set — see `statement.rs`). A second `result()` call - * after the first resolved surfaces `InvalidStatementHandle`. - */ -export declare class CancellableExecution { - /** - * The server-issued statement id this execution targets, if the - * server has issued one yet (`null` before the initial submit - * round-trip publishes it mid-`result()`). Useful for log - * correlation while the blocking drive is in flight. - */ - get statementId(): string | null - /** - * Drive the blocking `execute()` and resolve to a `Statement` - * (identical to what `executeStatement` returns) once the kernel - * reaches a terminal state and the result stream is ready. - * - * Consumes the pending statement: a second `result()` call returns - * `KernelError(InvalidStatementHandle)`. The future is - * drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState` - * guard fires a fire-and-forget `cancel_statement` if this future is - * dropped mid-flight (`Promise.race` / timeout loser), independently - * of an explicit `cancel()`. - * - * On a server-side cancel the kernel's blocking `execute()` currently - * surfaces `InvalidArgument` (a known kernel quirk — the async path - * returns `Cancelled`). When this handle's `cancel()` actually dispatched a - * server-side cancel, we normalise that into `Cancelled` here so JS callers - * can rely on a single cancelled-status code regardless of execution path. - * - * Three outcomes can race the blocking drive: (1) a natural terminal state - * → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a - * server cancel → this `result()` rejects with a `Cancelled`-coded error - * (the normalisation above); (3) the future being **dropped** mid-flight - * (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState` - * drop-guard fires a fire-and-forget `cancel_statement`, but there is no - * `result()` left to observe a code. Only (2) yields a `Cancelled` error. - */ - result(): Promise - /** - * Server-side cancel of the in-flight statement. - * - * Lock-free: fires the detached `StatementCanceller` captured at - * construction rather than taking the mutex `result()` holds, so it - * interrupts a still-running blocking `result()` instead of queueing - * behind it. No-op (returns `Ok`) if `result()` already finished - * successfully, or if no statement id has been observed yet (query still - * in its initial submit round-trip), and idempotent against a server - * already in a terminal state. - */ - cancel(): Promise -} -/** - * Opaque connection handle wrapping a kernel `Session`. - * - * `inner` is `Arc>>` so: - * - the Drop impl can clone the `Arc` and `.take()` the session on a - * background tokio task without holding `&mut self` (which Drop is - * forbidden from doing across an `await`), - * - `close()` can `.take()` the session to consume it for the kernel's - * move-by-value `Session::close(self)` signature. - * - * **Concurrency shape** — both `executeStatement` and - * `submitStatement` build the kernel `Statement` under `inner.lock()` - * and then RELEASE the guard before the wire call - * (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()` - * is `&self`-callable and only clones the session's internal `Arc`, so - * the built statement is independent of the guard. Concurrent - * `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore - * serialise only for the microsecond statement-build, not the network - * round-trip, and `close()` never blocks behind an in-flight execute or - * submit. See - * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. - */ -export declare class Connection { - /** - * Server-issued session id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate - * against kernel / server logs which key on the same id. - */ - get sessionId(): string - /** - * Execute a SQL statement and return a Statement handle that - * streams batches via `fetchNextBatch()`. - * - * Catalog / schema / sessionConf are session-level - * (`openSession`). Per-statement options on `ExecuteOptions`: - * - `statementConf` — per-statement Spark conf overlay - * - `queryTags` — serialised to a comma-separated `key:value` - * string and placed in `statement_conf["query_tags"]`, - * matching NodeJS Thrift's `serializeQueryTags` wire shape - * - * `options` is omitted/`None` for the no-options path; passing - * `{ statementConf: {} }` (an empty map) is treated the same as - * omission to keep the wire shape stable for the common case. - */ - executeStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise - /** - * directResults execute — the Thrift/JDBC model. Sends ExecuteStatement - * with no `wait_timeout` field (server applies its ~10s default inline wait - * and auto-closes on success) and returns WITHOUT polling past it: - * - * - a **`Statement`** (left arm) when the query finished within the inline - * wait — terminal, result ready inline, `close()` is a clean release; - * - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel - * handle the caller drives (`status()` / `awaitResult()` / `cancel()`). - * - * JS distinguishes the arms by feature-detecting `awaitResult` (present - * only on `AsyncStatement`). This is the path that gives mid-run cancel for - * long queries WITHOUT the eager-handle / close-drives workaround: the - * returned handle always corresponds to a server-owned statement. - * - * **Load-bearing contract:** the kernel's `DirectStatement::{Completed, - * Running}` discriminant cannot ride on these opaque `#[napi]` classes, so - * consumers MUST feature-detect via `awaitResult` (the only member unique to - * `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an - * `awaitResult` member, or every consumer silently misroutes. The pyo3 - * binding makes the same `await_result`-probe assumption. - */ - executeStatementDirect(sql: string, options?: ExecuteOptions | undefined | null): Promise - /** - * Execute a SQL statement on the blocking (sync) path, but return a - * `CancellableExecution` handle so a concurrent JS task can cancel - * the query *while it is still running server-side*. - * - * `executeStatement` builds the kernel `Statement`, awaits the - * blocking `execute()`, and only then hands JS a `Statement` — so a - * query that runs for several seconds is uncancellable from JS on - * that path (there is no handle until the blocking call resolves). - * This method instead builds the statement, captures a detached - * `StatementCanceller` **before** dispatching `execute()`, and hands - * JS a `CancellableExecution` immediately. The caller drives the - * blocking execution via `result()` (resolves to the same - * `Statement` `executeStatement` returns) and can fire `cancel()` - * concurrently to interrupt a still-running query mid-COMPUTE. - * - * Option semantics are identical to `executeStatement`. - * Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` - * split (PR #121): obtain the canceller before the blocking drive. - */ - executeStatementCancellable(sql: string, options?: ExecuteOptions | undefined | null): Promise - /** - * Submit a SQL statement and return immediately with an - * `AsyncStatement` handle, without blocking until the query - * finishes. The kernel's `Statement::submit()` sends - * `wait_timeout=0s`, so the server responds as soon as it has a - * `statement_id` (state `Pending`/`Running`); JS drives polling - * via `AsyncStatement.status()` and materialises results with - * `AsyncStatement.awaitResult()`. - * - * This is the async-execution path the Thrift backend always - * uses (`runAsync: true`): the SEA backend submits, returns a - * pending operation handle, and polls to terminal during - * fetch. Option semantics (statementConf / queryTags / - * rowLimit / positional + named params) match `executeStatement`. - * Submit always sends `wait_timeout=0s` so the call returns - * immediately; the caller drives completion via `status()` / - * `awaitResult()`. Only the blocking-vs-pending return contract - * differs from `executeStatement`. - */ - submitStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise - /** - * Explicit close. Awaits the server-side `DeleteSession` so the - * JS caller can observe failures (auth revoked mid-session, - * warehouse stopped, network error). Idempotent — a second call - * on an already-closed connection returns `Ok`. - * - * **Errors are terminal from the JS side.** The kernel session - * handle is consumed (`take()`) BEFORE the wire `DeleteSession` - * runs, because `Session::close` takes `self` by value. On `Err`, - * the napi `inner` is already `None`, so a JS-side retry sees a - * closed connection and returns `Ok(())` without re-attempting - * the wire call. The kernel's own `Drop` fire-and-forget retry - * runs once in the background — the JS caller can log the error - * but cannot drive a retry. If you need retry-on-failure - * semantics for `DeleteSession`, layer them above this method. - */ - close(): Promise - /** - * All catalogs visible to the session. - * - * JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. - */ - listCatalogs(): Promise - /** - * Schemas filtered by catalog (exact) and schema name pattern. - * - * JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. - */ - listSchemas(catalog?: string | undefined | null, schemaPattern?: string | undefined | null): Promise - /** - * Tables filtered by catalog (exact), schema (pattern), table (pattern). - * - * JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, - * filters rows by `TABLE_TYPE` kernel-side. - * - * `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does - * NOT honour the table-type filter server-side; the kernel applies - * it client-side after the result returns. Callers expecting - * server-side rejection of off-type tables should not rely on this. - */ - listTables(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, tableTypes?: Array | undefined | null): Promise - /** - * Columns of tables matching the filter. - * - * JDBC `getColumns` shape: 23 columns. - */ - listColumns(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, columnPattern?: string | undefined | null): Promise - /** - * Functions visible to the session. `catalog` is exact; - * `schemaPattern` and `functionPattern` are SQL LIKE. - */ - listFunctions(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, functionPattern?: string | undefined | null): Promise - /** - * Procedures visible to the session. `catalog` is exact; - * `schemaPattern` and `procedurePattern` are SQL LIKE. - */ - listProcedures(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, procedurePattern?: string | undefined | null): Promise - /** - * All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). - * No wire call — static in-memory result. - */ - listTableTypes(): Promise - /** - * SQL data types supported by the workspace. - * No wire call — static in-memory result. - */ - listTypeInfo(): Promise - /** - * Primary keys for the given table. All three identifiers are - * exact — ODBC `SQLPrimaryKeys` does not support patterns. - */ - getPrimaryKeys(catalog: string, schema: string, table: string): Promise - /** - * Foreign-key relationships. The foreign side must be fully - * specified (catalog + schema + table); the parent side is - * optional. All identifiers are exact — no LIKE patterns. - */ - getCrossReference(parentCatalog: string | undefined | null, parentSchema: string | undefined | null, parentTable: string | undefined | null, foreignCatalog: string, foreignSchema: string, foreignTable: string): Promise -} -/** - * Opaque executed-statement handle. - * - * **Current concurrency shape** — every method takes `inner.lock()` - * and holds the guard across the kernel `.await`. tokio `Mutex` is - * FIFO, so cancel/close queue behind any in-flight `fetchNextBatch` - * until it returns naturally. This is a known limitation that exists - * because the napi shape has not yet been split into an - * `Arc` (for cancel/close, which the - * kernel exposes as `&self`-callable) plus a `Mutex>` only - * for the borrowed-mut fetch path. The lock-shape refactor needs a - * small kernel-side accessor and lands in a follow-up PR — see - * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. - * - * `schema` and `statement_id` are cached at construction so they - * survive `close()` — JS callers building error reports against a - * disposed statement can still read them. - */ -export declare class Statement { - /** - * Server-issued statement id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate against - * kernel / server logs which key on the same id. - */ - get statementId(): string - /** - * Number of rows modified by the statement (UPDATE / INSERT / - * DELETE / MERGE). `null` for SELECT and on warehouses that don't - * surface the counter. Mirrors Thrift's - * `TGetOperationStatusResp.numModifiedRows`. - */ - numModifiedRows(): Promise - /** - * Server-supplied user-facing message. Mirrors Thrift's - * `TGetOperationStatusResp.displayMessage`. **PII / sensitive- - * data note:** may contain SQL fragments or parameter values — - * redact before centralised logging. - * - * Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`). - * On terminal-error states (`Failed` / `Cancelled`) the kernel returns - * an Error instead of a `Statement`, and the same field rides on the JS - * Error envelope under the same `displayMessage` key. - */ - displayMessage(): Promise - /** - * Server-supplied diagnostic detail — multi-line operator / - * stack context. Mirrors Thrift's - * `TGetOperationStatusResp.diagnosticInfo`. For support surfaces, - * not user-facing. Same reachability + PII caveats as - * `displayMessage`. - */ - diagnosticInfo(): Promise - /** - * Server-supplied JSON blob with extended error details. Mirrors - * Thrift's `TGetOperationStatusResp.errorDetailsJson`. - * Pass-through string — JS callers parse with `JSON.parse` if - * they need structured access. - * - * **Server-side gating:** populated only when the workspace has - * `spark.databricks.sql.errorDetailsJson.enabled = true` on the - * underlying SQL cluster. The flag is internal-only / default- - * false in the Databricks runtime, so for most JS callers this - * will return `null`. Admin-enabled workspaces return content - * shaped like `{"errorClass": "...", "messageTemplate": "..."}`. - * - * **Unbounded:** when populated, server can return a multi-MB - * blob; size before logging. - */ - errorDetailsJson(): Promise - /** - * Pull the next batch of results. Returns `null` when the stream - * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete - * Arrow IPC stream (schema header + 1 record-batch message) - * suitable for handing to `apache-arrow`'s `RecordBatchReader`. - * - * On `Err`, the stream is in an unspecified state — call - * `close()` and discard the `Statement`. Subsequent - * `fetchNextBatch()` calls after an error are not guaranteed to - * succeed or fail consistently. - */ - fetchNextBatch(): Promise - /** - * Result schema as an Arrow IPC payload (schema header only, no - * record-batch message). Available before any batches have been - * fetched, and remains available after `close()` — the kernel - * materialises the schema eagerly so JS callers can build error - * reports against a disposed statement. - * - * Sync because the body has no `.await` — `encode_ipc_stream` is - * pure CPU work over an `Arc` already cached on the - * wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync). - * napi-rs converts a panic in a sync `#[napi]` entry point into a - * thrown JS error via its own macro-expanded boundary, so the - * `util::guarded` `catch_unwind` wrapper that the `async fn` - * entry points use is not required for this method. - */ - schema(): ArrowSchema - /** - * Server-side cancel. - * - * For executed statements: short-circuits to `Ok(())` if - * `fetchNextBatch` has already returned `null` (stream - * naturally exhausted) — matches the JDBC `Statement.cancel()` - * no-op-after-completion contract, so JS callers can fire cancel - * defensively without distinguishing "real cancel" from "raced - * with natural completion." - * - * For metadata streams: no-op (the kernel has no in-flight - * cancellation surface for metadata calls today). - * - * Returns `KernelError(InvalidStatementHandle)` if the statement - * has been explicitly `close()`d. - */ - cancel(): Promise - /** - * Explicit close. - * - * For executed statements: awaits the server-side `CloseStatement` - * so the JS caller can observe failures (auth revoked mid-session, - * network error, server-side error). Idempotent — a second call - * on an already-closed statement returns `Ok`. - * - * **Errors are terminal from the JS side.** The kernel executed - * handle is taken out of `inner` BEFORE the wire `CloseStatement` - * runs (so `Drop` knows there's nothing left to clean up). On - * `Err`, the napi `inner` is already `None`, so a JS-side retry - * sees a closed statement and returns `Ok(())` without re- - * attempting the wire call. The kernel-level `ExecutedStatement` - * has been consumed at that point and the value is dropped on - * the way out of the closure — the kernel's `ExecutedStatement:: - * Drop` then fires-and-forgets a single retry on the captured - * runtime. The JS caller can log the error but cannot drive a - * further retry. If you need retry-on-failure semantics for - * `CloseStatement`, layer them above this method. - * - * For metadata streams: drops the stream (no server round-trip - * needed — metadata results have no in-flight server-side - * resource to release). - */ - close(): Promise -} diff --git a/napi/index.js b/napi/index.js index ad50ecc9..45ea1ec8 100644 --- a/napi/index.js +++ b/napi/index.js @@ -1,325 +1,713 @@ -/* tslint:disable */ +// prettier-ignore /* eslint-disable */ -/* prettier-ignore */ - +// @ts-nocheck /* auto-generated by NAPI-RS */ -const { existsSync, readFileSync } = require('fs') -const { join } = require('path') +const { readFileSync } = require('fs') +let nativeBinding = null +const loadErrors = [] -const { platform, arch } = process +const isMusl = () => { + let musl = false + if (process.platform === 'linux') { + musl = isMuslFromFilesystem() + if (musl === null) { + musl = isMuslFromReport() + } + if (musl === null) { + musl = isMuslFromChildProcess() + } + } + return musl +} -let nativeBinding = null -let localFileExisted = false -let loadError = null +const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') -function isMusl() { - // For Node 10 - if (!process.report || typeof process.report.getReport !== 'function') { - try { - const lddPath = require('child_process').execSync('which ldd').toString().trim() - return readFileSync(lddPath, 'utf8').includes('musl') - } catch (e) { +const isMuslFromFilesystem = () => { + try { + return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') + } catch { + return null + } +} + +const isMuslFromReport = () => { + let report = null + if (process.report && typeof process.report.getReport === 'function') { + process.report.excludeNetwork = true + report = process.report.getReport() + } + if (!report) { + return null + } + if (report.header && report.header.glibcVersionRuntime) { + return false + } + if (Array.isArray(report.sharedObjects)) { + if (report.sharedObjects.some(isFileMusl)) { return true } - } else { - const { glibcVersionRuntime } = process.report.getReport().header - return !glibcVersionRuntime } + return false } -switch (platform) { - case 'android': - switch (arch) { - case 'arm64': - localFileExisted = existsSync(join(__dirname, 'index.android-arm64.node')) +const isMuslFromChildProcess = () => { + try { + return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl') + } catch (e) { + // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false + return false + } +} + +function requireNative() { + if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) { + try { + return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH); + } catch (err) { + loadErrors.push(err) + } + } else if (process.platform === 'android') { + if (process.arch === 'arm64') { + try { + return require('./index.android-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-android-arm64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-android-arm64/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./index.android-arm-eabi.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-android-arm-eabi') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-android-arm-eabi/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`)) + } + } else if (process.platform === 'win32') { + if (process.arch === 'x64') { + if ((process.config && process.config.variables && process.config.variables.shlib_suffix === 'dll.a') || (process.config && process.config.variables && process.config.variables.node_target_type === 'shared_library')) { try { - if (localFileExisted) { - nativeBinding = require('./index.android-arm64.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-android-arm64') - } + return require('./index.win32-x64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-win32-x64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-x64-gnu/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./index.win32-x64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-win32-x64-msvc') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-x64-msvc/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ia32') { + try { + return require('./index.win32-ia32-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-win32-ia32-msvc') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-ia32-msvc/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./index.win32-arm64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-win32-arm64-msvc') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-arm64-msvc/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`)) + } + } else if (process.platform === 'darwin') { + try { + return require('./index.darwin-universal.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-darwin-universal') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-universal/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + if (process.arch === 'x64') { + try { + return require('./index.darwin-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-darwin-x64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-x64/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./index.darwin-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-darwin-arm64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-arm64/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`)) + } + } else if (process.platform === 'freebsd') { + if (process.arch === 'x64') { + try { + return require('./index.freebsd-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-freebsd-x64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-freebsd-x64/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./index.freebsd-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-freebsd-arm64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-freebsd-arm64/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`)) + } + } else if (process.platform === 'linux') { + if (process.arch === 'x64') { + if (isMusl()) { + try { + return require('./index.linux-x64-musl.node') } catch (e) { - loadError = e + loadErrors.push(e) } - break - case 'arm': - localFileExisted = existsSync(join(__dirname, 'index.android-arm-eabi.node')) try { - if (localFileExisted) { - nativeBinding = require('./index.android-arm-eabi.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-android-arm-eabi') + const binding = require('@databricks/databricks-sql-kernel-linux-x64-musl') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-x64-musl/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding } catch (e) { - loadError = e + loadErrors.push(e) } - break - default: - throw new Error(`Unsupported architecture on Android ${arch}`) - } - break - case 'win32': - switch (arch) { - case 'x64': - localFileExisted = existsSync( - join(__dirname, 'index.win32-x64-msvc.node') - ) + } else { try { - if (localFileExisted) { - nativeBinding = require('./index.win32-x64-msvc.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-win32-x64-msvc') - } + return require('./index.linux-x64-gnu.node') } catch (e) { - loadError = e + loadErrors.push(e) } - break - case 'ia32': - localFileExisted = existsSync( - join(__dirname, 'index.win32-ia32-msvc.node') - ) try { - if (localFileExisted) { - nativeBinding = require('./index.win32-ia32-msvc.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-win32-ia32-msvc') + const binding = require('@databricks/databricks-sql-kernel-linux-x64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-x64-gnu/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding } catch (e) { - loadError = e + loadErrors.push(e) } - break - case 'arm64': - localFileExisted = existsSync( - join(__dirname, 'index.win32-arm64-msvc.node') - ) + } + } else if (process.arch === 'arm64') { + if (isMusl()) { try { - if (localFileExisted) { - nativeBinding = require('./index.win32-arm64-msvc.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-win32-arm64-msvc') + return require('./index.linux-arm64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-arm64-musl') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm64-musl/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding } catch (e) { - loadError = e + loadErrors.push(e) } - break - default: - throw new Error(`Unsupported architecture on Windows: ${arch}`) - } - break - case 'darwin': - localFileExisted = existsSync(join(__dirname, 'index.darwin-universal.node')) - try { - if (localFileExisted) { - nativeBinding = require('./index.darwin-universal.node') } else { - nativeBinding = require('@databricks/databricks-sql-kernel-darwin-universal') - } - break - } catch {} - switch (arch) { - case 'x64': - localFileExisted = existsSync(join(__dirname, 'index.darwin-x64.node')) try { - if (localFileExisted) { - nativeBinding = require('./index.darwin-x64.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-darwin-x64') - } + return require('./index.linux-arm64-gnu.node') } catch (e) { - loadError = e + loadErrors.push(e) } - break - case 'arm64': - localFileExisted = existsSync( - join(__dirname, 'index.darwin-arm64.node') - ) try { - if (localFileExisted) { - nativeBinding = require('./index.darwin-arm64.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-darwin-arm64') + const binding = require('@databricks/databricks-sql-kernel-linux-arm64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm64-gnu/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding } catch (e) { - loadError = e + loadErrors.push(e) } - break - default: - throw new Error(`Unsupported architecture on macOS: ${arch}`) - } - break - case 'freebsd': - if (arch !== 'x64') { - throw new Error(`Unsupported architecture on FreeBSD: ${arch}`) - } - localFileExisted = existsSync(join(__dirname, 'index.freebsd-x64.node')) - try { - if (localFileExisted) { - nativeBinding = require('./index.freebsd-x64.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-freebsd-x64') } - } catch (e) { - loadError = e - } - break - case 'linux': - switch (arch) { - case 'x64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'index.linux-x64-musl.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-x64-musl.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-x64-musl') - } - } catch (e) { - loadError = e - } - } else { - localFileExisted = existsSync( - join(__dirname, 'index.linux-x64-gnu.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-x64-gnu.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-x64-gnu') - } - } catch (e) { - loadError = e + } else if (process.arch === 'arm') { + if (isMusl()) { + try { + return require('./index.linux-arm-musleabihf.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./index.linux-arm-gnueabihf.node') + } catch (e) { + loadErrors.push(e) } - break - case 'arm64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'index.linux-arm64-musl.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-arm64-musl.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm64-musl') - } - } catch (e) { - loadError = e + try { + const binding = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } - } else { - localFileExisted = existsSync( - join(__dirname, 'index.linux-arm64-gnu.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-arm64-gnu.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm64-gnu') - } - } catch (e) { - loadError = e + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'loong64') { + if (isMusl()) { + try { + return require('./index.linux-loong64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-loong64-musl') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-loong64-musl/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding + } catch (e) { + loadErrors.push(e) } - break - case 'arm': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'index.linux-arm-musleabihf.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-arm-musleabihf.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf') - } - } catch (e) { - loadError = e + } else { + try { + return require('./index.linux-loong64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-loong64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-loong64-gnu/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } - } else { - localFileExisted = existsSync( - join(__dirname, 'index.linux-arm-gnueabihf.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-arm-gnueabihf.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf') - } - } catch (e) { - loadError = e + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'riscv64') { + if (isMusl()) { + try { + return require('./index.linux-riscv64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-riscv64-musl') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-riscv64-musl/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding + } catch (e) { + loadErrors.push(e) } - break - case 'riscv64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'index.linux-riscv64-musl.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-riscv64-musl.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-riscv64-musl') - } - } catch (e) { - loadError = e + } else { + try { + return require('./index.linux-riscv64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } - } else { - localFileExisted = existsSync( - join(__dirname, 'index.linux-riscv64-gnu.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-riscv64-gnu.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu') - } - } catch (e) { - loadError = e + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ppc64') { + try { + return require('./index.linux-ppc64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-ppc64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-ppc64-gnu/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 's390x') { + try { + return require('./index.linux-s390x-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-s390x-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-s390x-gnu/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`)) + } + } else if (process.platform === 'openharmony') { + if (process.arch === 'arm64') { + try { + return require('./index.openharmony-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-openharmony-arm64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-arm64/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'x64') { + try { + return require('./index.openharmony-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-openharmony-x64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-x64/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./index.openharmony-arm.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-openharmony-arm') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-arm/package.json').version + if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`)) + } + } else { + loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`)) + } +} + +function createLoadErrorChain(errors) { + return errors.reduce((previous, current) => { + let message + try { + message = + current && typeof current.message === 'string' + ? current.message + : String(current) + } catch { + message = 'Unknown error' + } + const error = new Error(message) + error.cause = previous + return error + }, null) +} + +// NAPI_RS_FORCE_WASI is a tri-state flag: +// unset / any other value → native binding preferred, WASI is only a fallback +// 'true' → prefer WASI, but retain native as a lazy fallback +// 'error' → require WASI without initializing a native fallback +// Treating any non-empty string as truthy (the historical behavior) meant +// NAPI_RS_FORCE_WASI=false, NAPI_RS_FORCE_WASI=0, etc. inadvertently triggered +// the WASI path, causing ENOENT for packages shipped without a .wasi.cjs file. +// +// NAPI_RS_WASI_FLAVOR selects one exact generated flavor and implies strict +// WASI loading. It never crosses into another flavor or falls back to native. +const __napiWasiFlavors = ["wasm32-wasi"] +const __napiWasiFlavor = process.env.NAPI_RS_WASI_FLAVOR +const __napiWasiFlavorRequested = + typeof __napiWasiFlavor === 'string' && __napiWasiFlavor.length > 0 +if ( + __napiWasiFlavorRequested && + __napiWasiFlavors.indexOf(__napiWasiFlavor) === -1 +) { + throw new Error( + 'Unsupported WASI flavor "' + + __napiWasiFlavor + + '". Available flavors: ' + + __napiWasiFlavors.join(', '), + ) +} +const forceWasiError = process.env.NAPI_RS_FORCE_WASI === 'error' +const forceWasi = + process.env.NAPI_RS_FORCE_WASI === 'true' || + forceWasiError || + __napiWasiFlavorRequested + +if (!forceWasi) { + nativeBinding = requireNative() +} + +if (!nativeBinding || forceWasi) { + let wasiBinding = null + let wasiBindingLoaded = false + const wasiBindingErrors = [] + const __napiWasiResolveCandidate = (specifier, isPackage, localArtifacts) => { + try { + require.resolve(specifier) + } catch (resolveError) { + if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { + throw resolveError + } + if (isPackage) { + try { + require.resolve(specifier + '/package.json') + } catch (packageError) { + if (packageError && packageError.code === 'MODULE_NOT_FOUND') { + return resolveError } + // An exports restriction proves the package exists even when its + // package.json is not public. Preserve the root resolution failure. + throw resolveError } - break - case 's390x': - localFileExisted = existsSync( - join(__dirname, 'index.linux-s390x-gnu.node') - ) + // The package exists but its main/export target is broken. + throw resolveError + } + return resolveError + } + if (localArtifacts) { + let artifactError = null + for (let i = 0; i < localArtifacts.length; i++) { try { - if (localFileExisted) { - nativeBinding = require('./index.linux-s390x-gnu.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-s390x-gnu') + require.resolve(localArtifacts[i]) + return null + } catch (resolveError) { + if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { + throw resolveError + } + artifactError = resolveError + } + } + return artifactError + } + return null + } + if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) { + let candidateError = null + let candidateFailed = false + try { + candidateError = __napiWasiResolveCandidate('./index.wasi.cjs', false, ["./index.wasm32-wasi.debug.wasm","./index.wasm32-wasi.wasm"]) + candidateFailed = candidateError !== null + if (!candidateFailed) { + wasiBinding = require('./index.wasi.cjs') + nativeBinding = wasiBinding + wasiBindingLoaded = true + } + } catch (err) { + candidateError = err + candidateFailed = true + } + if (candidateFailed) { + wasiBindingErrors.push(candidateError) + loadErrors.push(candidateError) + } + } + if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) { + let candidateError = null + let candidateFailed = false + try { + candidateError = __napiWasiResolveCandidate('@databricks/databricks-sql-kernel-wasm32-wasi', true, undefined) + candidateFailed = candidateError !== null + if (!candidateFailed) { + if (process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-wasm32-wasi/package.json').version + if (bindingPackageVersion !== '0.2.0') { + throw new Error(`WASI binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } - } catch (e) { - loadError = e } - break - default: - throw new Error(`Unsupported architecture on Linux: ${arch}`) + wasiBinding = require('@databricks/databricks-sql-kernel-wasm32-wasi') + nativeBinding = wasiBinding + wasiBindingLoaded = true + } + } catch (err) { + candidateError = err + candidateFailed = true } - break - default: - throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`) + if (candidateFailed) { + wasiBindingErrors.push(candidateError) + loadErrors.push(candidateError) + } + } + if ( + !wasiBindingLoaded && + forceWasi && + !forceWasiError && + !__napiWasiFlavorRequested + ) { + nativeBinding = requireNative() + } + if ((forceWasiError || __napiWasiFlavorRequested) && !wasiBindingLoaded) { + const error = new Error( + __napiWasiFlavorRequested + ? 'WASI binding for flavor "' + __napiWasiFlavor + '" not found' + : 'WASI binding not found and NAPI_RS_FORCE_WASI is set to error', + ) + error.cause = createLoadErrorChain(wasiBindingErrors) + throw error + } } if (!nativeBinding) { - if (loadError) { - throw loadError + if (loadErrors.length > 0) { + const error = new Error( + `Cannot find native binding. ` + + `npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` + + 'Please try `npm i` again after removing both package-lock.json and node_modules directory.', + ) + // assign instead of the `new Error(message, { cause })` options form, + // which Node < 16.9 silently ignores + error.cause = createLoadErrorChain(loadErrors) + throw error } throw new Error(`Failed to load native binding`) } -const { AsyncStatement, AsyncResultHandle, CancellableExecution, Connection, AuthMode, openSession, initKernelLogging, kernelLoggingStats, setKernelLogLevel, Statement, version } = nativeBinding - -module.exports.AsyncStatement = AsyncStatement -module.exports.AsyncResultHandle = AsyncResultHandle -module.exports.CancellableExecution = CancellableExecution -module.exports.Connection = Connection -module.exports.AuthMode = AuthMode -module.exports.openSession = openSession -module.exports.initKernelLogging = initKernelLogging -module.exports.kernelLoggingStats = kernelLoggingStats -module.exports.setKernelLogLevel = setKernelLogLevel -module.exports.Statement = Statement -module.exports.version = version +module.exports = nativeBinding +module.exports.AsyncResultHandle = nativeBinding.AsyncResultHandle +module.exports.AsyncStatement = nativeBinding.AsyncStatement +module.exports.CancellableExecution = nativeBinding.CancellableExecution +module.exports.Connection = nativeBinding.Connection +module.exports.Statement = nativeBinding.Statement +module.exports.AuthMode = nativeBinding.AuthMode +module.exports.initKernelLogging = nativeBinding.initKernelLogging +module.exports.kernelLoggingStats = nativeBinding.kernelLoggingStats +module.exports.openSession = nativeBinding.openSession +module.exports.setKernelLogLevel = nativeBinding.setKernelLogLevel +module.exports.version = nativeBinding.version diff --git a/napi/src/database.rs b/napi/src/database.rs index 32bc1dd4..e00e396f 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -33,10 +33,14 @@ use napi::bindgen_prelude::Buffer; #[cfg(test)] type Buffer = Vec; +use databricks_sql_kernel::auth::oauth::persistence::TokenPersistence; +use databricks_sql_kernel::auth::oauth::OAuthToken; use databricks_sql_kernel::{ AuthConfig, DefaultOpts, DriverSystemConfiguration, Error as KernelError, HttpConfig, ProxyConfig, ResultConfig, Session, TelemetryConfig, TlsConfig, }; +use napi::bindgen_prelude::Promise; +use napi::threadsafe_function::ThreadsafeFunction; /// NodeJS-driver-appropriate default for `pool_max_idle_per_host`. /// @@ -437,9 +441,118 @@ pub struct ConnectionOptions { /// kernel's validating constructors ([`AuthConfig::pat`] / /// [`AuthConfig::oauth_m2m`]); this binding just forwards the JS /// optionals and maps any kernel `InvalidArgument` onto a napi error. +/// `#[napi(object)]` argument for the persist callback: the workspace host +/// plus the kernel's serialized `OAuthToken` (JSON). The token crosses the +/// boundary as an opaque JSON string — the exact bytes the on-disk cache would +/// store — so the full token (including expiry) round-trips losslessly through +/// the caller's store. +#[napi(object)] +pub struct KernelPersistArgs { + /// Workspace host the token is scoped to (the store's key). + pub host: String, + /// The kernel's `OAuthToken` serialized as JSON. Opaque to the caller. + pub token_json: String, +} + +/// JS `read(host) => Promise` — returns the kernel- +/// serialized token JSON, or `undefined`/`null` on a miss. `CalleeHandled = +/// false` so the JS callback receives a bare `host` (not the Node error-first +/// `(err, host)` shape). +type ReadTsfn = + ThreadsafeFunction>, String, napi::Status, false>; +/// JS `persist({ host, tokenJson }) => Promise`. +type PersistTsfn = ThreadsafeFunction< + KernelPersistArgs, + Promise<()>, + KernelPersistArgs, + napi::Status, + false, +>; + +/// [`TokenPersistence`] backed by two JS callbacks (via `ThreadsafeFunction`), +/// installed when the caller supplies an `OAuthPersistence` on the kernel path. +/// `load`/`save` invoke the JS store and await its returned `Promise`. +struct NapiTokenStore { + read: ReadTsfn, + persist: PersistTsfn, +} + +impl std::fmt::Debug for NapiTokenStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // `ThreadsafeFunction` is not `Debug`; the kernel only needs a name + // here (the field is behind `Arc` in `Debug` + // output). + f.write_str("NapiTokenStore") + } +} + +/// Map a napi callback failure into a kernel error. Per the +/// [`TokenPersistence`] contract the kernel logs and swallows these (load → +/// cache miss, save → warn), so the category is informational. +fn kernel_err_from_napi(e: napi::Error) -> KernelError { + KernelError::io().message(format!("OAuth token store callback failed: {e}")) +} + +#[async_trait::async_trait] +impl TokenPersistence for NapiTokenStore { + async fn load( + &self, + host: &str, + _client_id: &str, + _scopes: &[String], + ) -> databricks_sql_kernel::Result> { + // Two awaits: `call_async` schedules the JS call and resolves once the + // JS function *returns* (a Promise); the second await resolves that + // Promise to the token JSON. + let promise = self + .read + .call_async(host.to_string()) + .await + .map_err(kernel_err_from_napi)?; + let maybe_json: Option = promise.await.map_err(kernel_err_from_napi)?; + match maybe_json { + Some(json) => { + let token: OAuthToken = serde_json::from_str(&json).map_err(|e| { + KernelError::invalid_state() + .message(format!("token store returned malformed token JSON: {e}")) + })?; + Ok(Some(token)) + } + None => Ok(None), + } + } + + async fn save( + &self, + host: &str, + _client_id: &str, + _scopes: &[String], + token: &OAuthToken, + ) -> databricks_sql_kernel::Result<()> { + let token_json = serde_json::to_string(token).map_err(|e| { + KernelError::invalid_state().message(format!("failed to serialize OAuth token: {e}")) + })?; + let args = KernelPersistArgs { + host: host.to_string(), + token_json, + }; + let promise = self + .persist + .call_async(args) + .await + .map_err(kernel_err_from_napi)?; + promise.await.map_err(kernel_err_from_napi)?; + Ok(()) + } +} + /// Pure (borrows `options`) so it is unit-testable without opening a -/// session. -fn build_auth_config(options: &ConnectionOptions) -> napi::Result { +/// session. `token_store`, when `Some`, is threaded into the U2M arm as the +/// caller-supplied [`TokenPersistence`] (other arms ignore it). +fn build_auth_config( + options: &ConnectionOptions, + token_store: Option>, +) -> napi::Result { match options.auth_mode.unwrap_or_default() { AuthMode::Pat => AuthConfig::pat( options.token.clone(), @@ -500,10 +613,13 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { None, // `None` takes the kernel default: on-disk cache enabled, // encrypted under a machine-local derived key since this - // binding exposes no passphrase option. Surfacing one through - // `options` would strengthen it further. + // binding exposes no passphrase option. Ignored when + // `token_store` below is `Some`. None, options.identity_federation_client_id.clone(), + // Caller-supplied JS token store (`OAuthPersistence`), when the + // driver passed the persistence callbacks to `openSession`. + token_store, )) } // Azure Entra service-principal M2M. The kernel owns Azure @@ -722,7 +838,20 @@ fn build_driver_system_configuration( reason = "exported via napi macro codegen; not called from Rust" )] #[napi] -pub async fn open_session(mut options: ConnectionOptions) -> napi::Result { +pub async fn open_session( + mut options: ConnectionOptions, + // Optional pluggable OAuth token store (U2M only). Both callbacks must be + // supplied together; when present they override the built-in disk cache. + // The driver adapts its `OAuthPersistence` object into these two functions. + // Types are inlined (not the `ReadTsfn`/`PersistTsfn` aliases) so napi-rs + // emits a concrete TS function signature rather than a dangling alias name. + oauth_persistence_read: Option< + ThreadsafeFunction>, String, napi::Status, false>, + >, + oauth_persistence_persist: Option< + ThreadsafeFunction, KernelPersistArgs, napi::Status, false>, + >, +) -> napi::Result { guarded(async move { // Cache the napi-rs tokio Handle on the very first async call // so Drop impls (which run on the V8 GC thread, outside any @@ -730,9 +859,19 @@ pub async fn open_session(mut options: ConnectionOptions) -> napi::Result> = + match (oauth_persistence_read, oauth_persistence_persist) { + (Some(read), Some(persist)) => { + Some(Arc::new(NapiTokenStore { read, persist }) as Arc) + } + _ => None, + }; + // Resolve auth before the builder moves `host_name` / `http_path` // out of `options` (validation can fail fast, before any network). - let auth_config = build_auth_config(&options)?; + let auth_config = build_auth_config(&options, token_store)?; // Build the TLS config before the builder moves fields out of // `options`. Always wired (even at defaults) because the // permissive-by-default stance needs the relaxation flags set — @@ -907,12 +1046,12 @@ mod tests { // No authMode + no token → fail-fast InvalidArgument from the // kernel `AuthConfig::pat` ctor. assert_invalid_arg( - build_auth_config(&o).unwrap_err(), + build_auth_config(&o, None).unwrap_err(), "requires a non-empty access token", ); o.token = Some("dapi-xxx".to_owned()); assert!(matches!( - build_auth_config(&o).unwrap(), + build_auth_config(&o, None).unwrap(), AuthConfig::Pat { .. } )); } @@ -928,7 +1067,7 @@ mod tests { o.azure_tenant_id = Some("tenant-abc".to_owned()); o.azure_workspace_resource_id = Some("/subscriptions/s/resourceGroups/rg/workspace/w".to_owned()); - match build_auth_config(&o).unwrap() { + match build_auth_config(&o, None).unwrap() { AuthConfig::AzureServicePrincipal { azure_client_id, azure_client_secret, @@ -956,7 +1095,7 @@ mod tests { o.auth_mode = Some(AuthMode::AzureSpM2m); o.azure_client_id = Some("entra-app-id".to_owned()); o.azure_client_secret = Some("entra-secret".to_owned()); - match build_auth_config(&o).unwrap() { + match build_auth_config(&o, None).unwrap() { AuthConfig::AzureServicePrincipal { azure_tenant_id, azure_workspace_resource_id, @@ -976,12 +1115,12 @@ mod tests { let mut o = base(); o.auth_mode = Some(AuthMode::AzureSpM2m); o.azure_client_secret = Some("entra-secret".to_owned()); - assert_invalid_arg(build_auth_config(&o).unwrap_err(), "azure_client_id"); + assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "azure_client_id"); let mut o = base(); o.auth_mode = Some(AuthMode::AzureSpM2m); o.azure_client_id = Some("entra-app-id".to_owned()); - assert_invalid_arg(build_auth_config(&o).unwrap_err(), "azure_client_secret"); + assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "azure_client_secret"); } #[test] @@ -990,7 +1129,7 @@ mod tests { o.auth_mode = Some(AuthMode::Pat); o.token = Some(String::new()); assert_invalid_arg( - build_auth_config(&o).unwrap_err(), + build_auth_config(&o, None).unwrap_err(), "requires a non-empty access token", ); } @@ -1001,7 +1140,7 @@ mod tests { o.token = Some("dapi-xxx".to_owned()); o.identity_federation_client_id = Some("federation-client".to_owned()); - match build_auth_config(&o).unwrap() { + match build_auth_config(&o, None).unwrap() { AuthConfig::Pat { identity_federation_client_id, .. @@ -1026,7 +1165,7 @@ mod tests { m2m.oauth_client_id = Some("cid".to_owned()); m2m.oauth_client_secret = Some("sec".to_owned()); m2m.token_url = Some(endpoint.to_owned()); - match build_auth_config(&m2m).unwrap() { + match build_auth_config(&m2m, None).unwrap() { AuthConfig::OAuthM2M { token_url_override, .. } => assert_eq!(token_url_override.as_deref(), Some(endpoint)), @@ -1036,7 +1175,7 @@ mod tests { let mut u2m = base(); u2m.auth_mode = Some(AuthMode::OAuthU2m); u2m.token_url = Some(endpoint.to_owned()); - match build_auth_config(&u2m).unwrap() { + match build_auth_config(&u2m, None).unwrap() { AuthConfig::OAuthU2M { token_url_override, .. } => assert_eq!(token_url_override.as_deref(), Some(endpoint)), @@ -1049,7 +1188,7 @@ mod tests { jwt.jwt_key_file = Some("/k.pem".to_owned()); jwt.jwt_kid = Some("kid".to_owned()); jwt.token_url = Some(endpoint.to_owned()); - match build_auth_config(&jwt).unwrap() { + match build_auth_config(&jwt, None).unwrap() { AuthConfig::OAuthM2MPrivateKey { token_url_override, .. } => assert_eq!(token_url_override.as_deref(), Some(endpoint)), @@ -1061,7 +1200,7 @@ mod tests { none.auth_mode = Some(AuthMode::OAuthM2m); none.oauth_client_id = Some("cid".to_owned()); none.oauth_client_secret = Some("sec".to_owned()); - match build_auth_config(&none).unwrap() { + match build_auth_config(&none, None).unwrap() { AuthConfig::OAuthM2M { token_url_override, .. } => assert!(token_url_override.is_none()), @@ -1073,13 +1212,13 @@ mod tests { fn m2m_requires_client_id_and_secret() { let mut o = base(); o.auth_mode = Some(AuthMode::OAuthM2m); - assert_invalid_arg(build_auth_config(&o).unwrap_err(), "client_id"); + assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "client_id"); o.oauth_client_id = Some("cid".to_owned()); - assert_invalid_arg(build_auth_config(&o).unwrap_err(), "client_secret"); + assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "client_secret"); o.oauth_client_secret = Some("sec".to_owned()); o.oauth_scopes = Some(vec!["all-apis".to_owned()]); o.identity_federation_client_id = Some("federation-client".to_owned()); - match build_auth_config(&o).unwrap() { + match build_auth_config(&o, None).unwrap() { AuthConfig::OAuthM2M { client_id, client_secret, @@ -1103,18 +1242,18 @@ mod tests { fn m2m_jwt_requires_client_id_key_file_and_kid() { let mut o = base(); o.auth_mode = Some(AuthMode::OAuthM2mJwt); - assert_invalid_arg(build_auth_config(&o).unwrap_err(), "client_id"); + assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "client_id"); o.oauth_client_id = Some("cid".to_owned()); - assert_invalid_arg(build_auth_config(&o).unwrap_err(), "jwt_key_file"); + assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "jwt_key_file"); o.jwt_key_file = Some("/k.pem".to_owned()); - assert_invalid_arg(build_auth_config(&o).unwrap_err(), "jwt_kid"); + assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "jwt_kid"); o.jwt_kid = Some("kid".to_owned()); o.jwt_passphrase = Some("pass".to_owned()); o.jwt_algorithm = Some("ES256".to_owned()); o.oauth_scopes = Some(vec!["all-apis".to_owned()]); let token_url = "https://idp.example/token"; o.token_url = Some(token_url.to_owned()); - match build_auth_config(&o).unwrap() { + match build_auth_config(&o, None).unwrap() { AuthConfig::OAuthM2MPrivateKey { client_id, jwt_key_file, @@ -1145,7 +1284,7 @@ mod tests { // redirect_port are all None and the kernel fills its default bundle // (databricks-sql-connector / sql offline_access / 8030). See // PECOBLR-4039. - match build_auth_config(&o).unwrap() { + match build_auth_config(&o, None).unwrap() { AuthConfig::OAuthU2M { client_id, redirect_ports, @@ -1163,7 +1302,7 @@ mod tests { o.oauth_client_id = Some("custom-cli".to_owned()); o.oauth_redirect_port = Some(9000); o.identity_federation_client_id = Some("federation-client".to_owned()); - match build_auth_config(&o).unwrap() { + match build_auth_config(&o, None).unwrap() { AuthConfig::OAuthU2M { client_id, redirect_ports, @@ -1189,7 +1328,7 @@ mod tests { let mut o = base(); o.auth_mode = Some(AuthMode::OAuthU2m); o.oauth_client_id = Some(String::new()); - assert_invalid_arg(build_auth_config(&o).unwrap_err(), "oauthClientId"); + assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "oauthClientId"); } #[test] From 642747c4f593cfd5dbe953d6c8014d6383b67918 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Fri, 21 Aug 2026 19:17:59 -0700 Subject: [PATCH 03/10] feat(pyo3): pluggable OAuth token store via oauth_persistence (PECOBLR-4146) Thread the kernel's TokenPersistence through the Python binding so a caller can supply a custom OAuth U2M token store on the kernel path. - Session(...) gains an oauth_persistence kwarg: a Python object exposing read(host)->Optional[str] / persist(host, token_json). It is wrapped as a PyTokenStore (impl TokenPersistence) that calls the object under the GIL and exchanges the kernel OAuthToken as an opaque JSON string (lossless; the same bytes the disk cache stores; consistent with the napi binding). - Carried on OAuthParams.token_store so build_auth_config's signature and its GIL-less unit-testable inner stay unchanged; the U2M arm forwards it. - add async-trait + serde_json deps. The databricks-sql-python connector adapts its experimental_oauth_persistence onto this in a follow-up (#913). Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- pyo3/Cargo.lock | 2 + pyo3/Cargo.toml | 6 +++ pyo3/src/auth.rs | 98 ++++++++++++++++++++++++++++++++++++++++++++- pyo3/src/session.rs | 8 ++++ 4 files changed, 112 insertions(+), 2 deletions(-) diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index a0492194..c1a1d747 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -591,11 +591,13 @@ dependencies = [ "arrow-array", "arrow-pyarrow", "arrow-schema", + "async-trait", "chrono", "databricks-sql-kernel", "log", "pyo3", "pyo3-log", + "serde_json", "tokio", "tracing", ] diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml index 5a05c999..35b43e69 100644 --- a/pyo3/Cargo.toml +++ b/pyo3/Cargo.toml @@ -77,6 +77,12 @@ pyo3 = { version = "0.29", features = ["extension-module", "abi3-py39"] } # Multi-thread runtime — one per Session, owned on the Rust side. tokio = { version = "1", features = ["rt-multi-thread"] } +# Implement the kernel's `#[async_trait] TokenPersistence` for the Python-backed +# pluggable OAuth token store, and (de)serialize the kernel OAuthToken JSON that +# crosses to the Python `oauth_persistence` object (PECOBLR-4146). +async-trait = "0.1" +serde_json = "1" + # Arrow handoff. Pinned to 59 to match the kernel's arrow-* deps so we # share the same RecordBatch / Schema types and never have to convert. arrow-array = "59" diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index c846f9a0..ee183d10 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -41,9 +41,12 @@ //! wrapper rejects unknown `auth_type` values here so the mistake //! surfaces at construction time, not deep inside an HTTP retry loop. +use std::sync::Arc; use std::time::Duration; -use databricks_sql_kernel::AuthConfig; +use databricks_sql_kernel::auth::oauth::persistence::TokenPersistence; +use databricks_sql_kernel::auth::oauth::OAuthToken; +use databricks_sql_kernel::{AuthConfig, Error as KernelError}; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; @@ -83,6 +86,93 @@ pub(crate) struct OAuthParams { pub azure_client_secret: Option, pub azure_tenant_id: Option, pub azure_workspace_resource_id: Option, + /// Caller-supplied U2M token store (from the Python `oauth_persistence` + /// object), or `None` for the built-in disk cache. Carried here so it + /// flows through the existing `build_auth_config` plumbing without + /// changing that signature; the U2M arm forwards it to the kernel. See + /// [`py_token_store`]. + pub token_store: Option>, +} + +/// Wrap a Python `oauth_persistence` object as a kernel [`TokenPersistence`]. +/// +/// The object must expose `read(host: str) -> Optional[str]` and +/// `persist(host: str, token_json: str) -> None`, exchanging the kernel's +/// `OAuthToken` as an opaque JSON string — the same bytes the on-disk cache +/// stores, so the token (including expiry) round-trips losslessly. The +/// databricks-sql-python connector adapts its `experimental_oauth_persistence` +/// onto this. Consistent with the napi binding's JSON-string wire format. +pub(crate) fn py_token_store(obj: Py) -> Arc { + Arc::new(PyTokenStore { obj }) +} + +struct PyTokenStore { + obj: Py, +} + +impl std::fmt::Debug for PyTokenStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("PyTokenStore") + } +} + +#[async_trait::async_trait] +impl TokenPersistence for PyTokenStore { + async fn load( + &self, + host: &str, + _client_id: &str, + _scopes: &[String], + ) -> databricks_sql_kernel::Result> { + // Call the sync Python `read` under the GIL. No `.await` is held across + // the GIL, so the async future stays `Send`. The error string is + // produced inside the closure (formatting a `PyErr` needs the GIL). + let json: Option = + Python::attach(|py| -> std::result::Result, String> { + let obj = self.obj.bind(py); + let ret = obj + .call_method1("read", (host,)) + .map_err(|e| e.to_string())?; + if ret.is_none() { + Ok(None) + } else { + ret.extract::().map(Some).map_err(|e| e.to_string()) + } + }) + .map_err(|e| { + KernelError::io().message(format!("OAuth token store read failed: {e}")) + })?; + match json { + Some(s) => { + let token = serde_json::from_str::(&s).map_err(|e| { + KernelError::invalid_state() + .message(format!("token store returned malformed token JSON: {e}")) + })?; + Ok(Some(token)) + } + None => Ok(None), + } + } + + async fn save( + &self, + host: &str, + _client_id: &str, + _scopes: &[String], + token: &OAuthToken, + ) -> databricks_sql_kernel::Result<()> { + let json = serde_json::to_string(token).map_err(|e| { + KernelError::invalid_state().message(format!("failed to serialize OAuth token: {e}")) + })?; + Python::attach(|py| -> std::result::Result<(), String> { + let obj = self.obj.bind(py); + obj.call_method1("persist", (host, json)) + .map_err(|e| e.to_string())?; + Ok(()) + }) + .map_err(|e| KernelError::io().message(format!("OAuth token store persist failed: {e}")))?; + Ok(()) + } } /// Default U2M OAuth client id for the **Python** binding. @@ -327,9 +417,13 @@ fn build_auth_config_inner( // cross-connection SSO reuse (the point of the cache) without // ever writing the refresh token in the clear. Surfacing a // passphrase through `OAuthParams` — the equivalent of JDBC's - // TokenCachePassPhrase — would strengthen it further. + // TokenCachePassPhrase — would strengthen it further. Ignored + // when `token_store` below is `Some`. None, oauth.identity_federation_client_id, + // Caller-supplied Python token store (`oauth_persistence`), + // when provided; overrides the built-in disk cache above. + oauth.token_store, )) } "azure-sp-m2m" => { diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 7d95dabe..72e6585d 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -218,6 +218,7 @@ impl Session { azure_client_secret=None, azure_tenant_id=None, azure_workspace_resource_id=None, + oauth_persistence=None, tls_ca_cert=None, tls_skip_verify=false, tls_skip_hostname_verify=false, @@ -274,6 +275,10 @@ impl Session { azure_client_secret: Option, azure_tenant_id: Option, azure_workspace_resource_id: Option, + // Optional pluggable OAuth U2M token store (Python object with + // `read(host)->Optional[str]` / `persist(host, token_json)`); overrides + // the built-in disk cache. See `crate::auth::py_token_store`. + oauth_persistence: Option>, tls_ca_cert: Option>, tls_skip_verify: bool, tls_skip_hostname_verify: bool, @@ -347,6 +352,9 @@ impl Session { azure_client_secret, azure_tenant_id, azure_workspace_resource_id, + // Wrap a supplied Python persistence object as a kernel token store + // (U2M only; other auth types ignore it). + token_store: oauth_persistence.map(crate::auth::py_token_store), }; let auth_config = build_auth_config(&resolved_auth_type, access_token, oauth)?; From a48bb3a0b080c461418fdbcbc6095d480f29cfea Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Fri, 21 Aug 2026 19:20:25 -0700 Subject: [PATCH 04/10] style(napi): apply rustfmt to database.rs (PECOBLR-4146) Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- napi/src/database.rs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/napi/src/database.rs b/napi/src/database.rs index e00e396f..7140c8e4 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -458,16 +458,10 @@ pub struct KernelPersistArgs { /// serialized token JSON, or `undefined`/`null` on a miss. `CalleeHandled = /// false` so the JS callback receives a bare `host` (not the Node error-first /// `(err, host)` shape). -type ReadTsfn = - ThreadsafeFunction>, String, napi::Status, false>; +type ReadTsfn = ThreadsafeFunction>, String, napi::Status, false>; /// JS `persist({ host, tokenJson }) => Promise`. -type PersistTsfn = ThreadsafeFunction< - KernelPersistArgs, - Promise<()>, - KernelPersistArgs, - napi::Status, - false, ->; +type PersistTsfn = + ThreadsafeFunction, KernelPersistArgs, napi::Status, false>; /// [`TokenPersistence`] backed by two JS callbacks (via `ThreadsafeFunction`), /// installed when the caller supplies an `OAuthPersistence` on the kernel path. @@ -1120,7 +1114,10 @@ mod tests { let mut o = base(); o.auth_mode = Some(AuthMode::AzureSpM2m); o.azure_client_id = Some("entra-app-id".to_owned()); - assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "azure_client_secret"); + assert_invalid_arg( + build_auth_config(&o, None).unwrap_err(), + "azure_client_secret", + ); } #[test] From 8399c9530e340ad6f2f1ce2f8757dd37fd3b2c53 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Fri, 21 Aug 2026 19:20:38 -0700 Subject: [PATCH 05/10] docs(auth): design doc + changelogs for pluggable OAuth token persistence (PECOBLR-4146) Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- CHANGELOG.md | 10 ++ ...BLR-4146-oauth-token-persistence-design.md | 104 ++++++++++++++++++ napi/CHANGELOG.md | 15 +++ pyo3/CHANGELOG.md | 11 ++ 4 files changed, 140 insertions(+) create mode 100644 docs/designs/PECOBLR-4146-oauth-token-persistence-design.md diff --git a/CHANGELOG.md b/CHANGELOG.md index aca699b1..f1fbabd9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,16 @@ cadences and may not move in lockstep with the crate. ## [Unreleased] ### Added +- **Pluggable OAuth U2M token persistence** — a new + `auth::oauth::persistence::TokenPersistence` trait lets a caller supply a + custom token store (database, OS keychain, in-memory, …) via + `AuthConfig::OAuthU2M { token_store }` instead of the built-in encrypted disk + cache. The disk cache becomes the default impl (`DiskTokenCache`), so behavior + is unchanged when no store is supplied. Exposed to the bindings — napi + (`openSession` persistence callbacks) and pyo3 (`Session(oauth_persistence=…)`) + — which exchange the token as its serialized JSON. Load errors fall back to a + fresh login; save errors are logged and swallowed. Go / C-ABI is out of scope + (no callback surface). See `docs/designs/PECOBLR-4146-oauth-token-persistence-design.md`. - **Transaction control on `Session`** — `set_autocommit(bool)` / `autocommit()` / `commit()` / `rollback()`, exposed over the C ABI as `kernel_session_set_autocommit` / `_get_autocommit` / `_commit` / diff --git a/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md b/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md new file mode 100644 index 00000000..e3d5c426 --- /dev/null +++ b/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md @@ -0,0 +1,104 @@ + + +# Pluggable OAuth token persistence (PECOBLR-4146) + +**Status:** implemented (kernel core + napi + pyo3). Go / C-ABI out of scope. +**Parent:** PECOBLR-3727 (databricks-sql-kernel Reyden support). + +## Problem + +On the kernel path the kernel owns the OAuth **U2M** flow and persists the +refresh token to a hardcoded encrypted on-disk cache +(`~/.config/databricks-sql-kernel/oauth/`). Callers could not supply their own +token store, so there was no equivalent to the Thrift connectors' +`OAuthPersistence` (Node) / `experimental_oauth_persistence` (Python) — a +caller-supplied `read`/`persist` object that can back onto a database, an OS +keychain, or an in-memory store. + +## Design + +A single kernel-side trait, injected through `AuthConfig`, with the two +callback-capable bindings wiring their host-language callables onto it. + +### Kernel core — `src/auth/oauth/persistence.rs` + +```rust +#[async_trait] +pub trait TokenPersistence: Send + Sync + std::fmt::Debug { + async fn load(&self, host: &str, client_id: &str, scopes: &[String]) -> Result>; + async fn save(&self, host: &str, client_id: &str, scopes: &[String], token: &OAuthToken) -> Result<()>; +} +``` + +- **`DiskTokenCache`** (same module) is the default impl, wrapping the existing + `TokenCache` + resolved passphrase — so behavior is **unchanged** when no + custom store is supplied. +- `AuthConfig::OAuthU2M` gains `token_store: Option>`. + When `Some`, it overrides the `token_cache` disk policy. Because `AuthConfig` + is `#[non_exhaustive]`, cross-crate bindings set it through the `oauth_u2m(…)` + constructor (a new trailing argument), not a struct literal. +- `session.rs::build_base_auth_provider` resolves the effective store: a + caller store wins; otherwise it derives a `DiskTokenCache` from the + `token_cache` policy (or `None` to disable persistence). +- `AuthorizationCodeProvider` calls `store.load(…)` before deciding to open a + browser and `store.save(…)` after every acquisition/refresh. + +**Error semantics (lenient by contract):** a `load` error is treated as a +cache miss (fresh browser login, never fails the connection); a `save` error is +logged and swallowed (a failed cache write must not fail otherwise-good auth). + +### Wire format + +The token crosses every binding boundary as the kernel's `OAuthToken` +**serialized to JSON** (serde) — the exact bytes the on-disk cache stores. This +is lossless (preserves `expires_at`, scopes, refresh token) and identical +across bindings, and it sidesteps reconstructing expiry from a partial token. +The `{host, client_id, scopes}` triple is the store key. + +### napi (Node) — `napi/src/database.rs` + +- `openSession(options, oauthPersistenceRead?, oauthPersistencePersist?)` — two + optional JS callbacks. Both required together; a lone one is treated as "no + store". +- `NapiTokenStore` wraps them as `ThreadsafeFunction`s (mirroring the existing + `logger.rs` kernel→JS bridge). `load`/`save` call the JS function via + `call_async` and `await` the returned `Promise`. `read(host) => Promise`; `persist({host, tokenJson}) => Promise`. + +### pyo3 (Python) — `pyo3/src/auth.rs`, `pyo3/src/session.rs` + +- `Session(…, oauth_persistence=…)` — a Python object exposing + `read(host) -> Optional[str]` and `persist(host, token_json) -> None`. +- `PyTokenStore` calls the object under the GIL (`Python::attach`); no `await` + is held across the GIL, so the async future stays `Send`. Carried on + `OAuthParams.token_store` so `build_auth_config`'s signature and its + GIL-less unit-testable inner stay unchanged. + +### Out of scope — Go / C-ABI + +The C-ABI has no callback surface (data-only config), and Go has no persistence +concept to forward, so a Go/C-ABI callback bridge is deferred. Go's only +existing knob (`kernel_session_config_set_u2m_token_cache_config`, +enable/disable + passphrase) already covers the one Go-relevant case. The same +`AuthConfig::External(Box)`-style bridge would later unblock +both a Go store and the currently-rejected `token-provider` / `external-token` / +`custom` authTypes. + +## Driver follow-ups + +The connector repos adapt their existing persistence objects onto the new +binding surface: databricks-sql-python#913 (`experimental_oauth_persistence`) +and databricks-sql-nodejs#457 / #505 (`OAuthPersistence`, currently rejected on +the kernel path). + +## Testing + +- Rust: in-memory mock `TokenPersistence` (load-hit skips browser, save after + acquire/refresh); existing wiremock U2M suite refactored onto `DiskTokenCache`. +- napi: `cargo test --features dyn-symbols`; end-to-end through the nodejs + connector (needs a live Node host for the TSFN). +- pyo3: `cargo clippy` + maturin-linked build; full Python E2E with a fake + store via the connector. diff --git a/napi/CHANGELOG.md b/napi/CHANGELOG.md index 8016b83e..654b122f 100644 --- a/napi/CHANGELOG.md +++ b/napi/CHANGELOG.md @@ -6,6 +6,21 @@ The Rust crate and Python binding have their own changelogs under [`../CHANGELOG.md`](../CHANGELOG.md) and [`../pyo3/CHANGELOG.md`](../pyo3/CHANGELOG.md); they ship on independent cadences. +## [Unreleased] + +### Added +- **Pluggable OAuth token store on `openSession`** — two optional callbacks + (`oauthPersistenceRead` / `oauthPersistencePersist`) let a Node caller supply + a custom OAuth U2M token store on the kernel path instead of the built-in disk + cache. Both must be supplied together; they receive/return the kernel's + `OAuthToken` as a JSON string (`KernelPersistArgs`). Wired via + `ThreadsafeFunction`, awaiting the JS `Promise`. (PECOBLR-4146) + + The generated native contract (`index.js` / `index.d.ts`) was regenerated + with the crate-correct `@napi-rs/cli@3.8.2`; the previously-committed contract + was stale `@napi-rs/cli` v2 output, so that diff also migrates the loader to + v3 (version-consistency checks, WASI fallback). + ## [v0.2.0] - 2026-06-08 **Beta release of the Databricks SQL Kernel (Node.js binding).** diff --git a/pyo3/CHANGELOG.md b/pyo3/CHANGELOG.md index 1a5dc9f8..9db2acd2 100644 --- a/pyo3/CHANGELOG.md +++ b/pyo3/CHANGELOG.md @@ -6,6 +6,17 @@ crate and Node.js binding have their own changelogs under [`../CHANGELOG.md`](../CHANGELOG.md) and [`../napi/CHANGELOG.md`](../napi/CHANGELOG.md); they ship on independent cadences. +## [Unreleased] + +### Added +- **Pluggable OAuth token store via `oauth_persistence`** — `Session(…, + oauth_persistence=obj)` lets a caller supply a custom OAuth U2M token store on + the kernel path instead of the built-in disk cache. `obj` must expose + `read(host) -> Optional[str]` and `persist(host, token_json) -> None`, + exchanging the kernel's `OAuthToken` as a JSON string. Invoked under the GIL. + The `databricks-sql-python` connector adapts its `experimental_oauth_persistence` + onto this (#913). (PECOBLR-4146) + ## [v0.2.0] - 2026-06-08 **Beta release of the Databricks SQL Kernel (Python binding).** From 4386bd843c65c1e2a91994587b9468be90476ca3 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Fri, 21 Aug 2026 23:29:26 -0700 Subject: [PATCH 06/10] =?UTF-8?q?docs(auth):=20scope=20PECOBLR-4146=20?= =?UTF-8?q?=E2=80=94=20PuPr=20kernel-owned=20persistence;=20custom=20store?= =?UTF-8?q?=20post-GA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PuPr ships kernel-owned persistence: the kernel owns the token lifetime + the built-in encrypted disk cache, and the caller can enable / disable / locate it via TokenCacheConfig exposed through napi/pyo3. A caller-supplied custom token store (via napi/pyo3 callback bridges) is deferred post-GA, built only when a named consumer needs a non-file sink. Records the rationale (no named customer, no prod store in the connector today, kernel disk cache already covers the common case better, no telemetry signal, the custom-store path is the untested higher-risk surface) and keeps the custom-store design + prototype status under Post-GA. NOTE: the code on this branch still carries the custom-store prototype; scoping the implementation down to the PuPr surface is the follow-up. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- ...BLR-4146-oauth-token-persistence-design.md | 217 +++++++++++------- 1 file changed, 129 insertions(+), 88 deletions(-) diff --git a/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md b/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md index e3d5c426..e66364f1 100644 --- a/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md +++ b/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md @@ -3,102 +3,143 @@ Copyright (c) 2026 Databricks, Inc. Licensed under the Apache License, Version 2.0. --> -# Pluggable OAuth token persistence (PECOBLR-4146) +# OAuth token persistence on the kernel path (PECOBLR-4146) -**Status:** implemented (kernel core + napi + pyo3). Go / C-ABI out of scope. +**Status:** Decided. **PuPr:** kernel-owned persistence (enable / disable / +locate the built-in encrypted disk cache). **Post-GA:** caller-supplied custom +token store, only if a named consumer needs a non-file sink. **Parent:** PECOBLR-3727 (databricks-sql-kernel Reyden support). ## Problem -On the kernel path the kernel owns the OAuth **U2M** flow and persists the -refresh token to a hardcoded encrypted on-disk cache -(`~/.config/databricks-sql-kernel/oauth/`). Callers could not supply their own -token store, so there was no equivalent to the Thrift connectors' -`OAuthPersistence` (Node) / `experimental_oauth_persistence` (Python) — a -caller-supplied `read`/`persist` object that can back onto a database, an OS -keychain, or an in-memory store. - -## Design - -A single kernel-side trait, injected through `AuthConfig`, with the two -callback-capable bindings wiring their host-language callables onto it. - -### Kernel core — `src/auth/oauth/persistence.rs` - -```rust -#[async_trait] -pub trait TokenPersistence: Send + Sync + std::fmt::Debug { - async fn load(&self, host: &str, client_id: &str, scopes: &[String]) -> Result>; - async fn save(&self, host: &str, client_id: &str, scopes: &[String], token: &OAuthToken) -> Result<()>; -} -``` - -- **`DiskTokenCache`** (same module) is the default impl, wrapping the existing - `TokenCache` + resolved passphrase — so behavior is **unchanged** when no - custom store is supplied. -- `AuthConfig::OAuthU2M` gains `token_store: Option>`. - When `Some`, it overrides the `token_cache` disk policy. Because `AuthConfig` - is `#[non_exhaustive]`, cross-crate bindings set it through the `oauth_u2m(…)` - constructor (a new trailing argument), not a struct literal. -- `session.rs::build_base_auth_provider` resolves the effective store: a - caller store wins; otherwise it derives a `DiskTokenCache` from the - `token_cache` policy (or `None` to disable persistence). -- `AuthorizationCodeProvider` calls `store.load(…)` before deciding to open a - browser and `store.save(…)` after every acquisition/refresh. - -**Error semantics (lenient by contract):** a `load` error is treated as a -cache miss (fresh browser login, never fails the connection); a `save` error is -logged and swallowed (a failed cache write must not fail otherwise-good auth). - -### Wire format - -The token crosses every binding boundary as the kernel's `OAuthToken` -**serialized to JSON** (serde) — the exact bytes the on-disk cache stores. This -is lossless (preserves `expires_at`, scopes, refresh token) and identical -across bindings, and it sidesteps reconstructing expiry from a partial token. -The `{host, client_id, scopes}` triple is the store key. - -### napi (Node) — `napi/src/database.rs` - -- `openSession(options, oauthPersistenceRead?, oauthPersistencePersist?)` — two - optional JS callbacks. Both required together; a lone one is treated as "no - store". -- `NapiTokenStore` wraps them as `ThreadsafeFunction`s (mirroring the existing - `logger.rs` kernel→JS bridge). `load`/`save` call the JS function via - `call_async` and `await` the returned `Promise`. `read(host) => Promise`; `persist({host, tokenJson}) => Promise`. - -### pyo3 (Python) — `pyo3/src/auth.rs`, `pyo3/src/session.rs` - -- `Session(…, oauth_persistence=…)` — a Python object exposing - `read(host) -> Optional[str]` and `persist(host, token_json) -> None`. -- `PyTokenStore` calls the object under the GIL (`Python::attach`); no `await` - is held across the GIL, so the async future stays `Send`. Carried on - `OAuthParams.token_store` so `build_auth_config`'s signature and its - GIL-less unit-testable inner stay unchanged. +On the kernel path the kernel owns the OAuth **U2M** flow and, by default, +persists the refresh token to an encrypted on-disk cache +(`~/.config/databricks-sql-kernel/oauth/`, `0600`, `TokenCacheConfig.enabled = +true`, matching JDBC `EnableTokenCache=1`). Two questions follow: + +1. Should a caller be able to **turn that off / relocate it** (e.g. a policy that + forbids tokens at rest)? +2. Should a caller be able to substitute their **own token store** — the Thrift + connectors' `OAuthPersistence` (Node) / `experimental_oauth_persistence` + (Python) — backing a database, OS keychain, or in-memory object? + +## Decision + +For **PuPr**, answer (1): the kernel owns the token lifetime, and the caller can +enable/disable/locate the built-in encrypted disk cache. Answer (2) — a +caller-supplied custom store — is **post-GA**, built only when a named consumer +needs a non-file sink. + +### Rationale + +- **No demonstrated demand for custom stores.** `experimental_oauth_persistence` + was introduced in the *foundational* OAuth PR (databricks-sql-python#15, 2022) + as an extensibility hook — `experimental_`, documented "beta (private + preview)", with **no named customer** driving it. The connector ships only + `OAuthPersistenceCache` (in-memory) and `DevOnlyFilePersistence` ("only + intended for development", writes **plaintext**). It ships **no production + store**; the docstring tells prod users to "write your own". +- **The kernel already provides the missing prod store.** The kernel's built-in + disk cache is exactly the hardened, restart-surviving store the connector told + users to build — encrypted (`cache_crypto`), `0600`, cross-process — and it is + **stronger** than anything the connector ships. So the common prod U2M need + ("make the browser login survive restarts, securely") is met with **zero user + code**. +- **The default divergence is really an on/off question.** Thrift Python defaults + to *no* persistence; Thrift Node defaults to *in-memory*; the kernel defaults + to *on-disk* (JDBC convention). Reconciling this is an **enable/disable** + decision — squarely the PuPr scope. +- **No telemetry signal.** Connector telemetry records `auth_mech` + `auth_flow` + only — nothing about whether a persistence object was supplied or its type — so + custom-store adoption can't even be measured. +- **The custom-store path is the entire high-risk surface** (an async + request/response `ThreadsafeFunction` on napi; a GIL callback on pyo3), and + would ship without live-host E2E coverage. The PuPr scope is scalar config — no + callbacks, no async-FFI, trivially testable. + +Low-regret: the custom-store design is fully worked out and prototyped (see +*Post-GA*), so it can be added later with nothing lost by waiting. + +## PuPr scope — kernel-owned persistence + +The kernel already owns acquisition, refresh, in-memory reuse, and encrypted +on-disk persistence. PuPr adds **no new kernel auth machinery** — it exposes the +*existing* `TokenCacheConfig` (in `src/config.rs`, already `enabled` + +`passphrase`, already reachable over the C-ABI via +`kernel_session_config_set_u2m_token_cache_config`) through the two bindings as +scalar config: + +- **napi** — `ConnectionOptions` gains optional `tokenCacheEnabled` / + (optional) `tokenCachePassphrase` / (optional) cache-dir override. +- **pyo3** — `Session(…)` gains the matching optional kwargs. +- **Kernel** — optionally add a `dir`/`path` override field to `TokenCacheConfig` + (the default location is fine for most; the override is a nice-to-have, not + required for PuPr). + +No token-store trait, no binding callbacks. A caller who supplies nothing gets +today's encrypted-disk default; a caller can disable persistence (no token at +rest) or point it at a chosen location. + +### The default the connector adapters must choose + +The kernel defaults **on-disk**; Thrift defaults **in-memory / none**. The +connector adapters (databricks-sql-nodejs#457, databricks-sql-python#913) must +consciously pick per binding: + +- **Adopt the kernel/JDBC default** — persist to disk by default (fewer logins; + but the refresh token is now at rest where it wasn't on Thrift), or +- **Match Thrift's conservative default** — disable the kernel disk cache unless + the user opts in. + +The enable/disable knob is what makes either choice expressible. This is a +product decision, flagged on those tickets — not something the kernel picks +silently. ### Out of scope — Go / C-ABI -The C-ABI has no callback surface (data-only config), and Go has no persistence -concept to forward, so a Go/C-ABI callback bridge is deferred. Go's only -existing knob (`kernel_session_config_set_u2m_token_cache_config`, -enable/disable + passphrase) already covers the one Go-relevant case. The same -`AuthConfig::External(Box)`-style bridge would later unblock -both a Go store and the currently-rejected `token-provider` / `external-token` / -`custom` authTypes. - -## Driver follow-ups - -The connector repos adapt their existing persistence objects onto the new -binding surface: databricks-sql-python#913 (`experimental_oauth_persistence`) -and databricks-sql-nodejs#457 / #505 (`OAuthPersistence`, currently rejected on -the kernel path). +The C-ABI has no callback surface and Go has no persistence concept to forward. +Its existing `kernel_session_config_set_u2m_token_cache_config` (enable/disable + +passphrase) already covers the PuPr scope for Go. + +## Post-GA — caller-supplied custom store + +Add this **only when a named consumer needs a non-file token sink** (OS keychain, +secrets manager / Vault, corporate policy mandating "no token on disk", or a +multi-tenant server sharing tokens in a DB). Until then it stays deferred. + +**Design (prototyped — see below):** + +- Kernel: a `TokenPersistence` trait (`async load/save` over `OAuthToken`), with + today's disk cache refactored into a `DiskTokenCache` default impl, and + `AuthConfig::OAuthU2M { token_store: Option> }` (set + via the `oauth_u2m(…)` constructor, since `AuthConfig` is `#[non_exhaustive]`). +- Wire format: the kernel's `OAuthToken` serialized to JSON (lossless; the exact + bytes the disk cache stores) — avoids reconstructing expiry from a partial + token. +- napi: `openSession` gains two callbacks wrapped as `ThreadsafeFunction`s; + `load`/`save` `call_async` the JS function and `await` its `Promise`. +- pyo3: a `PyTokenStore` calling the Python object under the GIL + (`Python::attach`), carried on `OAuthParams.token_store`. +- Error semantics: `load` error → cache miss (fresh login, never fails connect); + `save` error → logged and swallowed. +- The same bridge (a callback into the binding) would also unblock the + currently-rejected `token-provider` / `external-token` / `custom` authTypes and + a Go/C-ABI store. + +**Prototype status:** the full custom-store implementation (kernel trait + +`DiskTokenCache` + napi `ThreadsafeFunction` bridge + pyo3 GIL bridge) was built +and compiles / unit-tests clean; it lives in the branch history of the initial +PECOBLR-4146 PR. **It was not E2E-tested against live Node/Python U2M** — that, +plus a named requirement, is the gate before it ships. ## Testing -- Rust: in-memory mock `TokenPersistence` (load-hit skips browser, save after - acquire/refresh); existing wiremock U2M suite refactored onto `DiskTokenCache`. -- napi: `cargo test --features dyn-symbols`; end-to-end through the nodejs - connector (needs a live Node host for the TSFN). -- pyo3: `cargo clippy` + maturin-linked build; full Python E2E with a fake - store via the connector. +- **PuPr:** scalar-config plumbing — assert the napi/pyo3 flags map to + `TokenCacheConfig`; kernel U2M E2E with the cache enabled (survives restart) + and disabled (fresh login each run). The default disk path is already verified + E2E (U2M open + a two-run disk-cache round-trip that skips the browser on the + second run). +- **Post-GA (custom store):** the prototype's Rust mock-store unit tests, plus + the missing piece — live-host E2E through the Node and Python connectors with a + real custom in-memory store (round-trip + no deadlock on the napi TSFN / pyo3 + GIL paths). From 081f254143e23bbaf66024319b72b3eab42564a5 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Fri, 21 Aug 2026 23:48:04 -0700 Subject: [PATCH 07/10] =?UTF-8?q?refactor(auth):=20scope=20PECOBLR-4146=20?= =?UTF-8?q?to=20PuPr=20=E2=80=94=20kernel-owned=20token-cache=20control?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Revert the custom-store surface (the TokenPersistence trait + napi/pyo3 callback bridges) added earlier on this branch, and ship the PuPr surface instead: expose the kernel's existing TokenCacheConfig (enable/disable + passphrase) through the napi and pyo3 bindings. - napi: openSession ConnectionOptions gains tokenCacheEnabled / tokenCachePassphrase; build_auth_config maps them to TokenCacheConfig on the U2M arm. Native contract regenerated with @napi-rs/cli@3.8.2 (also migrates the stale v2-CLI loader to v3). - pyo3: Session gains token_cache_enabled / token_cache_passphrase kwargs, carried on OAuthParams and mapped to TokenCacheConfig in the U2M arm. - Kernel core is unchanged from main (no trait, no callbacks) — TokenCacheConfig already exists; this is purely binding surface. - Caller-supplied custom stores are deferred post-GA; the prototype remains in this branch's history (see docs/designs/PECOBLR-4146-...). Unit tests added for the enable/disable/passphrase mapping in both bindings. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- CHANGELOG.md | 10 -- napi/CHANGELOG.md | 13 +- napi/Cargo.lock | 1 - napi/Cargo.toml | 4 - napi/index.d.ts | 35 ++--- napi/src/database.rs | 257 ++++++++++++--------------------- pyo3/CHANGELOG.md | 15 +- pyo3/Cargo.lock | 2 - pyo3/Cargo.toml | 6 - pyo3/src/auth.rs | 173 +++++++++------------- pyo3/src/session.rs | 16 +- src/auth/oauth/mod.rs | 2 - src/auth/oauth/persistence.rs | 196 ------------------------- src/auth/oauth/u2m.rs | 161 ++++++++------------- src/c_abi/session.rs | 3 - src/config.rs | 26 +--- src/session.rs | 25 ++-- tests/oauth_u2m_integration.rs | 21 +-- tests/v0_session_e2e.rs | 2 - 19 files changed, 276 insertions(+), 692 deletions(-) delete mode 100644 src/auth/oauth/persistence.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index f1fbabd9..aca699b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,16 +9,6 @@ cadences and may not move in lockstep with the crate. ## [Unreleased] ### Added -- **Pluggable OAuth U2M token persistence** — a new - `auth::oauth::persistence::TokenPersistence` trait lets a caller supply a - custom token store (database, OS keychain, in-memory, …) via - `AuthConfig::OAuthU2M { token_store }` instead of the built-in encrypted disk - cache. The disk cache becomes the default impl (`DiskTokenCache`), so behavior - is unchanged when no store is supplied. Exposed to the bindings — napi - (`openSession` persistence callbacks) and pyo3 (`Session(oauth_persistence=…)`) - — which exchange the token as its serialized JSON. Load errors fall back to a - fresh login; save errors are logged and swallowed. Go / C-ABI is out of scope - (no callback surface). See `docs/designs/PECOBLR-4146-oauth-token-persistence-design.md`. - **Transaction control on `Session`** — `set_autocommit(bool)` / `autocommit()` / `commit()` / `rollback()`, exposed over the C ABI as `kernel_session_set_autocommit` / `_get_autocommit` / `_commit` / diff --git a/napi/CHANGELOG.md b/napi/CHANGELOG.md index 654b122f..04fd3e4b 100644 --- a/napi/CHANGELOG.md +++ b/napi/CHANGELOG.md @@ -9,12 +9,13 @@ they ship on independent cadences. ## [Unreleased] ### Added -- **Pluggable OAuth token store on `openSession`** — two optional callbacks - (`oauthPersistenceRead` / `oauthPersistencePersist`) let a Node caller supply - a custom OAuth U2M token store on the kernel path instead of the built-in disk - cache. Both must be supplied together; they receive/return the kernel's - `OAuthToken` as a JSON string (`KernelPersistArgs`). Wired via - `ThreadsafeFunction`, awaiting the JS `Promise`. (PECOBLR-4146) +- **U2M on-disk token-cache control on `openSession`** — `tokenCacheEnabled` + and `tokenCachePassphrase` let a Node caller enable/disable (or set the + AES-256 passphrase for) the kernel's built-in encrypted disk cache on the + kernel path. Omitted keeps the kernel default (enabled, machine-local key, + survives restarts); `tokenCacheEnabled: false` re-logins each fresh process; a + passphrase with no explicit flag implies enabled. Applies to `OAuthU2m`. + (PECOBLR-4146) The generated native contract (`index.js` / `index.d.ts`) was regenerated with the crate-correct `@napi-rs/cli@3.8.2`; the previously-committed contract diff --git a/napi/Cargo.lock b/napi/Cargo.lock index b0a7f57e..fe76a0cb 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -585,7 +585,6 @@ dependencies = [ "arrow-array", "arrow-ipc", "arrow-schema", - "async-trait", "chrono", "databricks-sql-kernel", "futures", diff --git a/napi/Cargo.toml b/napi/Cargo.toml index e91b440f..8becf712 100644 --- a/napi/Cargo.toml +++ b/napi/Cargo.toml @@ -69,10 +69,6 @@ dyn-symbols = ["napi/dyn-symbols"] napi = { version = "3", default-features = false, features = ["napi6", "async"] } napi-derive = "3" -# Needed to implement the kernel's `#[async_trait] TokenPersistence` for the -# `ThreadsafeFunction`-backed pluggable OAuth token store (PECOBLR-4146). -async-trait = "0.1" - # Kernel — path dep on the async-public-api branch worktree. Once the # kernel is published this becomes a version dep. # diff --git a/napi/index.d.ts b/napi/index.d.ts index ca13529d..9e33b65d 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -679,6 +679,20 @@ export interface ConnectionOptions { * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. */ tokenUrl?: string + /** + * U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel + * default (cache enabled, encrypted under a machine-local key, survives + * restarts). `false` disables on-disk persistence (re-login each fresh + * process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. + */ + tokenCacheEnabled?: boolean + /** + * Optional passphrase for the U2M on-disk token cache (AES-256 key). + * Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. + * A passphrase with no explicit `tokenCacheEnabled` implies enabled. + * Applies to [`AuthMode::OAuthU2m`]. + */ + tokenCachePassphrase?: string /** * Path to the PEM private-key file. Required for * [`AuthMode::OAuthM2mJwt`]. @@ -1153,25 +1167,6 @@ export interface KernelLoggingStats { dropped: number } -/** - * Map the JS `ConnectionOptions` auth fields onto the kernel - * [`AuthConfig`]. Per-mode required-field validation lives in the - * kernel's validating constructors ([`AuthConfig::pat`] / - * [`AuthConfig::oauth_m2m`]); this binding just forwards the JS - * optionals and maps any kernel `InvalidArgument` onto a napi error. - * `#[napi(object)]` argument for the persist callback: the workspace host - * plus the kernel's serialized `OAuthToken` (JSON). The token crosses the - * boundary as an opaque JSON string — the exact bytes the on-disk cache would - * store — so the full token (including expiry) round-trips losslessly through - * the caller's store. - */ -export interface KernelPersistArgs { - /** Workspace host the token is scoped to (the store's key). */ - host: string - /** The kernel's `OAuthToken` serialized as JSON. Opaque to the caller. */ - tokenJson: string -} - /** * One kernel log event, as handed to JS. `level` is a lower-case string * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its @@ -1205,7 +1200,7 @@ export interface NamedTypedValueInput { * The JS-visible name is `openSession` (napi-rs converts snake_case * to camelCase for free functions). */ -export declare function openSession(options: ConnectionOptions, oauthPersistenceRead?: (((arg: string) => Promise)) | undefined | null, oauthPersistencePersist?: (((arg: KernelPersistArgs) => Promise)) | undefined | null): Promise +export declare function openSession(options: ConnectionOptions): Promise /** * Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's diff --git a/napi/src/database.rs b/napi/src/database.rs index 7140c8e4..746a8327 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -33,14 +33,10 @@ use napi::bindgen_prelude::Buffer; #[cfg(test)] type Buffer = Vec; -use databricks_sql_kernel::auth::oauth::persistence::TokenPersistence; -use databricks_sql_kernel::auth::oauth::OAuthToken; use databricks_sql_kernel::{ AuthConfig, DefaultOpts, DriverSystemConfiguration, Error as KernelError, HttpConfig, - ProxyConfig, ResultConfig, Session, TelemetryConfig, TlsConfig, + ProxyConfig, ResultConfig, Session, TelemetryConfig, TlsConfig, TokenCacheConfig, }; -use napi::bindgen_prelude::Promise; -use napi::threadsafe_function::ThreadsafeFunction; /// NodeJS-driver-appropriate default for `pool_max_idle_per_host`. /// @@ -181,6 +177,16 @@ pub struct ConnectionOptions { /// which is required when that IdP — not Databricks-native OIDC — is the /// authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. pub token_url: Option, + /// U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel + /// default (cache enabled, encrypted under a machine-local key, survives + /// restarts). `false` disables on-disk persistence (re-login each fresh + /// process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. + pub token_cache_enabled: Option, + /// Optional passphrase for the U2M on-disk token cache (AES-256 key). + /// Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. + /// A passphrase with no explicit `tokenCacheEnabled` implies enabled. + /// Applies to [`AuthMode::OAuthU2m`]. + pub token_cache_passphrase: Option, /// Path to the PEM private-key file. Required for /// [`AuthMode::OAuthM2mJwt`]. pub jwt_key_file: Option, @@ -441,112 +447,9 @@ pub struct ConnectionOptions { /// kernel's validating constructors ([`AuthConfig::pat`] / /// [`AuthConfig::oauth_m2m`]); this binding just forwards the JS /// optionals and maps any kernel `InvalidArgument` onto a napi error. -/// `#[napi(object)]` argument for the persist callback: the workspace host -/// plus the kernel's serialized `OAuthToken` (JSON). The token crosses the -/// boundary as an opaque JSON string — the exact bytes the on-disk cache would -/// store — so the full token (including expiry) round-trips losslessly through -/// the caller's store. -#[napi(object)] -pub struct KernelPersistArgs { - /// Workspace host the token is scoped to (the store's key). - pub host: String, - /// The kernel's `OAuthToken` serialized as JSON. Opaque to the caller. - pub token_json: String, -} - -/// JS `read(host) => Promise` — returns the kernel- -/// serialized token JSON, or `undefined`/`null` on a miss. `CalleeHandled = -/// false` so the JS callback receives a bare `host` (not the Node error-first -/// `(err, host)` shape). -type ReadTsfn = ThreadsafeFunction>, String, napi::Status, false>; -/// JS `persist({ host, tokenJson }) => Promise`. -type PersistTsfn = - ThreadsafeFunction, KernelPersistArgs, napi::Status, false>; - -/// [`TokenPersistence`] backed by two JS callbacks (via `ThreadsafeFunction`), -/// installed when the caller supplies an `OAuthPersistence` on the kernel path. -/// `load`/`save` invoke the JS store and await its returned `Promise`. -struct NapiTokenStore { - read: ReadTsfn, - persist: PersistTsfn, -} - -impl std::fmt::Debug for NapiTokenStore { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - // `ThreadsafeFunction` is not `Debug`; the kernel only needs a name - // here (the field is behind `Arc` in `Debug` - // output). - f.write_str("NapiTokenStore") - } -} - -/// Map a napi callback failure into a kernel error. Per the -/// [`TokenPersistence`] contract the kernel logs and swallows these (load → -/// cache miss, save → warn), so the category is informational. -fn kernel_err_from_napi(e: napi::Error) -> KernelError { - KernelError::io().message(format!("OAuth token store callback failed: {e}")) -} - -#[async_trait::async_trait] -impl TokenPersistence for NapiTokenStore { - async fn load( - &self, - host: &str, - _client_id: &str, - _scopes: &[String], - ) -> databricks_sql_kernel::Result> { - // Two awaits: `call_async` schedules the JS call and resolves once the - // JS function *returns* (a Promise); the second await resolves that - // Promise to the token JSON. - let promise = self - .read - .call_async(host.to_string()) - .await - .map_err(kernel_err_from_napi)?; - let maybe_json: Option = promise.await.map_err(kernel_err_from_napi)?; - match maybe_json { - Some(json) => { - let token: OAuthToken = serde_json::from_str(&json).map_err(|e| { - KernelError::invalid_state() - .message(format!("token store returned malformed token JSON: {e}")) - })?; - Ok(Some(token)) - } - None => Ok(None), - } - } - - async fn save( - &self, - host: &str, - _client_id: &str, - _scopes: &[String], - token: &OAuthToken, - ) -> databricks_sql_kernel::Result<()> { - let token_json = serde_json::to_string(token).map_err(|e| { - KernelError::invalid_state().message(format!("failed to serialize OAuth token: {e}")) - })?; - let args = KernelPersistArgs { - host: host.to_string(), - token_json, - }; - let promise = self - .persist - .call_async(args) - .await - .map_err(kernel_err_from_napi)?; - promise.await.map_err(kernel_err_from_napi)?; - Ok(()) - } -} - /// Pure (borrows `options`) so it is unit-testable without opening a -/// session. `token_store`, when `Some`, is threaded into the U2M arm as the -/// caller-supplied [`TokenPersistence`] (other arms ignore it). -fn build_auth_config( - options: &ConnectionOptions, - token_store: Option>, -) -> napi::Result { +/// session. +fn build_auth_config(options: &ConnectionOptions) -> napi::Result { match options.auth_mode.unwrap_or_default() { AuthMode::Pat => AuthConfig::pat( options.token.clone(), @@ -605,15 +508,18 @@ fn build_auth_config( options.oauth_scopes.clone(), options.token_url.clone(), None, - // `None` takes the kernel default: on-disk cache enabled, - // encrypted under a machine-local derived key since this - // binding exposes no passphrase option. Ignored when - // `token_store` below is `Some`. - None, + // U2M on-disk token-cache control. Both omitted ⇒ kernel + // default (enabled, machine-local key). Otherwise honor the + // caller's enable flag / passphrase; a passphrase alone + // implies enabled. + match (options.token_cache_enabled, &options.token_cache_passphrase) { + (None, None) => None, + (enabled, passphrase) => Some(TokenCacheConfig { + enabled: enabled.unwrap_or(true), + passphrase: passphrase.clone(), + }), + }, options.identity_federation_client_id.clone(), - // Caller-supplied JS token store (`OAuthPersistence`), when the - // driver passed the persistence callbacks to `openSession`. - token_store, )) } // Azure Entra service-principal M2M. The kernel owns Azure @@ -832,20 +738,7 @@ fn build_driver_system_configuration( reason = "exported via napi macro codegen; not called from Rust" )] #[napi] -pub async fn open_session( - mut options: ConnectionOptions, - // Optional pluggable OAuth token store (U2M only). Both callbacks must be - // supplied together; when present they override the built-in disk cache. - // The driver adapts its `OAuthPersistence` object into these two functions. - // Types are inlined (not the `ReadTsfn`/`PersistTsfn` aliases) so napi-rs - // emits a concrete TS function signature rather than a dangling alias name. - oauth_persistence_read: Option< - ThreadsafeFunction>, String, napi::Status, false>, - >, - oauth_persistence_persist: Option< - ThreadsafeFunction, KernelPersistArgs, napi::Status, false>, - >, -) -> napi::Result { +pub async fn open_session(mut options: ConnectionOptions) -> napi::Result { guarded(async move { // Cache the napi-rs tokio Handle on the very first async call // so Drop impls (which run on the V8 GC thread, outside any @@ -853,19 +746,9 @@ pub async fn open_session( // runtime that's driving this future. let _ = runtime::get_handle(); - // Build the caller-supplied token store when (and only when) both - // callbacks were provided; a lone callback is treated as "no store". - let token_store: Option> = - match (oauth_persistence_read, oauth_persistence_persist) { - (Some(read), Some(persist)) => { - Some(Arc::new(NapiTokenStore { read, persist }) as Arc) - } - _ => None, - }; - // Resolve auth before the builder moves `host_name` / `http_path` // out of `options` (validation can fail fast, before any network). - let auth_config = build_auth_config(&options, token_store)?; + let auth_config = build_auth_config(&options)?; // Build the TLS config before the builder moves fields out of // `options`. Always wired (even at defaults) because the // permissive-by-default stance needs the relaxation flags set — @@ -967,6 +850,8 @@ mod tests { oauth_redirect_port: None, oauth_scopes: None, token_url: None, + token_cache_enabled: None, + token_cache_passphrase: None, jwt_key_file: None, jwt_kid: None, jwt_passphrase: None, @@ -1040,12 +925,12 @@ mod tests { // No authMode + no token → fail-fast InvalidArgument from the // kernel `AuthConfig::pat` ctor. assert_invalid_arg( - build_auth_config(&o, None).unwrap_err(), + build_auth_config(&o).unwrap_err(), "requires a non-empty access token", ); o.token = Some("dapi-xxx".to_owned()); assert!(matches!( - build_auth_config(&o, None).unwrap(), + build_auth_config(&o).unwrap(), AuthConfig::Pat { .. } )); } @@ -1061,7 +946,7 @@ mod tests { o.azure_tenant_id = Some("tenant-abc".to_owned()); o.azure_workspace_resource_id = Some("/subscriptions/s/resourceGroups/rg/workspace/w".to_owned()); - match build_auth_config(&o, None).unwrap() { + match build_auth_config(&o).unwrap() { AuthConfig::AzureServicePrincipal { azure_client_id, azure_client_secret, @@ -1089,7 +974,7 @@ mod tests { o.auth_mode = Some(AuthMode::AzureSpM2m); o.azure_client_id = Some("entra-app-id".to_owned()); o.azure_client_secret = Some("entra-secret".to_owned()); - match build_auth_config(&o, None).unwrap() { + match build_auth_config(&o).unwrap() { AuthConfig::AzureServicePrincipal { azure_tenant_id, azure_workspace_resource_id, @@ -1109,15 +994,12 @@ mod tests { let mut o = base(); o.auth_mode = Some(AuthMode::AzureSpM2m); o.azure_client_secret = Some("entra-secret".to_owned()); - assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "azure_client_id"); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "azure_client_id"); let mut o = base(); o.auth_mode = Some(AuthMode::AzureSpM2m); o.azure_client_id = Some("entra-app-id".to_owned()); - assert_invalid_arg( - build_auth_config(&o, None).unwrap_err(), - "azure_client_secret", - ); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "azure_client_secret"); } #[test] @@ -1126,7 +1008,7 @@ mod tests { o.auth_mode = Some(AuthMode::Pat); o.token = Some(String::new()); assert_invalid_arg( - build_auth_config(&o, None).unwrap_err(), + build_auth_config(&o).unwrap_err(), "requires a non-empty access token", ); } @@ -1137,7 +1019,7 @@ mod tests { o.token = Some("dapi-xxx".to_owned()); o.identity_federation_client_id = Some("federation-client".to_owned()); - match build_auth_config(&o, None).unwrap() { + match build_auth_config(&o).unwrap() { AuthConfig::Pat { identity_federation_client_id, .. @@ -1162,7 +1044,7 @@ mod tests { m2m.oauth_client_id = Some("cid".to_owned()); m2m.oauth_client_secret = Some("sec".to_owned()); m2m.token_url = Some(endpoint.to_owned()); - match build_auth_config(&m2m, None).unwrap() { + match build_auth_config(&m2m).unwrap() { AuthConfig::OAuthM2M { token_url_override, .. } => assert_eq!(token_url_override.as_deref(), Some(endpoint)), @@ -1172,7 +1054,7 @@ mod tests { let mut u2m = base(); u2m.auth_mode = Some(AuthMode::OAuthU2m); u2m.token_url = Some(endpoint.to_owned()); - match build_auth_config(&u2m, None).unwrap() { + match build_auth_config(&u2m).unwrap() { AuthConfig::OAuthU2M { token_url_override, .. } => assert_eq!(token_url_override.as_deref(), Some(endpoint)), @@ -1185,7 +1067,7 @@ mod tests { jwt.jwt_key_file = Some("/k.pem".to_owned()); jwt.jwt_kid = Some("kid".to_owned()); jwt.token_url = Some(endpoint.to_owned()); - match build_auth_config(&jwt, None).unwrap() { + match build_auth_config(&jwt).unwrap() { AuthConfig::OAuthM2MPrivateKey { token_url_override, .. } => assert_eq!(token_url_override.as_deref(), Some(endpoint)), @@ -1197,7 +1079,7 @@ mod tests { none.auth_mode = Some(AuthMode::OAuthM2m); none.oauth_client_id = Some("cid".to_owned()); none.oauth_client_secret = Some("sec".to_owned()); - match build_auth_config(&none, None).unwrap() { + match build_auth_config(&none).unwrap() { AuthConfig::OAuthM2M { token_url_override, .. } => assert!(token_url_override.is_none()), @@ -1209,13 +1091,13 @@ mod tests { fn m2m_requires_client_id_and_secret() { let mut o = base(); o.auth_mode = Some(AuthMode::OAuthM2m); - assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "client_id"); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "client_id"); o.oauth_client_id = Some("cid".to_owned()); - assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "client_secret"); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "client_secret"); o.oauth_client_secret = Some("sec".to_owned()); o.oauth_scopes = Some(vec!["all-apis".to_owned()]); o.identity_federation_client_id = Some("federation-client".to_owned()); - match build_auth_config(&o, None).unwrap() { + match build_auth_config(&o).unwrap() { AuthConfig::OAuthM2M { client_id, client_secret, @@ -1239,18 +1121,18 @@ mod tests { fn m2m_jwt_requires_client_id_key_file_and_kid() { let mut o = base(); o.auth_mode = Some(AuthMode::OAuthM2mJwt); - assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "client_id"); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "client_id"); o.oauth_client_id = Some("cid".to_owned()); - assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "jwt_key_file"); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "jwt_key_file"); o.jwt_key_file = Some("/k.pem".to_owned()); - assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "jwt_kid"); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "jwt_kid"); o.jwt_kid = Some("kid".to_owned()); o.jwt_passphrase = Some("pass".to_owned()); o.jwt_algorithm = Some("ES256".to_owned()); o.oauth_scopes = Some(vec!["all-apis".to_owned()]); let token_url = "https://idp.example/token"; o.token_url = Some(token_url.to_owned()); - match build_auth_config(&o, None).unwrap() { + match build_auth_config(&o).unwrap() { AuthConfig::OAuthM2MPrivateKey { client_id, jwt_key_file, @@ -1281,7 +1163,7 @@ mod tests { // redirect_port are all None and the kernel fills its default bundle // (databricks-sql-connector / sql offline_access / 8030). See // PECOBLR-4039. - match build_auth_config(&o, None).unwrap() { + match build_auth_config(&o).unwrap() { AuthConfig::OAuthU2M { client_id, redirect_ports, @@ -1299,7 +1181,7 @@ mod tests { o.oauth_client_id = Some("custom-cli".to_owned()); o.oauth_redirect_port = Some(9000); o.identity_federation_client_id = Some("federation-client".to_owned()); - match build_auth_config(&o, None).unwrap() { + match build_auth_config(&o).unwrap() { AuthConfig::OAuthU2M { client_id, redirect_ports, @@ -1317,6 +1199,45 @@ mod tests { } } + #[test] + fn u2m_token_cache_control_maps_to_config() { + let mut o = base(); + o.auth_mode = Some(AuthMode::OAuthU2m); + + // Neither field set → None → the kernel default (enabled, machine key). + match build_auth_config(&o).unwrap() { + AuthConfig::OAuthU2M { token_cache, .. } => assert!(token_cache.is_none()), + other => panic!("expected OAuthU2M, got {other:?}"), + } + + // Explicit disable → Some(TokenCacheConfig { enabled: false }). + o.token_cache_enabled = Some(false); + match build_auth_config(&o).unwrap() { + AuthConfig::OAuthU2M { + token_cache: Some(tc), + .. + } => { + assert!(!tc.enabled); + assert!(tc.passphrase.is_none()); + } + other => panic!("expected OAuthU2M with token_cache, got {other:?}"), + } + + // Passphrase with no explicit enable flag implies enabled. + o.token_cache_enabled = None; + o.token_cache_passphrase = Some("s3cret".to_owned()); + match build_auth_config(&o).unwrap() { + AuthConfig::OAuthU2M { + token_cache: Some(tc), + .. + } => { + assert!(tc.enabled); + assert_eq!(tc.passphrase.as_deref(), Some("s3cret")); + } + other => panic!("expected OAuthU2M with token_cache, got {other:?}"), + } + } + #[test] fn u2m_rejects_explicit_empty_client_id() { // Parity with pyo3: an explicit empty oauthClientId is rejected @@ -1325,7 +1246,7 @@ mod tests { let mut o = base(); o.auth_mode = Some(AuthMode::OAuthU2m); o.oauth_client_id = Some(String::new()); - assert_invalid_arg(build_auth_config(&o, None).unwrap_err(), "oauthClientId"); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "oauthClientId"); } #[test] diff --git a/pyo3/CHANGELOG.md b/pyo3/CHANGELOG.md index 9db2acd2..0043612f 100644 --- a/pyo3/CHANGELOG.md +++ b/pyo3/CHANGELOG.md @@ -9,13 +9,14 @@ they ship on independent cadences. ## [Unreleased] ### Added -- **Pluggable OAuth token store via `oauth_persistence`** — `Session(…, - oauth_persistence=obj)` lets a caller supply a custom OAuth U2M token store on - the kernel path instead of the built-in disk cache. `obj` must expose - `read(host) -> Optional[str]` and `persist(host, token_json) -> None`, - exchanging the kernel's `OAuthToken` as a JSON string. Invoked under the GIL. - The `databricks-sql-python` connector adapts its `experimental_oauth_persistence` - onto this (#913). (PECOBLR-4146) +- **U2M on-disk token-cache control** — `Session(…, token_cache_enabled=…, + token_cache_passphrase=…)` lets a caller enable/disable (or set the AES-256 + passphrase for) the kernel's built-in encrypted disk cache on the kernel path. + Omitted keeps the kernel default (enabled, machine-local key, survives + restarts); `token_cache_enabled=False` re-logins each fresh process; a + passphrase with no explicit flag implies enabled. Applies to `oauth-u2m`. + The `databricks-sql-python` connector maps its `experimental_oauth_persistence` + presence onto this enable flag (#913). (PECOBLR-4146) ## [v0.2.0] - 2026-06-08 diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index c1a1d747..a0492194 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -591,13 +591,11 @@ dependencies = [ "arrow-array", "arrow-pyarrow", "arrow-schema", - "async-trait", "chrono", "databricks-sql-kernel", "log", "pyo3", "pyo3-log", - "serde_json", "tokio", "tracing", ] diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml index 35b43e69..5a05c999 100644 --- a/pyo3/Cargo.toml +++ b/pyo3/Cargo.toml @@ -77,12 +77,6 @@ pyo3 = { version = "0.29", features = ["extension-module", "abi3-py39"] } # Multi-thread runtime — one per Session, owned on the Rust side. tokio = { version = "1", features = ["rt-multi-thread"] } -# Implement the kernel's `#[async_trait] TokenPersistence` for the Python-backed -# pluggable OAuth token store, and (de)serialize the kernel OAuthToken JSON that -# crosses to the Python `oauth_persistence` object (PECOBLR-4146). -async-trait = "0.1" -serde_json = "1" - # Arrow handoff. Pinned to 59 to match the kernel's arrow-* deps so we # share the same RecordBatch / Schema types and never have to convert. arrow-array = "59" diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index ee183d10..821871b8 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -41,12 +41,9 @@ //! wrapper rejects unknown `auth_type` values here so the mistake //! surfaces at construction time, not deep inside an HTTP retry loop. -use std::sync::Arc; use std::time::Duration; -use databricks_sql_kernel::auth::oauth::persistence::TokenPersistence; -use databricks_sql_kernel::auth::oauth::OAuthToken; -use databricks_sql_kernel::{AuthConfig, Error as KernelError}; +use databricks_sql_kernel::{AuthConfig, TokenCacheConfig}; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; @@ -86,93 +83,14 @@ pub(crate) struct OAuthParams { pub azure_client_secret: Option, pub azure_tenant_id: Option, pub azure_workspace_resource_id: Option, - /// Caller-supplied U2M token store (from the Python `oauth_persistence` - /// object), or `None` for the built-in disk cache. Carried here so it - /// flows through the existing `build_auth_config` plumbing without - /// changing that signature; the U2M arm forwards it to the kernel. See - /// [`py_token_store`]. - pub token_store: Option>, -} - -/// Wrap a Python `oauth_persistence` object as a kernel [`TokenPersistence`]. -/// -/// The object must expose `read(host: str) -> Optional[str]` and -/// `persist(host: str, token_json: str) -> None`, exchanging the kernel's -/// `OAuthToken` as an opaque JSON string — the same bytes the on-disk cache -/// stores, so the token (including expiry) round-trips losslessly. The -/// databricks-sql-python connector adapts its `experimental_oauth_persistence` -/// onto this. Consistent with the napi binding's JSON-string wire format. -pub(crate) fn py_token_store(obj: Py) -> Arc { - Arc::new(PyTokenStore { obj }) -} - -struct PyTokenStore { - obj: Py, -} - -impl std::fmt::Debug for PyTokenStore { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("PyTokenStore") - } -} - -#[async_trait::async_trait] -impl TokenPersistence for PyTokenStore { - async fn load( - &self, - host: &str, - _client_id: &str, - _scopes: &[String], - ) -> databricks_sql_kernel::Result> { - // Call the sync Python `read` under the GIL. No `.await` is held across - // the GIL, so the async future stays `Send`. The error string is - // produced inside the closure (formatting a `PyErr` needs the GIL). - let json: Option = - Python::attach(|py| -> std::result::Result, String> { - let obj = self.obj.bind(py); - let ret = obj - .call_method1("read", (host,)) - .map_err(|e| e.to_string())?; - if ret.is_none() { - Ok(None) - } else { - ret.extract::().map(Some).map_err(|e| e.to_string()) - } - }) - .map_err(|e| { - KernelError::io().message(format!("OAuth token store read failed: {e}")) - })?; - match json { - Some(s) => { - let token = serde_json::from_str::(&s).map_err(|e| { - KernelError::invalid_state() - .message(format!("token store returned malformed token JSON: {e}")) - })?; - Ok(Some(token)) - } - None => Ok(None), - } - } - - async fn save( - &self, - host: &str, - _client_id: &str, - _scopes: &[String], - token: &OAuthToken, - ) -> databricks_sql_kernel::Result<()> { - let json = serde_json::to_string(token).map_err(|e| { - KernelError::invalid_state().message(format!("failed to serialize OAuth token: {e}")) - })?; - Python::attach(|py| -> std::result::Result<(), String> { - let obj = self.obj.bind(py); - obj.call_method1("persist", (host, json)) - .map_err(|e| e.to_string())?; - Ok(()) - }) - .map_err(|e| KernelError::io().message(format!("OAuth token store persist failed: {e}")))?; - Ok(()) - } + /// U2M on-disk token-cache control. `None` ⇒ kernel default (enabled, + /// machine-local key). `Some(false)` disables on-disk persistence; + /// `Some(true)` keeps it. A passphrase with no explicit flag implies + /// enabled. + pub token_cache_enabled: Option, + /// Optional passphrase for the U2M on-disk token cache (AES-256 key). + /// `None`/blank ⇒ a machine-local derived key. + pub token_cache_passphrase: Option, } /// Default U2M OAuth client id for the **Python** binding. @@ -411,19 +329,19 @@ fn build_auth_config_inner( scopes, oauth.token_url, oauth.callback_timeout_secs.map(Duration::from_secs), - // `None` takes the kernel default: on-disk cache ENABLED, - // encrypted under a machine-local derived key since this - // binding exposes no passphrase option. That preserves - // cross-connection SSO reuse (the point of the cache) without - // ever writing the refresh token in the clear. Surfacing a - // passphrase through `OAuthParams` — the equivalent of JDBC's - // TokenCachePassPhrase — would strengthen it further. Ignored - // when `token_store` below is `Some`. - None, + // U2M on-disk token-cache control. Both omitted ⇒ kernel + // default (enabled, machine-local derived key — preserves + // cross-restart SSO reuse without writing the token in the + // clear). Otherwise honor the caller's enable flag / + // passphrase; a passphrase alone implies enabled. + match (oauth.token_cache_enabled, oauth.token_cache_passphrase) { + (None, None) => None, + (enabled, passphrase) => Some(TokenCacheConfig { + enabled: enabled.unwrap_or(true), + passphrase, + }), + }, oauth.identity_federation_client_id, - // Caller-supplied Python token store (`oauth_persistence`), - // when provided; overrides the built-in disk cache above. - oauth.token_store, )) } "azure-sp-m2m" => { @@ -717,6 +635,55 @@ mod tests { } } + #[test] + fn u2m_token_cache_control_maps_to_config() { + // Neither field set → None → the kernel default (enabled, machine key). + match build_auth_config_inner("oauth-u2m", None, OAuthParams::default()).unwrap() { + AuthConfig::OAuthU2M { token_cache, .. } => assert!(token_cache.is_none()), + other => panic!("expected OAuthU2M, got {other:?}"), + } + // Explicit disable → Some(TokenCacheConfig { enabled: false }). + let cfg = build_auth_config_inner( + "oauth-u2m", + None, + OAuthParams { + token_cache_enabled: Some(false), + ..Default::default() + }, + ) + .unwrap(); + match cfg { + AuthConfig::OAuthU2M { + token_cache: Some(tc), + .. + } => { + assert!(!tc.enabled); + assert!(tc.passphrase.is_none()); + } + other => panic!("expected OAuthU2M with token_cache, got {other:?}"), + } + // Passphrase with no explicit flag implies enabled. + let cfg = build_auth_config_inner( + "oauth-u2m", + None, + OAuthParams { + token_cache_passphrase: Some("s3cret".to_string()), + ..Default::default() + }, + ) + .unwrap(); + match cfg { + AuthConfig::OAuthU2M { + token_cache: Some(tc), + .. + } => { + assert!(tc.enabled); + assert_eq!(tc.passphrase.as_deref(), Some("s3cret")); + } + other => panic!("expected OAuthU2M with token_cache, got {other:?}"), + } + } + #[test] fn u2m_empty_redirect_ports_rejected() { let err = build_auth_config_inner( diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 72e6585d..2f512a99 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -218,7 +218,8 @@ impl Session { azure_client_secret=None, azure_tenant_id=None, azure_workspace_resource_id=None, - oauth_persistence=None, + token_cache_enabled=None, + token_cache_passphrase=None, tls_ca_cert=None, tls_skip_verify=false, tls_skip_hostname_verify=false, @@ -275,10 +276,10 @@ impl Session { azure_client_secret: Option, azure_tenant_id: Option, azure_workspace_resource_id: Option, - // Optional pluggable OAuth U2M token store (Python object with - // `read(host)->Optional[str]` / `persist(host, token_json)`); overrides - // the built-in disk cache. See `crate::auth::py_token_store`. - oauth_persistence: Option>, + // U2M on-disk token-cache control (kernel path); overrides the kernel + // default (enabled). `False` disables on-disk persistence. + token_cache_enabled: Option, + token_cache_passphrase: Option, tls_ca_cert: Option>, tls_skip_verify: bool, tls_skip_hostname_verify: bool, @@ -352,9 +353,8 @@ impl Session { azure_client_secret, azure_tenant_id, azure_workspace_resource_id, - // Wrap a supplied Python persistence object as a kernel token store - // (U2M only; other auth types ignore it). - token_store: oauth_persistence.map(crate::auth::py_token_store), + token_cache_enabled, + token_cache_passphrase, }; let auth_config = build_auth_config(&resolved_auth_type, access_token, oauth)?; diff --git a/src/auth/oauth/mod.rs b/src/auth/oauth/mod.rs index 98f93400..68053ada 100644 --- a/src/auth/oauth/mod.rs +++ b/src/auth/oauth/mod.rs @@ -31,7 +31,6 @@ pub(crate) mod jwt_key; pub mod jwt_m2m; pub mod m2m; pub mod oidc; -pub mod persistence; #[cfg(test)] pub(crate) mod test_keys; pub mod token; @@ -45,6 +44,5 @@ pub use federation::FederationProvider; pub use jwt_m2m::JwtClientCredentialsProvider; pub use m2m::ClientCredentialsProvider; pub use oidc::OidcEndpoints; -pub use persistence::{DiskTokenCache, TokenPersistence}; pub use token::OAuthToken; pub use u2m::AuthorizationCodeProvider; diff --git a/src/auth/oauth/persistence.rs b/src/auth/oauth/persistence.rs deleted file mode 100644 index 23205efb..00000000 --- a/src/auth/oauth/persistence.rs +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright (c) 2026 Databricks, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Pluggable OAuth token persistence. -//! -//! The U2M flow caches its refresh token so a browser login survives process -//! restarts. By default that is an encrypted on-disk cache ([`DiskTokenCache`], -//! under `~/.config/databricks-sql-kernel/oauth/`), but a caller can inject any -//! [`TokenPersistence`] — a database, an OS keychain, an in-memory store — via -//! the `token_store` field of -//! [`AuthConfig::OAuthU2M`](crate::config::AuthConfig). This is the kernel-side -//! contract the driver bindings map their `OAuthPersistence` (Node) / -//! `experimental_oauth_persistence` (Python) objects onto. - -use crate::auth::oauth::cache::TokenCache; -use crate::auth::oauth::token::OAuthToken; -use crate::kernel_error::Result; - -/// A store for U2M OAuth tokens, keyed by the `{host, client_id, scopes}` -/// triple. -/// -/// The kernel calls [`load`](TokenPersistence::load) before deciding whether to -/// open a browser — a returned token carrying a refresh token is reused and -/// refreshed instead of prompting — and [`save`](TokenPersistence::save) after -/// every acquisition or refresh. -/// -/// **Error handling is lenient by contract:** a `load` error is treated as a -/// cache miss (the kernel falls back to a fresh browser login and never fails -/// the connection on it), and a `save` error is logged and swallowed (a failed -/// cache write must not fail an otherwise-successful authentication). So -/// implementations may surface store/transport errors freely. -#[async_trait::async_trait] -pub trait TokenPersistence: Send + Sync + std::fmt::Debug { - /// Load the cached token for this `{host, client_id, scopes}` key, or - /// `Ok(None)` on a miss. - async fn load( - &self, - host: &str, - client_id: &str, - scopes: &[String], - ) -> Result>; - - /// Persist `token` under this `{host, client_id, scopes}` key. - async fn save( - &self, - host: &str, - client_id: &str, - scopes: &[String], - token: &OAuthToken, - ) -> Result<()>; -} - -/// The default [`TokenPersistence`]: the built-in encrypted on-disk cache. -/// -/// Wraps [`TokenCache`] with the resolved passphrase, preserving the kernel's -/// historical caching behavior exactly. [`Session::open`](crate::Session::open) -/// installs this when the caller supplies no custom `token_store` and on-disk -/// caching is enabled. -#[derive(Debug, Clone)] -pub struct DiskTokenCache { - passphrase: String, -} - -impl DiskTokenCache { - /// Create a disk cache that encrypts entries under `passphrase`. - pub fn new(passphrase: String) -> Self { - Self { passphrase } - } -} - -#[async_trait::async_trait] -impl TokenPersistence for DiskTokenCache { - async fn load( - &self, - host: &str, - client_id: &str, - scopes: &[String], - ) -> Result> { - // `TokenCache::load` is synchronous, local, and fast (one small - // encrypted file). The U2M paths that call this already run inside a - // `block_in_place` region, so invoking it directly preserves the exact - // prior behavior without an extra `spawn_blocking` hop. - Ok(TokenCache::load(host, client_id, scopes, &self.passphrase)) - } - - async fn save( - &self, - host: &str, - client_id: &str, - scopes: &[String], - token: &OAuthToken, - ) -> Result<()> { - TokenCache::save(host, client_id, scopes, token, &self.passphrase); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::collections::HashMap; - use std::sync::{Arc, Mutex}; - - /// In-memory [`TokenPersistence`] test double: records calls and serves - /// tokens from a map keyed by `{host}|{client_id}|{scopes}`. - #[derive(Debug, Default)] - pub(crate) struct InMemoryTokenStore { - pub tokens: Mutex>, - pub loads: Mutex>, - pub saves: Mutex>, - } - - fn key(host: &str, client_id: &str, scopes: &[String]) -> String { - format!("{host}|{client_id}|{}", scopes.join(" ")) - } - - #[async_trait::async_trait] - impl TokenPersistence for InMemoryTokenStore { - async fn load( - &self, - host: &str, - client_id: &str, - scopes: &[String], - ) -> Result> { - let k = key(host, client_id, scopes); - self.loads.lock().unwrap().push(k.clone()); - Ok(self.tokens.lock().unwrap().get(&k).cloned()) - } - - async fn save( - &self, - host: &str, - client_id: &str, - scopes: &[String], - token: &OAuthToken, - ) -> Result<()> { - let k = key(host, client_id, scopes); - self.saves.lock().unwrap().push(k.clone()); - self.tokens.lock().unwrap().insert(k, token.clone()); - Ok(()) - } - } - - #[tokio::test] - async fn in_memory_store_roundtrips() { - let store = InMemoryTokenStore::default(); - let scopes = vec!["sql".to_string(), "offline_access".to_string()]; - assert!(store - .load("https://h", "cid", &scopes) - .await - .unwrap() - .is_none()); - - let token = OAuthToken::new( - "access".to_string(), - "Bearer".to_string(), - 3600, - Some("refresh".to_string()), - scopes.clone(), - ); - store - .save("https://h", "cid", &scopes, &token) - .await - .unwrap(); - - let got = store.load("https://h", "cid", &scopes).await.unwrap(); - assert_eq!(got.unwrap().access_token, "access"); - assert_eq!(store.loads.lock().unwrap().len(), 2); - assert_eq!(store.saves.lock().unwrap().len(), 1); - } - - #[test] - fn disk_token_cache_is_debug_and_clone() { - // Guards the `Debug` bound that `AuthorizationCodeProvider`'s derived - // `Debug` and `AuthConfig`'s manual `Debug` rely on. - let c = DiskTokenCache::new("pass".to_string()); - let _ = format!("{c:?}"); - let _ = c.clone(); - } - - /// The trait must stay object-safe (`Arc` is how it - /// is threaded through `AuthConfig` and the provider). - #[allow(dead_code)] - fn assert_object_safe(_: Arc) {} -} diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 12522fd9..5a27d3b3 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -36,9 +36,9 @@ //! the cache IS enabled the payload is always encrypted under the //! configured passphrase, because it carries that long-lived refresh token. +use crate::auth::oauth::cache::TokenCache; use crate::auth::oauth::callback::CallbackServer; use crate::auth::oauth::oidc::OidcEndpoints; -use crate::auth::oauth::persistence::TokenPersistence; use crate::auth::oauth::token::OAuthToken; use crate::auth::oauth::token_store::TokenStore; use crate::auth::AuthProvider; @@ -62,27 +62,23 @@ const DEFAULT_CALLBACK_PORT: u16 = 8030; /// Default timeout for waiting for the OAuth callback. const DEFAULT_CALLBACK_TIMEOUT: Duration = Duration::from_secs(120); -/// Persist `token` via the configured [`TokenPersistence`] store, or do -/// nothing when no store is configured (`store` is `None`). +/// Persist `token` to the on-disk cache, or do nothing when disk caching +/// is disabled (`passphrase` is `None`). /// /// Exists so the two save sites in the token-acquisition flow (post-refresh -/// and post-browser-flow) cannot drift apart. Per the [`TokenPersistence`] -/// contract a save error is logged and swallowed — a failed cache write must -/// not fail an otherwise-successful authentication. -async fn persist_token( - store: &Option>, +/// and post-browser-flow) cannot drift apart, in particular so neither can +/// accidentally write an unencrypted token or write one when the user asked +/// for no cache at all. +fn save_to_cache( + passphrase: Option<&str>, host: &str, client_id: &str, scopes: &[String], token: &OAuthToken, ) { - match store { - Some(store) => { - if let Err(e) = store.save(host, client_id, scopes, token).await { - crate::klog::warn!("Failed to persist OAuth token to store: {}", e); - } - } - None => crate::klog::debug!("Token persistence disabled; not saving token"), + match passphrase { + Some(passphrase) => TokenCache::save(host, client_id, scopes, token, passphrase), + None => crate::klog::debug!("Token cache disabled; not persisting token to disk"), } } @@ -146,13 +142,12 @@ pub struct AuthorizationCodeProvider { callback_timeout: Duration, /// Whether to open browser automatically (set to false in tests) open_browser: bool, - /// Token store used to load a cached token before opening a browser and to - /// persist after every acquisition/refresh, or `None` when persistence is - /// disabled. `Session::open` installs the built-in encrypted disk cache - /// ([`DiskTokenCache`](crate::auth::oauth::persistence::DiskTokenCache)) - /// here by default, or a caller-supplied store. See - /// [`crate::auth::oauth::persistence`]. - token_persistence: Option>, + /// Passphrase for the on-disk token cache, or `None` when disk + /// caching is disabled. `Some` implies the cache is enabled: the + /// enabled-without-passphrase combination is rejected upstream in + /// [`crate::config::TokenCacheConfig::resolve`], so this field carries + /// both the "should I cache?" and "with what key?" decisions. + cache_passphrase: Option, /// Tokio runtime handle captured from the constructing context; /// used to drive the async token exchange from the sync /// `get_auth_header` trait method safely whether or not the @@ -247,7 +242,7 @@ impl AuthorizationCodeProvider { vec![callback_port], callback_timeout, None, // No token_endpoint override - None, // No token store: persistence disabled + None, // On-disk cache disabled: no passphrase available here ) .await } @@ -257,10 +252,9 @@ impl AuthorizationCodeProvider { /// This is used by Database when a custom token endpoint is configured. /// Most users should use `new()` or `new_with_config()` which use OIDC discovery. /// - /// `token_persistence` is `Some` to enable token caching (the built-in - /// encrypted disk cache or a caller-supplied store) and `None` to disable - /// it. `Session::open` resolves it from the `token_store` / `token_cache` - /// policy — see [`crate::auth::oauth::persistence`]. + /// `cache_passphrase` is `Some` to enable the encrypted on-disk token + /// cache and `None` to disable it; the enabled-but-passphraseless case is + /// rejected upstream by [`crate::config::TokenCacheConfig::resolve`]. // The "full config" constructor is a flat parameter list by design — it is // the single place every U2M knob is threaded in from `Session::open`. #[allow(clippy::too_many_arguments)] @@ -272,7 +266,7 @@ impl AuthorizationCodeProvider { callback_ports: Vec, callback_timeout: Duration, token_endpoint_override: Option, - token_persistence: Option>, + cache_passphrase: Option, ) -> Result { // Discover OIDC endpoints (unless token_endpoint is overridden, we still need auth endpoint) let endpoints = OidcEndpoints::discover(host, &http_client).await?; @@ -283,37 +277,27 @@ impl AuthorizationCodeProvider { // Create token store let token_store = TokenStore::new(); - // Try loading a cached token. A `None` store means persistence is - // disabled, so nothing is read — the in-memory TokenStore above still - // reuses and refreshes within this process. Per the TokenPersistence - // contract a load error is treated as a cache miss (browser flow on - // first auth), never fatal. - if let Some(store) = &token_persistence { - match store.load(host, client_id, &scopes).await { - Ok(Some(cached_token)) if cached_token.refresh_token.is_some() => { - crate::klog::debug!("Loaded cached token with refresh_token for U2M flow"); - // Seed the in-memory TokenStore; it will refresh if needed. - let _ = token_store.get_or_refresh(move || Ok(cached_token.clone())); - } - Ok(Some(_)) => { - crate::klog::debug!( - "Cached token has no refresh_token, will trigger browser flow" - ); - } - Ok(None) => { - crate::klog::debug!( - "No cached token found for U2M flow, will trigger browser flow on first auth" - ); - } - Err(e) => { - crate::klog::warn!( - "Failed to load cached OAuth token (treating as cache miss): {}", - e - ); - } + // Try loading cached token. A `None` passphrase means the on-disk + // cache is disabled, so the file is never even read — the in-memory + // TokenStore above still reuses and refreshes within this process. + if let Some(cached_token) = cache_passphrase + .as_deref() + .and_then(|passphrase| TokenCache::load(host, client_id, &scopes, passphrase)) + { + // Check if the cached token has a refresh token + if cached_token.refresh_token.is_some() { + crate::klog::debug!("Loaded cached token with refresh_token for U2M flow"); + // Store the cached token - TokenStore will handle refresh if needed + // We need to manually insert it since get_or_refresh expects to call the closure + // Let's trigger a get_or_refresh with a closure that returns the cached token + let _ = token_store.get_or_refresh(move || Ok(cached_token.clone())); + } else { + crate::klog::debug!("Cached token has no refresh_token, will trigger browser flow"); } } else { - crate::klog::debug!("Token persistence disabled; browser flow on first auth"); + crate::klog::debug!( + "No cached token found for U2M flow, will trigger browser flow on first auth" + ); } Ok(Self { @@ -327,7 +311,7 @@ impl AuthorizationCodeProvider { callback_ports, callback_timeout, open_browser: true, - token_persistence, + cache_passphrase, // `new_with_full_config` is `async`, so we're guaranteed // to be inside a tokio runtime here. Capture that handle // so `get_auth_header` can dispatch correctly later via @@ -379,7 +363,7 @@ impl AuthProvider for AuthorizationCodeProvider { let callback_timeout = self.callback_timeout; let open_browser = self.open_browser; let http_client = self.http_client.clone(); - let token_persistence = self.token_persistence.clone(); + let cache_passphrase = self.cache_passphrase.clone(); // Get or refresh token via TokenStore let runtime_handle = self.runtime_handle.clone(); @@ -390,23 +374,12 @@ impl AuthProvider for AuthorizationCodeProvider { // inside a runtime, direct `block_on` otherwise. See // `crate::util::runtime`. block_on_in_runtime(&runtime_handle, async { - // Try loading from the store first (skipped when - // persistence is disabled; a load error is treated as a - // miss and falls through to the browser flow). - let cached_token = match &token_persistence { - Some(store) => match store.load(&host, &client_id, &scopes).await { - Ok(cached) => cached, - Err(e) => { - crate::klog::warn!( - "Failed to load cached OAuth token (treating as miss): {}", - e - ); - None - } - }, - None => None, - }; - if let Some(cached_token) = cached_token { + // Try loading from cache first (skipped entirely when + // on-disk caching is disabled). + if let Some(cached_token) = cache_passphrase + .as_deref() + .and_then(|p| TokenCache::load(&host, &client_id, &scopes, p)) + { if let Some(ref refresh_token_str) = cached_token.refresh_token { // Try refreshing the token crate::klog::debug!("Attempting to refresh token via refresh_token"); @@ -464,15 +437,14 @@ impl AuthProvider for AuthorizationCodeProvider { scopes_result, ); - // Save via the store (no-op when disabled) - persist_token( - &token_persistence, + // Save to cache (no-op when disabled) + save_to_cache( + cache_passphrase.as_deref(), &host, &client_id, &scopes, &token, - ) - .await; + ); return Ok(token); } Err(e) => { @@ -593,8 +565,14 @@ impl AuthProvider for AuthorizationCodeProvider { scopes_result, ); - // Save via the store (no-op when disabled) - persist_token(&token_persistence, &host, &client_id, &scopes, &token).await; + // Save to cache (no-op when disabled) + save_to_cache( + cache_passphrase.as_deref(), + &host, + &client_id, + &scopes, + &token, + ); Ok(token) }) @@ -608,8 +586,6 @@ impl AuthProvider for AuthorizationCodeProvider { #[cfg(test)] mod tests { use super::*; - use crate::auth::oauth::cache::TokenCache; - use crate::auth::oauth::persistence::DiskTokenCache; use crate::client::http::HttpClientConfig; use wiremock::matchers::{body_string_contains, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -686,10 +662,7 @@ mod tests { vec![8020], Duration::from_secs(120), None, - Some( - Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) - as Arc, - ), + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create provider"); @@ -742,10 +715,7 @@ mod tests { vec![8020], Duration::from_secs(120), None, - Some( - Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) - as Arc, - ), + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create provider"); @@ -814,10 +784,7 @@ mod tests { vec![0], // Use port 0 to avoid conflicts Duration::from_secs(5), // Short timeout for test None, - Some( - Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) - as Arc, - ), + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create provider"); diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 891d03ac..9467c97b 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -1265,9 +1265,6 @@ fn auth_spec_to_config( None, Some(token_cache), identity_federation_client_id, - // No caller token store over the C ABI (no callback surface); the - // disk cache above is the only U2M persistence path here. - None, ), AuthSpec::AzureServicePrincipal { azure_client_id, diff --git a/src/config.rs b/src/config.rs index d05d531c..5d00859f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -354,17 +354,7 @@ pub enum AuthConfig { callback_timeout: Option, /// On-disk token-cache policy. `None` → [`TokenCacheConfig::default`] /// (enabled, which then requires a passphrase — see that type). - /// Ignored when `token_store` is `Some` (a caller store fully - /// replaces the built-in disk cache). token_cache: Option, - /// Caller-supplied token store. When `Some`, it fully overrides the - /// built-in [`token_cache`](Self::OAuthU2M::token_cache) disk policy: - /// the kernel calls it to load/persist the U2M token instead of the - /// encrypted disk cache. `None` → use the `token_cache` policy. This is - /// the injection point the bindings map their `OAuthPersistence` / - /// `experimental_oauth_persistence` objects onto. See - /// [`crate::auth::oauth::persistence`]. - token_store: Option>, /// SP-wide Workload Identity Federation client id. `None` selects /// BYOT / account-wide WIF behavior when token exchange is needed. identity_federation_client_id: Option, @@ -517,15 +507,6 @@ impl AuthConfig { /// (first free binds). Single-port callers pass a one-element list /// (`Some(vec![port])`); `None`/empty falls back to the /// `[8030, 8031, 8032, 8033, 8034]` default window. - /// - /// `token_store` optionally injects a caller-supplied - /// [`TokenPersistence`](crate::auth::oauth::persistence::TokenPersistence) - /// (a DB / keychain / in-memory store); when `Some` it fully overrides the - /// `token_cache` disk policy. Bindings forward it as the last argument - /// because [`AuthConfig`] is `#[non_exhaustive]` — cross-crate wrappers - /// cannot build the `OAuthU2M` struct literal directly and must go through - /// this constructor. - #[allow(clippy::too_many_arguments)] pub fn oauth_u2m( client_id: Option, redirect_ports: Option>, @@ -534,7 +515,6 @@ impl AuthConfig { callback_timeout: Option, token_cache: Option, identity_federation_client_id: Option, - token_store: Option>, ) -> Self { AuthConfig::OAuthU2M { client_id, @@ -543,7 +523,6 @@ impl AuthConfig { token_url_override, callback_timeout, token_cache, - token_store, identity_federation_client_id, } } @@ -2070,7 +2049,6 @@ mod tests { None, None, Some("federation-client".to_string()), - None, ); assert_eq!( @@ -2082,7 +2060,7 @@ mod tests { #[test] fn oauth_u2m_none_ports_stays_none() { // No ports supplied → redirect_ports is None (session fills the default). - let auth = AuthConfig::oauth_u2m(None, None, None, None, None, None, None, None); + let auth = AuthConfig::oauth_u2m(None, None, None, None, None, None, None); match auth { AuthConfig::OAuthU2M { redirect_ports, .. } => assert_eq!(redirect_ports, None), other => panic!("expected OAuthU2M, got {other:?}"), @@ -2101,7 +2079,6 @@ mod tests { None, None, None, - None, ); match auth { AuthConfig::OAuthU2M { redirect_ports, .. } => { @@ -2132,7 +2109,6 @@ mod tests { token_url_override: None, callback_timeout: None, token_cache: None, - token_store: None, identity_federation_client_id: Some("federation-client".to_string()), }, ]; diff --git a/src/session.rs b/src/session.rs index 7acf64ff..7a2f31bf 100644 --- a/src/session.rs +++ b/src/session.rs @@ -45,7 +45,6 @@ //! enabled, they drive real transactions (a Private Preview feature that //! requires catalog-managed tables server-side). -use crate::auth::oauth::persistence::{DiskTokenCache, TokenPersistence}; use crate::auth::{ AuthProvider, AuthorizationCodeProvider, ClientCredentialsProvider, FederationProvider, JwtClientCredentialsProvider, PersonalAccessToken, @@ -1275,7 +1274,6 @@ async fn build_base_auth_provider( token_url_override, callback_timeout, token_cache, - token_store, .. } => { // Fill the coupled kernel default bundle for any unset field @@ -1289,18 +1287,15 @@ async fn build_base_auth_provider( scopes.as_deref(), ); let timeout = callback_timeout.unwrap_or_else(|| Duration::from_secs(120)); - // A caller-supplied `token_store` wins outright; otherwise derive - // the built-in encrypted disk cache from the `token_cache` policy. - // `resolve()` returns `Some(passphrase)` when caching is enabled - // (substituting a machine-local derived key when the caller gave - // none, rather than failing or writing plaintext — see - // `TokenCacheConfig`) and `None` to disable persistence entirely. - let token_persistence: Option> = - token_store.clone().or_else(|| { - token_cache.clone().unwrap_or_default().resolve().map(|p| { - Arc::new(DiskTokenCache::new(p.into_owned())) as Arc - }) - }); + // `Some(passphrase)` enables the on-disk cache, `None` disables + // it. When the cache is on but the caller supplied no passphrase, + // `resolve` substitutes a machine-local derived one rather than + // failing or writing plaintext — see `TokenCacheConfig`. + let cache_policy = token_cache + .clone() + .unwrap_or_default() + .resolve() + .map(|p| p.into_owned()); let provider = AuthorizationCodeProvider::new_with_full_config( host, &client_id, @@ -1309,7 +1304,7 @@ async fn build_base_auth_provider( callback_ports, timeout, token_url_override.clone(), - token_persistence, + cache_policy, ) .await?; Ok(Arc::new(provider)) diff --git a/tests/oauth_u2m_integration.rs b/tests/oauth_u2m_integration.rs index 2a59cf56..95b83782 100644 --- a/tests/oauth_u2m_integration.rs +++ b/tests/oauth_u2m_integration.rs @@ -18,7 +18,6 @@ //! allowing us to test the complete U2M refresh flow without requiring a real OAuth server //! or browser interaction. -use databricks_sql_kernel::auth::oauth::persistence::{DiskTokenCache, TokenPersistence}; use databricks_sql_kernel::auth::oauth::u2m::AuthorizationCodeProvider; use databricks_sql_kernel::auth::AuthProvider; use databricks_sql_kernel::client::http::{DatabricksHttpClient, HttpClientConfig}; @@ -122,10 +121,7 @@ async fn test_u2m_refresh_token_full_flow() { vec![8020], Duration::from_secs(120), None, - Some( - Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) - as Arc, - ), + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create AuthorizationCodeProvider"); @@ -199,10 +195,7 @@ async fn test_u2m_refresh_token_stale_immediate_return() { vec![8021], Duration::from_secs(120), None, - Some( - Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) - as Arc, - ), + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create provider"); @@ -282,10 +275,7 @@ async fn test_u2m_refresh_token_expired_fallback() { vec![0], // Use port 0 to avoid conflicts Duration::from_secs(5), // Short timeout for test None, - Some( - Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) - as Arc, - ), + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create provider"); @@ -360,10 +350,7 @@ async fn test_u2m_refresh_updates_cache() { vec![8023], Duration::from_secs(120), None, - Some( - Arc::new(DiskTokenCache::new(TEST_CACHE_PASSPHRASE.to_string())) - as Arc, - ), + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create provider"); diff --git a/tests/v0_session_e2e.rs b/tests/v0_session_e2e.rs index fab498fc..26489b05 100644 --- a/tests/v0_session_e2e.rs +++ b/tests/v0_session_e2e.rs @@ -134,7 +134,6 @@ async fn open_with_oauth_u2m_against_live_warehouse() { enabled: false, passphrase: None, }), - token_store: None, identity_federation_client_id: None, }) .open() @@ -190,7 +189,6 @@ async fn open_with_oauth_u2m_falls_back_past_busy_port() { enabled: false, passphrase: None, }), - token_store: None, identity_federation_client_id: None, }) .open() From 74223c954089f50a6eef840bed5efa7311a8d199 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Sat, 22 Aug 2026 07:01:08 +0000 Subject: [PATCH 08/10] ai: apply changes for #283 (1 review thread) Addresses: - #3834840985 at napi/src/database.rs:452 Signed-off-by: peco-engineer-bot[bot] --- .../PECOBLR-4146-oauth-token-persistence-design.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md b/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md index e66364f1..efcccb5c 100644 --- a/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md +++ b/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md @@ -116,6 +116,15 @@ multi-tenant server sharing tokens in a DB). Until then it stays deferred. - Wire format: the kernel's `OAuthToken` serialized to JSON (lossless; the exact bytes the disk cache stores) — avoids reconstructing expiry from a partial token. +- Store key: the callback boundary MUST carry the full `{host, client_id, + scopes}` triple — the same key `TokenPersistence` / `DiskTokenCache` use (the + cache filename is a SHA-256 of all three; see `src/auth/oauth/cache.rs`). + Keying a caller-supplied store on `host` alone would collide two U2M sessions + to the same host with different `client_id`/`scopes` — the second `save` + overwrites the first and a `load` can return a token minted for a different + client/scope set — silently diverging from the built-in disk cache, which + keeps those as distinct entries. So the napi/pyo3 persist/load args must + include `client_id` and `scopes`, not just `host` and `token_json`. - napi: `openSession` gains two callbacks wrapped as `ThreadsafeFunction`s; `load`/`save` `call_async` the JS function and `await` its `Promise`. - pyo3: a `PyTokenStore` calling the Python object under the GIL From a3c32b6d2eb4cdc2f6da6ec9eb7bdc2679a286f5 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Sat, 22 Aug 2026 00:10:39 -0700 Subject: [PATCH 09/10] fix(napi): keep the V2 generated contract; add token-cache fields to index.d.ts only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI's check-napi-loader-drift.sh parses index.js for the @napi-rs/cli v2-style `const { ... } = nativeBinding` destructure; the earlier V3 regen (cli 3.8.2) broke it. New `#[napi(object)]` fields don't change the exported symbol set, so the loader (index.js) needs no change — restore it to the committed V2 output and add only `tokenCacheEnabled` / `tokenCachePassphrase` to the ConnectionOptions interface in index.d.ts. Drift check passes locally. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- napi/CHANGELOG.md | 7 +- napi/index.d.ts | 1739 ++++++++++++++++++++++----------------------- napi/index.js | 918 +++++++----------------- 3 files changed, 1124 insertions(+), 1540 deletions(-) diff --git a/napi/CHANGELOG.md b/napi/CHANGELOG.md index 04fd3e4b..63498d50 100644 --- a/napi/CHANGELOG.md +++ b/napi/CHANGELOG.md @@ -17,10 +17,9 @@ they ship on independent cadences. passphrase with no explicit flag implies enabled. Applies to `OAuthU2m`. (PECOBLR-4146) - The generated native contract (`index.js` / `index.d.ts`) was regenerated - with the crate-correct `@napi-rs/cli@3.8.2`; the previously-committed contract - was stale `@napi-rs/cli` v2 output, so that diff also migrates the loader to - v3 (version-consistency checks, WASI fallback). + The generated `index.d.ts` gains the two optional fields; `index.js` (the + loader) is unchanged — new `#[napi(object)]` fields don't alter the exported + symbol set. ## [v0.2.0] - 2026-06-08 diff --git a/napi/index.d.ts b/napi/index.d.ts index 9e33b65d..21cf939e 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -1,804 +1,356 @@ -/* auto-generated by NAPI-RS */ +/* tslint:disable */ /* eslint-disable */ -/** - * Opaque result-fetch handle returned by - * `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` - * directly; structurally analogous to the sync `Statement`'s - * fetch-side surface (`fetchNextBatch` / `schema` / - * `statementId`). - * - * `cancel()` / `close()` are not exposed: the parent - * `AsyncStatement` owns server-side lifecycle. A `close()` here - * would create dual-ownership of the same statement_id with - * inconsistent close semantics. Callers `close()` the parent - * `AsyncStatement` after they're done fetching. - * - * Schema is cached at construction so it survives the underlying - * stream being drained; mirrors the sync `Statement.schema()` - * post-close contract. - */ -export declare class AsyncResultHandle { - /** - * Server-issued statement id. Cached at construction; readable - * for log correlation. Matches the parent `AsyncStatement`'s - * `statementId`. - */ - get statementId(): string - /** - * Pull the next batch of results. Returns `null` when the - * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a - * complete Arrow IPC stream (schema header + 1 record-batch - * message), suitable for handing to `apache-arrow`'s - * `RecordBatchReader`. Byte-identical to the sync - * `Statement.fetchNextBatch()` payload for the same query. - */ - fetchNextBatch(): Promise - /** - * Result schema as an Arrow IPC payload (schema header only, - * no record-batch message). Available before any batches have - * been fetched. Sync because the body has no `.await` — - * `encode_ipc_stream` is pure CPU work over the cached - * `Arc`. - */ - schema(): ArrowSchema -} + +/* auto-generated by NAPI-RS */ /** - * Opaque async-statement handle. + * Per-statement options for `Connection.executeStatement`. * - * Returned by `Connection.submitStatement(...)` after the kernel - * `Statement::submit()` returns (server sent `wait_timeout=0s`, so - * the response carries a `statement_id` but the statement is still - * `Pending`/`Running`). JS drives polling via `status()` / - * `awaitResult()`. + * Mirrors the kernel `StatementSpec` knobs that are safe to thread + * through napi without a kernel-side change. Today this covers: + * - `statementConf` — per-statement Spark conf overlay + * (`StatementSpec.statement_conf` → SEA `parameters` / + * Thrift `confOverlay`) + * - `queryTags` — convenience wrapper over `statementConf` with + * key `query_tags`; serialised to the same comma-separated + * `key:value` wire shape NodeJS Thrift's `serializeQueryTags` + * produces (`lib/utils/queryTags.ts`). Backslashes in keys are + * doubled; backslash/colon/comma in values are backslash-escaped. * - * Concurrency shape: `status()`, `awaitResult()`, and `close()` take - * `inner.lock()` and hold the guard across the kernel `.await` (tokio - * `Mutex` is FIFO), so `status()` / `close()` queue behind any - * in-flight `awaitResult()` until it returns naturally. `cancel()` is - * the deliberate exception: it does **not** touch `inner` — it fires - * through the detached `AsyncStatementCanceller` (session + - * statement_id, captured at construction), so an explicit - * `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of - * queueing behind it. The server-side cancel flips the statement - * terminal, which the parked `awaitResult()` poll loop observes - * (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard` - * still covers the drop-cancel case (Promise.race / timeout) - * independently — see module docs. + * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel + * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) + * carry bound query parameters, decoded via `params::parse_typed_value`. + * (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold + * window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.) + * + * **Tag-order caveat (M4 parity note).** The napi `queryTags` field + * is a Rust `HashMap` whose iteration order is + * non-deterministic, so the serialised `query_tags` value may have + * a different key order than Thrift's `serializeQueryTags` (which + * iterates `Object.keys(...)` in insertion order) for the same + * input. The SEA server is order-insensitive on conf values, so + * the two are functionally equivalent. If a caller needs + * byte-identical Thrift parity, the JS adapter pre-serialises via + * `serializeQueryTags` and writes the result into + * `statementConf["query_tags"]` directly — see + * `KernelSessionBackend.executeStatement` in the NodeJS driver. This + * path is the one the production code uses. */ -export declare class AsyncStatement { +export interface ExecuteOptions { /** - * Server-issued statement id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate - * against kernel / server logs which key on the same id. + * Per-statement Spark conf overlay. Merged on top of the + * session-level `sessionConf` at execute time; this map wins + * on key collisions. Unknown keys are rejected by the server. */ - get statementId(): string + statementConf?: Record /** - * One-shot status check. Returns a string enum matching the - * kernel `StatementStatus` shape: - * `'Pending' | 'Running' | 'Succeeded' | 'Failed' | - * 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the - * `#[non_exhaustive]` forward-compat catch-all that - * `StatementStatus::as_str` can return — consumers switching on - * the state must handle it.) Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. + * Query tags as key→value pairs. Serialised to a comma- + * separated `key:value` string (backslash-escaping `\`, `:`, + * `,`) and placed into `statementConf["query_tags"]`, matching + * NodeJS Thrift's `serializeQueryTags` wire shape. Passing + * both `queryTags` AND a `query_tags` key in `statementConf` + * raises `InvalidArgument` — the caller's intent is ambiguous + * so we refuse to silently pick one over the other. * - * The `Failed` variant collapses to the string `'Failed'` on - * the JS side; the underlying error envelope (sql_state / - * error_code / query_id) is surfaced by `awaitResult()`'s - * rejection, which is where callers actually need the typed - * error. `status()` is intended for polling progress UIs - * 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). + * A **`null`** value emits a **bare key** (no colon) — e.g. + * `{ production: null }` → `"production"` — matching the + * connectors' `key`-only tag form. + * + * See the struct-level "Tag-order caveat" for the + * HashMap-iteration-order vs `Object.keys`-iteration-order + * divergence and the byte-identical-Thrift-parity workaround. */ - displayMessage(): Promise - /** Server-supplied diagnostic detail. */ - diagnosticInfo(): Promise - /** Server-supplied structured error detail (JSON), when enabled. */ - errorDetailsJson(): Promise + queryTags?: Record /** - * Block until the server reaches a terminal state, then return - * an `AsyncResultHandle` that wraps the materialised result - * stream. The handle exposes `fetchNextBatch()` / `schema()` - * for consuming the result, plus `statementId` for log - * correlation. - * - * Drop-cancel safety: kernel `await_result` installs - * `AwaitResultCancelGuard` which fires a fire-and-forget - * `cancel_statement` if the future is dropped mid-poll - * (timeout, tokio::select! loser, JS-side `Promise.race` - * loser). The `util::guarded` `catch_unwind` here covers the - * V8-panic-across-boundary case on top. Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. + * Server-side cap on the number of rows this statement returns + * (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to + * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. */ - awaitResult(): Promise + rowLimit?: number /** - * Server-side cancel. Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. Idempotent against a server - * that already reached a terminal state — the kernel's - * `cancel_statement` is a no-op there. - * - * **Lock-free by design.** Unlike `status()` / `awaitResult()` / - * `close()`, this does not take `inner.lock()` — it fires through - * the detached `AsyncStatementCanceller` captured at construction. - * That lets `stmt.cancel()` interrupt an in-flight `awaitResult()` - * (which holds the mutex for the whole poll) instead of queueing - * behind it: the server-side cancel flips the statement terminal, - * the parked `awaitResult()` poll loop observes `Cancelled` and - * returns. The closed-state check reads a lock-free flag so a - * cancel after an explicit `close()` still surfaces - * `InvalidStatementHandle`. + * Positional parameters, in 1-based wire order. Index `i` in this + * Vec corresponds to the `i+1`-th `?` placeholder in the SQL. + * Each entry is a `{ sqlType, value }` pair — `value` is the + * string-encoded literal or `null` for SQL NULL. Mirrors + * `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. */ - cancel(): Promise + positionalParams?: Array /** - * Explicit close. Idempotent — a second call on an - * already-closed handle returns `Ok(())`. On `Err`, the napi - * inner is already `None`, so a JS-side retry sees the - * closed-handle short-circuit and returns `Ok(())` without - * re-attempting the wire call. The kernel's own `Drop` - * fire-and-forget retry runs once in the background. + * Named parameters (`:name` placeholders). Each carries its `name` + * alongside the `{ sqlType, value? }` pair. Mapped to a kernel + * `TypedValue` via the same [`parse_typed_value`] codec and bound with + * `StatementSpec::param_named`. Named is the SEA-spec-required public + * param form (`StatementParameter.name` is `openapi_required`); + * positional is the documented-undocumented variant. The two are + * mutually exclusive at the SQL level (`?` vs `:name`). */ - close(): Promise + namedParams?: Array } - /** - * Handle returned by `Connection.executeStatementCancellable`. Owns the - * built-but-not-yet-executed kernel `Statement` plus a detached - * [`StatementCanceller`] captured before dispatch, so JS can fire a - * server-side cancel while the blocking `result()` is in flight. + * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a + * distinct napi object (rather than an optional `name` on `TypedValueInput`) + * so the positional surface stays a clean ordered list with no name field. + */ +export interface NamedTypedValueInput { + name: string + sqlType: string + value?: string +} +/** + * Authentication mode selector crossing the napi boundary. The string + * literals are what napi-rs emits from this `#[napi(string_enum)]` — the + * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`, + * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). * - * `pending` is `Arc>>` so `result()` can - * `.take()` the statement (the kernel `execute()` borrows it `&mut`, - * then it moves into the produced `Statement` wrapper to keep its - * `ValidityFlag` set — see `statement.rs`). A second `result()` call - * after the first resolved surfaces `InvalidStatementHandle`. + * Mirrors the kernel [`AuthConfig`] variants this binding supports. + * `OAuthFederation` / `External` are intentionally not exposed yet — the + * kernel marks federation as not-yet-implemented and `External` is a + * Rust-trait escape hatch with no JS-callback bridge. */ -export declare class CancellableExecution { +export const enum AuthMode { + /** Personal access token (`token`). */ + Pat = 'Pat', + /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */ + OAuthM2m = 'OAuthM2m', /** - * The server-issued statement id this execution targets, if the - * server has issued one yet (`null` before the initial submit - * round-trip publishes it mid-`result()`). Useful for log - * correlation while the blocking drive is in flight. + * OAuth 2.0 machine-to-machine with a JWT private-key client + * assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. */ - get statementId(): string | null + OAuthM2mJwt = 'OAuthM2mJwt', /** - * Drive the blocking `execute()` and resolve to a `Statement` - * (identical to what `executeStatement` returns) once the kernel - * reaches a terminal state and the result stream is ready. - * - * Consumes the pending statement: a second `result()` call returns - * `KernelError(InvalidStatementHandle)`. The future is - * drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState` - * guard fires a fire-and-forget `cancel_statement` if this future is - * dropped mid-flight (`Promise.race` / timeout loser), independently - * of an explicit `cancel()`. - * - * On a server-side cancel the kernel's blocking `execute()` currently - * surfaces `InvalidArgument` (a known kernel quirk — the async path - * returns `Cancelled`). When this handle's `cancel()` actually dispatched a - * server-side cancel, we normalise that into `Cancelled` here so JS callers - * can rely on a single cancelled-status code regardless of execution path. - * - * Three outcomes can race the blocking drive: (1) a natural terminal state - * → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a - * server cancel → this `result()` rejects with a `Cancelled`-coded error - * (the normalisation above); (3) the future being **dropped** mid-flight - * (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState` - * drop-guard fires a fire-and-forget `cancel_statement`, but there is no - * `result()` left to observe a code. Only (2) yields a `Cancelled` error. + * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` + * + `oauthRedirectPort`. */ - result(): Promise + OAuthU2m = 'OAuthU2m', /** - * Server-side cancel of the in-flight statement. - * - * Lock-free: fires the detached `StatementCanceller` captured at - * construction rather than taking the mutex `result()` holds, so it - * interrupts a still-running blocking `result()` instead of queueing - * behind it. No-op (returns `Ok`) if `result()` already finished - * successfully, or if no statement id has been observed yet (query still - * in its initial submit round-trip), and idempotent against a server - * already in a terminal state. + * Azure Entra service-principal M2M — `azureClientId` + + * `azureClientSecret` (+ optional `azureTenantId` / + * `azureWorkspaceResourceId`). The kernel builds the Entra token + * endpoint + `.default` scope, auto-discovers the tenant from the + * workspace when `azureTenantId` is omitted, and — when + * `azureWorkspaceResourceId` is set — additionally sends the SP + * management token for an RBAC-only service principal. */ - cancel(): Promise + AzureSpM2m = 'AzureSpM2m' } - /** - * Opaque connection handle wrapping a kernel `Session`. + * A single extra HTTP header as an explicit `{ name, value }` pair. * - * `inner` is `Arc>>` so: - * - the Drop impl can clone the `Arc` and `.take()` the session on a - * background tokio task without holding `&mut self` (which Drop is - * forbidden from doing across an `await`), - * - `close()` can `.take()` the session to consume it for the kernel's - * move-by-value `Session::close(self)` signature. + * An ordered list of these (`ConnectionOptions.custom_headers`) mirrors + * the kernel core's `Vec<(String, String)>` and the pyo3 binding's + * `http_headers`: order is preserved and duplicate `name`s are allowed. + * A struct (rather than a raw `[name, value]` tuple) because napi-rs + * does not marshal Rust tuples through `#[napi(object)]` fields; the + * struct is the idiomatic, self-documenting equivalent and maps to a JS + * `{ name: string, value: string }`. + */ +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. * - * **Concurrency shape** — both `executeStatement` and - * `submitStatement` build the kernel `Statement` under `inner.lock()` - * and then RELEASE the guard before the wire call - * (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()` - * is `&self`-callable and only clones the session's internal `Arc`, so - * the built statement is independent of the guard. Concurrent - * `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore - * serialise only for the microsecond statement-build, not the network - * round-trip, and `close()` never blocks behind an in-flight execute or - * submit. See - * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. + * - `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 declare class Connection { +export interface ProxyInput { + url: string + username?: string + password?: string + bypassHosts?: string +} +/** + * JS-visible options for opening a Databricks SQL session. + * + * Authentication is selected by `authMode` (default [`AuthMode::Pat`]): + * - `Pat` — `token` required. + * - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. + * - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional + * (defaults to the `databricks-sql-connector` client on port 8030). + * - `AzureSpM2m` — `azureClientId` + `azureClientSecret` required + * (+ optional `azureTenantId` / `azureWorkspaceResourceId`). + * + * Catalog / schema / sessionConf are applied once at session creation + * and remain in effect for every statement run on the resulting + * `Connection`. The SEA wire protocol carries them on + * `CreateSession`, not on `ExecuteStatement` — so there is no + * per-statement override path on this binding. + */ +export interface ConnectionOptions { /** - * Server-issued session id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate - * against kernel / server logs which key on the same id. + * Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel + * normalises this — bare hostnames get `https://` prepended. */ - get sessionId(): string + hostName: string /** - * Execute a SQL statement and return a Statement handle that - * streams batches via `fetchNextBatch()`. - * - * Catalog / schema / sessionConf are session-level - * (`openSession`). Per-statement options on `ExecuteOptions`: - * - `statementConf` — per-statement Spark conf overlay - * - `queryTags` — serialised to a comma-separated `key:value` - * string and placed in `statement_conf["query_tags"]`, - * matching NodeJS Thrift's `serializeQueryTags` wire shape - * - * `options` is omitted/`None` for the no-options path; passing - * `{ statementConf: {} }` (an empty map) is treated the same as - * omission to keep the wire shape stable for the common case. + * JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The + * kernel parses out the warehouse id. */ - executeStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise + httpPath: string /** - * directResults execute — the Thrift/JDBC model. Sends ExecuteStatement - * with no `wait_timeout` field (server applies its ~10s default inline wait - * and auto-closes on success) and returns WITHOUT polling past it: - * - * - a **`Statement`** (left arm) when the query finished within the inline - * wait — terminal, result ready inline, `close()` is a clean release; - * - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel - * handle the caller drives (`status()` / `awaitResult()` / `cancel()`). - * - * JS distinguishes the arms by feature-detecting `awaitResult` (present - * only on `AsyncStatement`). This is the path that gives mid-run cancel for - * long queries WITHOUT the eager-handle / close-drives workaround: the - * returned handle always corresponds to a server-owned statement. - * - * **Load-bearing contract:** the kernel's `DirectStatement::{Completed, - * Running}` discriminant cannot ride on these opaque `#[napi]` classes, so - * consumers MUST feature-detect via `awaitResult` (the only member unique to - * `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an - * `awaitResult` member, or every consumer silently misroutes. The pyo3 - * binding makes the same `await_result`-probe assumption. + * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: + * existing PAT callers pass only `token`). */ - executeStatementDirect(sql: string, options?: ExecuteOptions | undefined | null): Promise + authMode?: AuthMode /** - * Execute a SQL statement on the blocking (sync) path, but return a - * `CancellableExecution` handle so a concurrent JS task can cancel - * the query *while it is still running server-side*. - * - * `executeStatement` builds the kernel `Statement`, awaits the - * blocking `execute()`, and only then hands JS a `Statement` — so a - * query that runs for several seconds is uncancellable from JS on - * that path (there is no handle until the blocking call resolves). - * This method instead builds the statement, captures a detached - * `StatementCanceller` **before** dispatching `execute()`, and hands - * JS a `CancellableExecution` immediately. The caller drives the - * blocking execution via `result()` (resolves to the same - * `Statement` `executeStatement` returns) and can fire `cancel()` - * concurrently to interrupt a still-running query mid-COMPUTE. - * - * Option semantics are identical to `executeStatement`. - * Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` - * split (PR #121): obtain the canceller before the blocking drive. + * Personal access token. Required (and non-empty) for + * [`AuthMode::Pat`]; ignored otherwise. */ - executeStatementCancellable(sql: string, options?: ExecuteOptions | undefined | null): Promise + token?: string /** - * Submit a SQL statement and return immediately with an - * `AsyncStatement` handle, without blocking until the query - * finishes. The kernel's `Statement::submit()` sends - * `wait_timeout=0s`, so the server responds as soon as it has a - * `statement_id` (state `Pending`/`Running`); JS drives polling - * via `AsyncStatement.status()` and materialises results with - * `AsyncStatement.awaitResult()`. - * - * This is the async-execution path the Thrift backend always - * uses (`runAsync: true`): the SEA backend submits, returns a - * pending operation handle, and polls to terminal during - * fetch. Option semantics (statementConf / queryTags / - * rowLimit / positional + named params) match `executeStatement`. - * Submit always sends `wait_timeout=0s` so the call returns - * immediately; the caller drives completion via `status()` / - * `awaitResult()`. Only the blocking-vs-pending return contract - * differs from `executeStatement`. + * OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for + * [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). */ - submitStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise + oauthClientId?: string + /** OAuth client secret. Required for [`AuthMode::OAuthM2m`]. */ + oauthClientSecret?: string /** - * Explicit close. Awaits the server-side `DeleteSession` so the - * JS caller can observe failures (auth revoked mid-session, - * warehouse stopped, network error). Idempotent — a second call - * on an already-closed connection returns `Ok`. - * - * **Errors are terminal from the JS side.** The kernel session - * handle is consumed (`take()`) BEFORE the wire `DeleteSession` - * runs, because `Session::close` takes `self` by value. On `Err`, - * the napi `inner` is already `None`, so a JS-side retry sees a - * closed connection and returns `Ok(())` without re-attempting - * the wire call. The kernel's own `Drop` fire-and-forget retry - * runs once in the background — the JS caller can log the error - * but cannot drive a retry. If you need retry-on-failure - * semantics for `DeleteSession`, layer them above this method. + * Localhost callback port for the [`AuthMode::OAuthU2m`] browser + * flow. Omitted ⇒ kernel default (8030). */ - close(): Promise + oauthRedirectPort?: number /** - * All catalogs visible to the session. - * - * JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. + * OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults + * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). */ - listCatalogs(): Promise + oauthScopes?: Array /** - * Schemas filtered by catalog (exact) and schema name pattern. - * - * JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. + * OAuth token endpoint override. When omitted the kernel discovers the + * endpoint via the workspace's OIDC configuration. Set it to point the + * client-credentials / JWT client-assertion grant at the workspace's + * configured IdP token endpoint (e.g. Entra ID for Azure Databricks), + * which is required when that IdP — not Databricks-native OIDC — is the + * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. */ - listSchemas(catalog?: string | undefined | null, schemaPattern?: string | undefined | null): Promise + tokenUrl?: string /** - * Tables filtered by catalog (**pattern**), schema (pattern), table - * (pattern). - * - * The catalog is an ODBC/JDBC LIKE pattern (`%` / `_`), matching - * Thrift `getTables`: a wildcard catalog matches multiple catalogs; - * a literal name (or an escaped `\_` / `\%`) takes the fast exact - * path. `undefined`/omitted catalog means "all catalogs", while an - * **empty string** means "match nothing" (zero rows) — pass - * `undefined`, not `""`, for all catalogs. The catalog pattern is - * validated (whitespace-only / NUL / >255 bytes are rejected with an - * error). - * - * JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, - * filters rows by `TABLE_TYPE` kernel-side. - * - * `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does - * NOT honour the table-type filter server-side; the kernel applies - * it client-side after the result returns. Callers expecting - * server-side rejection of off-type tables should not rely on this. + * U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel + * default (cache enabled, encrypted under a machine-local key, survives + * restarts). `false` disables on-disk persistence (re-login each fresh + * process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. */ - listTables(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, tableTypes?: Array | undefined | null): Promise + tokenCacheEnabled?: boolean /** - * Columns of tables matching the filter. - * - * JDBC `getColumns` shape: 23 columns. + * Optional passphrase for the U2M on-disk token cache (AES-256 key). + * Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. + * A passphrase with no explicit `tokenCacheEnabled` implies enabled. + * Applies to [`AuthMode::OAuthU2m`]. */ - listColumns(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, columnPattern?: string | undefined | null): Promise + tokenCachePassphrase?: string /** - * Functions visible to the session. `catalog` is exact; - * `schemaPattern` and `functionPattern` are SQL LIKE. + * Path to the PEM private-key file. Required for + * [`AuthMode::OAuthM2mJwt`]. */ - listFunctions(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, functionPattern?: string | undefined | null): Promise + jwtKeyFile?: string + /** JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. */ + jwtKid?: string /** - * Procedures visible to the session. `catalog` is exact; - * `schemaPattern` and `procedurePattern` are SQL LIKE. + * Passphrase for an encrypted PKCS#8 key. Optional for + * [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). */ - listProcedures(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, procedurePattern?: string | undefined | null): Promise + jwtPassphrase?: string /** - * All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). - * No wire call — static in-memory result. + * JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, + * `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] + * (omitted ⇒ kernel default `RS256`). */ - listTableTypes(): Promise + jwtAlgorithm?: string /** - * SQL data types supported by the workspace. - * No wire call — static in-memory result. + * SP-wide Workload Identity Federation client id used during mandatory + * token exchange. Omitted selects BYOT / account-wide WIF. */ - listTypeInfo(): Promise + identityFederationClientId?: string /** - * Primary keys for the given table. All three identifiers are - * exact — ODBC `SQLPrimaryKeys` does not support patterns. + * Azure Entra app-registration client id. Required for + * [`AuthMode::AzureSpM2m`]; ignored otherwise. */ - getPrimaryKeys(catalog: string, schema: string, table: string): Promise + azureClientId?: string /** - * Foreign-key relationships. The foreign side must be fully - * specified (catalog + schema + table); the parent side is - * optional. All identifiers are exact — no LIKE patterns. + * Azure Entra app-registration client secret. Required for + * [`AuthMode::AzureSpM2m`]. */ - getCrossReference(parentCatalog: string | undefined | null, parentSchema: string | undefined | null, parentTable: string | undefined | null, foreignCatalog: string, foreignSchema: string, foreignTable: string): Promise -} - -/** - * Opaque executed-statement handle. - * - * **Current concurrency shape** — every method takes `inner.lock()` - * and holds the guard across the kernel `.await`. tokio `Mutex` is - * FIFO, so cancel/close queue behind any in-flight `fetchNextBatch` - * until it returns naturally. This is a known limitation that exists - * because the napi shape has not yet been split into an - * `Arc` (for cancel/close, which the - * kernel exposes as `&self`-callable) plus a `Mutex>` only - * for the borrowed-mut fetch path. The lock-shape refactor needs a - * small kernel-side accessor and lands in a follow-up PR — see - * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. - * - * `schema` and `statement_id` are cached at construction so they - * survive `close()` — JS callers building error reports against a - * disposed statement can still read them. - */ -export declare class Statement { + azureClientSecret?: string /** - * Server-issued statement id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate against - * kernel / server logs which key on the same id. + * Azure Entra tenant id. Optional for [`AuthMode::AzureSpM2m`]; + * omitted ⇒ the kernel auto-discovers it from the workspace's + * `/aad/auth` redirect (matching the Thrift connector). */ - get statementId(): string + azureTenantId?: string /** - * Number of rows modified by the statement (UPDATE / INSERT / - * DELETE / MERGE). `null` for SELECT and on warehouses that don't - * surface the counter. Mirrors Thrift's - * `TGetOperationStatusResp.numModifiedRows`. + * Azure workspace ARM resource id. Optional for [`AuthMode::AzureSpM2m`]; + * when set the kernel also sends the SP management token + * (`X-Databricks-Azure-SP-Management-Token`) + the + * `X-Databricks-Azure-Workspace-Resource-Id` header, so a service + * principal with an Azure RBAC role but no workspace membership can + * authenticate. Omitted ⇒ the data token authenticates alone. */ - numModifiedRows(): Promise + azureWorkspaceResourceId?: string /** - * Server-supplied user-facing message. Mirrors Thrift's - * `TGetOperationStatusResp.displayMessage`. **PII / sensitive- - * data note:** may contain SQL fragments or parameter values — - * redact before centralised logging. - * - * Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`). - * On terminal-error states (`Failed` / `Cancelled`) the kernel returns - * an Error instead of a `Statement`, and the same field rides on the JS - * Error envelope under the same `displayMessage` key. + * Default catalog for statements executed on this session. + * Routed through the kernel's `DefaultOpts` and onto the SEA + * `CreateSession.catalog` wire field. */ - displayMessage(): Promise + catalog?: string /** - * Server-supplied diagnostic detail — multi-line operator / - * stack context. Mirrors Thrift's - * `TGetOperationStatusResp.diagnosticInfo`. For support surfaces, - * not user-facing. Same reachability + PII caveats as - * `displayMessage`. + * Default schema for statements executed on this session. + * Routed through the kernel's `DefaultOpts` and onto the SEA + * `CreateSession.schema` wire field. */ - diagnosticInfo(): Promise + schema?: string /** - * Server-supplied JSON blob with extended error details. Mirrors - * Thrift's `TGetOperationStatusResp.errorDetailsJson`. - * Pass-through string — JS callers parse with `JSON.parse` if - * they need structured access. - * - * **Server-side gating:** populated only when the workspace has - * `spark.databricks.sql.errorDetailsJson.enabled = true` on the - * underlying SQL cluster. The flag is internal-only / default- - * false in the Databricks runtime, so for most JS callers this - * will return `null`. Admin-enabled workspaces return content - * shaped like `{"errorClass": "...", "messageTemplate": "..."}`. - * - * **Unbounded:** when populated, server can return a multi-MB - * blob; size before logging. + * Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`, + * query-tag presets, …). Forwarded verbatim to SEA + * `session_confs`. Unknown keys are rejected server-side. */ - errorDetailsJson(): Promise + sessionConf?: Record /** - * Pull the next batch of results. Returns `null` when the stream - * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete - * Arrow IPC stream (schema header + 1 record-batch message) - * suitable for handing to `apache-arrow`'s `RecordBatchReader`. - * - * On `Err`, the stream is in an unspecified state — call - * `close()` and discard the `Statement`. Subsequent - * `fetchNextBatch()` calls after an error are not guaranteed to - * succeed or fail consistently. + * Driver name reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - fetchNextBatch(): Promise + driverName?: string /** - * Result schema as an Arrow IPC payload (schema header only, no - * record-batch message). Available before any batches have been - * fetched, and remains available after `close()` — the kernel - * materialises the schema eagerly so JS callers can build error - * reports against a disposed statement. - * - * Sync because the body has no `.await` — `encode_ipc_stream` is - * pure CPU work over an `Arc` already cached on the - * wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync). - * napi-rs converts a panic in a sync `#[napi]` entry point into a - * thrown JS error via its own macro-expanded boundary, so the - * `util::guarded` `catch_unwind` wrapper that the `async fn` - * entry points use is not required for this method. + * Driver version reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - schema(): ArrowSchema + driverVersion?: string /** - * Server-side cancel. - * - * For executed statements: short-circuits to `Ok(())` if - * `fetchNextBatch` has already returned `null` (stream - * naturally exhausted) — matches the JDBC `Statement.cancel()` - * no-op-after-completion contract, so JS callers can fire cancel - * defensively without distinguishing "real cancel" from "raced - * with natural completion." - * - * For metadata streams: no-op (the kernel has no in-flight - * cancellation surface for metadata calls today). - * - * Returns `KernelError(InvalidStatementHandle)` if the statement - * has been explicitly `close()`d. + * Runtime name reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - cancel(): Promise + runtimeName?: string /** - * Explicit close. - * - * For executed statements: awaits the server-side `CloseStatement` - * so the JS caller can observe failures (auth revoked mid-session, - * network error, server-side error). Idempotent — a second call - * on an already-closed statement returns `Ok`. - * - * **Errors are terminal from the JS side.** The kernel executed - * handle is taken out of `inner` BEFORE the wire `CloseStatement` - * runs (so `Drop` knows there's nothing left to clean up). On - * `Err`, the napi `inner` is already `None`, so a JS-side retry - * sees a closed statement and returns `Ok(())` without re- - * attempting the wire call. The kernel-level `ExecutedStatement` - * has been consumed at that point and the value is dropped on - * the way out of the closure — the kernel's `ExecutedStatement:: - * Drop` then fires-and-forgets a single retry on the captured - * runtime. The JS caller can log the error but cannot drive a - * further retry. If you need retry-on-failure semantics for - * `CloseStatement`, layer them above this method. - * - * For metadata streams: drops the stream (no server round-trip - * needed — metadata results have no in-flight server-side - * resource to release). + * Runtime version reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - close(): Promise -} - -/** - * A single Arrow IPC stream payload encoding one record batch (plus - * the schema header so the JS-side reader is stateless). - */ -export interface ArrowBatch { + runtimeVersion?: string /** - * Arrow IPC stream payload (schema header + 1 record-batch - * message). Decode with `apache-arrow`'s `RecordBatchReader`. + * Runtime vendor reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - ipcBytes: Buffer -} - -/** - * An Arrow IPC stream payload encoding just the result schema (no - * record-batch messages). Returned by `Statement.schema()`. - */ -export interface ArrowSchema { + runtimeVendor?: string /** - * Arrow IPC stream payload (schema header only, no record-batch - * messages). Decode with `apache-arrow`'s `RecordBatchReader` — - * the reader will expose the schema and immediately end. + * Operating system name reported in telemetry system configuration. + * Omitted ⇒ kernel default. */ - ipcBytes: Buffer -} - -/** - * Authentication mode selector crossing the napi boundary. The string - * literals are what napi-rs emits from this `#[napi(string_enum)]` — the - * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`, - * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). - * - * Mirrors the kernel [`AuthConfig`] variants this binding supports. - * `OAuthFederation` / `External` are intentionally not exposed yet — the - * kernel marks federation as not-yet-implemented and `External` is a - * Rust-trait escape hatch with no JS-callback bridge. - */ -export declare const enum AuthMode { - /** Personal access token (`token`). */ - Pat = 'Pat', - /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */ - OAuthM2m = 'OAuthM2m', + osName?: string /** - * OAuth 2.0 machine-to-machine with a JWT private-key client - * assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. + * Operating system version reported in telemetry system configuration. + * Omitted ⇒ kernel default. */ - OAuthM2mJwt = 'OAuthM2mJwt', + osVersion?: string /** - * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` - * + `oauthRedirectPort`. + * Operating system architecture reported in telemetry system + * configuration. Omitted ⇒ kernel default. */ - OAuthU2m = 'OAuthU2m', - /** - * Azure Entra service-principal M2M — `azureClientId` + - * `azureClientSecret` (+ optional `azureTenantId` / - * `azureWorkspaceResourceId`). The kernel builds the Entra token - * endpoint + `.default` scope, auto-discovers the tenant from the - * workspace when `azureTenantId` is omitted, and — when - * `azureWorkspaceResourceId` is set — additionally sends the SP - * management token for an RBAC-only service principal. - */ - AzureSpM2m = 'AzureSpM2m' -} - -/** - * JS-visible options for opening a Databricks SQL session. - * - * Authentication is selected by `authMode` (default [`AuthMode::Pat`]): - * - `Pat` — `token` required. - * - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. - * - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional - * (defaults to the `databricks-sql-connector` client on port 8030). - * - `AzureSpM2m` — `azureClientId` + `azureClientSecret` required - * (+ optional `azureTenantId` / `azureWorkspaceResourceId`). - * - * Catalog / schema / sessionConf are applied once at session creation - * and remain in effect for every statement run on the resulting - * `Connection`. The SEA wire protocol carries them on - * `CreateSession`, not on `ExecuteStatement` — so there is no - * per-statement override path on this binding. - */ -export interface ConnectionOptions { - /** - * Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel - * normalises this — bare hostnames get `https://` prepended. - */ - hostName: string - /** - * JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The - * kernel parses out the warehouse id. - */ - httpPath: string - /** - * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: - * existing PAT callers pass only `token`). - */ - authMode?: AuthMode - /** - * Personal access token. Required (and non-empty) for - * [`AuthMode::Pat`]; ignored otherwise. - */ - token?: string - /** - * OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for - * [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). - */ - oauthClientId?: string - /** OAuth client secret. Required for [`AuthMode::OAuthM2m`]. */ - oauthClientSecret?: string - /** - * Localhost callback port for the [`AuthMode::OAuthU2m`] browser - * flow. Omitted ⇒ kernel default (8030). - */ - oauthRedirectPort?: number - /** - * OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults - * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). - */ - oauthScopes?: Array - /** - * OAuth token endpoint override. When omitted the kernel discovers the - * endpoint via the workspace's OIDC configuration. Set it to point the - * client-credentials / JWT client-assertion grant at the workspace's - * configured IdP token endpoint (e.g. Entra ID for Azure Databricks), - * which is required when that IdP — not Databricks-native OIDC — is the - * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. - */ - tokenUrl?: string - /** - * U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel - * default (cache enabled, encrypted under a machine-local key, survives - * restarts). `false` disables on-disk persistence (re-login each fresh - * process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. - */ - tokenCacheEnabled?: boolean - /** - * Optional passphrase for the U2M on-disk token cache (AES-256 key). - * Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. - * A passphrase with no explicit `tokenCacheEnabled` implies enabled. - * Applies to [`AuthMode::OAuthU2m`]. - */ - tokenCachePassphrase?: string - /** - * Path to the PEM private-key file. Required for - * [`AuthMode::OAuthM2mJwt`]. - */ - jwtKeyFile?: string - /** JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. */ - jwtKid?: string - /** - * Passphrase for an encrypted PKCS#8 key. Optional for - * [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). - */ - jwtPassphrase?: string - /** - * JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, - * `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] - * (omitted ⇒ kernel default `RS256`). - */ - jwtAlgorithm?: string - /** - * SP-wide Workload Identity Federation client id used during mandatory - * token exchange. Omitted selects BYOT / account-wide WIF. - */ - identityFederationClientId?: string - /** - * Azure Entra app-registration client id. Required for - * [`AuthMode::AzureSpM2m`]; ignored otherwise. - */ - azureClientId?: string - /** - * Azure Entra app-registration client secret. Required for - * [`AuthMode::AzureSpM2m`]. - */ - azureClientSecret?: string - /** - * Azure Entra tenant id. Optional for [`AuthMode::AzureSpM2m`]; - * omitted ⇒ the kernel auto-discovers it from the workspace's - * `/aad/auth` redirect (matching the Thrift connector). - */ - azureTenantId?: string - /** - * Azure workspace ARM resource id. Optional for [`AuthMode::AzureSpM2m`]; - * when set the kernel also sends the SP management token - * (`X-Databricks-Azure-SP-Management-Token`) + the - * `X-Databricks-Azure-Workspace-Resource-Id` header, so a service - * principal with an Azure RBAC role but no workspace membership can - * authenticate. Omitted ⇒ the data token authenticates alone. - */ - azureWorkspaceResourceId?: string - /** - * Default catalog for statements executed on this session. - * Routed through the kernel's `DefaultOpts` and onto the SEA - * `CreateSession.catalog` wire field. - */ - catalog?: string - /** - * Default schema for statements executed on this session. - * Routed through the kernel's `DefaultOpts` and onto the SEA - * `CreateSession.schema` wire field. - */ - schema?: string - /** - * Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`, - * query-tag presets, …). Forwarded verbatim to SEA - * `session_confs`. Unknown keys are rejected server-side. - */ - sessionConf?: Record - /** - * Driver name reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - driverName?: string - /** - * Driver version reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - driverVersion?: string - /** - * Runtime name reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - runtimeName?: string - /** - * Runtime version reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - runtimeVersion?: string - /** - * Runtime vendor reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - runtimeVendor?: string - /** - * Operating system name reported in telemetry system configuration. - * Omitted ⇒ kernel default. - */ - osName?: string - /** - * Operating system version reported in telemetry system configuration. - * Omitted ⇒ kernel default. - */ - osVersion?: string - /** - * Operating system architecture reported in telemetry system - * configuration. Omitted ⇒ kernel default. - */ - osArch?: string + osArch?: string /** * Client application name reported in telemetry system configuration. * Omitted ⇒ absent unless the kernel can infer a default. @@ -1030,127 +582,41 @@ export interface ConnectionOptions { */ socketTimeoutMs?: number } - /** - * Per-statement options for `Connection.executeStatement`. + * Open a Databricks SQL session and return an opaque `Connection` + * wrapping the kernel `Session`. Authentication is selected by + * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see + * [`build_auth_config`]. * - * Mirrors the kernel `StatementSpec` knobs that are safe to thread - * through napi without a kernel-side change. Today this covers: - * - `statementConf` — per-statement Spark conf overlay - * (`StatementSpec.statement_conf` → SEA `parameters` / - * Thrift `confOverlay`) - * - `queryTags` — convenience wrapper over `statementConf` with - * key `query_tags`; serialised to the same comma-separated - * `key:value` wire shape NodeJS Thrift's `serializeQueryTags` - * produces (`lib/utils/queryTags.ts`). Backslashes in keys are - * doubled; backslash/colon/comma in values are backslash-escaped. + * The JS-visible name is `openSession` (napi-rs converts snake_case + * to camelCase for free functions). + */ +export declare function openSession(options: ConnectionOptions): Promise +/** + * One kernel log event, as handed to JS. `level` is a lower-case string + * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its + * `LogLevel`; `target` is the originating `tracing` target (e.g. + * `databricks::sql::kernel`); `message` is the rendered event plus any + * structured `key=value` fields. + */ +export interface LogRecord { + level: string + target: string + message: string +} +/** + * Install (idempotently) the kernel→JS log bridge and set its level. * - * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel - * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) - * carry bound query parameters, decoded via `params::parse_typed_value`. - * (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold - * window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.) + * `callback` is invoked with **an array of [`LogRecord`]s** (`(err, records)`) + * for each forwarded batch. `level` is one of + * `off`/`error`/`warn`/`info`/`debug`/`trace` (case-insensitive); unknown + * values fall back to `warn`. * - * **Tag-order caveat (M4 parity note).** The napi `queryTags` field - * is a Rust `HashMap` whose iteration order is - * non-deterministic, so the serialised `query_tags` value may have - * a different key order than Thrift's `serializeQueryTags` (which - * iterates `Object.keys(...)` in insertion order) for the same - * input. The SEA server is order-insensitive on conf values, so - * the two are functionally equivalent. If a caller needs - * byte-identical Thrift parity, the JS adapter pre-serialises via - * `serializeQueryTags` and writes the result into - * `statementConf["query_tags"]` directly — see - * `KernelSessionBackend.executeStatement` in the NodeJS driver. This - * path is the one the production code uses. + * Safe to call more than once: the process-global subscriber is installed on + * the first call only, while every call refreshes the sink + level (last + * writer wins — see module docs). */ -export interface ExecuteOptions { - /** - * Per-statement Spark conf overlay. Merged on top of the - * session-level `sessionConf` at execute time; this map wins - * on key collisions. Unknown keys are rejected by the server. - */ - statementConf?: Record - /** - * Query tags as key→value pairs. Serialised to a comma- - * separated `key:value` string (backslash-escaping `\`, `:`, - * `,`) and placed into `statementConf["query_tags"]`, matching - * NodeJS Thrift's `serializeQueryTags` wire shape. Passing - * both `queryTags` AND a `query_tags` key in `statementConf` - * raises `InvalidArgument` — the caller's intent is ambiguous - * so we refuse to silently pick one over the other. - * - * A **`null`** value emits a **bare key** (no colon) — e.g. - * `{ production: null }` → `"production"` — matching the - * connectors' `key`-only tag form. - * - * See the struct-level "Tag-order caveat" for the - * HashMap-iteration-order vs `Object.keys`-iteration-order - * divergence and the byte-identical-Thrift-parity workaround. - */ - queryTags?: Record - /** - * Server-side cap on the number of rows this statement returns - * (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to - * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. - */ - rowLimit?: number - /** - * Positional parameters, in 1-based wire order. Index `i` in this - * Vec corresponds to the `i+1`-th `?` placeholder in the SQL. - * Each entry is a `{ sqlType, value }` pair — `value` is the - * string-encoded literal or `null` for SQL NULL. Mirrors - * `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. - */ - positionalParams?: Array - /** - * Named parameters (`:name` placeholders). Each carries its `name` - * alongside the `{ sqlType, value? }` pair. Mapped to a kernel - * `TypedValue` via the same [`parse_typed_value`] codec and bound with - * `StatementSpec::param_named`. Named is the SEA-spec-required public - * param form (`StatementParameter.name` is `openapi_required`); - * positional is the documented-undocumented variant. The two are - * mutually exclusive at the SQL level (`?` vs `:name`). - */ - namedParams?: Array -} - -/** - * A single extra HTTP header as an explicit `{ name, value }` pair. - * - * An ordered list of these (`ConnectionOptions.custom_headers`) mirrors - * the kernel core's `Vec<(String, String)>` and the pyo3 binding's - * `http_headers`: order is preserved and duplicate `name`s are allowed. - * A struct (rather than a raw `[name, value]` tuple) because napi-rs - * does not marshal Rust tuples through `#[napi(object)]` fields; the - * struct is the idiomatic, self-documenting equivalent and maps to a JS - * `{ name: string, value: string }`. - */ -export interface HeaderEntry { - name: string - value: string -} - -/** - * Install (idempotently) the kernel→JS log bridge and set its level. - * - * `callback` is invoked with **an array of [`LogRecord`]s** (`(err, records)`) - * for each forwarded batch. `level` is one of - * `off`/`error`/`warn`/`info`/`debug`/`trace` (case-insensitive); unknown - * values fall back to `warn`. - * - * Safe to call more than once: the process-global subscriber is installed on - * the first call only, while every call refreshes the sink + level (last - * writer wins — see module docs). - */ -export declare function initKernelLogging(callback: ((err: Error | null, arg: Array) => any), level: string): void - -/** - * Return the bridge's [`KernelLoggingStats`]. Safe to call before - * `initKernelLogging` (reports `installed: false`, `dropped: 0`). - */ -export declare function kernelLoggingStats(): KernelLoggingStats - +export declare function initKernelLogging(callback: (err: Error | null, arg: Array) => any, level: string): void /** * Snapshot of the bridge's runtime state for observability. * @@ -1166,68 +632,16 @@ export interface KernelLoggingStats { installed: boolean dropped: number } - -/** - * One kernel log event, as handed to JS. `level` is a lower-case string - * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its - * `LogLevel`; `target` is the originating `tracing` target (e.g. - * `databricks::sql::kernel`); `message` is the rendered event plus any - * structured `key=value` fields. - */ -export interface LogRecord { - level: string - target: string - message: string -} - -/** - * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a - * distinct napi object (rather than an optional `name` on `TypedValueInput`) - * so the positional surface stays a clean ordered list with no name field. - */ -export interface NamedTypedValueInput { - name: string - sqlType: string - value?: string -} - -/** - * Open a Databricks SQL session and return an opaque `Connection` - * wrapping the kernel `Session`. Authentication is selected by - * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see - * [`build_auth_config`]. - * - * The JS-visible name is `openSession` (napi-rs converts snake_case - * to camelCase for free functions). - */ -export declare function openSession(options: ConnectionOptions): Promise - /** - * 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"`). + * Return the bridge's [`KernelLoggingStats`]. Safe to call before + * `initKernelLogging` (reports `installed: false`, `dropped: 0`). */ -export interface ProxyInput { - url: string - username?: string - password?: string - bypassHosts?: string -} - +export declare function kernelLoggingStats(): KernelLoggingStats /** * Live-retarget the bridge's level (one of * `off`/`error`/`warn`/`info`/`debug`/`trace`, case-insensitive). */ export declare function setKernelLogLevel(level: string): void - /** * JS-visible binding for a single positional parameter. * @@ -1261,7 +675,29 @@ export interface TypedValueInput { */ value?: string } - +/** + * A single Arrow IPC stream payload encoding one record batch (plus + * the schema header so the JS-side reader is stateless). + */ +export interface ArrowBatch { + /** + * Arrow IPC stream payload (schema header + 1 record-batch + * message). Decode with `apache-arrow`'s `RecordBatchReader`. + */ + ipcBytes: Buffer +} +/** + * An Arrow IPC stream payload encoding just the result schema (no + * record-batch messages). Returned by `Statement.schema()`. + */ +export interface ArrowSchema { + /** + * Arrow IPC stream payload (schema header only, no record-batch + * messages). Decode with `apache-arrow`'s `RecordBatchReader` — + * the reader will expose the schema and immediately end. + */ + ipcBytes: Buffer +} /** * Returns the native binding's crate version (`CARGO_PKG_VERSION`). * @@ -1269,3 +705,540 @@ export interface TypedValueInput { * loaded?" probe for the JS-side loader's structured diagnostics. */ export declare function version(): string +/** + * Opaque async-statement handle. + * + * Returned by `Connection.submitStatement(...)` after the kernel + * `Statement::submit()` returns (server sent `wait_timeout=0s`, so + * the response carries a `statement_id` but the statement is still + * `Pending`/`Running`). JS drives polling via `status()` / + * `awaitResult()`. + * + * Concurrency shape: `status()`, `awaitResult()`, and `close()` take + * `inner.lock()` and hold the guard across the kernel `.await` (tokio + * `Mutex` is FIFO), so `status()` / `close()` queue behind any + * in-flight `awaitResult()` until it returns naturally. `cancel()` is + * the deliberate exception: it does **not** touch `inner` — it fires + * through the detached `AsyncStatementCanceller` (session + + * statement_id, captured at construction), so an explicit + * `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of + * queueing behind it. The server-side cancel flips the statement + * terminal, which the parked `awaitResult()` poll loop observes + * (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard` + * still covers the drop-cancel case (Promise.race / timeout) + * independently — see module docs. + */ +export declare class AsyncStatement { + /** + * Server-issued statement id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate + * against kernel / server logs which key on the same id. + */ + get statementId(): string + /** + * One-shot status check. Returns a string enum matching the + * kernel `StatementStatus` shape: + * `'Pending' | 'Running' | 'Succeeded' | 'Failed' | + * 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the + * `#[non_exhaustive]` forward-compat catch-all that + * `StatementStatus::as_str` can return — consumers switching on + * the state must handle it.) Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. + * + * The `Failed` variant collapses to the string `'Failed'` on + * the JS side; the underlying error envelope (sql_state / + * error_code / query_id) is surfaced by `awaitResult()`'s + * rejection, which is where callers actually need the typed + * error. `status()` is intended for polling progress UIs + * 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 + * stream. The handle exposes `fetchNextBatch()` / `schema()` + * for consuming the result, plus `statementId` for log + * correlation. + * + * Drop-cancel safety: kernel `await_result` installs + * `AwaitResultCancelGuard` which fires a fire-and-forget + * `cancel_statement` if the future is dropped mid-poll + * (timeout, tokio::select! loser, JS-side `Promise.race` + * loser). The `util::guarded` `catch_unwind` here covers the + * V8-panic-across-boundary case on top. Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. + */ + awaitResult(): Promise + /** + * Server-side cancel. Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. Idempotent against a server + * that already reached a terminal state — the kernel's + * `cancel_statement` is a no-op there. + * + * **Lock-free by design.** Unlike `status()` / `awaitResult()` / + * `close()`, this does not take `inner.lock()` — it fires through + * the detached `AsyncStatementCanceller` captured at construction. + * That lets `stmt.cancel()` interrupt an in-flight `awaitResult()` + * (which holds the mutex for the whole poll) instead of queueing + * behind it: the server-side cancel flips the statement terminal, + * the parked `awaitResult()` poll loop observes `Cancelled` and + * returns. The closed-state check reads a lock-free flag so a + * cancel after an explicit `close()` still surfaces + * `InvalidStatementHandle`. + */ + cancel(): Promise + /** + * Explicit close. Idempotent — a second call on an + * already-closed handle returns `Ok(())`. On `Err`, the napi + * inner is already `None`, so a JS-side retry sees the + * closed-handle short-circuit and returns `Ok(())` without + * re-attempting the wire call. The kernel's own `Drop` + * fire-and-forget retry runs once in the background. + */ + close(): Promise +} +/** + * Opaque result-fetch handle returned by + * `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` + * directly; structurally analogous to the sync `Statement`'s + * fetch-side surface (`fetchNextBatch` / `schema` / + * `statementId`). + * + * `cancel()` / `close()` are not exposed: the parent + * `AsyncStatement` owns server-side lifecycle. A `close()` here + * would create dual-ownership of the same statement_id with + * inconsistent close semantics. Callers `close()` the parent + * `AsyncStatement` after they're done fetching. + * + * Schema is cached at construction so it survives the underlying + * stream being drained; mirrors the sync `Statement.schema()` + * post-close contract. + */ +export declare class AsyncResultHandle { + /** + * Server-issued statement id. Cached at construction; readable + * for log correlation. Matches the parent `AsyncStatement`'s + * `statementId`. + */ + get statementId(): string + /** + * Pull the next batch of results. Returns `null` when the + * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a + * complete Arrow IPC stream (schema header + 1 record-batch + * message), suitable for handing to `apache-arrow`'s + * `RecordBatchReader`. Byte-identical to the sync + * `Statement.fetchNextBatch()` payload for the same query. + */ + fetchNextBatch(): Promise + /** + * Result schema as an Arrow IPC payload (schema header only, + * no record-batch message). Available before any batches have + * been fetched. Sync because the body has no `.await` — + * `encode_ipc_stream` is pure CPU work over the cached + * `Arc`. + */ + schema(): ArrowSchema +} +/** + * Handle returned by `Connection.executeStatementCancellable`. Owns the + * built-but-not-yet-executed kernel `Statement` plus a detached + * [`StatementCanceller`] captured before dispatch, so JS can fire a + * server-side cancel while the blocking `result()` is in flight. + * + * `pending` is `Arc>>` so `result()` can + * `.take()` the statement (the kernel `execute()` borrows it `&mut`, + * then it moves into the produced `Statement` wrapper to keep its + * `ValidityFlag` set — see `statement.rs`). A second `result()` call + * after the first resolved surfaces `InvalidStatementHandle`. + */ +export declare class CancellableExecution { + /** + * The server-issued statement id this execution targets, if the + * server has issued one yet (`null` before the initial submit + * round-trip publishes it mid-`result()`). Useful for log + * correlation while the blocking drive is in flight. + */ + get statementId(): string | null + /** + * Drive the blocking `execute()` and resolve to a `Statement` + * (identical to what `executeStatement` returns) once the kernel + * reaches a terminal state and the result stream is ready. + * + * Consumes the pending statement: a second `result()` call returns + * `KernelError(InvalidStatementHandle)`. The future is + * drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState` + * guard fires a fire-and-forget `cancel_statement` if this future is + * dropped mid-flight (`Promise.race` / timeout loser), independently + * of an explicit `cancel()`. + * + * On a server-side cancel the kernel's blocking `execute()` currently + * surfaces `InvalidArgument` (a known kernel quirk — the async path + * returns `Cancelled`). When this handle's `cancel()` actually dispatched a + * server-side cancel, we normalise that into `Cancelled` here so JS callers + * can rely on a single cancelled-status code regardless of execution path. + * + * Three outcomes can race the blocking drive: (1) a natural terminal state + * → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a + * server cancel → this `result()` rejects with a `Cancelled`-coded error + * (the normalisation above); (3) the future being **dropped** mid-flight + * (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState` + * drop-guard fires a fire-and-forget `cancel_statement`, but there is no + * `result()` left to observe a code. Only (2) yields a `Cancelled` error. + */ + result(): Promise + /** + * Server-side cancel of the in-flight statement. + * + * Lock-free: fires the detached `StatementCanceller` captured at + * construction rather than taking the mutex `result()` holds, so it + * interrupts a still-running blocking `result()` instead of queueing + * behind it. No-op (returns `Ok`) if `result()` already finished + * successfully, or if no statement id has been observed yet (query still + * in its initial submit round-trip), and idempotent against a server + * already in a terminal state. + */ + cancel(): Promise +} +/** + * Opaque connection handle wrapping a kernel `Session`. + * + * `inner` is `Arc>>` so: + * - the Drop impl can clone the `Arc` and `.take()` the session on a + * background tokio task without holding `&mut self` (which Drop is + * forbidden from doing across an `await`), + * - `close()` can `.take()` the session to consume it for the kernel's + * move-by-value `Session::close(self)` signature. + * + * **Concurrency shape** — both `executeStatement` and + * `submitStatement` build the kernel `Statement` under `inner.lock()` + * and then RELEASE the guard before the wire call + * (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()` + * is `&self`-callable and only clones the session's internal `Arc`, so + * the built statement is independent of the guard. Concurrent + * `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore + * serialise only for the microsecond statement-build, not the network + * round-trip, and `close()` never blocks behind an in-flight execute or + * submit. See + * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. + */ +export declare class Connection { + /** + * Server-issued session id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate + * against kernel / server logs which key on the same id. + */ + get sessionId(): string + /** + * Execute a SQL statement and return a Statement handle that + * streams batches via `fetchNextBatch()`. + * + * Catalog / schema / sessionConf are session-level + * (`openSession`). Per-statement options on `ExecuteOptions`: + * - `statementConf` — per-statement Spark conf overlay + * - `queryTags` — serialised to a comma-separated `key:value` + * string and placed in `statement_conf["query_tags"]`, + * matching NodeJS Thrift's `serializeQueryTags` wire shape + * + * `options` is omitted/`None` for the no-options path; passing + * `{ statementConf: {} }` (an empty map) is treated the same as + * omission to keep the wire shape stable for the common case. + */ + executeStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise + /** + * directResults execute — the Thrift/JDBC model. Sends ExecuteStatement + * with no `wait_timeout` field (server applies its ~10s default inline wait + * and auto-closes on success) and returns WITHOUT polling past it: + * + * - a **`Statement`** (left arm) when the query finished within the inline + * wait — terminal, result ready inline, `close()` is a clean release; + * - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel + * handle the caller drives (`status()` / `awaitResult()` / `cancel()`). + * + * JS distinguishes the arms by feature-detecting `awaitResult` (present + * only on `AsyncStatement`). This is the path that gives mid-run cancel for + * long queries WITHOUT the eager-handle / close-drives workaround: the + * returned handle always corresponds to a server-owned statement. + * + * **Load-bearing contract:** the kernel's `DirectStatement::{Completed, + * Running}` discriminant cannot ride on these opaque `#[napi]` classes, so + * consumers MUST feature-detect via `awaitResult` (the only member unique to + * `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an + * `awaitResult` member, or every consumer silently misroutes. The pyo3 + * binding makes the same `await_result`-probe assumption. + */ + executeStatementDirect(sql: string, options?: ExecuteOptions | undefined | null): Promise + /** + * Execute a SQL statement on the blocking (sync) path, but return a + * `CancellableExecution` handle so a concurrent JS task can cancel + * the query *while it is still running server-side*. + * + * `executeStatement` builds the kernel `Statement`, awaits the + * blocking `execute()`, and only then hands JS a `Statement` — so a + * query that runs for several seconds is uncancellable from JS on + * that path (there is no handle until the blocking call resolves). + * This method instead builds the statement, captures a detached + * `StatementCanceller` **before** dispatching `execute()`, and hands + * JS a `CancellableExecution` immediately. The caller drives the + * blocking execution via `result()` (resolves to the same + * `Statement` `executeStatement` returns) and can fire `cancel()` + * concurrently to interrupt a still-running query mid-COMPUTE. + * + * Option semantics are identical to `executeStatement`. + * Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` + * split (PR #121): obtain the canceller before the blocking drive. + */ + executeStatementCancellable(sql: string, options?: ExecuteOptions | undefined | null): Promise + /** + * Submit a SQL statement and return immediately with an + * `AsyncStatement` handle, without blocking until the query + * finishes. The kernel's `Statement::submit()` sends + * `wait_timeout=0s`, so the server responds as soon as it has a + * `statement_id` (state `Pending`/`Running`); JS drives polling + * via `AsyncStatement.status()` and materialises results with + * `AsyncStatement.awaitResult()`. + * + * This is the async-execution path the Thrift backend always + * uses (`runAsync: true`): the SEA backend submits, returns a + * pending operation handle, and polls to terminal during + * fetch. Option semantics (statementConf / queryTags / + * rowLimit / positional + named params) match `executeStatement`. + * Submit always sends `wait_timeout=0s` so the call returns + * immediately; the caller drives completion via `status()` / + * `awaitResult()`. Only the blocking-vs-pending return contract + * differs from `executeStatement`. + */ + submitStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise + /** + * Explicit close. Awaits the server-side `DeleteSession` so the + * JS caller can observe failures (auth revoked mid-session, + * warehouse stopped, network error). Idempotent — a second call + * on an already-closed connection returns `Ok`. + * + * **Errors are terminal from the JS side.** The kernel session + * handle is consumed (`take()`) BEFORE the wire `DeleteSession` + * runs, because `Session::close` takes `self` by value. On `Err`, + * the napi `inner` is already `None`, so a JS-side retry sees a + * closed connection and returns `Ok(())` without re-attempting + * the wire call. The kernel's own `Drop` fire-and-forget retry + * runs once in the background — the JS caller can log the error + * but cannot drive a retry. If you need retry-on-failure + * semantics for `DeleteSession`, layer them above this method. + */ + close(): Promise + /** + * All catalogs visible to the session. + * + * JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. + */ + listCatalogs(): Promise + /** + * Schemas filtered by catalog (exact) and schema name pattern. + * + * JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. + */ + listSchemas(catalog?: string | undefined | null, schemaPattern?: string | undefined | null): Promise + /** + * Tables filtered by catalog (exact), schema (pattern), table (pattern). + * + * JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, + * filters rows by `TABLE_TYPE` kernel-side. + * + * `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does + * NOT honour the table-type filter server-side; the kernel applies + * it client-side after the result returns. Callers expecting + * server-side rejection of off-type tables should not rely on this. + */ + listTables(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, tableTypes?: Array | undefined | null): Promise + /** + * Columns of tables matching the filter. + * + * JDBC `getColumns` shape: 23 columns. + */ + listColumns(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, columnPattern?: string | undefined | null): Promise + /** + * Functions visible to the session. `catalog` is exact; + * `schemaPattern` and `functionPattern` are SQL LIKE. + */ + listFunctions(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, functionPattern?: string | undefined | null): Promise + /** + * Procedures visible to the session. `catalog` is exact; + * `schemaPattern` and `procedurePattern` are SQL LIKE. + */ + listProcedures(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, procedurePattern?: string | undefined | null): Promise + /** + * All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). + * No wire call — static in-memory result. + */ + listTableTypes(): Promise + /** + * SQL data types supported by the workspace. + * No wire call — static in-memory result. + */ + listTypeInfo(): Promise + /** + * Primary keys for the given table. All three identifiers are + * exact — ODBC `SQLPrimaryKeys` does not support patterns. + */ + getPrimaryKeys(catalog: string, schema: string, table: string): Promise + /** + * Foreign-key relationships. The foreign side must be fully + * specified (catalog + schema + table); the parent side is + * optional. All identifiers are exact — no LIKE patterns. + */ + getCrossReference(parentCatalog: string | undefined | null, parentSchema: string | undefined | null, parentTable: string | undefined | null, foreignCatalog: string, foreignSchema: string, foreignTable: string): Promise +} +/** + * Opaque executed-statement handle. + * + * **Current concurrency shape** — every method takes `inner.lock()` + * and holds the guard across the kernel `.await`. tokio `Mutex` is + * FIFO, so cancel/close queue behind any in-flight `fetchNextBatch` + * until it returns naturally. This is a known limitation that exists + * because the napi shape has not yet been split into an + * `Arc` (for cancel/close, which the + * kernel exposes as `&self`-callable) plus a `Mutex>` only + * for the borrowed-mut fetch path. The lock-shape refactor needs a + * small kernel-side accessor and lands in a follow-up PR — see + * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. + * + * `schema` and `statement_id` are cached at construction so they + * survive `close()` — JS callers building error reports against a + * disposed statement can still read them. + */ +export declare class Statement { + /** + * Server-issued statement id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate against + * kernel / server logs which key on the same id. + */ + get statementId(): string + /** + * Number of rows modified by the statement (UPDATE / INSERT / + * DELETE / MERGE). `null` for SELECT and on warehouses that don't + * surface the counter. Mirrors Thrift's + * `TGetOperationStatusResp.numModifiedRows`. + */ + numModifiedRows(): Promise + /** + * Server-supplied user-facing message. Mirrors Thrift's + * `TGetOperationStatusResp.displayMessage`. **PII / sensitive- + * data note:** may contain SQL fragments or parameter values — + * redact before centralised logging. + * + * Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`). + * On terminal-error states (`Failed` / `Cancelled`) the kernel returns + * an Error instead of a `Statement`, and the same field rides on the JS + * Error envelope under the same `displayMessage` key. + */ + displayMessage(): Promise + /** + * Server-supplied diagnostic detail — multi-line operator / + * stack context. Mirrors Thrift's + * `TGetOperationStatusResp.diagnosticInfo`. For support surfaces, + * not user-facing. Same reachability + PII caveats as + * `displayMessage`. + */ + diagnosticInfo(): Promise + /** + * Server-supplied JSON blob with extended error details. Mirrors + * Thrift's `TGetOperationStatusResp.errorDetailsJson`. + * Pass-through string — JS callers parse with `JSON.parse` if + * they need structured access. + * + * **Server-side gating:** populated only when the workspace has + * `spark.databricks.sql.errorDetailsJson.enabled = true` on the + * underlying SQL cluster. The flag is internal-only / default- + * false in the Databricks runtime, so for most JS callers this + * will return `null`. Admin-enabled workspaces return content + * shaped like `{"errorClass": "...", "messageTemplate": "..."}`. + * + * **Unbounded:** when populated, server can return a multi-MB + * blob; size before logging. + */ + errorDetailsJson(): Promise + /** + * Pull the next batch of results. Returns `null` when the stream + * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete + * Arrow IPC stream (schema header + 1 record-batch message) + * suitable for handing to `apache-arrow`'s `RecordBatchReader`. + * + * On `Err`, the stream is in an unspecified state — call + * `close()` and discard the `Statement`. Subsequent + * `fetchNextBatch()` calls after an error are not guaranteed to + * succeed or fail consistently. + */ + fetchNextBatch(): Promise + /** + * Result schema as an Arrow IPC payload (schema header only, no + * record-batch message). Available before any batches have been + * fetched, and remains available after `close()` — the kernel + * materialises the schema eagerly so JS callers can build error + * reports against a disposed statement. + * + * Sync because the body has no `.await` — `encode_ipc_stream` is + * pure CPU work over an `Arc` already cached on the + * wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync). + * napi-rs converts a panic in a sync `#[napi]` entry point into a + * thrown JS error via its own macro-expanded boundary, so the + * `util::guarded` `catch_unwind` wrapper that the `async fn` + * entry points use is not required for this method. + */ + schema(): ArrowSchema + /** + * Server-side cancel. + * + * For executed statements: short-circuits to `Ok(())` if + * `fetchNextBatch` has already returned `null` (stream + * naturally exhausted) — matches the JDBC `Statement.cancel()` + * no-op-after-completion contract, so JS callers can fire cancel + * defensively without distinguishing "real cancel" from "raced + * with natural completion." + * + * For metadata streams: no-op (the kernel has no in-flight + * cancellation surface for metadata calls today). + * + * Returns `KernelError(InvalidStatementHandle)` if the statement + * has been explicitly `close()`d. + */ + cancel(): Promise + /** + * Explicit close. + * + * For executed statements: awaits the server-side `CloseStatement` + * so the JS caller can observe failures (auth revoked mid-session, + * network error, server-side error). Idempotent — a second call + * on an already-closed statement returns `Ok`. + * + * **Errors are terminal from the JS side.** The kernel executed + * handle is taken out of `inner` BEFORE the wire `CloseStatement` + * runs (so `Drop` knows there's nothing left to clean up). On + * `Err`, the napi `inner` is already `None`, so a JS-side retry + * sees a closed statement and returns `Ok(())` without re- + * attempting the wire call. The kernel-level `ExecutedStatement` + * has been consumed at that point and the value is dropped on + * the way out of the closure — the kernel's `ExecutedStatement:: + * Drop` then fires-and-forgets a single retry on the captured + * runtime. The JS caller can log the error but cannot drive a + * further retry. If you need retry-on-failure semantics for + * `CloseStatement`, layer them above this method. + * + * For metadata streams: drops the stream (no server round-trip + * needed — metadata results have no in-flight server-side + * resource to release). + */ + close(): Promise +} diff --git a/napi/index.js b/napi/index.js index 45ea1ec8..ad50ecc9 100644 --- a/napi/index.js +++ b/napi/index.js @@ -1,713 +1,325 @@ -// prettier-ignore +/* tslint:disable */ /* eslint-disable */ -// @ts-nocheck +/* prettier-ignore */ + /* auto-generated by NAPI-RS */ -const { readFileSync } = require('fs') -let nativeBinding = null -const loadErrors = [] +const { existsSync, readFileSync } = require('fs') +const { join } = require('path') -const isMusl = () => { - let musl = false - if (process.platform === 'linux') { - musl = isMuslFromFilesystem() - if (musl === null) { - musl = isMuslFromReport() - } - if (musl === null) { - musl = isMuslFromChildProcess() - } - } - return musl -} +const { platform, arch } = process -const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') - -const isMuslFromFilesystem = () => { - try { - return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') - } catch { - return null - } -} +let nativeBinding = null +let localFileExisted = false +let loadError = null -const isMuslFromReport = () => { - let report = null - if (process.report && typeof process.report.getReport === 'function') { - process.report.excludeNetwork = true - report = process.report.getReport() - } - if (!report) { - return null - } - if (report.header && report.header.glibcVersionRuntime) { - return false - } - if (Array.isArray(report.sharedObjects)) { - if (report.sharedObjects.some(isFileMusl)) { +function isMusl() { + // For Node 10 + if (!process.report || typeof process.report.getReport !== 'function') { + try { + const lddPath = require('child_process').execSync('which ldd').toString().trim() + return readFileSync(lddPath, 'utf8').includes('musl') + } catch (e) { return true } - } - return false -} - -const isMuslFromChildProcess = () => { - try { - return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl') - } catch (e) { - // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false - return false + } else { + const { glibcVersionRuntime } = process.report.getReport().header + return !glibcVersionRuntime } } -function requireNative() { - if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) { - try { - return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH); - } catch (err) { - loadErrors.push(err) - } - } else if (process.platform === 'android') { - if (process.arch === 'arm64') { - try { - return require('./index.android-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-android-arm64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-android-arm64/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm') { - try { - return require('./index.android-arm-eabi.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-android-arm-eabi') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-android-arm-eabi/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`)) - } - } else if (process.platform === 'win32') { - if (process.arch === 'x64') { - if ((process.config && process.config.variables && process.config.variables.shlib_suffix === 'dll.a') || (process.config && process.config.variables && process.config.variables.node_target_type === 'shared_library')) { - try { - return require('./index.win32-x64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-win32-x64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-x64-gnu/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - try { - return require('./index.win32-x64-msvc.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-win32-x64-msvc') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-x64-msvc/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'ia32') { - try { - return require('./index.win32-ia32-msvc.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-win32-ia32-msvc') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-ia32-msvc/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm64') { - try { - return require('./index.win32-arm64-msvc.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-win32-arm64-msvc') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-arm64-msvc/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`)) - } - } else if (process.platform === 'darwin') { - try { - return require('./index.darwin-universal.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-darwin-universal') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-universal/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - if (process.arch === 'x64') { - try { - return require('./index.darwin-x64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-darwin-x64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-x64/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm64') { - try { - return require('./index.darwin-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-darwin-arm64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-arm64/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`)) - } - } else if (process.platform === 'freebsd') { - if (process.arch === 'x64') { - try { - return require('./index.freebsd-x64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-freebsd-x64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-freebsd-x64/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm64') { - try { - return require('./index.freebsd-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-freebsd-arm64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-freebsd-arm64/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`)) - } - } else if (process.platform === 'linux') { - if (process.arch === 'x64') { - if (isMusl()) { +switch (platform) { + case 'android': + switch (arch) { + case 'arm64': + localFileExisted = existsSync(join(__dirname, 'index.android-arm64.node')) try { - return require('./index.linux-x64-musl.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-x64-musl') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-x64-musl/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.android-arm64.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-android-arm64') } - return binding } catch (e) { - loadErrors.push(e) + loadError = e } - } else { + break + case 'arm': + localFileExisted = existsSync(join(__dirname, 'index.android-arm-eabi.node')) try { - return require('./index.linux-x64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-x64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-x64-gnu/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.android-arm-eabi.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-android-arm-eabi') } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'arm64') { - if (isMusl()) { - try { - return require('./index.linux-arm64-musl.node') } catch (e) { - loadErrors.push(e) + loadError = e } + break + default: + throw new Error(`Unsupported architecture on Android ${arch}`) + } + break + case 'win32': + switch (arch) { + case 'x64': + localFileExisted = existsSync( + join(__dirname, 'index.win32-x64-msvc.node') + ) try { - const binding = require('@databricks/databricks-sql-kernel-linux-arm64-musl') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm64-musl/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.win32-x64-msvc.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-win32-x64-msvc') } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - try { - return require('./index.linux-arm64-gnu.node') } catch (e) { - loadErrors.push(e) + loadError = e } + break + case 'ia32': + localFileExisted = existsSync( + join(__dirname, 'index.win32-ia32-msvc.node') + ) try { - const binding = require('@databricks/databricks-sql-kernel-linux-arm64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm64-gnu/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.win32-ia32-msvc.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-win32-ia32-msvc') } - return binding } catch (e) { - loadErrors.push(e) + loadError = e } - } - } else if (process.arch === 'arm') { - if (isMusl()) { + break + case 'arm64': + localFileExisted = existsSync( + join(__dirname, 'index.win32-arm64-msvc.node') + ) try { - return require('./index.linux-arm-musleabihf.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.win32-arm64-msvc.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-win32-arm64-msvc') } - return binding } catch (e) { - loadErrors.push(e) + loadError = e } + break + default: + throw new Error(`Unsupported architecture on Windows: ${arch}`) + } + break + case 'darwin': + localFileExisted = existsSync(join(__dirname, 'index.darwin-universal.node')) + try { + if (localFileExisted) { + nativeBinding = require('./index.darwin-universal.node') } else { - try { - return require('./index.linux-arm-gnueabihf.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } + nativeBinding = require('@databricks/databricks-sql-kernel-darwin-universal') } - } else if (process.arch === 'loong64') { - if (isMusl()) { - try { - return require('./index.linux-loong64-musl.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-loong64-musl') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-loong64-musl/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { + break + } catch {} + switch (arch) { + case 'x64': + localFileExisted = existsSync(join(__dirname, 'index.darwin-x64.node')) try { - return require('./index.linux-loong64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-loong64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-loong64-gnu/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.darwin-x64.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-darwin-x64') } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'riscv64') { - if (isMusl()) { - try { - return require('./index.linux-riscv64-musl.node') } catch (e) { - loadErrors.push(e) + loadError = e } + break + case 'arm64': + localFileExisted = existsSync( + join(__dirname, 'index.darwin-arm64.node') + ) try { - const binding = require('@databricks/databricks-sql-kernel-linux-riscv64-musl') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-riscv64-musl/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.darwin-arm64.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-darwin-arm64') } - return binding } catch (e) { - loadErrors.push(e) + loadError = e } + break + default: + throw new Error(`Unsupported architecture on macOS: ${arch}`) + } + break + case 'freebsd': + if (arch !== 'x64') { + throw new Error(`Unsupported architecture on FreeBSD: ${arch}`) + } + localFileExisted = existsSync(join(__dirname, 'index.freebsd-x64.node')) + try { + if (localFileExisted) { + nativeBinding = require('./index.freebsd-x64.node') } else { - try { - return require('./index.linux-riscv64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'ppc64') { - try { - return require('./index.linux-ppc64-gnu.node') - } catch (e) { - loadErrors.push(e) + nativeBinding = require('@databricks/databricks-sql-kernel-freebsd-x64') } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-ppc64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-ppc64-gnu/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 's390x') { - try { - return require('./index.linux-s390x-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-s390x-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-s390x-gnu/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`)) + } catch (e) { + loadError = e } - } else if (process.platform === 'openharmony') { - if (process.arch === 'arm64') { - try { - return require('./index.openharmony-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-openharmony-arm64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-arm64/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'x64') { - try { - return require('./index.openharmony-x64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-openharmony-x64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-x64/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + break + case 'linux': + switch (arch) { + case 'x64': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'index.linux-x64-musl.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-x64-musl.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-x64-musl') + } + } catch (e) { + loadError = e + } + } else { + localFileExisted = existsSync( + join(__dirname, 'index.linux-x64-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-x64-gnu.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-x64-gnu') + } + } catch (e) { + loadError = e + } } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm') { - try { - return require('./index.openharmony-arm.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-openharmony-arm') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-arm/package.json').version - if (bindingPackageVersion !== '0.2.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + break + case 'arm64': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'index.linux-arm64-musl.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-arm64-musl.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm64-musl') + } + } catch (e) { + loadError = e + } + } else { + localFileExisted = existsSync( + join(__dirname, 'index.linux-arm64-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-arm64-gnu.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm64-gnu') + } + } catch (e) { + loadError = e + } } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`)) - } - } else { - loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`)) - } -} - -function createLoadErrorChain(errors) { - return errors.reduce((previous, current) => { - let message - try { - message = - current && typeof current.message === 'string' - ? current.message - : String(current) - } catch { - message = 'Unknown error' - } - const error = new Error(message) - error.cause = previous - return error - }, null) -} - -// NAPI_RS_FORCE_WASI is a tri-state flag: -// unset / any other value → native binding preferred, WASI is only a fallback -// 'true' → prefer WASI, but retain native as a lazy fallback -// 'error' → require WASI without initializing a native fallback -// Treating any non-empty string as truthy (the historical behavior) meant -// NAPI_RS_FORCE_WASI=false, NAPI_RS_FORCE_WASI=0, etc. inadvertently triggered -// the WASI path, causing ENOENT for packages shipped without a .wasi.cjs file. -// -// NAPI_RS_WASI_FLAVOR selects one exact generated flavor and implies strict -// WASI loading. It never crosses into another flavor or falls back to native. -const __napiWasiFlavors = ["wasm32-wasi"] -const __napiWasiFlavor = process.env.NAPI_RS_WASI_FLAVOR -const __napiWasiFlavorRequested = - typeof __napiWasiFlavor === 'string' && __napiWasiFlavor.length > 0 -if ( - __napiWasiFlavorRequested && - __napiWasiFlavors.indexOf(__napiWasiFlavor) === -1 -) { - throw new Error( - 'Unsupported WASI flavor "' + - __napiWasiFlavor + - '". Available flavors: ' + - __napiWasiFlavors.join(', '), - ) -} -const forceWasiError = process.env.NAPI_RS_FORCE_WASI === 'error' -const forceWasi = - process.env.NAPI_RS_FORCE_WASI === 'true' || - forceWasiError || - __napiWasiFlavorRequested - -if (!forceWasi) { - nativeBinding = requireNative() -} - -if (!nativeBinding || forceWasi) { - let wasiBinding = null - let wasiBindingLoaded = false - const wasiBindingErrors = [] - const __napiWasiResolveCandidate = (specifier, isPackage, localArtifacts) => { - try { - require.resolve(specifier) - } catch (resolveError) { - if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { - throw resolveError - } - if (isPackage) { - try { - require.resolve(specifier + '/package.json') - } catch (packageError) { - if (packageError && packageError.code === 'MODULE_NOT_FOUND') { - return resolveError + break + case 'arm': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'index.linux-arm-musleabihf.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-arm-musleabihf.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf') + } + } catch (e) { + loadError = e + } + } else { + localFileExisted = existsSync( + join(__dirname, 'index.linux-arm-gnueabihf.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-arm-gnueabihf.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf') + } + } catch (e) { + loadError = e } - // An exports restriction proves the package exists even when its - // package.json is not public. Preserve the root resolution failure. - throw resolveError } - // The package exists but its main/export target is broken. - throw resolveError - } - return resolveError - } - if (localArtifacts) { - let artifactError = null - for (let i = 0; i < localArtifacts.length; i++) { - try { - require.resolve(localArtifacts[i]) - return null - } catch (resolveError) { - if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { - throw resolveError + break + case 'riscv64': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'index.linux-riscv64-musl.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-riscv64-musl.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-riscv64-musl') + } + } catch (e) { + loadError = e + } + } else { + localFileExisted = existsSync( + join(__dirname, 'index.linux-riscv64-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-riscv64-gnu.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu') + } + } catch (e) { + loadError = e } - artifactError = resolveError } - } - return artifactError - } - return null - } - if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) { - let candidateError = null - let candidateFailed = false - try { - candidateError = __napiWasiResolveCandidate('./index.wasi.cjs', false, ["./index.wasm32-wasi.debug.wasm","./index.wasm32-wasi.wasm"]) - candidateFailed = candidateError !== null - if (!candidateFailed) { - wasiBinding = require('./index.wasi.cjs') - nativeBinding = wasiBinding - wasiBindingLoaded = true - } - } catch (err) { - candidateError = err - candidateFailed = true - } - if (candidateFailed) { - wasiBindingErrors.push(candidateError) - loadErrors.push(candidateError) - } - } - if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) { - let candidateError = null - let candidateFailed = false - try { - candidateError = __napiWasiResolveCandidate('@databricks/databricks-sql-kernel-wasm32-wasi', true, undefined) - candidateFailed = candidateError !== null - if (!candidateFailed) { - if (process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-wasm32-wasi/package.json').version - if (bindingPackageVersion !== '0.2.0') { - throw new Error(`WASI binding package version mismatch, expected 0.2.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + break + case 's390x': + localFileExisted = existsSync( + join(__dirname, 'index.linux-s390x-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-s390x-gnu.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-s390x-gnu') } + } catch (e) { + loadError = e } - wasiBinding = require('@databricks/databricks-sql-kernel-wasm32-wasi') - nativeBinding = wasiBinding - wasiBindingLoaded = true - } - } catch (err) { - candidateError = err - candidateFailed = true + break + default: + throw new Error(`Unsupported architecture on Linux: ${arch}`) } - if (candidateFailed) { - wasiBindingErrors.push(candidateError) - loadErrors.push(candidateError) - } - } - if ( - !wasiBindingLoaded && - forceWasi && - !forceWasiError && - !__napiWasiFlavorRequested - ) { - nativeBinding = requireNative() - } - if ((forceWasiError || __napiWasiFlavorRequested) && !wasiBindingLoaded) { - const error = new Error( - __napiWasiFlavorRequested - ? 'WASI binding for flavor "' + __napiWasiFlavor + '" not found' - : 'WASI binding not found and NAPI_RS_FORCE_WASI is set to error', - ) - error.cause = createLoadErrorChain(wasiBindingErrors) - throw error - } + break + default: + throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`) } if (!nativeBinding) { - if (loadErrors.length > 0) { - const error = new Error( - `Cannot find native binding. ` + - `npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` + - 'Please try `npm i` again after removing both package-lock.json and node_modules directory.', - ) - // assign instead of the `new Error(message, { cause })` options form, - // which Node < 16.9 silently ignores - error.cause = createLoadErrorChain(loadErrors) - throw error + if (loadError) { + throw loadError } throw new Error(`Failed to load native binding`) } -module.exports = nativeBinding -module.exports.AsyncResultHandle = nativeBinding.AsyncResultHandle -module.exports.AsyncStatement = nativeBinding.AsyncStatement -module.exports.CancellableExecution = nativeBinding.CancellableExecution -module.exports.Connection = nativeBinding.Connection -module.exports.Statement = nativeBinding.Statement -module.exports.AuthMode = nativeBinding.AuthMode -module.exports.initKernelLogging = nativeBinding.initKernelLogging -module.exports.kernelLoggingStats = nativeBinding.kernelLoggingStats -module.exports.openSession = nativeBinding.openSession -module.exports.setKernelLogLevel = nativeBinding.setKernelLogLevel -module.exports.version = nativeBinding.version +const { AsyncStatement, AsyncResultHandle, CancellableExecution, Connection, AuthMode, openSession, initKernelLogging, kernelLoggingStats, setKernelLogLevel, Statement, version } = nativeBinding + +module.exports.AsyncStatement = AsyncStatement +module.exports.AsyncResultHandle = AsyncResultHandle +module.exports.CancellableExecution = CancellableExecution +module.exports.Connection = Connection +module.exports.AuthMode = AuthMode +module.exports.openSession = openSession +module.exports.initKernelLogging = initKernelLogging +module.exports.kernelLoggingStats = kernelLoggingStats +module.exports.setKernelLogLevel = setKernelLogLevel +module.exports.Statement = Statement +module.exports.version = version From 456fb80d4edb78169efc9a226759237e36153948 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Tue, 25 Aug 2026 10:53:13 -0700 Subject: [PATCH 10/10] fix(pyo3): make extension-module opt-in so cargo test links libpython The pyo3 dep enabled `extension-module` unconditionally, which tells the linker NOT to link libpython (symbols are supplied by the host interpreter at wheel load time). That is correct for the built extension but breaks the `cargo test` step in pyo3-checks.yml: the unit-test binary must link libpython, so it failed on Linux CI with a wall of undefined `Py*` symbols (PyEval_RestoreThread, PyGILState_Ensure, ...). main is currently red for the same reason. Make `extension-module` an opt-in crate feature and have maturin turn it on via [tool.maturin] features, so plain `cargo test` links libpython while the wheel build keeps the dynamic-lookup behaviour. Same fix as the in-flight #request-timeout binding PR; verified locally (22 pyo3 unit tests pass, incl. u2m_token_cache_control_maps_to_config). Signed-off-by: eric-wang-1990 --- pyo3/Cargo.toml | 7 ++++++- pyo3/pyproject.toml | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) 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/pyproject.toml b/pyo3/pyproject.toml index 2070cad8..1cb1778a 100644 --- a/pyo3/pyproject.toml +++ b/pyo3/pyproject.toml @@ -57,3 +57,7 @@ dev = [ [tool.maturin] module-name = "databricks_sql_kernel" +# The pyo3 `extension-module` feature is opt-in (see pyo3/Cargo.toml) so plain +# `cargo test` can link libpython for the unit-test binaries. Maturin builds the +# real wheel, where the interpreter supplies those symbols, so enable it here. +features = ["extension-module"]