From 9673364e3085ff85b3bc687f08093dd9b19d76b6 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 23:47:38 +0000 Subject: [PATCH 1/3] perf(client): stop copying every request for retries reqwest can't make; reuse the Authorization value reqwest's default retry layer clones each request (headers, URI, extensions, body) so it can replay HTTP/2 and HTTP/3 refusals. This client speaks HTTP/1.1 only and execute_impl does the kernel's retries, so the layer is turned off. The validated Authorization header value is reused while the provider returns the same string, and FederationProvider decides whether a token's issuer is foreign once per distinct token instead of decoding the JWT and parsing its issuer URL on every request. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- NEXT_CHANGELOG.md | 4 ++ src/auth/oauth/federation.rs | 77 +++++++++++++++++++++++++++++++----- src/client/http.rs | 64 ++++++++++++++++++++++++++++-- 3 files changed, 133 insertions(+), 12 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 6aa75289..994e8519 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -20,6 +20,10 @@ changes go in their respective binding's NEXT_CHANGELOG. with an optional partner entry from `adbc.databricks.user_agent_entry` (`adbc.spark.user_agent_entry` is a compatibility alias). `User-Agent` in `adbc.databricks.http.headers` is now rejected; use the dedicated entry option. +- Each HTTP request costs less CPU: the client no longer copies every request + for HTTP/2 retries it cannot make, and an unchanged token's `Authorization` + value (and, with token federation, its issuer check) is reused instead of + being rebuilt per request. ### Updated diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index ed239bb4..277ccdce 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -123,6 +123,16 @@ pub struct FederationProvider { /// coordination so concurrent callers on a rotated / expired token don't /// each mint a distinct server token (which SP-wide WIF would otherwise do). exchanging: AtomicBool, + /// The inner provider's last header and whether its token's issuer is + /// foreign. Keyed on the exact header, so the JWT is decoded once per + /// token rather than on every request, and a fresher token from the inner + /// provider is always checked again. + issuer_decision: RwLock>, +} + +struct IssuerDecision { + header: String, + foreign: bool, } /// How long a follower sleeps between polls while the leader runs the exchange. @@ -191,9 +201,28 @@ impl FederationProvider { runtime_handle: RuntimeHandle::current(), cache: RwLock::new(None), exchanging: AtomicBool::new(false), + issuer_decision: RwLock::new(None), }) } + /// Whether the bearer token in `header` (`source_token`) needs exchange, + /// decided once per distinct header. + fn token_is_foreign(&self, header: &str, source_token: &str) -> bool { + if let Ok(slot) = self.issuer_decision.read() { + if let Some(decision) = slot.as_ref().filter(|d| d.header == header) { + return decision.foreign; + } + } + let foreign = jwt::issuer(source_token).is_some_and(|iss| self.issuer_is_foreign(&iss)); + if let Ok(mut slot) = self.issuer_decision.write() { + *slot = Some(IssuerDecision { + header: header.to_string(), + foreign, + }); + } + foreign + } + /// Whether a token with issuer `iss` needs exchange (i.e. it is foreign to /// this workspace). An unparseable / empty issuer host is treated as "same /// host" (no exchange) so malformed values fall back to pass-through. @@ -441,16 +470,15 @@ impl AuthProvider for FederationProvider { return Ok(header); }; - // Re-check the issuer on every call (rather than trusting a cached - // decision) so a fresher in-house token from the inner provider is - // never shadowed by a stale exchange. - match jwt::issuer(source_token) { - Some(iss) if self.issuer_is_foreign(&iss) => { - let token = self.exchanged_or_original(source_token); - Ok(format!("Bearer {token}")) - } + // Check the issuer of every new token (rather than trusting a + // decision made for an earlier one) so a fresher in-house token from + // the inner provider is never shadowed by a stale exchange. + if self.token_is_foreign(&header, source_token) { + let token = self.exchanged_or_original(source_token); + Ok(format!("Bearer {token}")) + } else { // Not a JWT, or issued by this workspace: use as-is. - _ => Ok(header), + Ok(header) } } } @@ -559,6 +587,7 @@ mod tests { runtime_handle: RuntimeHandle::current(), cache: RwLock::new(None), exchanging: AtomicBool::new(false), + issuer_decision: RwLock::new(None), } } @@ -586,6 +615,36 @@ mod tests { assert!(p.issuer_is_foreign("https://login.microsoftonline.com/tenant/v2.0")); } + fn unsigned_jwt(iss: &str) -> String { + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + use base64::Engine; + let part = |v: serde_json::Value| URL_SAFE_NO_PAD.encode(v.to_string()); + format!( + "{}.{}.sig", + part(serde_json::json!({"alg": "none"})), + part(serde_json::json!({ "iss": iss })) + ) + } + + /// The issuer decision is remembered per exact header: repeating a token + /// reuses it, and a different token is checked again. + #[tokio::test(flavor = "multi_thread")] + async fn issuer_decision_follows_the_current_token() { + let p = provider_for("https://ws.cloud.databricks.com", "Bearer x"); + let in_house = unsigned_jwt("https://ws.cloud.databricks.com/oidc"); + let foreign = unsigned_jwt("https://login.microsoftonline.com/tenant/v2.0"); + let header = |t: &str| format!("Bearer {t}"); + + for _ in 0..2 { + assert!(!p.token_is_foreign(&header(&in_house), &in_house)); + } + for _ in 0..2 { + assert!(p.token_is_foreign(&header(&foreign), &foreign)); + } + assert!(!p.token_is_foreign(&header(&in_house), &in_house)); + assert!(!p.token_is_foreign("Bearer opaque", "opaque")); + } + #[tokio::test(flavor = "multi_thread")] async fn non_bearer_header_passes_through() { let p = provider_for("https://ws.cloud.databricks.com", "Basic abc123"); diff --git a/src/client/http.rs b/src/client/http.rs index e5f9ad0b..3ec7fcec 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -30,6 +30,7 @@ use crate::client::retry::{ use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; use crate::types::sea::ServiceError; +use reqwest::header::HeaderValue; use reqwest::{Client, NoProxy, Proxy, Request, Response}; use std::collections::HashMap; use std::sync::{Arc, OnceLock}; @@ -386,6 +387,36 @@ pub struct DatabricksHttpClient { config: HttpClientConfig, auth_provider: OnceLock>, retry_configs: HashMap, + auth_value: AuthValueCache, +} + +/// The last `Authorization` string from the provider and its validated header +/// value, so an unchanged token is not re-validated and copied per request. +/// `Debug` never prints the credential. +#[derive(Default)] +struct AuthValueCache(std::sync::Mutex>); + +impl std::fmt::Debug for AuthValueCache { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("AuthValueCache()") + } +} + +impl AuthValueCache { + fn get_or_build(&self, header: String) -> Result { + let mut slot = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((cached, value)) = slot.as_ref() { + if *cached == header { + return Ok(value.clone()); + } + } + let mut value = HeaderValue::from_str(&header).map_err(|e| { + Error::invalid_argument().message(format!("Failed to build request: {e}")) + })?; + value.set_sensitive(true); + *slot = Some((header, value.clone())); + Ok(value) + } } impl DatabricksHttpClient { @@ -502,6 +533,7 @@ impl DatabricksHttpClient { config, auth_provider: OnceLock::new(), retry_configs, + auth_value: AuthValueCache::default(), }) } @@ -522,7 +554,11 @@ impl DatabricksHttpClient { .timeout(config.read_timeout) .pool_max_idle_per_host(config.max_connections_per_host) .user_agent(&config.user_agent) - .redirect(redirect); + .redirect(redirect) + // reqwest's default retry layer copies every request so it can + // replay HTTP/2 or HTTP/3 refusals, neither of which this client + // speaks; `execute_impl` does the kernel's retries. + .retry(reqwest::retry::never().max_retries_per_request(0)); // Apply TLS configuration if config.tls.enabled == Some(false) { @@ -902,8 +938,8 @@ impl DatabricksHttpClient { if !self.config.sea_response_compression_enabled { req_builder = req_builder.header("Accept-Encoding", "identity"); } - let auth_header = self.auth_header()?; - req_builder = req_builder.header("Authorization", auth_header); + let auth_value = self.auth_value.get_or_build(self.auth_header()?)?; + req_builder = req_builder.header(reqwest::header::AUTHORIZATION, auth_value); // Extra auth headers (Azure SP management-token pair). Empty for // every other provider. Applied only on authenticated requests, // never on the token/OIDC calls that use `execute_without_auth`. @@ -1085,6 +1121,28 @@ mod tests { build_retry_configs(&RetryConfig::default(), &HashMap::new()) } + #[test] + fn auth_value_cache_reuses_the_value_until_the_header_changes() { + let cache = AuthValueCache::default(); + let first = cache.get_or_build("Bearer one".to_string()).unwrap(); + assert!(first.is_sensitive()); + assert_eq!(first, "Bearer one"); + assert_eq!( + cache.get_or_build("Bearer one".to_string()).unwrap(), + "Bearer one" + ); + assert_eq!( + cache.get_or_build("Bearer two".to_string()).unwrap(), + "Bearer two" + ); + assert!(cache.get_or_build("Bearer bad\nvalue".to_string()).is_err()); + assert_eq!( + cache.get_or_build("Bearer two".to_string()).unwrap(), + "Bearer two" + ); + assert!(!format!("{cache:?}").contains("two")); + } + #[test] fn test_http_client_config_default() { let config = HttpClientConfig::default(); From c0728f952682c84f37c61a41bb550197fb677d8e Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 01:10:41 +0000 Subject: [PATCH 2/3] build: require reqwest 0.12.23, the first release with ClientBuilder::retry Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- Cargo.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index f428c382..19c5123e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,7 +59,8 @@ arrow-ipc = "59" # (which `native-tls` pulls in on Linux) collides with Node's symbols at # module load time and segfaults the process before any Rust code runs. # `rustls` is pure Rust + ring and avoids the conflict entirely. -reqwest = { version = "0.12", default-features = false, features = ["json", "gzip", "stream"] } +# 0.12.23: first release with `ClientBuilder::retry` (see `client/http.rs`). +reqwest = { version = "0.12.23", default-features = false, features = ["json", "gzip", "stream"] } native-tls = { version = "0.2", optional = true } rustls = { version = "0.23.41", optional = true, default-features = false, features = ["ring", "std", "tls12"] } # Enforce TLS dependency minimums for consumers with their own lockfiles. From d43d3e468c4284aae14a5a4a62164e95ada16897 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 01:23:07 +0000 Subject: [PATCH 3/3] perf(client): read the cached Authorization value under a read lock Requests that share a token now only take the read side, so concurrent requests don't serialize on the cache; the write lock is taken only when the provider returns a new header. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/client/http.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index 3ec7fcec..fba9bea8 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -394,7 +394,7 @@ pub struct DatabricksHttpClient { /// value, so an unchanged token is not re-validated and copied per request. /// `Debug` never prints the credential. #[derive(Default)] -struct AuthValueCache(std::sync::Mutex>); +struct AuthValueCache(std::sync::RwLock>); impl std::fmt::Debug for AuthValueCache { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -404,8 +404,8 @@ impl std::fmt::Debug for AuthValueCache { impl AuthValueCache { fn get_or_build(&self, header: String) -> Result { - let mut slot = self.0.lock().unwrap_or_else(|e| e.into_inner()); - if let Some((cached, value)) = slot.as_ref() { + // Requests sharing a token only read, so they don't wait on each other. + if let Some((cached, value)) = self.0.read().unwrap_or_else(|e| e.into_inner()).as_ref() { if *cached == header { return Ok(value.clone()); } @@ -414,7 +414,7 @@ impl AuthValueCache { Error::invalid_argument().message(format!("Failed to build request: {e}")) })?; value.set_sensitive(true); - *slot = Some((header, value.clone())); + *self.0.write().unwrap_or_else(|e| e.into_inner()) = Some((header, value.clone())); Ok(value) } }