diff --git a/src/config.rs b/src/config.rs index d5f8050e..8ac22266 100644 --- a/src/config.rs +++ b/src/config.rs @@ -54,6 +54,8 @@ use std::collections::HashMap; use std::path::PathBuf; use std::time::Duration; +use crate::telemetry::DriverSystemConfiguration; + // ─── Connection identity ──────────────────────────────────────────────────── /// Required: identifies the workspace and warehouse to connect to. @@ -1185,11 +1187,68 @@ pub struct LoggingConfig { // ─── Telemetry (reserved) ─────────────────────────────────────────────────── -/// Reserved for v0.1. Fields land once the telemetry exporter contract -/// is finalised. +/// Telemetry collection and export settings. +/// +/// Telemetry is disabled by default. When enabled, the kernel records +/// driver operation metrics and exports them through the Databricks SQL +/// driver telemetry envelope. Telemetry failures are fail-open: export +/// errors are logged at trace/debug level and never change user operation +/// results. #[non_exhaustive] -#[derive(Debug, Clone, Default)] -pub struct TelemetryConfig {} +#[derive(Clone)] +pub struct TelemetryConfig { + /// Whether telemetry collection is enabled. + pub enabled: bool, + + /// Number of telemetry events to buffer before triggering a flush. + pub batch_size: usize, + + /// Maximum time an explicit session close should wait for the final + /// telemetry flush. `Drop` never waits. + pub close_flush_timeout: Duration, + + #[cfg(test)] + pub(crate) exporter: Option>, +} + +impl std::fmt::Debug for TelemetryConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut debug = f.debug_struct("TelemetryConfig"); + debug + .field("enabled", &self.enabled) + .field("batch_size", &self.batch_size) + .field("close_flush_timeout", &self.close_flush_timeout); + #[cfg(test)] + debug.field( + "exporter", + &self.exporter.as_ref().map(|_| ""), + ); + debug.finish() + } +} + +impl Default for TelemetryConfig { + fn default() -> Self { + Self { + enabled: false, + batch_size: 200, + close_flush_timeout: Duration::from_secs(5), + #[cfg(test)] + exporter: None, + } + } +} + +impl TelemetryConfig { + #[cfg(test)] + pub(crate) fn with_exporter( + mut self, + exporter: std::sync::Arc, + ) -> Self { + self.exporter = Some(exporter); + self + } +} // ─── Transport mode ───────────────────────────────────────────────────────── @@ -1223,6 +1282,11 @@ pub struct SessionConfig { /// Required: how to authenticate. pub auth: AuthConfig, + /// Client-provided driver/runtime identity. Telemetry uses this for + /// `DriverSystemConfiguration`, filling any missing fields with + /// kernel defaults at session-open time. + pub driver_system_configuration: Option, + /// Server-bound session conf. Maps to SEA `session_confs` / /// Thrift `configuration`. Typed sub-structs above translate /// the *client-side* knobs; this map carries everything else. diff --git a/src/lib.rs b/src/lib.rs index a2da2b4d..e7272cda 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -147,6 +147,7 @@ pub use statement::handle::ExecutedStatementHandle; pub use statement::mutable::{DirectStatement, Statement, StatementCanceller}; pub use statement::params_codec::parse_typed_value; pub use statement::spec::{ResultFormat, StatementSpec, TypedValue}; +pub use telemetry::DriverSystemConfiguration; // === Compile-time guarantees on auto-traits === // diff --git a/src/session.rs b/src/session.rs index e4870bcd..021b76cf 100644 --- a/src/session.rs +++ b/src/session.rs @@ -68,9 +68,10 @@ use crate::metadata_v0::Metadata; use crate::reader::ResultReaderFactory; use crate::statement::executed_async::ExecutedAsyncStatement; use crate::statement::mutable::Statement; +use crate::telemetry::{DriverSystemConfiguration, OperationType, TelemetryRuntime}; use std::collections::HashMap; use std::sync::Arc; -use std::time::Duration; +use std::time::{Duration, Instant}; use tracing::{info_span, Instrument, Span}; /// Crate-internal session state. Wrapped in `Arc` and shared with @@ -104,6 +105,11 @@ pub(crate) struct SessionInner { /// so log lines tied to a session are visibly grouped. log_span: Span, + /// Session-scoped telemetry runtime. It is a no-op runtime when + /// telemetry is disabled or initialization fails, so callsites can + /// emit lifecycle events without branching on config. + telemetry: Arc, + /// Flips to `true` only after [`Session::close`] has /// **successfully** awaited the `delete_session` call. Tells /// [`Drop`] to skip its fire-and-forget cleanup so a successful @@ -354,6 +360,7 @@ impl Session { // ExecuteStatement with `CONFIG_NOT_AVAILABLE` (issue #196). So the // user's `session_conf` flows to CreateSession untouched; the // kernel synthesises nothing here. + let create_started = Instant::now(); let session_info = transport .create_session( defaults.catalog.as_deref(), @@ -361,6 +368,18 @@ impl Session { crate::config::filter_session_conf(config.session_conf.clone()), ) .await?; + let create_elapsed = create_started.elapsed(); + + let telemetry = Arc::new(TelemetryRuntime::from_config( + &config.telemetry, + &config.connection, + &config.auth, + config.driver_system_configuration.clone(), + session_info.session_id.clone(), + )); + telemetry + .connection() + .emit_operation(OperationType::CreateSession, create_elapsed, None); // 5. Tag the per-session tracing span. Future log lines // inherit `session_id` automatically. Target is pinned to the @@ -380,6 +399,7 @@ impl Session { config, runtime_handle, log_span, + telemetry, closed: std::sync::atomic::AtomicBool::new(false), // Autocommit defaults to on (every statement commits); a // caller opts into explicit transactions via set_autocommit. @@ -629,10 +649,24 @@ impl Session { } let span = self.inner.log_span.clone(); async { - self.inner + let telemetry = self.inner.telemetry.connection(); + let delete_started = Instant::now(); + if let Err(error) = self + .inner .transport .delete_session(&self.inner.session_id) - .await?; + .await + { + telemetry.emit_operation( + OperationType::DeleteSession, + delete_started.elapsed(), + Some(&error), + ); + telemetry.flush().await; + return Err(error); + } + telemetry.emit_operation(OperationType::DeleteSession, delete_started.elapsed(), None); + telemetry.flush().await; self.inner .closed .store(true, std::sync::atomic::Ordering::Release); @@ -661,6 +695,7 @@ pub struct SessionBuilder { result: Option, logging: Option, telemetry: Option, + driver_system_configuration: Option, session_conf: HashMap, transport: Option, /// Sentinel for [`SessionBuilder::http_path`] parse failures. @@ -790,6 +825,19 @@ impl SessionBuilder { self } + /// Driver/runtime identity stamped onto telemetry logs. + /// + /// Binding layers should use this to pass their own driver name, + /// version, runtime, and process details. Any fields left unset are + /// filled from kernel defaults when the session opens. + pub fn driver_system_configuration( + mut self, + system_configuration: DriverSystemConfiguration, + ) -> Self { + self.driver_system_configuration = Some(system_configuration); + self + } + /// Server-bound session conf passed through to SEA `session_confs`. pub fn session_conf(mut self, conf: HashMap) -> Self { self.session_conf = conf; @@ -828,6 +876,7 @@ impl SessionBuilder { connection, defaults: self.defaults, auth, + driver_system_configuration: self.driver_system_configuration, session_conf: self.session_conf, http: self.http.unwrap_or_default(), proxy: self.proxy, @@ -1295,6 +1344,7 @@ mod retry_config_tests { token: "dapi-test".to_string(), identity_federation_client_id: None, }, + driver_system_configuration: None, session_conf: Default::default(), http, proxy: None, @@ -1658,6 +1708,11 @@ mod retry_config_tests { #[cfg(test)] mod is_open_tests { use super::*; + use crate::telemetry::test_support::CapturingTelemetryExporter; + use crate::telemetry::{TelemetryExportResult, TelemetryExporter, TelemetryRequest}; + use serde_json::Value; + use std::future::Future; + use std::pin::Pin; use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -1771,4 +1826,179 @@ mod is_open_tests { "autocommit must stay on when transactions are ignored" ); } + + #[tokio::test] + async fn telemetry_disabled_emits_no_connection_events() { + let server = MockServer::start().await; + mount_session_create_delete(&server, "sess-telemetry-disabled").await; + let exporter = CapturingTelemetryExporter::default(); + + let session = telemetry_test_session(&server, "sess-telemetry-disabled", { + let exporter = std::sync::Arc::new(exporter.clone()); + TelemetryConfig::default().with_exporter(exporter) + }) + .await; + + session.close().await.expect("close succeeds"); + + assert!( + exporter.requests().is_empty(), + "disabled telemetry must not export requests" + ); + } + + #[tokio::test] + async fn telemetry_enabled_exports_create_and_delete_on_close() { + let server = MockServer::start().await; + mount_session_create_delete(&server, "sess-telemetry-enabled").await; + let exporter = CapturingTelemetryExporter::default(); + + let telemetry = TelemetryConfig { + enabled: true, + ..Default::default() + } + .with_exporter(std::sync::Arc::new(exporter.clone())); + let session = telemetry_test_session(&server, "sess-telemetry-enabled", telemetry).await; + + session.close().await.expect("close succeeds"); + + let requests = exporter.requests(); + assert_eq!(requests.len(), 1, "close should flush one pending batch"); + assert_eq!(requests[0].proto_logs.len(), 2); + let operations = requests[0] + .proto_logs + .iter() + .map(|log| { + let value: Value = serde_json::from_str(log).expect("valid frontend log json"); + assert_eq!( + value["entry"]["sql_driver_log"]["session_id"], + "sess-telemetry-enabled" + ); + value["entry"]["sql_driver_log"]["sql_operation"]["operation_detail"] + ["operation_type"] + .as_str() + .expect("operation_type string") + .to_string() + }) + .collect::>(); + + assert_eq!(operations, vec!["CREATE_SESSION", "DELETE_SESSION"]); + } + + #[tokio::test] + async fn telemetry_uses_client_driver_system_configuration_with_kernel_defaults() { + let server = MockServer::start().await; + mount_session_create_delete(&server, "sess-telemetry-system-config").await; + let exporter = CapturingTelemetryExporter::default(); + let telemetry = TelemetryConfig { + enabled: true, + ..Default::default() + } + .with_exporter(std::sync::Arc::new(exporter.clone())); + + let session = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid http_path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .telemetry(telemetry) + .driver_system_configuration(DriverSystemConfiguration { + driver_name: Some("databricks-sql-python".to_string()), + driver_version: Some("1.2.3".to_string()), + runtime_name: Some("python".to_string()), + ..Default::default() + }) + .open() + .await + .expect("session must open"); + + session.close().await.expect("close succeeds"); + + let requests = exporter.requests(); + assert_eq!(requests.len(), 1, "close should flush one pending batch"); + let value: Value = + serde_json::from_str(&requests[0].proto_logs[0]).expect("valid frontend log json"); + let system = &value["entry"]["sql_driver_log"]["system_configuration"]; + assert_eq!(system["driver_name"], "databricks-sql-python"); + assert_eq!(system["driver_version"], "1.2.3"); + assert_eq!(system["runtime_name"], "python"); + assert_eq!(system["runtime_vendor"], "rust-lang"); + assert_eq!(system["char_set_encoding"], "UTF-8"); + } + + #[tokio::test] + async fn telemetry_export_failure_does_not_fail_session_close() { + let server = MockServer::start().await; + mount_session_create_delete(&server, "sess-telemetry-failure").await; + let telemetry = TelemetryConfig { + enabled: true, + ..Default::default() + } + .with_exporter(std::sync::Arc::new(FailingTelemetryExporter)); + + let session = telemetry_test_session(&server, "sess-telemetry-failure", telemetry).await; + + session + .close() + .await + .expect("telemetry export failure must be fail-open"); + } + + async fn telemetry_test_session( + server: &MockServer, + expected_session_id: &str, + telemetry: TelemetryConfig, + ) -> Session { + let session = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid http_path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .telemetry(telemetry) + .open() + .await + .expect("session must open"); + + assert_eq!(session.session_id(), expected_session_id); + session + } + + async fn mount_session_create_delete(server: &MockServer, session_id: &str) { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with(ResponseTemplate::new(200).set_body_string(format!( + r#"{{"session_id":"{session_id}","warehouse_id":"test_wh"}}"# + ))) + .mount(server) + .await; + Mock::given(method("DELETE")) + .and(path(format!("/api/2.0/sql/sessions/{session_id}"))) + .respond_with(ResponseTemplate::new(200)) + .mount(server) + .await; + } + + #[derive(Debug)] + struct FailingTelemetryExporter; + + impl TelemetryExporter for FailingTelemetryExporter { + fn export<'a>( + &'a self, + _request: TelemetryRequest, + ) -> Pin + Send + 'a>> { + Box::pin(async { + Err(crate::telemetry::TelemetryExportError::Export( + "expected test failure".to_string(), + )) + }) + } + } } diff --git a/src/telemetry/client.rs b/src/telemetry/client.rs new file mode 100644 index 00000000..74a90fc8 --- /dev/null +++ b/src/telemetry/client.rs @@ -0,0 +1,101 @@ +// 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. + +use super::exporter::{export_batch, TelemetryExporter}; +use super::models::TelemetryFrontendLog; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +pub(super) struct TelemetryClient { + exporter: Arc, + batch_size: usize, + close_flush_timeout: Duration, + pending: Mutex>, + in_flight: Mutex>>, +} + +impl TelemetryClient { + pub(super) fn new( + exporter: Arc, + batch_size: usize, + close_flush_timeout: Duration, + ) -> Self { + Self { + exporter, + batch_size, + close_flush_timeout, + pending: Mutex::new(Vec::new()), + in_flight: Mutex::new(Vec::new()), + } + } + + pub(super) fn enqueue(&self, log: TelemetryFrontendLog) { + let batch = { + let mut pending = self.pending.lock().expect("poisoned telemetry queue"); + pending.push(log); + if pending.len() >= self.batch_size { + Some(pending.drain(..).collect::>()) + } else { + None + } + }; + + if let Some(batch) = batch { + let exporter = Arc::clone(&self.exporter); + let handle = tokio::spawn(async move { + export_batch(exporter, batch).await; + }); + self.in_flight + .lock() + .expect("poisoned telemetry in-flight queue") + .push(handle); + } + } + + pub(super) async fn flush_bounded(&self) { + let batch = self.drain_pending(); + let in_flight = self.drain_in_flight(); + if batch.is_empty() && in_flight.is_empty() { + return; + } + + let exporter = Arc::clone(&self.exporter); + let timeout = self.close_flush_timeout; + let _ = tokio::time::timeout(timeout, async move { + for handle in in_flight { + let _ = handle.await; + } + if !batch.is_empty() { + export_batch(exporter, batch).await; + } + }) + .await; + } + + fn drain_pending(&self) -> Vec { + self.pending + .lock() + .expect("poisoned telemetry queue") + .drain(..) + .collect() + } + + fn drain_in_flight(&self) -> Vec> { + self.in_flight + .lock() + .expect("poisoned telemetry in-flight queue") + .drain(..) + .collect() + } +} diff --git a/src/telemetry/exporter.rs b/src/telemetry/exporter.rs index 50b5db3f..536ced0e 100644 --- a/src/telemetry/exporter.rs +++ b/src/telemetry/exporter.rs @@ -12,9 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::models::TelemetryRequest; +use super::models::{TelemetryFrontendLog, TelemetryRequest}; use std::future::Future; use std::pin::Pin; +use std::sync::Arc; pub(crate) type TelemetryExportResult = Result<(), TelemetryExportError>; @@ -32,3 +33,20 @@ pub(crate) trait TelemetryExporter: Send + Sync { request: TelemetryRequest, ) -> Pin + Send + 'a>>; } + +pub(super) async fn export_batch( + exporter: Arc, + batch: Vec, +) { + let request = match TelemetryRequest::from_logs(&batch) { + Ok(request) => request, + Err(e) => { + tracing::debug!(error = %e, "failed to serialize telemetry batch"); + return; + } + }; + + if let Err(e) = exporter.export(request).await { + tracing::debug!(error = %e, "failed to export telemetry batch"); + } +} diff --git a/src/telemetry/mod.rs b/src/telemetry/mod.rs index 1c1988f5..7b87ddc6 100644 --- a/src/telemetry/mod.rs +++ b/src/telemetry/mod.rs @@ -12,16 +12,27 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Telemetry model and serialization support. +//! Telemetry model, collection, and export support. //! //! These types mirror the SQL driver telemetry envelope used by the ADBC and -//! JDBC drivers. Phase 1 intentionally stops at model/serialization boundaries; -//! later phases add lifecycle observers and production export. +//! JDBC drivers. The module is split by responsibility so later phases can add +//! statement, result-stream, metadata, and production exporter code without +//! growing a single catch-all file. #![allow(dead_code)] +mod client; mod exporter; mod models; +mod runtime; #[cfg(test)] pub(crate) mod test_support; + +#[cfg(test)] +pub(crate) use exporter::{TelemetryExportError, TelemetryExportResult, TelemetryExporter}; +pub use models::DriverSystemConfiguration; +pub(crate) use models::OperationType; +#[cfg(test)] +pub(crate) use models::TelemetryRequest; +pub(crate) use runtime::TelemetryRuntime; diff --git a/src/telemetry/models.rs b/src/telemetry/models.rs index bbb5d871..8479e6fd 100644 --- a/src/telemetry/models.rs +++ b/src/telemetry/models.rs @@ -87,7 +87,7 @@ pub(crate) struct OssSqlDriverTelemetryLog { } #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] -pub(crate) struct DriverSystemConfiguration { +pub struct DriverSystemConfiguration { #[serde(skip_serializing_if = "Option::is_none")] pub driver_version: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -260,7 +260,7 @@ pub(crate) struct SqlExecutionEvent { pub java_uses_patched_arrow: Option, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] pub(crate) struct OperationDetail { #[serde(skip_serializing_if = "Option::is_none")] pub n_operation_status_calls: Option, diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs new file mode 100644 index 00000000..78312742 --- /dev/null +++ b/src/telemetry/runtime.rs @@ -0,0 +1,323 @@ +// 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. + +use super::client::TelemetryClient; +use super::exporter::TelemetryExporter; +use super::models::{ + unix_time_millis, DriverAuthFlow, DriverAuthMech, DriverConnectionParameters, DriverErrorInfo, + DriverMode, DriverSystemConfiguration, FrontendLogContext, FrontendLogEntry, HostDetails, + OperationDetail, OperationType, OssSqlDriverTelemetryLog, SqlExecutionEvent, + TelemetryClientContext, TelemetryFrontendLog, +}; +use crate::config::{AuthConfig, ConnectionConfig, TelemetryConfig}; +use crate::kernel_error::Error as KernelError; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +pub(crate) struct TelemetryRuntime { + connection: Arc, +} + +impl TelemetryRuntime { + pub(crate) fn disabled() -> Self { + Self { + connection: Arc::new(NoOpConnectionTelemetry), + } + } + + pub(crate) fn from_config( + config: &TelemetryConfig, + connection: &ConnectionConfig, + auth: &AuthConfig, + system_configuration: Option, + session_id: String, + ) -> Self { + if !config.enabled || config.batch_size == 0 { + return Self::disabled(); + } + + let Some(exporter) = test_or_noop_exporter(config) else { + return Self::disabled(); + }; + + let session = Arc::new(TelemetrySessionContext { + session_id, + workspace_id: connection + .org_id + .as_deref() + .and_then(|org_id| org_id.parse::().ok()) + .unwrap_or_default(), + system_configuration: build_system_configuration(system_configuration), + connection_params: build_connection_params(connection, auth), + auth_type: auth_type(auth), + }); + let client = Arc::new(TelemetryClient::new( + exporter, + config.batch_size, + config.close_flush_timeout, + )); + + Self { + connection: Arc::new(RealConnectionTelemetry { + session, + client, + next_event_id: AtomicU64::new(1), + }), + } + } + + pub(crate) fn connection(&self) -> Arc { + Arc::clone(&self.connection) + } +} + +pub(crate) trait ConnectionTelemetry: Send + Sync { + fn session(&self) -> Option>; + + fn emit_operation( + &self, + operation_type: OperationType, + elapsed: Duration, + error: Option<&KernelError>, + ); + + fn flush<'a>(&'a self) -> Pin + Send + 'a>>; +} + +#[derive(Debug)] +pub(crate) struct TelemetrySessionContext { + pub session_id: String, + pub workspace_id: i64, + pub system_configuration: DriverSystemConfiguration, + pub connection_params: DriverConnectionParameters, + pub auth_type: String, +} + +#[derive(Debug)] +struct NoOpConnectionTelemetry; + +impl ConnectionTelemetry for NoOpConnectionTelemetry { + fn session(&self) -> Option> { + None + } + + fn emit_operation( + &self, + _operation_type: OperationType, + _elapsed: Duration, + _error: Option<&KernelError>, + ) { + } + + fn flush<'a>(&'a self) -> Pin + Send + 'a>> { + Box::pin(async {}) + } +} + +struct RealConnectionTelemetry { + session: Arc, + client: Arc, + next_event_id: AtomicU64, +} + +impl RealConnectionTelemetry { + fn build_operation_log( + &self, + operation_type: OperationType, + elapsed: Duration, + error: Option<&KernelError>, + ) -> TelemetryFrontendLog { + let event_id = self.next_event_id.fetch_add(1, Ordering::Relaxed); + TelemetryFrontendLog { + workspace_id: self.session.workspace_id, + frontend_log_event_id: format!("{}-{event_id}", self.session.session_id), + context: Some(FrontendLogContext { + client_context: Some(TelemetryClientContext { + user_agent: Some(format!( + "{}/{}", + env!("CARGO_PKG_NAME"), + env!("CARGO_PKG_VERSION") + )), + }), + timestamp_millis: unix_time_millis(), + }), + entry: Some(FrontendLogEntry { + sql_driver_log: Some(OssSqlDriverTelemetryLog { + session_id: Some(self.session.session_id.clone()), + system_configuration: Some(self.session.system_configuration.clone()), + driver_connection_params: Some(self.session.connection_params.clone()), + auth_type: Some(self.session.auth_type.clone()), + sql_operation: Some(SqlExecutionEvent { + operation_detail: Some(OperationDetail { + operation_type: Some(operation_type), + is_internal_call: Some(false), + ..Default::default() + }), + ..Default::default() + }), + error_info: error.map(sanitize_error), + operation_latency_ms: Some(duration_millis(elapsed)), + ..Default::default() + }), + }), + } + } +} + +impl ConnectionTelemetry for RealConnectionTelemetry { + fn session(&self) -> Option> { + Some(Arc::clone(&self.session)) + } + + fn emit_operation( + &self, + operation_type: OperationType, + elapsed: Duration, + error: Option<&KernelError>, + ) { + self.client + .enqueue(self.build_operation_log(operation_type, elapsed, error)); + } + + fn flush<'a>(&'a self) -> Pin + Send + 'a>> { + Box::pin(async move { + self.client.flush_bounded().await; + }) + } +} + +fn test_or_noop_exporter(config: &TelemetryConfig) -> Option> { + #[cfg(test)] + { + config.exporter.clone() + } + + #[cfg(not(test))] + { + let _ = config; + None + } +} + +fn build_system_configuration( + override_config: Option, +) -> DriverSystemConfiguration { + let defaults = DriverSystemConfiguration { + driver_version: Some(env!("CARGO_PKG_VERSION").to_string()), + runtime_name: Some("rust".to_string()), + runtime_version: option_env!("RUSTC_VERSION").map(str::to_string), + runtime_vendor: Some("rust-lang".to_string()), + os_name: Some(std::env::consts::OS.to_string()), + os_version: None, + os_arch: Some(std::env::consts::ARCH.to_string()), + driver_name: Some("Databricks SQL Kernel".to_string()), + client_app_name: None, + locale_name: std::env::var("LANG").ok().filter(|s| !s.is_empty()), + char_set_encoding: Some("UTF-8".to_string()), + process_name: std::env::args().next(), + }; + + merge_system_configuration(defaults, override_config) +} + +fn merge_system_configuration( + defaults: DriverSystemConfiguration, + override_config: Option, +) -> DriverSystemConfiguration { + let Some(override_config) = override_config else { + return defaults; + }; + + DriverSystemConfiguration { + driver_version: override_config.driver_version.or(defaults.driver_version), + runtime_name: override_config.runtime_name.or(defaults.runtime_name), + runtime_version: override_config.runtime_version.or(defaults.runtime_version), + runtime_vendor: override_config.runtime_vendor.or(defaults.runtime_vendor), + os_name: override_config.os_name.or(defaults.os_name), + os_version: override_config.os_version.or(defaults.os_version), + os_arch: override_config.os_arch.or(defaults.os_arch), + driver_name: override_config.driver_name.or(defaults.driver_name), + client_app_name: override_config.client_app_name.or(defaults.client_app_name), + locale_name: override_config.locale_name.or(defaults.locale_name), + char_set_encoding: override_config + .char_set_encoding + .or(defaults.char_set_encoding), + process_name: override_config.process_name.or(defaults.process_name), + } +} + +fn build_connection_params( + connection: &ConnectionConfig, + auth: &AuthConfig, +) -> DriverConnectionParameters { + DriverConnectionParameters { + http_path: Some(format!("/sql/1.0/warehouses/{}", connection.warehouse_id)), + mode: Some(DriverMode::Sea), + host_info: Some(HostDetails { + host_url: Some(connection.host.clone()), + port: None, + proxy_auth_type: None, + }), + auth_mech: Some(auth_mech(auth)), + auth_flow: auth_flow(auth), + enable_arrow: Some(true), + enable_direct_results: Some(true), + auto_commit: Some(true), + ..Default::default() + } +} + +fn auth_type(auth: &AuthConfig) -> String { + match auth { + AuthConfig::Pat { .. } => "pat", + AuthConfig::OAuthM2M { .. } => "oauth-m2m", + AuthConfig::OAuthU2M { .. } => "oauth-u2m", + AuthConfig::OAuthFederation { .. } => "oauth-federation", + AuthConfig::External(_) => "external", + } + .to_string() +} + +fn auth_mech(auth: &AuthConfig) -> DriverAuthMech { + match auth { + AuthConfig::Pat { .. } => DriverAuthMech::Pat, + AuthConfig::OAuthM2M { .. } + | AuthConfig::OAuthU2M { .. } + | AuthConfig::OAuthFederation { .. } => DriverAuthMech::Oauth, + AuthConfig::External(_) => DriverAuthMech::Other, + } +} + +fn auth_flow(auth: &AuthConfig) -> Option { + match auth { + AuthConfig::Pat { .. } => Some(DriverAuthFlow::TokenPassthrough), + AuthConfig::OAuthM2M { .. } => Some(DriverAuthFlow::ClientCredentials), + AuthConfig::OAuthU2M { .. } => Some(DriverAuthFlow::BrowserBasedAuthentication), + AuthConfig::OAuthFederation { .. } | AuthConfig::External(_) => None, + } +} + +fn sanitize_error(error: &KernelError) -> DriverErrorInfo { + DriverErrorInfo { + error_name: Some(error.code.slug().to_string()), + stack_trace: error.sql_state.clone(), + } +} + +fn duration_millis(duration: Duration) -> i64 { + duration.as_millis().min(i64::MAX as u128) as i64 +}