diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 95f5e23d..11a82936 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -636,7 +636,9 @@ dependencies = [ "adbc_ffi", "arrow-array", "arrow-buffer", + "arrow-ipc", "arrow-schema", + "base64 0.22.1", "databricks-sql-kernel", "serde_json", "tokio", diff --git a/adbc/Cargo.toml b/adbc/Cargo.toml index 69380384..8f88645e 100644 --- a/adbc/Cargo.toml +++ b/adbc/Cargo.toml @@ -37,6 +37,8 @@ serde_json = "1" tokio = { version = "1", features = ["rt-multi-thread"] } [dev-dependencies] +arrow-ipc = "59" +base64 = "0.22" adbc_driver_manager = "0.24" wiremock = "0.6" diff --git a/adbc/README.md b/adbc/README.md index de153783..882b415c 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -73,6 +73,21 @@ optional C interface and native Rust asynchronous submission and polling. Transactions, partitioned execution, statistics, and progress reporting are not currently implemented. +## Volume file operations + +Set `adbc.databricks.statement.staging_allowed_local_paths` to a JSON array of +local directories to run the file transfer for Volume `PUT`, `GET` and `REMOVE` +before results are returned. The result rows stay readable. Without the option +no file moves and the result is only the server's instruction row. +`execute_update` returns no rows, so without the option it fails with +`InvalidState` for a Volume statement. +The option remains enabled for the statement until set to JSON `null`; an empty +array still permits REMOVE while denying file PUT and GET. REMOVE of a missing object succeeds. Input-stream PUT is unsupported. +The client timeout ends at the terminal SQL status and does not bound Volume transfers. +`SocketTimeout` (milliseconds) also sets the idle limit for Volume transfers (15 minutes when unset; `0` disables it); +`adbc.databricks.http_request_timeout` sets only the SQL request deadline. +See the kernel [Volume file operations](../README.md#volume-file-operations). + ## Compatibility and status The current implementation targets Rust 1.89+, Rust edition 2021, ADBC 1.1, diff --git a/adbc/src/config.rs b/adbc/src/config.rs index 65b42e9e..ca15f31e 100644 --- a/adbc/src/config.rs +++ b/adbc/src/config.rs @@ -386,7 +386,11 @@ impl DatabaseConfig { "adbc.databricks.http_request_timeout" => { self.http.request_timeout = duration_seconds(value, key)? } - "SocketTimeout" => self.http.request_timeout = duration(value, key, false)?, + "SocketTimeout" => { + let timeout = duration(value, key, false)?; + self.http.request_timeout = timeout; + self.http.storage_read_timeout = Some(timeout); + } _ if key.starts_with(HTTP_PREFIX) => self.set_http(key, value)?, _ if key.starts_with(PROXY_PREFIX) => self.set_proxy(key, value)?, _ if key.starts_with(TLS_PREFIX) => self.set_tls(key, value)?, @@ -1695,6 +1699,7 @@ mod tests { #[test] fn http_pool_and_custom_headers_reach_kernel_config() { let mut config = DatabaseConfig::default(); + set(&mut config, "SocketTimeout", 4500_i64); set(&mut config, HOST, "https://example.databricks.com"); set(&mut config, HTTP_PATH, "/sql/1.0/warehouses/warehouse-id"); set(&mut config, ACCESS_TOKEN, "sentinel-token"); @@ -1712,6 +1717,10 @@ mod tests { let resolved = config.resolve().unwrap(); assert_eq!(resolved.http.pool_max_idle_per_host, 37); + assert_eq!( + resolved.http.storage_read_timeout, + Some(Duration::from_millis(4500)) + ); assert_eq!( resolved.user_agent_entry.as_deref(), Some("partner+product") diff --git a/adbc/src/error.rs b/adbc/src/error.rs index 54cbe4a9..c8a84533 100644 --- a/adbc/src/error.rs +++ b/adbc/src/error.rs @@ -60,6 +60,20 @@ pub(crate) fn map_kernel_error(source: kernel::Error) -> Error { mapped.details = source .error_code .map(|code| vec![("databricks.error_code".to_string(), code.into_bytes())]); + if let Some(local) = source.local_error { + let details = mapped.details.get_or_insert_default(); + details.push(( + "databricks.local_error_kind".into(), + format!("{:?}", local.kind).into_bytes(), + )); + details.push(("databricks.local_path".into(), local.path.into_bytes())); + if let Some(errno) = local.raw_os_error { + details.push(( + "databricks.local_os_error".into(), + errno.to_string().into_bytes(), + )); + } + } mapped } @@ -101,7 +115,12 @@ mod tests { kernel::Error::sql_error() .message("bad query") .with_sql_state("42000") - .with_vendor_code(42), + .with_vendor_code(42) + .with_local_error(kernel::LocalFileError::new( + Some(2), + std::io::ErrorKind::NotFound, + "/allowed/missing", + )), ); assert_eq!(mapped.status, Status::InvalidData); assert_eq!(mapped.vendor_code, 42); @@ -109,6 +128,10 @@ mod tests { mapped.sqlstate, (*b"42000").map(|byte| byte as std::ffi::c_char) ); + assert!(mapped + .details + .unwrap() + .contains(&("databricks.local_path".into(), b"/allowed/missing".to_vec()))); } #[test] diff --git a/adbc/src/reader.rs b/adbc/src/reader.rs index d4288904..f6930d22 100644 --- a/adbc/src/reader.rs +++ b/adbc/src/reader.rs @@ -461,6 +461,7 @@ pub(crate) struct SequenceReader { base_spec: kernel::StatementSpec, parameter_style: ParameterStyle, client_timeout: Option, + volume_options: Option, rows: BoundRows, current: Option, schema: SchemaRef, @@ -476,6 +477,7 @@ impl SequenceReader { base_spec: kernel::StatementSpec, parameter_style: ParameterStyle, client_timeout: Option, + volume_options: Option, rows: BoundRows, executed: kernel::ExecutedStatement, connection_operation: OperationGuard, @@ -489,6 +491,7 @@ impl SequenceReader { base_spec, parameter_style, client_timeout, + volume_options, rows, current: Some(executed), schema, @@ -582,6 +585,7 @@ impl Iterator for SequenceReader { &row, self.parameter_style, self.client_timeout, + self.volume_options.as_ref(), ) { Ok(executed) => executed, Err(source) => return self.fail(ArrowError::ExternalError(Box::new(source))), diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs index 1a6b5899..d4f60a53 100644 --- a/adbc/src/statement.rs +++ b/adbc/src/statement.rs @@ -32,6 +32,7 @@ use crate::error::{adbc_error, map_kernel_error, option_not_found, unsupported}; use crate::reader::{AsyncKernelReader, BoundRows, KernelReader, SequenceReader, SlicingReader}; use crate::runtime::{RuntimeExt as _, RuntimeHandle}; +const STAGING_ALLOWED_PATHS_OPTION: &str = "adbc.databricks.statement.staging_allowed_local_paths"; const PARAMETER_STYLE_OPTION: &str = "adbc.databricks.statement.parameter_style"; const QUERY_TAGS_OPTION: &str = "adbc.databricks.statement.query_tags"; const CLIENT_TIMEOUT_OPTION: &str = "adbc.databricks.statement.client_timeout_ms"; @@ -84,6 +85,7 @@ pub struct Statement { cancellation_notify: Arc, connection_cancellation: Arc, metadata_options: MetadataCommandOptions, + volume_options: Option, } #[derive(Debug, Default)] @@ -161,11 +163,16 @@ impl SubmittedStatement<'_> { .executed .take() .ok_or_else(|| adbc_error("submitted statement was consumed", Status::InvalidState))?; - let stream = self + let mut stream = self .statement .runtime .block_on_safe(executed.await_result()) .map_err(map_kernel_error)?; + complete_volume( + &self.statement.runtime, + &mut stream, + self.statement.volume_options.as_ref(), + )?; let reader: Box = Box::new(AsyncKernelReader::new( Arc::clone(&self.statement.runtime), executed, @@ -188,11 +195,16 @@ impl SubmittedStatement<'_> { .executed .take() .ok_or_else(|| adbc_error("submitted statement was consumed", Status::InvalidState))?; - let stream = self + let mut stream = self .statement .runtime .block_on_safe(executed.fetch_result()) .map_err(map_kernel_error)?; + complete_volume( + &self.statement.runtime, + &mut stream, + self.statement.volume_options.as_ref(), + )?; let reader: Box = Box::new(AsyncKernelReader::new( Arc::clone(&self.statement.runtime), executed, @@ -234,6 +246,7 @@ pub struct StatementCancellationHandle { impl StatementCancellationHandle { pub fn cancel(&self) -> Result<()> { + self.canceller.cancel_volume_operation(); if self.current_cancellation.load(Ordering::Acquire) { return Ok(()); } @@ -335,6 +348,7 @@ impl Statement { canceller, runtime, binding: None, + volume_options: None, parameter_style: ParameterStyle::default(), prepared: false, client_timeout: None, @@ -392,10 +406,17 @@ impl Statement { )), }; self.blocking_execute.store(false, Ordering::Release); - match result { - Some(result) => result.map_err(map_kernel_error), - None => Err(adbc_error("operation was cancelled", Status::Cancelled)), - } + drop(inner); + let mut executed = match result { + Some(result) => result.map_err(map_kernel_error)?, + None => return Err(adbc_error("operation was cancelled", Status::Cancelled)), + }; + complete_volume( + &self.runtime, + executed.result_stream_mut(), + self.volume_options.as_ref(), + )?; + Ok(executed) } fn execute_async_inner( @@ -444,7 +465,9 @@ impl Statement { None => Err(adbc_error("operation was cancelled", Status::Cancelled)), }; self.blocking_execute.store(false, Ordering::Release); - result + let (executed, mut stream) = result?; + complete_volume(&self.runtime, &mut stream, self.volume_options.as_ref())?; + Ok((executed, stream)) } fn invalidate_results(&self) { @@ -470,6 +493,19 @@ impl Statement { return Ok(()); } match key { + STAGING_ALLOWED_PATHS_OPTION => { + let text = expect_string(value, key)?; + let roots: Option> = serde_json::from_str(&text).map_err(|_| { + adbc_error( + format!("{key} expects a JSON array of strings or null"), + Status::InvalidArguments, + ) + })?; + self.volume_options = roots.map(|roots| { + kernel::VolumeOptions::new(roots.into_iter().map(Into::into).collect(), true) + }); + Ok(()) + } ENABLE_DIRECT_RESULTS_OPTION => { self.enable_direct_results = expect_bool_string(value, key)?; Ok(()) @@ -584,6 +620,14 @@ impl Statement { fn get_other_string(&self, key: &str) -> Result { match key { + STAGING_ALLOWED_PATHS_OPTION => self + .volume_options + .as_ref() + .map(|options| { + serde_json::to_string(&options.allowed_paths) + .expect("paths serialize as strings") + }) + .ok_or_else(|| option_not_found("statement string", key)), ENABLE_DIRECT_RESULTS_OPTION => Ok(self.enable_direct_results.to_string()), IS_METADATA_COMMAND_OPTION => Ok(self.metadata_options.enabled.to_string()), METADATA_CATALOG_OPTION => metadata_string_option( @@ -825,6 +869,7 @@ impl adbc_core::Statement for Statement { &row, self.parameter_style, self.client_timeout, + self.volume_options.as_ref(), )?; let expected_generation = self.generation.load(Ordering::Acquire); let reader: Box = Box::new(SequenceReader::new( @@ -835,6 +880,7 @@ impl adbc_core::Statement for Statement { base_spec, self.parameter_style, self.client_timeout, + self.volume_options.clone(), rows, executed, connection_operation, @@ -851,6 +897,7 @@ impl adbc_core::Statement for Statement { let Some(binding) = self.binding.take() else { if !self.enable_direct_results { let (executed, stream) = self.execute_async_inner()?; + require_staging_option(stream.is_volume_operation(), self.volume_options.as_ref())?; let count = executed.num_modified_rows(); drop(stream); self.runtime @@ -859,6 +906,10 @@ impl adbc_core::Statement for Statement { return Ok(count); } let executed = self.execute_inner()?; + require_staging_option( + executed.result_stream().is_volume_operation(), + self.volume_options.as_ref(), + )?; let count = executed.num_modified_rows(); self.runtime .block_on_safe(executed.close()) @@ -888,7 +939,15 @@ impl adbc_core::Statement for Statement { &row, self.parameter_style, self.client_timeout, - ) { + self.volume_options.as_ref(), + ) + .and_then(|executed| { + require_staging_option( + executed.result_stream().is_volume_operation(), + self.volume_options.as_ref(), + )?; + Ok(executed) + }) { Ok(executed) => executed, Err(mut error) => { row_index += 1; @@ -1123,6 +1182,7 @@ pub(crate) fn execute_bound_row( row: &RecordBatch, style: ParameterStyle, client_timeout: Option, + volume_options: Option<&kernel::VolumeOptions>, ) -> Result { let parameters = convert_binding(row, style)?; let mut inner = inner @@ -1164,11 +1224,47 @@ pub(crate) fn execute_bound_row( .spec() .param_raw(parameter.name, parameter.param_type, parameter.value); } - match client_timeout { + let mut executed = match client_timeout { Some(timeout) => runtime.block_on_safe(inner.execute_with_timeout(timeout)), None => runtime.block_on_safe(inner.execute()), } - .map_err(map_kernel_error) + .map_err(map_kernel_error)?; + drop(inner); + complete_volume(runtime, executed.result_stream_mut(), volume_options)?; + Ok(executed) +} + +/// `execute_update` returns no rows, so an uncompleted Volume statement would read as success. +fn require_staging_option(marked: bool, options: Option<&kernel::VolumeOptions>) -> Result<()> { + if marked && options.is_none() { + return Err(adbc_error( + format!( + "execute_update on a Volume PUT, GET or REMOVE requires the \ + {STAGING_ALLOWED_PATHS_OPTION} option; [] is enough for REMOVE" + ), + Status::InvalidState, + )); + } + Ok(()) +} + +fn complete_volume( + runtime: &RuntimeHandle, + stream: &mut kernel::ResultStream, + options: Option<&kernel::VolumeOptions>, +) -> Result<()> { + let Some(options) = options else { + return Ok(()); + }; + match runtime + .block_on_safe(stream.complete_volume_operation(options, None)) + .map_err(map_kernel_error)? + { + kernel::VolumeCompletion::NeedsInputStream => { + Err(unsupported("Volume PUT with input streams")) + } + kernel::VolumeCompletion::Completed | kernel::VolumeCompletion::NotVolume => Ok(()), + } } #[derive(Clone, Copy, PartialEq, Eq)] @@ -1459,8 +1555,213 @@ fn parse_client_timeout_option(key: &str, value: OptionValue) -> Option>()}}, + "result":{"chunk_index":0,"row_offset":0,"row_count":1,"attachment":STANDARD.encode(&ipc)} + }); + runtime.block_on_safe(async { + for verb in ["POST", "GET"] { + Mock::given(method(verb)) + .and(path(if verb == "POST" { + "/api/2.0/sql/statements" + } else { + "/api/2.0/sql/statements/volume" + })) + .respond_with(ResponseTemplate::new(200).set_body_json(response.clone())) + .mount(&server) + .await; + } + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/wh/sessions")) + .respond_with( + ResponseTemplate::new(200).set_body_json(json!({"session_id":"session"})), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(404)) + .with_priority(1) + .expect(7) + .mount(&server) + .await; + }); + let session = runtime + .block_on_safe( + kernel::Session::builder() + .http_path(server.uri(), "/sql/1.0/warehouses/wh") + .auth(kernel::AuthConfig::Pat { + token: "test-token".into(), + identity_federation_client_id: None, + }) + .open(), + ) + .unwrap(); + let mut statement = Statement::new( + session.statement(), + session.metadata(), + Arc::clone(&runtime), + Arc::new(CancellationRegistry::default()), + false, + ); + let key = OptionStatement::Other(STAGING_ALLOWED_PATHS_OPTION.into()); + assert_eq!( + statement.get_option_string(key.clone()).unwrap_err().status, + Status::NotFound + ); + for value in [OptionValue::Int(1), OptionValue::String("[1]".into())] { + assert_eq!( + statement.set_option(key.clone(), value).unwrap_err().status, + Status::InvalidArguments + ); + } + statement.set_option(key.clone(), "[]".into()).unwrap(); + statement.set_sql_query("SELECT 1").unwrap(); + assert_eq!(statement.get_option_string(key.clone()).unwrap(), "[]"); + statement.set_option(key.clone(), "null".into()).unwrap(); + assert_eq!( + statement.get_option_string(key.clone()).unwrap_err().status, + Status::NotFound + ); + statement.set_option(key.clone(), "[]".into()).unwrap(); + let mut transfers = 0; + for mode in ["raw", "sync", "async", "await", "fetch", "bound", "update"] { + let mut statement = Statement::new( + session.statement(), + session.metadata(), + Arc::clone(&runtime), + Arc::new(CancellationRegistry::default()), + false, + ); + statement.set_sql_query("operation ?, ?").unwrap(); + if mode != "raw" { + statement.set_option(key.clone(), "[]".into()).unwrap(); + } + if mode == "async" { + statement + .set_option( + OptionStatement::Other(ENABLE_DIRECT_RESULTS_OPTION.into()), + "false".into(), + ) + .unwrap(); + } + if mode == "bound" { + statement.bind(batch(2)).unwrap(); + } + let reader = match mode { + "await" => statement.submit().unwrap().await_result().unwrap(), + "fetch" => statement.submit().unwrap().fetch_result().unwrap(), + "update" => { + assert_eq!(statement.execute_update().unwrap(), None); + transfers += 1; + continue; + } + _ => statement.execute().unwrap(), + }; + let batches = reader.collect::, _>>().unwrap(); + assert_eq!(batches.len(), if mode == "bound" { 2 } else { 1 }, "{mode}"); + for batch in batches { + assert_eq!( + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + "REMOVE" + ); + } + transfers += match mode { + "raw" => 0, + "bound" => 2, + _ => 1, + }; + assert_eq!( + runtime + .block_on_safe(server.received_requests()) + .unwrap() + .iter() + .filter(|request| request.url.path() == "/object") + .count(), + transfers, + "{mode}" + ); + } + for path in ["direct", "async", "bound"] { + let mut statement = Statement::new( + session.statement(), + session.metadata(), + Arc::clone(&runtime), + Arc::new(CancellationRegistry::default()), + false, + ); + statement.set_sql_query("operation ?, ?").unwrap(); + if path == "async" { + statement + .set_option( + OptionStatement::Other(ENABLE_DIRECT_RESULTS_OPTION.into()), + "false".into(), + ) + .unwrap(); + } + if path == "bound" { + statement.bind(batch(2)).unwrap(); + } + let error = statement.execute_update().unwrap_err(); + assert_eq!(error.status, Status::InvalidState, "{path}"); + assert!( + error.message.contains(STAGING_ALLOWED_PATHS_OPTION), + "{path}" + ); + } + assert_eq!(transfers, 7); + runtime.block_on_safe(session.close()).unwrap(); + } fn batch(rows: usize) -> RecordBatch { let schema = Arc::new(Schema::new(vec![ diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 7633698c..4b597d3b 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -54,8 +54,9 @@ * `KernelStatusCode_InvalidStatementHandle`. Don't hold two live * executed handles from one statement. * - **A result stream borrows its executed handle.** Closing the executed - * handle invalidates any stream obtained from it: subsequent stream - * calls return `InvalidStatementHandle` (a defined error, not UB). + * handle invalidates any stream obtained from it: schema access, fetching + * and Volume completion return `InvalidStatementHandle` (a defined error, + * not UB). * - **Close is awaited.** `kernel_session_close` waits for the server-side * delete to complete and flushes close-session telemetry before returning. * If close fails, the kernel still schedules best-effort cleanup when the @@ -190,6 +191,11 @@ typedef struct KernelError { * last kernel call cleared the buffer. */ bool kernel_get_last_error(KernelError* out); +/* These accessors preserve the last error. Strings are borrowed until the next + * error-clearing kernel call; absent strings are NULL, absent OS code is zero. */ +int32_t kernel_get_last_error_local_os_error(void); +const char* kernel_get_last_error_code(void); +const char* kernel_get_last_error_local_path(void); /* ─── Opaque handles ────────────────────────────────────────────────── * @@ -219,12 +225,12 @@ typedef struct kernel_statement_canceller_t kernel_statement_canceller_t; /* Detached canceller for a result stream, returned by * kernel_result_stream_canceller_new. Firing it interrupts an in-flight * kernel_result_stream_next_batch so it returns KernelStatusCode_Cancelled - * promptly instead of blocking until the (possibly slow / CloudFetch-link) - * batch fetch finishes. Unlike the statement canceller it holds ONLY a shared - * client-side cancellation token (no server RPC, no borrow of the stream's - * mutable state), so — see its doc — it is safe to obtain and to fire - * concurrently with a next_batch/close on the owning thread. Once fired, the - * stream is permanently aborted (every later next_batch returns Cancelled). */ + * promptly instead of waiting for the batch fetch to finish. It also stops a + * running Volume file transfer. Unlike the statement canceller it makes no + * server RPC and borrows no mutable stream state, so — see its doc — it is + * safe to obtain and fire concurrently with a next_batch/close on the owning + * thread. Once fired, the stream is permanently aborted (every later next_batch + * returns Cancelled). */ typedef struct kernel_result_stream_canceller_t kernel_result_stream_canceller_t; /* ─── Session config ────────────────────────────────────────────────── @@ -369,10 +375,16 @@ KernelStatusCode kernel_session_config_set_sea_response_compression_enabled( /* Configure the total timeout for one HTTP request, from connection start * through response-body completion. A separate 30s connection timeout also * applies, so connection establishment is bounded by the shorter limit. + * Does not apply to Volume file transfers; see the storage read timeout. * `request_timeout_ms == 0` keeps the kernel default (120s). */ KernelStatusCode kernel_session_config_set_request_timeout(KernelSessionConfig* config, uint64_t request_timeout_ms); +/* Idle limit for Volume file transfers: a transfer fails after this long without + * progress. Also caps connection setup. Omitted defaults to 15 minutes; zero sets no limit. */ +KernelStatusCode kernel_session_config_set_storage_read_timeout(KernelSessionConfig* config, + uint64_t timeout_ms); + /* Configure the maximum number of idle HTTP connections retained per host. * `max_connections` must be greater than zero. Omitting this setter keeps the * kernel default (100). */ @@ -979,6 +991,34 @@ KernelStatusCode kernel_executed_async_statement_close( */ KernelStatusCode kernel_result_stream_get_schema(kernel_result_stream_t* stream, struct ArrowSchema* out); +typedef enum KernelVolumeCompletion { + KernelVolumeCompletion_NotVolume = 0, + KernelVolumeCompletion_NeedsInputStream = 1, + KernelVolumeCompletion_Completed = 2 +} KernelVolumeCompletion; + +/* Whether the statement is a Volume PUT, GET or REMOVE. + * out is written only on success. */ +KernelStatusCode kernel_executed_statement_is_volume_operation( + const kernel_executed_statement_t* exec, bool* out); +/* Same flag, read from the stream. Still succeeds after the executed statement + * is closed. + * out is written only on success. */ +KernelStatusCode kernel_result_stream_is_volume_operation( + const kernel_result_stream_t* stream, bool* out); +/* Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before + * fetching; the rows stay readable afterwards. + * The outcome, success or failure, is cached, so a repeat call does not + * transfer again. + * allowed_paths_json: JSON array of local directories the transfer may use. + * remove_not_found_is_success: report success when the remote file is missing. + * Returns NeedsInputStream for a stream upload, which this API cannot perform. + * kernel_result_stream_canceller_cancel interrupts it from another thread. + * out_status is written only on success. */ +KernelStatusCode kernel_result_stream_complete_volume_operation( + kernel_result_stream_t* stream, const char* allowed_paths_json, + bool remove_not_found_is_success, KernelVolumeCompletion* out_status); + KernelStatusCode kernel_result_stream_next_batch(kernel_result_stream_t* stream, struct ArrowArray* out_array, struct ArrowSchema* out_schema); diff --git a/napi/Cargo.lock b/napi/Cargo.lock index f013d66b..2a9252fa 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -658,6 +658,7 @@ dependencies = [ "arrow-array", "arrow-ipc", "arrow-schema", + "base64", "chrono", "databricks-sql-kernel", "futures", diff --git a/napi/Cargo.toml b/napi/Cargo.toml index 78326e4d..a55dab43 100644 --- a/napi/Cargo.toml +++ b/napi/Cargo.toml @@ -129,6 +129,7 @@ serde_json = "1" chrono = { version = "0.4", default-features = false, features = ["clock"] } [dev-dependencies] +base64 = "0.22" wiremock = "0.6" [build-dependencies] diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 8597f31e..6b1eef17 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,12 +14,20 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added +- `Statement` and `AsyncResultHandle` gain `isVolumeOperation` and + `completeVolumeOperation` for Volume `PUT`, `GET` and `REMOVE`. Local file + errors carry `localOsError`, `localErrorKind` and `localPath`. + ### Changed ### Updated ### Fixed +- `AsyncStatement.close()` also releases a result stream that an in-flight + fetch holds, once that operation finishes; later fetches return + `InvalidStatementHandle`. `close()` still does not wait for it. + --- *Note: When making changes, please add your change under the appropriate section with a brief description. At release time, move the entries here diff --git a/napi/README.md b/napi/README.md index 91f28adf..bee4aa19 100644 --- a/napi/README.md +++ b/napi/README.md @@ -7,6 +7,13 @@ the umbrella loader that re-exports the per-platform native packages. The binding itself lives under `src/`; its public TypeScript surface is declared in `index.d.ts`. +`Statement` and `AsyncResultHandle` expose `isVolumeOperation` and +`completeVolumeOperation(allowedPaths, removeNotFoundIsSuccess)`, which runs +the file transfer for a Volume `PUT`, `GET` or `REMOVE`. It returns +`not_volume`, `needs_input_stream` or `completed`, and the result rows stay +readable. Local paths, and the files they resolve to through symlinks, must be +inside `allowedPaths`. The Node binding cannot upload from a stream. + --- ## Building diff --git a/napi/index.d.ts b/napi/index.d.ts index 064f856d..b0229ea2 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -603,15 +603,10 @@ export interface ConnectionOptions { */ proxy?: ProxyInput /** - * Per-connection socket read timeout, in milliseconds. Caps how - * long a single HTTP round-trip may block waiting on the server - * before the request errors out. Maps onto the kernel - * [`HttpConfig::request_timeout`] (the internal reqwest - * `Client::timeout`). - * - * Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs - * serialises `u32` as JS `number`; the largest representable value - * (~49.7 days) far exceeds any sensible socket timeout. + * Timeout for SQL HTTP requests, in milliseconds. A positive value also + * sets the idle limit for Volume file transfers. Omitted keeps the SQL + * default of 120 seconds and the Volume idle default of 15 minutes. + * Zero disables the Volume idle limit and keeps the SQL request default. */ socketTimeoutMs?: number } @@ -854,9 +849,8 @@ export declare class AsyncStatement { * re-attempting the wire call. The kernel's own `Drop` * fire-and-forget retry runs once in the background. * - * Also invalidates the handles `awaitResult()` returned: their - * `fetchNextBatch()` then rejects with `InvalidStatementHandle`, - * unless a fetch was in progress when `close()` ran. + * Also invalidates the handles `awaitResult()` returned. An operation + * already in flight may finish before its handle is cleared. */ close(): Promise } @@ -878,6 +872,14 @@ export declare class AsyncStatement { * post-close contract. */ export declare class AsyncResultHandle { + get isVolumeOperation(): boolean + /** + * Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before + * fetching; the rows stay readable afterwards. + * Keep the parent `AsyncStatement` alive until the transfer finishes; closing or + * collecting it stops the transfer. + */ + completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess: boolean): Promise /** * Server-issued statement id. Cached at construction; readable * for log correlation. Matches the parent `AsyncStatement`'s @@ -960,7 +962,8 @@ export declare class CancellableExecution { * 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. + * already in a terminal state. It still stops a Volume transfer in progress + * after `result()` has finished. */ cancel(): Promise } @@ -1172,6 +1175,12 @@ export declare class Connection { * disposed statement can still read them. */ export declare class Statement { + get isVolumeOperation(): boolean + /** + * Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before + * fetching; the rows stay readable afterwards. + */ + completeVolumeOperation(allowedPaths: Array, removeNotFoundIsSuccess: boolean): Promise /** * Server-issued statement id. Cached at construction; readable * even after `close()` so JS-side log lines can correlate against @@ -1294,3 +1303,9 @@ export declare class Statement { */ close(): Promise } + +export const enum VolumeCompletion { + NotVolume = 'not_volume', + NeedsInputStream = 'needs_input_stream', + Completed = 'completed' +} diff --git a/napi/index.js b/napi/index.js index ad50ecc9..104cb552 100644 --- a/napi/index.js +++ b/napi/index.js @@ -310,7 +310,7 @@ if (!nativeBinding) { throw new Error(`Failed to load native binding`) } -const { AsyncStatement, AsyncResultHandle, CancellableExecution, Connection, AuthMode, openSession, initKernelLogging, kernelLoggingStats, setKernelLogLevel, Statement, version } = nativeBinding +const { AsyncStatement, AsyncResultHandle, CancellableExecution, Connection, AuthMode, openSession, initKernelLogging, kernelLoggingStats, setKernelLogLevel, Statement, VolumeCompletion, version } = nativeBinding module.exports.AsyncStatement = AsyncStatement module.exports.AsyncResultHandle = AsyncResultHandle @@ -323,3 +323,4 @@ module.exports.kernelLoggingStats = kernelLoggingStats module.exports.setKernelLogLevel = setKernelLogLevel module.exports.Statement = Statement module.exports.version = version +module.exports.VolumeCompletion = VolumeCompletion diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs index df416254..073ec5ed 100644 --- a/napi/src/async_statement.rs +++ b/napi/src/async_statement.rs @@ -60,7 +60,7 @@ use tokio::sync::Mutex; use arrow_schema::SchemaRef; use databricks_sql_kernel::{ AsyncStatementCanceller, Error as KernelError, ExecutedAsyncStatement, ExecutedStatementHandle, - ResultBatch, ResultStream, Statement as KernelStatement, + ResultBatch, ResultStream, Statement as KernelStatement, VolumeOptions, }; use crate::error::napi_err_from_kernel; @@ -320,6 +320,7 @@ impl AsyncStatement { .map_err(napi_err_from_kernel)?; let statement_id = inner_state.executed_async.statement_id().to_owned(); let schema = stream.schema(); + let is_volume_operation = stream.is_volume_operation(); let stream = Arc::new(Mutex::new(Some(stream))); // Registered while `inner` is held, so a queued `close()` sees it. results @@ -330,6 +331,7 @@ impl AsyncStatement { inner: stream, schema, statement_id, + is_volume_operation, }) }) .await @@ -374,11 +376,18 @@ impl AsyncStatement { /// re-attempting the wire call. The kernel's own `Drop` /// fire-and-forget retry runs once in the background. /// - /// Also invalidates the handles `awaitResult()` returned: their - /// `fetchNextBatch()` then rejects with `InvalidStatementHandle`, - /// unless a fetch was in progress when `close()` ran. + /// Also invalidates the handles `awaitResult()` returned. An operation + /// already in flight may finish before its handle is cleared. #[napi] pub async fn close(&self) -> napi::Result<()> { + if let Some(canceller) = self + .canceller + .lock() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + { + canceller.cancel_volume_operation(); + } let inner = Arc::clone(&self.inner); let closed = Arc::clone(&self.closed); let canceller = Arc::clone(&self.canceller); @@ -400,7 +409,8 @@ impl AsyncStatement { .map_err(napi_err_from_kernel); // Release what holds the session, so JS references to closed // handles don't keep it (and the host's telemetry client) alive. - // A stream held by an in-flight fetch is left; close doesn't wait. + // A slot in use is cleared in the background, so close() does not wait + // for the running call. canceller .lock() .unwrap_or_else(PoisonError::into_inner) @@ -410,6 +420,11 @@ impl AsyncStatement { for slot in slots.iter().filter_map(Weak::upgrade) { if let Ok(mut stream) = slot.try_lock() { stream.take(); + } else { + let slot = Arc::clone(&slot); + tokio::spawn(async move { + slot.lock().await.take(); + }); } } outcome @@ -420,6 +435,14 @@ impl AsyncStatement { impl Drop for AsyncStatement { fn drop(&mut self) { + if let Some(canceller) = self + .canceller + .lock() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + { + canceller.cancel_volume_operation(); + } // Best-effort cleanup — same shape as `Connection::Drop`. // JS callers needing a guaranteed close-with-error-surface // call `close()` explicitly. @@ -455,14 +478,48 @@ impl Drop for AsyncStatement { /// post-close contract. #[napi] pub struct AsyncResultHandle { - /// Emptied by the parent's `close()`, unless a fetch holds it then. + /// Emptied after parent close once any in-flight operation releases it. inner: Arc, schema: SchemaRef, statement_id: String, + is_volume_operation: bool, } #[napi] impl AsyncResultHandle { + #[napi(getter)] + pub fn is_volume_operation(&self) -> bool { + self.is_volume_operation + } + + /// Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before + /// fetching; the rows stay readable afterwards. + /// Keep the parent `AsyncStatement` alive until the transfer finishes; closing or + /// collecting it stops the transfer. + #[napi] + pub async fn complete_volume_operation( + &self, + allowed_paths: Vec, + remove_not_found_is_success: bool, + ) -> napi::Result { + let options = VolumeOptions::new( + allowed_paths.into_iter().map(Into::into).collect(), + remove_not_found_is_success, + ); + let inner = Arc::clone(&self.inner); + guarded(async move { + let mut guard = inner.lock().await; + guard + .as_mut() + .ok_or_else(|| closed_err("AsyncResultHandle"))? + .complete_volume_operation(&options, None) + .await + .map(crate::result::VolumeCompletion::from) + .map_err(napi_err_from_kernel) + }) + .await + } + /// Server-issued statement id. Cached at construction; readable /// for log correlation. Matches the parent `AsyncStatement`'s /// `statementId`. @@ -676,7 +733,7 @@ mod tests { /// their statements are closed, even while JS still references the closed /// handles. Otherwise the next session on the host reuses it and ignores /// its own telemetry settings. - async fn next_session_gets_its_own_telemetry_client(fetch_result: bool) { + async fn next_session_gets_its_own_telemetry_client(fetch_result: bool, sync_statement: bool) { let server = lease_server().await; // Batch size 1: this client exports every event at once. let first = telemetry_connection(&server, 1, Duration::from_millis(100)).await; @@ -690,6 +747,16 @@ mod tests { None }; statement.close().await.expect("close statement"); + let sync_statement = if sync_statement { + let statement = first + .execute_statement("SELECT 1 AS n".into(), None) + .await + .expect("execute"); + statement.close().await.expect("close sync statement"); + Some(statement) + } else { + None + }; first.close().await.expect("close first session"); let second = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; @@ -714,29 +781,30 @@ mod tests { assert!(err.reason.contains("AsyncResultHandle already closed")); } // Dropped only now, as JS GC would. - drop((statement, result)); + drop((statement, result, sync_statement)); } #[tokio::test] async fn close_releases_session_held_by_canceller() { - next_session_gets_its_own_telemetry_client(false).await; + next_session_gets_its_own_telemetry_client(false, false).await; + next_session_gets_its_own_telemetry_client(false, true).await; } #[tokio::test] async fn close_releases_session_held_by_result_handles() { - next_session_gets_its_own_telemetry_client(true).await; + next_session_gets_its_own_telemetry_client(true, false).await; } #[tokio::test] - async fn close_does_not_wait_for_an_in_flight_fetch() { + async fn close_releases_session_after_an_in_flight_result() { let server = lease_server().await; - let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + let connection = telemetry_connection(&server, 1, Duration::from_millis(100)).await; let statement = connection .submit_statement("SELECT 1 AS n".into(), None) .await .expect("submit"); let result = statement.await_result().await.expect("await result"); - // Hold the stream the way an in-flight `fetchNextBatch()` does. + // Both fetching and Volume completion hold the result slot throughout I/O. let in_flight = result.inner.lock().await; tokio::time::timeout(Duration::from_secs(5), statement.close()) .await @@ -744,6 +812,18 @@ mod tests { .expect("close statement"); drop(in_flight); connection.close().await.expect("close session"); + tokio::time::timeout(Duration::from_secs(5), async { + while result.inner.lock().await.is_some() { + tokio::task::yield_now().await; + } + }) + .await + .expect("closed result must release its session after the operation finishes"); + + let second = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + second.close().await.expect("close second session"); + assert!(exports_for(&server, SECOND_SESSION).await > 0); + drop((statement, result)); } #[tokio::test] @@ -758,7 +838,7 @@ mod tests { .with_priority(1) .mount(&server) .await; - let connection = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + let connection = telemetry_connection(&server, 1, Duration::from_millis(100)).await; let statement = connection .submit_statement("SELECT 1 AS n".into(), None) .await @@ -770,6 +850,18 @@ mod tests { .expect_err("the close RPC must fail"); assert!(statement.canceller.lock().unwrap().is_none()); assert!(result.inner.lock().await.is_none()); + let sync_statement = connection + .execute_statement("SELECT 1 AS n".into(), None) + .await + .expect("execute"); + sync_statement + .close() + .await + .expect_err("the close RPC must fail"); + sync_statement.close().await.expect("close is terminal"); connection.close().await.expect("close session"); + let second = telemetry_connection(&server, 1_000, Duration::from_secs(300)).await; + second.close().await.expect("close second session"); + drop(sync_statement); } } diff --git a/napi/src/cancellable.rs b/napi/src/cancellable.rs index bc445019..d2695f55 100644 --- a/napi/src/cancellable.rs +++ b/napi/src/cancellable.rs @@ -219,9 +219,11 @@ impl CancellableExecution { /// 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. + /// already in a terminal state. It still stops a Volume transfer in progress + /// after `result()` has finished. #[napi] pub async fn cancel(&self) -> napi::Result<()> { + self.canceller.cancel_volume_operation(); // Skip the server-side cancel RPC once the statement is terminal (success // OR error) — it would be a redundant no-op-at-server call + confusing log. if self.terminal.load(Ordering::Acquire) { diff --git a/napi/src/database.rs b/napi/src/database.rs index 4a8fbe3f..4dcac2ac 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -453,15 +453,10 @@ pub struct ConnectionOptions { /// server) can now route a single connection through a proxy /// programmatically. pub proxy: Option, - /// Per-connection socket read timeout, in milliseconds. Caps how - /// long a single HTTP round-trip may block waiting on the server - /// before the request errors out. Maps onto the kernel - /// [`HttpConfig::request_timeout`] (the internal reqwest - /// `Client::timeout`). - /// - /// Omitted ⇒ kernel default (120 000 ms / 120 s). Napi-rs - /// serialises `u32` as JS `number`; the largest representable value - /// (~49.7 days) far exceeds any sensible socket timeout. + /// Timeout for SQL HTTP requests, in milliseconds. A positive value also + /// sets the idle limit for Volume file transfers. Omitted keeps the SQL + /// default of 120 seconds and the Volume idle default of 15 minutes. + /// Zero disables the Volume idle limit and keeps the SQL request default. pub socket_timeout_ms: Option, } @@ -657,7 +652,13 @@ fn build_http_config(options: &mut ConnectionOptions) -> HttpConfig { // `request_timeout` (the reqwest `Client::timeout`). Omitted ⇒ kernel // default (120 s). if let Some(ms) = options.socket_timeout_ms { - http.request_timeout = std::time::Duration::from_millis(u64::from(ms)); + if ms == 0 { + http.storage_read_timeout = None; + } else { + let timeout = std::time::Duration::from_millis(u64::from(ms)); + http.request_timeout = timeout; + http.storage_read_timeout = Some(timeout); + } } http } @@ -1536,6 +1537,30 @@ mod tests { } } + #[test] + fn socket_timeout_sets_sql_and_storage_limits() { + use std::time::Duration; + for (value, sql, storage) in [ + ( + None, + Duration::from_secs(120), + Some(Duration::from_secs(900)), + ), + (Some(0), Duration::from_secs(120), None), + ( + Some(1500), + Duration::from_millis(1500), + Some(Duration::from_millis(1500)), + ), + ] { + let mut options = base(); + options.socket_timeout_ms = value; + let http = build_http_config(&mut options); + assert_eq!(http.request_timeout, sql, "{value:?}"); + assert_eq!(http.storage_read_timeout, storage, "{value:?}"); + } + } + #[test] fn http_custom_headers_thread_through_in_order() { let mut o = base(); diff --git a/napi/src/error.rs b/napi/src/error.rs index 70518fe3..7f4b9f95 100644 --- a/napi/src/error.rs +++ b/napi/src/error.rs @@ -143,6 +143,16 @@ pub(crate) fn napi_err_from_kernel(e: KernelError) -> NapiError { if let Some(qid) = e.query_id { obj.insert("queryId".to_owned(), Value::from(qid)); } + if let Some(local) = e.local_error { + if let Some(errno) = local.raw_os_error { + obj.insert("localOsError".to_owned(), Value::from(errno)); + } + obj.insert( + "localErrorKind".to_owned(), + Value::from(format!("{:?}", local.kind)), + ); + obj.insert("localPath".to_owned(), Value::from(local.path)); + } // Thrift-parity extended status fields: surfaced on the napi // envelope so a JS caller's catch-block sees the same fields the // Thrift driver's `TGetOperationStatusResp` exposes. Only @@ -196,6 +206,24 @@ fn error_code_str(code: ErrorCode) -> &'static str { mod tests { use super::*; + #[test] + fn local_error_metadata_is_optional_and_preserved() { + let mut error = KernelError::not_found().message("missing local file"); + error.local_error = Some(Box::new(databricks_sql_kernel::LocalFileError::new( + Some(2), + std::io::ErrorKind::NotFound, + "local-file", + ))); + let encoded = napi_err_from_kernel(error); + let value: Value = serde_json::from_str(&encoded.reason[ERROR_SENTINEL.len()..]).unwrap(); + assert_eq!(value["localOsError"], 2); + assert_eq!(value["localErrorKind"], "NotFound"); + assert_eq!(value["localPath"], "local-file"); + let encoded = napi_err_from_kernel(KernelError::internal()); + let value: Value = serde_json::from_str(&encoded.reason[ERROR_SENTINEL.len()..]).unwrap(); + assert!(value.get("localErrorKind").is_none()); + } + #[test] fn envelope_carries_sentinel_and_code() { let e = KernelError::invalid_argument().message("hi"); diff --git a/napi/src/result.rs b/napi/src/result.rs index 2573bb84..80907046 100644 --- a/napi/src/result.rs +++ b/napi/src/result.rs @@ -94,6 +94,24 @@ pub(crate) fn encode_ipc_stream( Ok(buf) } +#[napi(string_enum = "snake_case")] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VolumeCompletion { + NotVolume, + NeedsInputStream, + Completed, +} + +impl From for VolumeCompletion { + fn from(value: databricks_sql_kernel::VolumeCompletion) -> Self { + match value { + databricks_sql_kernel::VolumeCompletion::NotVolume => Self::NotVolume, + databricks_sql_kernel::VolumeCompletion::NeedsInputStream => Self::NeedsInputStream, + databricks_sql_kernel::VolumeCompletion::Completed => Self::Completed, + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/napi/src/statement.rs b/napi/src/statement.rs index 40d682d2..0c314025 100644 --- a/napi/src/statement.rs +++ b/napi/src/statement.rs @@ -30,13 +30,13 @@ //! server logs which key on the same id. use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; +use std::sync::{Arc, Mutex as StdMutex, PoisonError}; use tokio::sync::Mutex; use arrow_schema::SchemaRef; use databricks_sql_kernel::{ Error as KernelError, ExecutedStatement, ExecutedStatementHandle, ResultBatch, ResultStream, - Statement as KernelStatement, + Statement as KernelStatement, StatementCanceller, VolumeOptions, }; use crate::error::napi_err_from_kernel; @@ -131,6 +131,8 @@ pub struct Statement { /// does not emit a statement id for SHOW/information_schema /// queries driven through `Metadata`). statement_id: String, + is_volume_operation: bool, + canceller: StdMutex>, /// Set to `true` when `fetchNextBatch` observes the natural end of /// the stream (`None`). `cancel()` short-circuits to `Ok(())` when /// this is set, matching the JDBC `Statement.cancel()` no-op-after- @@ -153,6 +155,8 @@ impl Statement { pub(crate) fn from_executed(parent: KernelStatement, executed: ExecutedStatement) -> Self { let schema = executed.schema(); let statement_id = executed.statement_id().to_owned(); + let is_volume_operation = executed.result_stream().is_volume_operation(); + let canceller = StdMutex::new(Some(parent.canceller())); Self { inner: Arc::new(Mutex::new(Some(AnyInner::Executed(Box::new( StatementInner { @@ -162,6 +166,8 @@ impl Statement { ))))), schema, statement_id, + is_volume_operation, + canceller, finished: Arc::new(AtomicBool::new(false)), } } @@ -182,6 +188,8 @@ impl Statement { inner: Arc::new(Mutex::new(Some(AnyInner::Metadata(stream)))), schema, statement_id: String::new(), + is_volume_operation: false, + canceller: StdMutex::new(None), finished: Arc::new(AtomicBool::new(false)), } } @@ -189,6 +197,39 @@ impl Statement { #[napi] impl Statement { + #[napi(getter)] + pub fn is_volume_operation(&self) -> bool { + self.is_volume_operation + } + + /// Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before + /// fetching; the rows stay readable afterwards. + #[napi] + pub async fn complete_volume_operation( + &self, + allowed_paths: Vec, + remove_not_found_is_success: bool, + ) -> napi::Result { + let options = VolumeOptions::new( + allowed_paths.into_iter().map(Into::into).collect(), + remove_not_found_is_success, + ); + let inner = Arc::clone(&self.inner); + guarded(async move { + let mut guard = inner.lock().await; + let stream = match guard.as_mut().ok_or_else(statement_closed_err)? { + AnyInner::Executed(s) => s.executed.result_stream_mut(), + AnyInner::Metadata(stream) => stream, + }; + stream + .complete_volume_operation(&options, None) + .await + .map(crate::result::VolumeCompletion::from) + .map_err(napi_err_from_kernel) + }) + .await + } + /// 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. @@ -418,6 +459,14 @@ impl Statement { /// has been explicitly `close()`d. #[napi] pub async fn cancel(&self) -> napi::Result<()> { + if let Some(canceller) = self + .canceller + .lock() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + { + canceller.cancel_volume_operation(); + } // Idempotent against natural completion. if self.finished.load(Ordering::Acquire) { return Ok(()); @@ -477,6 +526,14 @@ impl Statement { /// resource to release). #[napi] pub async fn close(&self) -> napi::Result<()> { + if let Some(canceller) = self + .canceller + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take() + { + canceller.cancel_volume_operation(); + } let inner = Arc::clone(&self.inner); guarded(async move { // Take the inner state out so `Drop` knows there's nothing @@ -503,6 +560,14 @@ impl Statement { impl Drop for Statement { fn drop(&mut self) { + if let Some(canceller) = self + .canceller + .get_mut() + .unwrap_or_else(PoisonError::into_inner) + .take() + { + canceller.cancel_volume_operation(); + } // Best-effort cleanup: schedule a drop of the kernel handle on // the captured tokio runtime. JS callers who need a // guaranteed `close_statement` round-trip must call `close()` @@ -551,7 +616,175 @@ pub(crate) fn statement_closed_err() -> napi::Error { #[cfg(test)] mod tests { use super::*; + use arrow_array::{RecordBatch, StringArray}; + use arrow_ipc::reader::StreamReader; use arrow_schema::{DataType, Field, Schema}; + use base64::{engine::general_purpose::STANDARD, Engine}; + use databricks_sql_kernel::{AuthConfig, Session}; + use serde_json::json; + use std::time::Duration; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + async fn volume_session() -> (MockServer, Session) { + let server = MockServer::start().await; + let names = ["operation", "presignedUrl", "headers", "localFile"]; + let schema = Arc::new(Schema::new( + names + .map(|name| Field::new(name, DataType::Utf8, false)) + .to_vec(), + )); + let values = [ + "REMOVE".to_owned(), + format!("{}/object", server.uri()), + "{}".into(), + "".into(), + ]; + let batch = RecordBatch::try_new( + schema.clone(), + values + .iter() + .map(|value| Arc::new(StringArray::from(vec![value.as_str()])) as _) + .collect(), + ) + .unwrap(); + let response = json!({ + "statement_id":"volume", "status":{"state":"CLOSED"}, + "manifest":{"format":"ARROW_STREAM", "is_volume_operation":true, "total_row_count":1, "total_chunk_count":1, + "schema":{"column_count":4,"columns":names.iter().enumerate().map(|(i,name)| json!({"name":name,"type_name":"STRING","type_text":"STRING","position":i})).collect::>()}}, + "result":{"chunk_index":0,"row_offset":0,"row_count":1,"attachment":STANDARD.encode(crate::result::encode_ipc_stream(&schema, Some(&batch)).unwrap())} + }); + for verb in ["POST", "GET"] { + Mock::given(method(verb)) + .and(path(if verb == "POST" { + "/api/2.0/sql/statements" + } else { + "/api/2.0/sql/statements/volume" + })) + .respond_with(ResponseTemplate::new(200).set_body_json(response.clone())) + .mount(&server) + .await; + } + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/wh/sessions")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"session_id":"session"}))) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + let session = Session::builder() + .http_path(server.uri(), "/sql/1.0/warehouses/wh") + .auth(AuthConfig::Pat { + token: "test-token".into(), + identity_federation_client_id: None, + }) + .open() + .await + .unwrap(); + (server, session) + } + + #[tokio::test] + async fn sync_and_async_volume_completion_preserves_instruction_ipc() { + for asynchronous in [false, true] { + let (server, session) = volume_session().await; + Mock::given(method("DELETE")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200)) + .with_priority(1) + .expect(1) + .mount(&server) + .await; + let mut parent = session.statement(); + parent.spec().sql("operation"); + let batch = if asynchronous { + let executed = parent.submit().await.unwrap(); + let owner = + crate::async_statement::AsyncStatement::from_executed_async(parent, executed); + let result = owner.await_result().await.unwrap(); + assert!(result.is_volume_operation()); + assert_eq!( + result + .complete_volume_operation(vec![], false) + .await + .unwrap(), + crate::result::VolumeCompletion::Completed + ); + let batch = result.fetch_next_batch().await.unwrap().unwrap(); + owner.close().await.unwrap(); + batch + } else { + let executed = parent.execute().await.unwrap(); + let result = Statement::from_executed(parent, executed); + assert!(result.is_volume_operation()); + assert_eq!( + result + .complete_volume_operation(vec![], false) + .await + .unwrap(), + crate::result::VolumeCompletion::Completed + ); + let batch = result.fetch_next_batch().await.unwrap().unwrap(); + result.close().await.unwrap(); + batch + }; + let decoded = + StreamReader::try_new(std::io::Cursor::new(batch.ipc_bytes.as_ref()), None) + .unwrap() + .next() + .unwrap() + .unwrap(); + assert_eq!( + decoded + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + "REMOVE" + ); + session.close().await.unwrap(); + } + } + + #[tokio::test] + async fn close_interrupts_volume_completion_before_waiting_for_its_lock() { + let (server, session) = volume_session().await; + Mock::given(method("DELETE")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(5))) + .with_priority(1) + .expect(1) + .mount(&server) + .await; + let mut parent = session.statement(); + parent.spec().sql("operation"); + let executed = parent.execute().await.unwrap(); + let result = Statement::from_executed(parent, executed); + let completion = result.complete_volume_operation(vec![], false); + tokio::pin!(completion); + tokio::select! { + finished = &mut completion => panic!("completion finished before close: {finished:?}"), + _ = async { + while !server.received_requests().await.unwrap().iter().any(|request| request.url.path() == "/object") { + tokio::task::yield_now().await; + } + } => {} + } + let (closed, completed) = tokio::time::timeout(Duration::from_secs(1), async { + tokio::join!(result.close(), &mut completion) + }) + .await + .expect("close must signal before waiting for the completion lock"); + closed.unwrap(); + assert!(completed + .unwrap_err() + .reason + .contains(r#""code":"Cancelled""#)); + session.close().await.unwrap(); + } fn make_schema() -> Arc { Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])) @@ -623,6 +856,8 @@ mod tests { let stmt = Statement { inner: Arc::new(Mutex::new(None)), // "already closed" schema: make_schema(), + is_volume_operation: false, + canceller: StdMutex::new(None), statement_id: "stmt-survives-close".to_owned(), finished: Arc::new(AtomicBool::new(false)), }; @@ -638,6 +873,8 @@ mod tests { let stmt = Statement { inner: Arc::new(Mutex::new(None)), schema: schema.clone(), + is_volume_operation: false, + canceller: StdMutex::new(None), statement_id: "x".to_owned(), finished: Arc::new(AtomicBool::new(false)), }; @@ -657,6 +894,8 @@ mod tests { let stmt = Statement { inner: Arc::new(Mutex::new(None)), schema: make_schema(), + is_volume_operation: false, + canceller: StdMutex::new(None), statement_id: "x".to_owned(), finished: Arc::new(AtomicBool::new(false)), }; @@ -673,6 +912,8 @@ mod tests { let stmt = Statement { inner: Arc::new(Mutex::new(None)), // closed schema: make_schema(), + is_volume_operation: false, + canceller: StdMutex::new(None), statement_id: "x".to_owned(), finished: Arc::new(AtomicBool::new(true)), }; diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..95e170cb 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -13,6 +13,11 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added +- `ExecutedStatement` and `ResultStream` expose `is_volume_operation` and + `complete_volume_operation` for Volume `PUT`, `GET` and `REMOVE`, including + uploads from `input_bytes`. Local file errors carry `local_os_error` and + `local_path`. + ### Changed ### Updated diff --git a/pyo3/src/errors.rs b/pyo3/src/errors.rs index 88ff4257..1a40fb7a 100644 --- a/pyo3/src/errors.rs +++ b/pyo3/src/errors.rs @@ -70,7 +70,10 @@ fn attach_attrs( display_message: Option<&str>, diagnostic_info: Option<&str>, error_details_json: Option<&str>, + local: Option<&databricks_sql_kernel::kernel_error::LocalFileError>, ) -> PyResult<()> { + bound.setattr("local_os_error", local.and_then(|e| e.raw_os_error))?; + bound.setattr("local_path", local.map(|e| e.path.as_str()))?; bound.setattr("code", code)?; bound.setattr("message", message)?; bound.setattr("sql_state", sql_state)?; @@ -138,6 +141,7 @@ pub(crate) fn to_py_err(py: Python<'_>, err: KError) -> PyErr { err.display_message.as_deref(), err.diagnostic_info.as_deref(), err.error_details_json.as_deref(), + err.local_error.as_deref(), ) { // Attribute attachment is best-effort. If something goes wrong // (extremely unlikely for plain string/int setattrs — but @@ -182,6 +186,7 @@ pub(crate) fn closed_err(handle_name: &str) -> PyErr { None, None, None, + None, ) { return setattr_err; } diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index 9ce1afb1..7220654d 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -84,6 +84,7 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_function(wrap_pyfunction!(init_logging, m)?)?; m.add_function(wrap_pyfunction!(reset_logging, m)?)?; diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index 1b5fc590..0f94b335 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -54,8 +54,71 @@ impl ResultStream { } } +#[pyclass(eq, skip_from_py_object)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VolumeCompletion { + NotVolume, + NeedsInputStream, + Completed, +} + +impl From for VolumeCompletion { + fn from(value: databricks_sql_kernel::VolumeCompletion) -> Self { + match value { + databricks_sql_kernel::VolumeCompletion::NotVolume => Self::NotVolume, + databricks_sql_kernel::VolumeCompletion::NeedsInputStream => Self::NeedsInputStream, + databricks_sql_kernel::VolumeCompletion::Completed => Self::Completed, + } + } +} + +pub(crate) fn complete_volume( + py: Python<'_>, + runtime: &Arc, + stream: &mut KResultStream, + allowed_paths: Vec, + remove_not_found_is_success: bool, + input_bytes: Option>, +) -> PyResult { + let options = databricks_sql_kernel::VolumeOptions::new( + allowed_paths.into_iter().map(Into::into).collect(), + remove_not_found_is_success, + ); + Ok(run_kernel_interruptible!( + py, + runtime, + stream.complete_volume_operation(&options, input_bytes) + )? + .into()) +} + #[pymethods] impl ResultStream { + #[getter] + fn is_volume_operation(&self) -> PyResult { + let inner = alive!(self, "ResultStream"); + Ok(inner.stream.is_volume_operation()) + } + + #[pyo3(signature = (allowed_paths, remove_not_found_is_success, input_bytes=None))] + fn complete_volume_operation( + &mut self, + py: Python<'_>, + allowed_paths: Vec, + remove_not_found_is_success: bool, + input_bytes: Option>, + ) -> PyResult { + let inner = alive_mut!(self, "ResultStream"); + complete_volume( + py, + &inner.runtime, + &mut inner.stream, + allowed_paths, + remove_not_found_is_success, + input_bytes, + ) + } + /// Result schema as a `pyarrow.Schema`. Available even after `close()`. fn arrow_schema<'py>(&self, py: Python<'py>) -> PyResult> { self.schema.as_ref().to_pyarrow(py) diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c626ee89..9a357443 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -207,6 +207,7 @@ fn build_http_config( http.sea_response_compression_enabled = sea_response_compression_enabled; if let Some(timeout) = request_timeout { http.request_timeout = timeout; + http.storage_read_timeout = Some(timeout); } if let Some(max) = max_connections { http.pool_max_idle_per_host = max; @@ -317,11 +318,15 @@ impl Session { /// CloudFetch requests; token-endpoint (auth) calls keep a fixed /// fast-fail policy. /// - /// `request_timeout_secs` sets the total timeout for one HTTP request, + /// `request_timeout_secs` sets the total timeout for one SQL HTTP request, /// from connection start through response-body completion. A separate /// 30-second connection timeout also applies, so connection establishment /// is bounded by the shorter limit. Unset or `0` keeps the kernel default /// (120 seconds). + /// For Volume file transfers a positive value is an idle limit instead: + /// a transfer fails after that long without progress, except a PUT + /// that storage redirects, which is resent without the limit. + /// Unset or `0` keeps the 15-minute default. /// /// `max_connections` sets the maximum idle connections retained per host. /// Unset keeps the kernel default (100); zero is rejected. @@ -869,6 +874,10 @@ mod send_sync_tests { .unwrap() .expect("positive request timeout should build an HTTP config"); assert_eq!(http.request_timeout, std::time::Duration::from_millis(500)); + assert_eq!( + http.storage_read_timeout, + Some(std::time::Duration::from_millis(500)) + ); assert_eq!(http.retry_min_wait, default.retry_min_wait); assert_eq!(http.overall_timeout, default.overall_timeout); diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 2777b114..c052f3a9 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -321,6 +321,31 @@ impl ExecutedStatement { #[pymethods] impl ExecutedStatement { + #[getter] + fn is_volume_operation(&self) -> PyResult { + let inner = alive!(self, "ExecutedStatement"); + Ok(inner.exec.result_stream().is_volume_operation()) + } + + #[pyo3(signature = (allowed_paths, remove_not_found_is_success, input_bytes=None))] + fn complete_volume_operation( + &mut self, + py: Python<'_>, + allowed_paths: Vec, + remove_not_found_is_success: bool, + input_bytes: Option>, + ) -> PyResult { + let inner = alive_mut!(self, "ExecutedStatement"); + crate::result_stream::complete_volume( + py, + &inner.runtime, + inner.exec.result_stream_mut(), + allowed_paths, + remove_not_found_is_success, + input_bytes, + ) + } + #[getter] fn statement_id(&self) -> &str { &self.statement_id diff --git a/pyo3/tests/sql_api.py b/pyo3/tests/sql_api.py index e4335bdf..56977c38 100644 --- a/pyo3/tests/sql_api.py +++ b/pyo3/tests/sql_api.py @@ -31,18 +31,33 @@ def sql_api(session_type, arrow_bytes=None): chunk_requested=threading.Event(), release_chunk=threading.Event(), statement_closed=threading.Event(), + volume=None, + storage_bytes=b"", ) statement_id = "00000001-0000-0000-0000-000000000001" statement_path = f"/api/2.0/sql/statements/{statement_id}" class Handler(BaseHTTPRequestHandler): def reply(self): - self.rfile.read(int(self.headers.get("Content-Length", 0))) + body = self.rfile.read(int(self.headers.get("Content-Length", 0))) path = self.path.split("?")[0] state.requests.append((self.command, path)) status, response = 200, {} if self.command == "POST" and path.endswith("/sessions"): response = {"session_id": "00000000-0000-0000-0000-000000000001"} + elif path == "/volume-bytes": + if self.command == "PUT": + state.storage_bytes = body + response = b"" + else: + response = state.storage_bytes + elif ( + self.command == "POST" + and path.endswith("/statements") + and state.volume is not None + ): + response = self.volume_response() + state.response = response elif self.command == "POST" and path.endswith("/statements"): pending = state.mode != "buffered" raw = arrow_bytes(state.batches) if state.batches else b"" @@ -120,6 +135,49 @@ def reply(self): self.end_headers() self.wfile.write(encoded) + def volume_response(self): + import pyarrow as pa + + names = ["operation", "presignedUrl", "headers", "localFile"] + values = [ + state.volume["operation"], + f"{state.host}/volume-bytes", + "{}", + state.volume["path"], + ] + batch = pa.record_batch([[value] for value in values], names=names) + output = pa.BufferOutputStream() + with pa.ipc.new_stream(output, batch.schema) as writer: + writer.write_batch(batch) + return { + "statement_id": statement_id, + "status": {"state": "SUCCEEDED"}, + "manifest": { + "format": "ARROW_STREAM", + "is_volume_operation": True, + "total_chunk_count": 1, + "total_row_count": 1, + "schema": { + "column_count": len(names), + "columns": [ + { + "name": name, + "type_name": "STRING", + "type_text": "STRING", + "position": index, + } + for index, name in enumerate(names) + ], + }, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": 1, + "attachment": base64.b64encode(output.getvalue()).decode(), + }, + } + def link(self, index): batches = state.batches if index == 0 else [] if index == 1 else [[3, 4]] return { @@ -132,7 +190,7 @@ def link(self, index): "expiration": "2099-01-01T00:00:00Z", } - do_POST = do_GET = do_DELETE = reply + do_POST = do_GET = do_DELETE = do_PUT = reply def log_message(self, *args): pass diff --git a/pyo3/tests/test_volume.py b/pyo3/tests/test_volume.py new file mode 100644 index 00000000..9f6829e2 --- /dev/null +++ b/pyo3/tests/test_volume.py @@ -0,0 +1,93 @@ +# 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. + +"""Volume transfers through the native binding and a loopback storage server.""" + +import errno + +import pytest + +import databricks_sql_kernel as k +from sql_api import sql_api as local_sql_api + + +@pytest.fixture +def sql_api(): + with local_sql_api(k.Session) as state: + yield state + + +def test_volume_get_round_trip(sql_api, tmp_path): + destination = tmp_path / "download" + sql_api.volume = {"operation": "GET", "path": str(destination)} + sql_api.storage_bytes = b"downloaded\x00\xff" + statement = sql_api.session.statement() + statement.set_sql("GET volume") + owner = statement.submit() + result = owner.await_result() + try: + assert result.is_volume_operation + assert ( + result.complete_volume_operation([str(tmp_path)], False) + == k.VolumeCompletion.Completed + ) + assert destination.read_bytes() == sql_api.storage_bytes + assert sql_api.requests.count(("GET", "/volume-bytes")) == 1 + assert result.fetch_next_batch().column(0).to_pylist() == ["GET"] + finally: + result.close() + owner.close() + statement.close() + + +def test_volume_put_with_input_bytes(sql_api): + sql_api.volume = {"operation": "PUT", "path": "__input_stream__"} + statement = sql_api.session.statement() + statement.set_sql("PUT volume") + result = statement.execute() + try: + assert result.is_volume_operation + assert ( + result.complete_volume_operation([], False) + == k.VolumeCompletion.NeedsInputStream + ) + assert ("PUT", "/volume-bytes") not in sql_api.requests + payload = b"uploaded\x00\xff" + assert ( + result.complete_volume_operation([], False, input_bytes=payload) + == k.VolumeCompletion.Completed + ) + assert sql_api.storage_bytes == payload + assert sql_api.requests.count(("PUT", "/volume-bytes")) == 1 + finally: + result.close() + statement.close() + + +def test_volume_local_file_error_details(sql_api, tmp_path): + source = tmp_path / "missing" + sql_api.volume = {"operation": "PUT", "path": str(source)} + statement = sql_api.session.statement() + statement.set_sql("PUT volume") + result = statement.execute() + try: + with pytest.raises(k.KernelError) as raised: + result.complete_volume_operation([str(tmp_path)], False) + assert raised.value.error_code == "VOLUME_LOCAL_FILE_ERROR" + assert raised.value.local_os_error == errno.ENOENT + assert raised.value.local_path == str(source) + assert ("PUT", "/volume-bytes") not in sql_api.requests + finally: + result.close() + statement.close() diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index f5243007..d8ff9ffa 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -55,6 +55,8 @@ pub struct KernelError { /// "no error recorded since the last clear". #[derive(Default)] struct LastError { + local_os_error: i32, + local_path: Option, code: Option, message: Option, sql_state: Option, @@ -62,6 +64,7 @@ struct LastError { http_status: u16, retryable: bool, query_id: Option, + error_code: Option, } thread_local! { @@ -130,6 +133,35 @@ pub unsafe extern "C" fn kernel_get_last_error(out: *mut KernelError) -> bool { }) } +/// Original local OS error number, or zero when unavailable. Does not clear the error. +#[no_mangle] +pub extern "C" fn kernel_get_last_error_local_os_error() -> i32 { + LAST_ERROR.with(|last| last.borrow().local_os_error) +} + +/// The error's string code, such as VOLUME_PATH_NOT_ALLOWED, or null. +/// Valid until the next call that clears the error. +#[no_mangle] +pub extern "C" fn kernel_get_last_error_code() -> *const c_char { + LAST_ERROR.with(|last| { + last.borrow() + .error_code + .as_ref() + .map_or(std::ptr::null(), |s| s.as_ptr()) + }) +} + +/// Borrowed requested local path, or null. Valid until the next error-clearing call. +#[no_mangle] +pub extern "C" fn kernel_get_last_error_local_path() -> *const c_char { + LAST_ERROR.with(|last| { + last.borrow() + .local_path + .as_ref() + .map_or(std::ptr::null(), |s| s.as_ptr()) + }) +} + /// Crate-internal: write a typed kernel [`Error`] into the thread-local /// last-error buffer. Every FFI function that returns a non-`Success` /// status code calls this (via [`crate::c_abi::block_on_ffi`] or directly) @@ -151,6 +183,12 @@ pub(crate) fn store_error(err: Error) { message.push_str(ec); } *last = LastError { + local_os_error: err + .local_error + .as_ref() + .and_then(|e| e.raw_os_error) + .unwrap_or(0), + local_path: err.local_error.as_ref().map(|e| to_cstring_lossy(&e.path)), code: Some(err.code), message: Some(to_cstring_lossy(&message)), sql_state: err.sql_state.as_deref().map(to_cstring_lossy), @@ -158,6 +196,7 @@ pub(crate) fn store_error(err: Error) { http_status: err.http_status.unwrap_or(0), retryable: err.retryable, query_id: err.query_id.as_deref().map(to_cstring_lossy), + error_code: err.error_code.as_deref().map(to_cstring_lossy), }; }); } @@ -243,12 +282,16 @@ mod tests { } #[test] - fn store_error_folds_error_code_slug_into_message() { - store_error( - Error::sql_error() - .message("statement gone") - .with_error_code("STATEMENT_NOT_FOUND"), - ); + fn store_error_exposes_error_code_and_local_file_details() { + let mut error = Error::sql_error() + .message("statement gone") + .with_error_code("STATEMENT_NOT_FOUND"); + error.local_error = Some(Box::new(crate::kernel_error::LocalFileError::new( + Some(2), + std::io::ErrorKind::NotFound, + "local-file", + ))); + store_error(error); with_last_error(|e| { let e = e.expect("error present"); let msg = unsafe { std::ffi::CStr::from_ptr(e.message) } @@ -256,8 +299,25 @@ mod tests { .unwrap(); assert!(msg.contains("statement gone")); assert!(msg.contains("STATEMENT_NOT_FOUND")); + assert_eq!( + unsafe { std::ffi::CStr::from_ptr(kernel_get_last_error_code()) } + .to_str() + .unwrap(), + "STATEMENT_NOT_FOUND" + ); }); + assert_eq!(kernel_get_last_error_local_os_error(), 2); + assert_eq!( + unsafe { std::ffi::CStr::from_ptr(kernel_get_last_error_local_path()) } + .to_str() + .unwrap(), + "local-file" + ); + with_last_error(|error| assert!(error.is_some())); clear_error(); + assert!(kernel_get_last_error_code().is_null()); + assert_eq!(kernel_get_last_error_local_os_error(), 0); + assert!(kernel_get_last_error_local_path().is_null()); } #[test] diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index 1c66a033..a1498893 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -86,6 +86,7 @@ pub struct kernel_result_stream_canceller_t { /// download — close the stream (and, for a sync-executed statement, the executed /// handle) to release those on their own completion. struct ResultStreamInner { + volume: Option>, /// Fired by a cloned [`ResultStreamCanceller`] to interrupt an in-flight /// `next_batch`. Once fired the stream is permanently aborted: `next_batch` /// returns `Cancelled` on every subsequent call rather than re-driving a @@ -119,6 +120,7 @@ enum ResultStreamShape { /// Detached canceller for a result stream. Holds a clone of the stream's /// [`CancellationToken`], so firing it interrupts an in-flight `next_batch`. +/// It also stops a running Volume file transfer. /// /// A `CancellationToken` clone shares the same underlying atomic state, so the /// canceller keeps working after the stream handle is closed — closing the @@ -127,6 +129,7 @@ enum ResultStreamShape { /// reference to the stream's `&mut` state, so it is safe to `cancel()` from any /// thread concurrently with `next_batch`/`close` on the owning thread. struct ResultStreamCanceller { + volume: Option>, cancel: CancellationToken, } @@ -139,6 +142,7 @@ pub(crate) fn into_raw_result_stream( stream: crate::result_stream::ResultStream, ) -> *mut kernel_result_stream_t { Box::into_raw(Box::new(ResultStreamInner { + volume: stream.volume_state(), cancel: CancellationToken::new(), shape: ResultStreamShape::Owned { schema, stream }, })) as *mut kernel_result_stream_t @@ -156,6 +160,7 @@ pub(crate) unsafe fn into_raw_executed_stream( valid: ValidityFlag, ) -> *mut kernel_result_stream_t { Box::into_raw(Box::new(ResultStreamInner { + volume: (*exec).result_stream().volume_state(), cancel: CancellationToken::new(), shape: ResultStreamShape::Executed { exec, valid }, })) as *mut kernel_result_stream_t @@ -584,6 +589,7 @@ pub unsafe extern "C" fn kernel_result_stream_canceller_new( // is a `Sync` atomic). SAFETY: `stream` is a live box (non-null checked). let p = stream as *mut ResultStreamInner; let handle = ResultStreamCanceller { + volume: (*std::ptr::addr_of!((*p).volume)).clone(), cancel: (*std::ptr::addr_of!((*p).cancel)).clone(), }; std::ptr::write( @@ -597,8 +603,9 @@ pub unsafe extern "C" fn kernel_result_stream_canceller_new( /// Fire the cancellation of the result stream this canceller was created for /// (odbc#355-B). Purely client-side (no server RPC): it flips the shared token, /// which an in-flight `kernel_result_stream_next_batch` observes via its -/// `tokio::select!` and unwinds. Idempotent, non-blocking, and safe to call -/// concurrently with `next_batch`/`close` on the stream's owning thread. +/// `tokio::select!` and unwinds. It also stops a running Volume file transfer. +/// Idempotent, non-blocking, and safe to call concurrently with +/// `next_batch`/`close` on the stream's owning thread. /// /// Always returns `Success` for a live handle. After this returns, the stream is /// permanently aborted: every subsequent `next_batch` returns `Cancelled`. @@ -618,6 +625,9 @@ pub unsafe extern "C" fn kernel_result_stream_canceller_cancel( "kernel_result_stream_canceller_cancel: handle must not be null", ); }; + if let Some(volume) = &handle.volume { + volume.cancel(); + } handle.cancel.cancel(); KernelStatusCode::Success }) @@ -646,6 +656,86 @@ pub unsafe extern "C" fn kernel_result_stream_canceller_free( }) } +/// Same flag, read from the stream. Still succeeds after the executed statement +/// is closed. +/// # Safety +/// `stream` must be live and `out` must be writable. +#[no_mangle] +pub unsafe extern "C" fn kernel_result_stream_is_volume_operation( + stream: *const kernel_result_stream_t, + out: *mut bool, +) -> KernelStatusCode { + catch_ffi(|| { + if stream.is_null() || out.is_null() { + return store_invalid_arg("Volume marker: null pointer"); + } + let p = stream as *const ResultStreamInner; + std::ptr::write(out, (*std::ptr::addr_of!((*p).volume)).is_some()); + KernelStatusCode::Success + }) +} + +/// Runs the file transfer for a Volume PUT, GET or REMOVE result. Call before +/// fetching; the rows stay readable afterwards. +/// `allowed_paths_json`: JSON array of local directories the transfer may use. +/// `remove_not_found_is_success`: report success when the remote file is missing. +/// Returns NeedsInputStream for a stream upload, which this API cannot perform. +/// `kernel_result_stream_canceller_cancel` interrupts it from another thread. +/// # Safety +/// `stream` must be live with exclusive fetch access, `allowed_paths_json` must +/// be NUL-terminated UTF-8, and `out_status` must be writable. +#[no_mangle] +pub unsafe extern "C" fn kernel_result_stream_complete_volume_operation( + stream: *mut kernel_result_stream_t, + allowed_paths_json: *const std::ffi::c_char, + remove_not_found_is_success: bool, + out_status: *mut crate::VolumeCompletion, +) -> KernelStatusCode { + catch_ffi(|| { + if stream.is_null() || allowed_paths_json.is_null() || out_status.is_null() { + return store_invalid_arg("Volume completion: null pointer"); + } + let roots = match std::ffi::CStr::from_ptr(allowed_paths_json) + .to_str() + .ok() + .and_then(|text| serde_json::from_str::>(text).ok()) + { + Some(roots) => roots, + None => { + return store_invalid_arg("Volume allowed paths must be a JSON array of strings") + } + }; + let options = crate::VolumeOptions::new( + roots.into_iter().map(Into::into).collect(), + remove_not_found_is_success, + ); + let p = stream as *mut ResultStreamInner; + let shape = &mut *std::ptr::addr_of_mut!((*p).shape); + let result = match shape { + ResultStreamShape::Owned { stream, .. } => { + block_on_ffi(|| stream.complete_volume_operation(&options, None)) + } + ResultStreamShape::Executed { exec, valid } => { + let exec = match executed_ref(*exec, valid) { + Ok(exec) => exec, + Err(code) => return code, + }; + block_on_ffi(|| { + exec.result_stream_mut() + .complete_volume_operation(&options, None) + }) + } + }; + match result { + Ok(status) => { + std::ptr::write(out_status, status); + KernelStatusCode::Success + } + Err(code) => code, + } + }) +} + #[cfg(test)] mod tests { use super::*; @@ -678,6 +768,76 @@ mod tests { into_raw_result_stream(schema, stream) } + #[test] + fn volume_completion_observes_detached_cancel() { + use crate::reader::test_utils::MockReader; + use crate::result_stream::ResultStream; + use arrow_array::StringArray; + use std::ffi::CString; + + let schema = Arc::new(Schema::new( + ["operation", "presignedUrl", "headers", "localFile"] + .map(|name| Field::new(name, DataType::Utf8, false)) + .to_vec(), + )); + let batch = RecordBatch::try_new( + schema.clone(), + ["REMOVE", "http://unused.invalid/object", "{}", ""] + .into_iter() + .map(|value| Arc::new(StringArray::from(vec![value])) as _) + .collect(), + ) + .unwrap(); + let rt = tokio::runtime::Runtime::new().unwrap(); + let volume = crate::volume::VolumeState::new( + Default::default(), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(None), + ), + Default::default(), + ); + let stream = rt.block_on(async { + let mut stream = + ResultStream::from_reader(Box::new(MockReader::new(vec![batch.clone()]))) + .await + .unwrap(); + stream.attach_volume(Arc::clone(&volume)); + into_raw_result_stream(schema.clone(), stream) + }); + let mut is_volume = false; + assert_eq!( + unsafe { kernel_result_stream_is_volume_operation(stream, &mut is_volume) }, + KernelStatusCode::Success + ); + assert!(is_volume); + let roots = CString::new("[]").unwrap(); + let mut status = crate::VolumeCompletion::NotVolume; + let mut canceller = std::ptr::null_mut(); + assert_eq!( + unsafe { kernel_result_stream_canceller_new(stream, &mut canceller) }, + KernelStatusCode::Success + ); + assert_eq!( + unsafe { kernel_result_stream_canceller_cancel(canceller) }, + KernelStatusCode::Success + ); + assert_eq!( + unsafe { + kernel_result_stream_complete_volume_operation( + stream, + roots.as_ptr(), + false, + &mut status, + ) + }, + KernelStatusCode::Cancelled + ); + unsafe { kernel_result_stream_canceller_free(canceller) }; + unsafe { kernel_result_stream_close(stream) }; + } + /// End-of-stream on an Owned stream returns `Success` with a /// **released** array (`release == null`) — the sentinel ODBC / Go /// consumers loop on. A regression that returned a non-released empty diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index b3365f49..f0f581d4 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -155,6 +155,7 @@ pub struct KernelSessionConfig { /// Total request timeout (populated by `..._set_request_timeout`). `None` /// keeps [`HttpConfig::default`]'s 120-second timeout. request_timeout: Option, + storage_read_timeout: Option, /// Maximum idle connections retained per host. `None` keeps the kernel /// default; populated by `..._set_max_connections`. max_connections: Option, @@ -289,6 +290,7 @@ pub unsafe extern "C" fn kernel_session_config_new( custom_headers: Vec::new(), sea_response_compression_enabled: false, request_timeout: None, + storage_read_timeout: None, max_connections: None, retry: None, // Default to ignoring transactions, matching IgnoreTransactions=1. @@ -629,6 +631,7 @@ pub unsafe extern "C" fn kernel_session_config_set_sea_response_compression_enab /// Configure the total timeout for one HTTP request, from connection start /// through response-body completion. A separate 30-second connection timeout /// also applies, so connection establishment is bounded by the shorter limit. +/// Does not apply to Volume file transfers; see the storage read timeout. /// `request_timeout_ms == 0` clears an earlier override and keeps the kernel /// default (120 seconds); a positive value overrides it. /// @@ -646,6 +649,26 @@ pub unsafe extern "C" fn kernel_session_config_set_request_timeout( }) } +/// Idle limit for Volume file transfers: a transfer fails after this long +/// without progress. Also caps connection setup. Zero sets no limit. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_storage_read_timeout( + config: *mut KernelSessionConfig, + timeout_ms: u64, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.storage_read_timeout = Some(if timeout_ms == 0 { + Duration::MAX + } else { + Duration::from_millis(timeout_ms) + }); + Ok(()) + }) +} + /// Configure the maximum number of idle HTTP connections retained per host. /// The value must be greater than zero; omitting this setter keeps the kernel /// default (100). @@ -1514,12 +1537,16 @@ fn merge_http_config( request_timeout: Option, max_connections: Option, retry: Option, + storage_read_timeout: Option, ) -> HttpConfig { let mut http = HttpConfig { custom_headers, sea_response_compression_enabled, ..HttpConfig::default() }; + if let Some(t) = storage_read_timeout { + http.storage_read_timeout = Some(t); + } if let Some(t) = request_timeout { http.request_timeout = t; } @@ -1652,6 +1679,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result Result KernelStatusCode { + catch_ffi(|| { + let Some(handle) = (exec as *const ExecutedHandle).as_ref() else { + return store_invalid_arg("Volume marker: null executed statement"); + }; + if out.is_null() { + return store_invalid_arg("Volume marker: null out pointer"); + } + if !handle.exec.is_valid() { + return store_and_code( + Error::invalid_statement_handle().message("executed statement is invalid"), + ); + } + std::ptr::write(out, handle.exec.result_stream().is_volume_operation()); + KernelStatusCode::Success + }) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/result_stream.rs b/src/result_stream.rs index 4c534f41..c310defa 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -729,6 +729,10 @@ impl ResultStream { result } + pub(crate) fn volume_state(&self) -> Option> { + self.volume.clone() + } + pub(crate) fn cancel_volume(&self) { if let Some(state) = &self.volume { state.cancel();