diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index ffaa60bd..a8f6d728 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -131,6 +131,32 @@ jobs: # a live workspace; `rust-e2e.yml` runs them separately. run: cargo test --workspace + volume-windows: + name: Volume tests (Windows) + runs-on: + group: databricks-protected-runner-group + labels: [windows-server-latest] + timeout-minutes: 45 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: ./.github/actions/setup-public-package-proxies + with: + cargo: "true" + + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: stable + + - name: Set up MSVC environment + uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1 + with: + arch: x64 + + - name: Volume file and cancellation tests + shell: pwsh + run: cargo test --locked --lib volume::tests + c-abi: name: C ABI smoke test runs-on: diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 2a11227d..3a8ba972 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -127,7 +127,8 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). | Field | Description | Default | |-------|-------------|---------| -| `request_timeout` | Per-request timeout (connect + body). | `120s` | +| `request_timeout` | Per-request timeout (connect + body) for SQL requests. Volume file transfers are limited by storage_read_timeout instead. | `120s` | +| `storage_read_timeout` | Idle limit for Volume file transfers: a transfer fails after this long without progress. | `None` (no limit) | | `overall_timeout` | Maximum total time across retries for one logical RPC. | `900s` | | `pool_max_idle_per_host` | Connection-pool size (max idle warm sockets per host). Raise for bursty concurrent workloads. | `100` | | `retry_min_wait` | Minimum backoff between retries; also the floor for a server `Retry-After` and the base of exponential backoff (`min_wait × 2^attempt`). | `1s` | diff --git a/Cargo.lock b/Cargo.lock index d4992a7f..4f312715 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2383,9 +2383,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", diff --git a/Cargo.toml b/Cargo.toml index 5a53e72c..a20ef673 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -105,9 +105,12 @@ moka = { version = "0.12.16", features = ["future"] } # Async utilities futures = "0.3" -tokio-util = "0.7" +tokio-util = { version = "0.7", features = ["io"] } async-trait = "0.1" +# Temporary file that holds a Volume GET download before it is copied into place +tempfile = "3" + # Error handling thiserror = "2" @@ -162,7 +165,6 @@ pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } [dev-dependencies] tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util"] } wiremock = "0.6" -tempfile = "3" log = "0.4" # Generate JWT test keys in-process to avoid PEM fixtures and an external # `openssl` dependency. `ring` already backs runtime JWT signing. diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 2ebce050..867d604c 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,8 +11,17 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- Volume `PUT`, `GET` and `REMOVE`: `ResultStream::complete_volume_operation` + runs the file transfer. Local paths, and the files they resolve to through + symlinks, must be inside the caller's allowed directories. A `PUT` can also + upload bytes the caller supplies. + ### Changed +- Adds public fields to `Error` and `ResultManifest`. Code that builds these + structs with struct literals must be updated. Supported consumers are the PyO3, + NAPI, C ABI and ADBC bindings. + ### Updated ### Fixed diff --git a/NOTICE b/NOTICE index 7cda1ab7..55dd3e4b 100644 --- a/NOTICE +++ b/NOTICE @@ -142,6 +142,11 @@ Project URL: https://github.com/serde-rs/json Copyright: Copyright serde_json Authors. +Package: tempfile +Project URL: https://github.com/Stebalien/tempfile +Copyright: Copyright (c) 2015 Steven Allen + + Package: thiserror Project URL: https://github.com/dtolnay/thiserror Copyright: Copyright thiserror Authors. diff --git a/README.md b/README.md index ba83c9f1..c7b02315 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,14 @@ and security vulnerabilities should be reported according to [SECURITY.md](SECURITY.md). For other project questions, contact [eng-oss-sql-driver@databricks.com](mailto:eng-oss-sql-driver@databricks.com). +## Volume file operations + +For a Volume `PUT`, `GET` or `REMOVE`, call +`ResultStream::complete_volume_operation` before reading rows. It runs the +file transfer; without it the result is only the server's instruction row. +See [`ResultStream::complete_volume_operation`](https://docs.rs/databricks-sql-kernel/latest/databricks_sql_kernel/struct.ResultStream.html#method.complete_volume_operation) +for transfer behavior. + ## License Apache 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE). diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index dcaa4b65..dce29af2 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", @@ -678,6 +680,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.1", + "tempfile", "thiserror 2.0.21", "tokio", "tokio-util", @@ -2169,9 +2172,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", 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/NOTICE b/adbc/NOTICE index 7cda1ab7..55dd3e4b 100644 --- a/adbc/NOTICE +++ b/adbc/NOTICE @@ -142,6 +142,11 @@ Project URL: https://github.com/serde-rs/json Copyright: Copyright serde_json Authors. +Package: tempfile +Project URL: https://github.com/Stebalien/tempfile +Copyright: Copyright (c) 2015 Steven Allen + + Package: thiserror Project URL: https://github.com/dtolnay/thiserror Copyright: Copyright thiserror Authors. diff --git a/adbc/README.md b/adbc/README.md index de153783..a2445d20 100644 --- a/adbc/README.md +++ b/adbc/README.md @@ -73,6 +73,20 @@ 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. +The option remains enabled for the statement until set to JSON `null`; an empty +array still permits REMOVE while denying file PUT and GET. Local `..` components collapse +before symlink resolution. 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; +`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..6d648de9 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, @@ -888,6 +934,7 @@ impl adbc_core::Statement for Statement { &row, self.parameter_style, self.client_timeout, + self.volume_options.as_ref(), ) { Ok(executed) => executed, Err(mut error) => { @@ -1123,6 +1170,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 +1212,33 @@ 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) +} + +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 +1529,186 @@ 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}" + ); + } + 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 e167f181..4f78960c 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. 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). */ @@ -966,6 +978,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 b3b4c36e..e3e9f50d 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -638,6 +638,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -656,6 +657,7 @@ dependencies = [ "arrow-array", "arrow-ipc", "arrow-schema", + "base64", "chrono", "databricks-sql-kernel", "futures", @@ -796,6 +798,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1493,6 +1501,12 @@ dependencies = [ "libc", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.2" @@ -2200,6 +2214,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.46" @@ -2546,6 +2573,19 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" 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..45c9a3b1 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -854,9 +854,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 +877,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 +967,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 +1180,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 +1308,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/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/Cargo.lock b/pyo3/Cargo.lock index fa59876f..6d9c3e25 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -634,6 +634,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -769,6 +770,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1423,6 +1430,12 @@ dependencies = [ "libc", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.2" @@ -2112,6 +2125,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.46" @@ -2464,6 +2490,19 @@ version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" 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..0ed7a4f7 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` sets no Volume idle limit. /// /// `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/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..1ecbd185 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,22 @@ 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 = (timeout_ms != 0).then(|| 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,10 +1533,12 @@ 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, + storage_read_timeout, ..HttpConfig::default() }; if let Some(t) = request_timeout { @@ -1652,6 +1673,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/client/http.rs b/src/client/http.rs index cac2243b..33c9b502 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -388,6 +388,39 @@ pub struct DatabricksHttpClient { retry_configs: HashMap, } +pub(crate) struct StorageClient { + pub(crate) read_timeout: Option, + config: HttpClientConfig, + client: tokio::sync::OnceCell, +} + +impl StorageClient { + pub(crate) async fn get(&self) -> Result<&Client> { + self.client + .get_or_try_init(|| async { + DatabricksHttpClient::build_reqwest_client( + &self.config, + reqwest::redirect::Policy::custom(|attempt| { + if attempt.url().scheme() == "http" + && attempt + .previous() + .last() + .is_some_and(|url| url.scheme() == "https") + { + attempt.error("Volume storage redirect cannot downgrade HTTPS to HTTP") + } else { + reqwest::redirect::Policy::default().redirect(attempt) + } + }), + None, + // No Referer on redirects: it would carry the presigned URL. + false, + ) + }) + .await + } +} + impl DatabricksHttpClient { /// Creates a new HTTP client with the given configuration and per-category retry configs. /// @@ -479,7 +512,13 @@ impl DatabricksHttpClient { } // Follow redirects for normal traffic (reqwest's default policy). - let client = Self::build_reqwest_client(&config, reqwest::redirect::Policy::default())?; + let client = Self::build_reqwest_client( + &config, + reqwest::redirect::Policy::default(), + // `read_timeout` is historical: reqwest applies it as a total SQL deadline. + Some(config.read_timeout), + true, + )?; // Surface which TLS backend was compiled in so oncall debugging // a handshake / unknown-CA report can tell at a glance whether @@ -514,15 +553,18 @@ impl DatabricksHttpClient { fn build_reqwest_client( config: &HttpClientConfig, redirect: reqwest::redirect::Policy, + request_timeout: Option, + referer: bool, ) -> Result { let mut builder = Client::builder() .connect_timeout(config.connect_timeout) - // `read_timeout` is a historical name; reqwest applies this as - // the total deadline from connect through response-body completion. - .timeout(config.read_timeout) .pool_max_idle_per_host(config.max_connections_per_host) .user_agent(&config.user_agent) - .redirect(redirect); + .redirect(redirect) + .referer(referer); + if let Some(timeout) = request_timeout { + builder = builder.timeout(timeout); + } // Apply TLS configuration if config.tls.enabled == Some(false) { @@ -736,6 +778,19 @@ impl DatabricksHttpClient { &self.client } + /// Storage transfers can outlive SQL RPCs, so retain connection settings without their deadline. + pub(crate) fn storage_client(&self, storage_read_timeout: Option) -> StorageClient { + let mut config = self.config.clone(); + if let Some(timeout) = storage_read_timeout { + config.connect_timeout = config.connect_timeout.min(timeout); + } + StorageClient { + read_timeout: storage_read_timeout, + config, + client: tokio::sync::OnceCell::new(), + } + } + /// Get the authorization header value. /// /// Returns an error if the auth provider has not been set via `set_auth_provider()`. @@ -805,7 +860,12 @@ impl DatabricksHttpClient { /// `azure_tenant_id` (which skips discovery entirely). A single hop is /// sufficient for discovery, so no retry is attempted here. pub async fn first_redirect_location(&self, url: &str) -> Result> { - let client = Self::build_reqwest_client(&self.config, reqwest::redirect::Policy::none())?; + let client = Self::build_reqwest_client( + &self.config, + reqwest::redirect::Policy::none(), + Some(self.config.read_timeout), + true, + )?; let response = client.get(url).send().await.map_err(|e| { Error::network_error().message(format!("Redirect-probe request to {url} failed: {e}")) })?; diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs index b4b2d8c3..5d326292 100644 --- a/src/client/http_tls_tests.rs +++ b/src/client/http_tls_tests.rs @@ -288,6 +288,119 @@ async fn expired_certificate_fails_once_with_certificate_cause() { assert_certificate_failure(CertificateFailure::Expired).await; } +#[tokio::test] +async fn storage_redirect_rejects_https_to_http_on_the_same_port() { + let key = KeyPair::generate().unwrap(); + let certificate = CertificateParams::new(vec!["127.0.0.1".to_string()]) + .unwrap() + .self_signed(&key) + .unwrap(); + let tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![certificate.der().clone()], + PrivatePkcs8KeyDer::from(key.serialize_der()).into(), + ) + .unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let socket = listener.accept().await.unwrap().0; + let mut stream = TlsAcceptor::from(Arc::new(tls)) + .accept(socket) + .await + .unwrap(); + let mut request = [0; 4096]; + assert!(stream.read(&mut request).await.unwrap() > 0); + stream + .write_all( + format!( + "HTTP/1.1 302 Found\r\nLocation: http://{address}/plain\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) + .as_bytes(), + ) + .await + .unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(150), listener.accept()) + .await + .is_err() + ); + }); + let client = test_client( + HttpClientConfig { + tls: TlsConfig { + allow_self_signed: Some(true), + ..Default::default() + }, + ..Default::default() + }, + Duration::from_secs(2), + ); + let storage = client.storage_client(None); + let error = storage + .get() + .await + .unwrap() + .get(format!("https://{address}/object")) + .send() + .await + .unwrap_err(); + assert!(error.is_redirect(), "{error}"); + server.await.unwrap(); +} + +#[tokio::test] +async fn storage_idle_timeout_also_bounds_connection_setup() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (shutdown, mut stopped) = oneshot::channel(); + let server = tokio::spawn(async move { + let mut sockets = Vec::new(); + loop { + tokio::select! { + _ = &mut stopped => return sockets.len(), + accepted = listener.accept() => sockets.push(accepted.unwrap().0), + } + } + }); + let client = test_client( + HttpClientConfig { + connect_timeout: Duration::from_secs(2), + read_timeout: Duration::from_millis(10), + ..Default::default() + }, + Duration::from_secs(10), + ); + for timeout in [None, Some(Duration::from_millis(100))] { + let storage = client.storage_client(timeout); + let storage = storage.get().await.unwrap(); + let deadline = if timeout.is_some() { + Duration::from_millis(500) + } else { + Duration::from_secs(3) + }; + let result = tokio::time::timeout( + deadline, + storage + .put(format!("https://{address}/object")) + .body("bytes") + .send(), + ) + .await; + let error = result + .expect("storage connection timeout must finish") + .unwrap_err(); + assert!(error.is_connect() && error.is_timeout(), "{error}"); + } + shutdown.send(()).unwrap(); + assert_eq!(server.await.unwrap(), 2); +} + #[tokio::test] async fn tls_handshake_timeout_still_retries() { for request_type in [RequestType::CreateSession, RequestType::ExecuteStatement] { diff --git a/src/client/mod.rs b/src/client/mod.rs index af553abf..4205b276 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -36,7 +36,7 @@ pub mod retry; pub mod sea; pub(crate) mod transport; -fn error_chain<'a>( +pub(crate) fn error_chain<'a>( error: &'a (dyn std::error::Error + 'static), ) -> impl Iterator { std::iter::successors(Some(error), |error| { diff --git a/src/client/sea.rs b/src/client/sea.rs index a5aa3563..f0163cb0 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -2400,6 +2400,7 @@ mod tests { error_details_json: None, }, manifest: Some(ResultManifest { + is_volume_operation: false, format: "ARROW_STREAM".to_string(), schema: ResultSchema { column_count: 0, diff --git a/src/config.rs b/src/config.rs index 9c1eb0a9..4457382b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -755,8 +755,14 @@ pub struct HttpConfig { /// 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. pub request_timeout: Duration, + /// Idle limit for Volume file transfers: a transfer fails after this long + /// without progress. Also caps connection setup. None sets no limit. + /// Exception: a PUT that storage redirects is resent without this limit. + pub storage_read_timeout: Option, + /// Maximum total time across retries for a single logical RPC. /// Retrying stops once cumulative elapsed time exceeds this. pub overall_timeout: Duration, @@ -836,6 +842,7 @@ impl Default for HttpConfig { Self { sea_response_compression_enabled: false, request_timeout: Duration::from_secs(120), + storage_read_timeout: None, overall_timeout: Duration::from_secs(900), pool_max_idle_per_host: 100, // Mirror `RetryConfig::default()` so a stock `HttpConfig` diff --git a/src/kernel_error.rs b/src/kernel_error.rs index ecfb7fb2..a5126853 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -41,12 +41,10 @@ //! Aborted, Unimplemented, …) lands in a follow-on PR. External //! `match` arms get a forced `_ =>` fallback — they keep compiling //! when the enum grows. -//! - `Error` **is not** `#[non_exhaustive]`: wrappers want to -//! pattern-match (`let Error { code, message, sql_state, .. }`) for -//! logging and host-language exception mapping. New fields go -//! through `Error::new(...).with_*(...)`, so adding a field is -//! non-breaking without the marker. Keeping the marker would block -//! useful pattern-matches for no real benefit. +//! - `Error` **is not** `#[non_exhaustive]`, so wrappers can pattern-match +//! (`let Error { code, message, sql_state, .. }`). Build it with +//! `Error::new(...).with_*(...)`: a struct literal stops compiling when a +//! field is added. #![allow(dead_code)] @@ -169,9 +167,6 @@ impl ErrorCode { /// chain `with_*` setters. **Pattern-matching is supported** — /// wrappers writing a comprehensive logger or host-language exception /// adapter can do `let Error { code, message, sql_state, .. } = err;`. -/// New fields land through additive setters, so the type does not -/// need `#[non_exhaustive]` (and the marker would block the -/// pattern-matching wrappers actually want). #[derive(Debug, Clone)] pub struct Error { pub code: ErrorCode, @@ -180,8 +175,8 @@ pub struct Error { /// 5-character SQLSTATE if the server returned one. pub sql_state: Option, - /// Databricks-specific error identifier from the SEA - /// `ServiceError.error_code` envelope — a stable string slug like + /// Stable error identifier from the kernel or the SEA + /// `ServiceError.error_code` envelope, such as /// `STATEMENT_NOT_FOUND` or `WAREHOUSE_STOPPED` that wrappers can /// branch on to map to host-language exceptions (PySQL's /// `OperationalError` taxonomy, JDBC's `SQLException` subclasses). @@ -248,6 +243,32 @@ pub struct Error { /// Underlying cause. Boxed to keep the struct stack-friendly. pub cause: Option>, + + /// Original local filesystem failure, for host-language OS error mapping. + pub local_error: Option>, +} + +/// The OS error behind a failed local file operation. +#[non_exhaustive] +#[derive(Debug, Clone)] +pub struct LocalFileError { + pub raw_os_error: Option, + pub kind: std::io::ErrorKind, + pub path: String, +} + +impl LocalFileError { + pub fn new( + raw_os_error: Option, + kind: std::io::ErrorKind, + path: impl Into, + ) -> Self { + Self { + raw_os_error, + kind, + path: path.into(), + } + } } impl Error { @@ -270,6 +291,7 @@ impl Error { diagnostic_info: None, error_details_json: None, cause: None, + local_error: None, } } @@ -442,6 +464,11 @@ impl Error { self } + pub fn with_local_error(mut self, local_error: LocalFileError) -> Self { + self.local_error = Some(Box::new(local_error)); + self + } + pub fn with_vendor_code(mut self, vendor_code: i32) -> Self { self.vendor_code = Some(vendor_code); self diff --git a/src/lib.rs b/src/lib.rs index 00340e94..4a189d3f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -127,6 +127,7 @@ pub mod metadata_v0; pub mod result_stream; pub mod session; pub(crate) mod util; +mod volume; // Custom C ABI for ODBC / Go consumers (lives in the core crate; see // `c_abi` module docs for why it is not a separate crate like pyo3 / napi). @@ -138,7 +139,7 @@ pub use config::{ LoggingConfig, ProxyConfig, ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, TokenCacheConfig, TransportMode, }; -pub use kernel_error::{Error, ErrorCode, Result}; +pub use kernel_error::{Error, ErrorCode, LocalFileError, Result}; /// The `tracing` target string stamped on every kernel log event. /// Binding crates (pyo3, napi) reference this constant directly so the /// logger name they expose to users can never drift from what the @@ -157,6 +158,7 @@ pub use statement::params_codec::parse_typed_value; pub use statement::spec::{ResultFormat, StatementSpec, TypedValue}; pub use statement::{MAX_CLIENT_QUERY_TIMEOUT, MAX_CLIENT_QUERY_TIMEOUT_MS}; pub use telemetry::DriverSystemConfiguration; +pub use volume::{VolumeCompletion, VolumeOptions}; // === Compile-time guarantees on auto-traits === // diff --git a/src/reader/mod.rs b/src/reader/mod.rs index fd616540..b89a31e9 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1472,6 +1472,7 @@ mod tests { fn make_manifest(columns: Vec) -> ResultManifest { ResultManifest { + is_volume_operation: false, format: "ARROW_STREAM".to_string(), schema: ResultSchema { column_count: columns.len() as i32, @@ -2149,6 +2150,7 @@ mod tests { fn minimal_manifest(total_chunk_count: Option) -> ResultManifest { ResultManifest { + is_volume_operation: false, format: "ARROW_STREAM".to_string(), schema: ResultSchema { column_count: 0, diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index 4c5c82ce..cc3f80cf 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -469,6 +469,7 @@ mod tests { fn make_manifest(columns: Vec) -> ResultManifest { ResultManifest { + is_volume_operation: false, format: "ARROW_STREAM".to_string(), schema: ResultSchema { column_count: columns.len() as i32, diff --git a/src/result_stream.rs b/src/result_stream.rs index 721424e1..f3b3d666 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -58,6 +58,7 @@ use arrow_array::types::{ use arrow_array::{Array, RecordBatch}; use arrow_schema::{DataType, Schema, TimeUnit}; use chrono::{NaiveDate, NaiveDateTime}; +use std::collections::VecDeque; use std::sync::Arc; /// Cheap-clone reference to a result schema. The kernel hands one @@ -90,7 +91,7 @@ pub enum TryNextBatch<'a> { End, } -type Prefetched = Option>>; +type Prefetched = VecDeque>>; // `ResultBatch::into_arrow()` was deliberately removed: the // `#[non_exhaustive]` envelope is the right escape hatch already. @@ -466,7 +467,7 @@ pub struct ResultStream { /// until the next call to `next_batch` replaces it. current: Option, - /// A peek must preserve both data and read errors for the caller's fetch. + /// Batches and read errors already pulled from the reader but not yet returned to the caller. prefetched: Prefetched, /// Row cursor inside [`current`](Self::current). Reset to `0` @@ -493,6 +494,7 @@ pub struct ResultStream { close_guard: Option, telemetry: Option, + volume: Option>, } struct ResultStreamTelemetry { @@ -603,11 +605,12 @@ impl ResultStream { reader: Some(reader), schema, current: None, - prefetched: None, + prefetched: VecDeque::new(), current_row_idx: 0, exhausted: false, close_guard: None, telemetry: None, + volume: None, }) } @@ -638,6 +641,102 @@ impl ResultStream { Ok(stream) } + pub(crate) fn attach_volume(&mut self, state: Arc) { + self.volume = Some(state); + } + + /// True when the server marked this result as a Volume PUT, GET or REMOVE. + pub fn is_volume_operation(&self) -> bool { + self.volume.is_some() + } + + /// Runs the file transfer for a Volume PUT, GET or REMOVE result. + /// + /// Call before reading rows; the rows stay readable afterwards. The outcome, + /// success or failure, is cached, so a repeat call does not transfer again. + /// A GET downloads to a temporary file and then copies it over the destination, + /// so a failed download leaves an existing file unchanged. + /// A failure during that copy can leave the destination partly written. + /// A file PUT that storage redirects with 307 or 308 is resent from memory, + /// so that upload needs memory equal to the file size. + /// Cancelling does not undo work already done: a PUT or REMOVE may already + /// have reached storage, and a copy that has started runs to the end. + /// Results from [`Session::attach_async_statement`](crate::Session::attach_async_statement) + /// cannot run transfers and return `NotVolume`. + pub async fn complete_volume_operation( + &mut self, + options: &crate::volume::VolumeOptions, + input_bytes: Option>, + ) -> Result { + let Some(state) = self.volume.clone() else { + return Ok(crate::volume::VolumeCompletion::NotVolume); + }; + if !state.completion.initialized() + && (self.current.is_some() || (self.exhausted && self.prefetched.is_empty())) + { + return Err(Error::invalid_state() + .message("complete_volume_operation must be called before reading result rows")); + } + let result = state + .complete( + async { + let batch = loop { + let batch = self.peek_first_batch().await?.ok_or_else(|| { + Error::invalid_argument() + .with_error_code("VOLUME_INVALID_INSTRUCTION") + .message("Missing Volume instruction row") + })?; + let ResultBatch::Arrow(batch) = batch; + if batch.num_rows() != 0 { + break batch.clone(); + } + self.prefetched.pop_front(); + }; + // Read to the end before transferring: a result with more than one row is rejected. + while !self.exhausted { + match self + .reader + .as_mut() + .expect("Volume completion retains its reader") + .next_batch() + .await + { + Err(error) => { + self.prefetched.push_back(Err(Box::new(error.clone()))); + return Err(error); + } + Ok(Some(batch)) if batch.num_rows() != 0 => { + self.prefetched.push_back(Ok(ResultBatch::Arrow(batch))); + return Err(Error::invalid_argument() + .with_error_code("VOLUME_INVALID_INSTRUCTION") + .message("Expected one Volume instruction row")); + } + Ok(Some(_)) => {} + Ok(None) => self.exhausted = true, + } + } + Ok(batch) + }, + options, + input_bytes, + ) + .await; + if let Err(error) = &result { + self.finalize_telemetry(Some(error)); + } + 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(); + } + } + pub(crate) fn attach_telemetry(&mut self, telemetry: StatementTelemetry) { self.telemetry = Some(ResultStreamTelemetry::new(telemetry)); } @@ -711,9 +810,9 @@ impl ResultStream { /// performed on this path, so calling from a tokio runtime /// (napi-rs, PyO3 async) is safe. pub async fn next_batch(&mut self) -> Result> { - // A batch buffered by `peek_first_batch` is replayed here first, - // so a non-consuming peek doesn't steal it from the caller. - if let Some(batch) = self.prefetched.take() { + // Return buffered batches first, so rows read ahead by a peek or by Volume + // completion still reach the caller. + if let Some(batch) = self.prefetched.pop_front() { self.set_current_batch(batch.map_err(|error| *error)?); return Ok(self.current.as_ref()); } @@ -747,7 +846,7 @@ impl ResultStream { /// Return the next batch if it is already available without waiting for /// network or background-prefetch progress. pub fn try_next_batch(&mut self) -> Result> { - if let Some(batch) = self.prefetched.take() { + if let Some(batch) = self.prefetched.pop_front() { self.set_current_batch(batch.map_err(|error| *error)?); return Ok(TryNextBatch::Ready( self.current.as_ref().expect("batch was just installed"), @@ -784,23 +883,17 @@ impl ResultStream { } } - /// Non-consuming peek at the **first** batch of the stream. - /// - /// Buffers the first batch or error so the caller's next read observes - /// the same outcome. Returns `None` for an empty - /// stream. Only valid before any `next_batch`/`peek_first_batch` has - /// run (it no-ops if a batch is already current or buffered), which is - /// the only context it's used in: deriving a DML row-count off the - /// terminal result at statement-construction time. + /// Before the first next_batch, returns the first batch without consuming it. + /// The following next_batch returns the same batch or error. pub(crate) async fn peek_first_batch(&mut self) -> Result> { - if self.prefetched.is_none() && self.current.is_none() && !self.exhausted { + if self.prefetched.is_empty() && self.current.is_none() && !self.exhausted { let reader = self .reader .as_mut() .expect("ResultStream reader is present until into_owned_batches consumes it"); match reader.next_batch().await { Ok(Some(rb)) => { - self.prefetched = Some(Ok(ResultBatch::Arrow(rb))); + self.prefetched.push_back(Ok(ResultBatch::Arrow(rb))); // Stamp first-batch (result-set-ready) latency at fetch // time, not when the caller later consumes the prefetched // batch via `next_batch`. `record_result_batch` is @@ -810,7 +903,7 @@ impl ResultStream { // result set became ready rather than the caller's // think-time before the first `next_batch` pull. if let (Some(telemetry), Some(Ok(batch))) = - (&self.telemetry, self.prefetched.as_ref()) + (&self.telemetry, self.prefetched.front()) { telemetry.record_batch(batch); } @@ -818,12 +911,12 @@ impl ResultStream { Ok(None) => self.exhausted = true, Err(e) => { self.finalize_telemetry(Some(&e)); - self.prefetched = Some(Err(Box::new(e.clone()))); + self.prefetched.push_back(Err(Box::new(e.clone()))); return Err(e); } } } - match self.prefetched.as_ref() { + match self.prefetched.front() { Some(Ok(batch)) => Ok(Some(batch)), Some(Err(error)) => Err((**error).clone()), None => Ok(None), @@ -916,13 +1009,11 @@ impl ResultStream { /// runtime at all. Errors are surfaced once; subsequent calls /// after an `Err` keep returning `None`. pub fn into_owned_batches(mut self) -> OwnedBatchIter { - // Preserve a peeked-but-not-yet-consumed first batch: it was - // pulled from the reader, so it must be yielded ahead of the - // reader's remaining batches or it would be silently dropped. - let prefetched = self - .prefetched - .take() - .map(|outcome| outcome.map(|ResultBatch::Arrow(rb)| rb)); + // Buffered batches were read first, so yield them first to keep row order. + let prefetched = std::mem::take(&mut self.prefetched) + .into_iter() + .map(|outcome| outcome.map(|ResultBatch::Arrow(rb)| rb)) + .collect(); OwnedBatchIter { reader: self .reader @@ -969,7 +1060,7 @@ impl Iterator for OwnedBatchIter { if self.done { return None; } - if let Some(outcome) = self.prefetched.take() { + if let Some(outcome) = self.prefetched.pop_front() { return match outcome { Ok(batch) => { if let Some(telemetry) = &self.telemetry { @@ -1401,16 +1492,19 @@ mod tests { let schema = schema_for(vec![Field::new("a", DataType::Int32, false)]); let b1 = RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![1, 2]))]) .unwrap(); - let b2 = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![3]))]).unwrap(); - let reader = InMemoryReader::new(b1.schema(), vec![b1.clone(), b2.clone()]); + let b2 = RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![3]))]) + .unwrap(); + let b3 = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![4]))]).unwrap(); + let reader = InMemoryReader::new(b1.schema(), vec![b1.clone(), b2.clone(), b3.clone()]); let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); assert!(stream.peek_first_batch().await.unwrap().is_some()); let mut iter = stream.into_owned_batches(); let first = iter.next().unwrap().unwrap(); - assert_eq!(first.num_rows(), 2); + assert_eq!(first, b1); let second = iter.next().unwrap().unwrap(); - assert_eq!(second.num_rows(), 1); + assert_eq!(second, b2); + assert_eq!(iter.next().unwrap().unwrap(), b3); assert!(iter.next().is_none(), "exhausted iterator returns None"); assert!(iter.next().is_none(), "still None on subsequent calls"); } diff --git a/src/session.rs b/src/session.rs index ac2f462f..8824c02f 100644 --- a/src/session.rs +++ b/src/session.rs @@ -97,6 +97,9 @@ pub(crate) struct SessionInner { /// behind the trait object; future variants slot in via /// `TransportMode`. transport: Arc, + storage_client: Arc, + storage_retry: RetryConfig, + volume_cancellation: tokio_util::sync::CancellationToken, /// Server-issued session identifier. session_id: String, @@ -158,6 +161,18 @@ pub(crate) struct SessionInner { } impl SessionInner { + pub(crate) fn new_volume_state(&self) -> Arc { + crate::volume::VolumeState::new( + self.storage_retry.clone(), + Arc::clone(&self.storage_client), + self.volume_cancellation.child_token(), + ) + } + + fn cancel_volume_operations(&self) { + self.volume_cancellation.cancel(); + } + /// Crate-internal accessor for the session's transport. Used by /// `Metadata` (and PR 4's `Statement`) to drive RPCs without /// reaching into private fields. @@ -226,6 +241,7 @@ impl SessionInner { /// explicit close genuinely *initiates* the delete rather than /// deferring it to an idle-timeout. pub(crate) fn initiate_delete(&self) { + self.cancel_volume_operations(); if self .closed .compare_exchange( @@ -367,11 +383,13 @@ impl Session { // it for OIDC discovery / token endpoint calls. let http_client_config = build_http_client_config(&config, org_id); let retry_configs = build_retry_configs_for_session(&config); + let storage_retry = retry_configs[&RequestCategory::Sea].clone(); let http_client = Arc::new( DatabricksHttpClient::new(http_client_config, retry_configs).map_err(|e| { Error::network_error().message(format!("Failed to construct HTTP client: {e}")) })?, ); + let storage_client = Arc::new(http_client.storage_client(config.http.storage_read_timeout)); // 2. Auth provider — async because OAuth flows hit the OIDC // discovery endpoint. @@ -472,6 +490,9 @@ impl Session { Ok(Session { inner: Arc::new(SessionInner { transport, + storage_client, + storage_retry, + volume_cancellation: tokio_util::sync::CancellationToken::new(), session_id: session_info.session_id, config, runtime_handle, @@ -778,6 +799,7 @@ impl Session { /// race): flag stays false, [`Drop`] picks up the slack. /// - On `Ok`: flag flips, [`Drop`] is a no-op. pub async fn close(self) -> Result<()> { + self.inner.cancel_volume_operations(); // Bail early if a concurrent caller already finished a // successful close — no point hitting the wire twice. if self.inner.closed.load(std::sync::atomic::Ordering::Acquire) { diff --git a/src/statement/executed.rs b/src/statement/executed.rs index 025db78e..ee852c5c 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -189,6 +189,7 @@ impl ExecutedStatement { } async fn close_server_statement(&self) -> Result<()> { + self.result_stream.cancel_volume(); // Idempotent on success: a prior successful close sets // `closed=true` and subsequent calls short-circuit. // @@ -348,6 +349,7 @@ impl ExecutedStatementHandle for ExecutedStatement { } async fn cancel(&self) -> Result<()> { + self.result_stream.cancel_volume(); // Local validity short-circuits a wire call against an // already-closed/superseded handle. `instrument` (rather // than `.entered()`) so the future stays `Send` per the @@ -370,6 +372,7 @@ impl ExecutedStatementHandle for ExecutedStatement { impl Drop for ExecutedStatement { fn drop(&mut self) { + self.result_stream.cancel_volume(); // Backstop for the not-fully-drained case (partial fetch / // abandoned result / early error): if the stream was drained, // `next_batch`'s auto-close already fired and flipped `closed`, diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index f9dfc2ac..28c2d379 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -172,6 +172,7 @@ impl StatementStatus { /// Async-consumption executed handle. pub struct ExecutedAsyncStatement { + volume: Option>, session: Arc, statement_id: String, /// Shared with the parent `Statement`; flipped on re-execute or @@ -276,10 +277,17 @@ fn deadline_policy(timeout: ExecutionTimeout) -> (Option, bo } impl ExecutedAsyncStatement { + fn cancel_volume(&self) { + if let Some(volume) = &self.volume { + volume.cancel(); + } + } + /// Produce the stable client query-timeout error and schedule bounded, /// best-effort server cleanup when a deadline retained across /// caller-driven status polls expires. pub(crate) fn expire_client_query_timeout(&self) -> Error { + self.cancel_volume(); self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); if !self.client_timeout_expired.swap(true, Ordering::AcqRel) { @@ -313,6 +321,7 @@ impl ExecutedAsyncStatement { /// deadline and the transport's default `poll_timeout` ceiling; /// `Default` keeps the `poll_timeout` ceiling with no client /// deadline. + #[allow(clippy::too_many_arguments)] pub(crate) fn new( session: Arc, statement_id: String, @@ -321,6 +330,7 @@ impl ExecutedAsyncStatement { initial_status: crate::types::sea::StatementStatus, statement_telemetry: StatementTelemetry, timeout: ExecutionTimeout, + volume: Arc, ) -> Self { let (client_deadline, poll_timeout_disabled) = deadline_policy(timeout); let initial_terminal = initial_status.state.is_terminal(); @@ -330,6 +340,7 @@ impl ExecutedAsyncStatement { valid, closed, owner_released: Arc::new(AtomicBool::new(false)), + volume: Some(volume), // The submitting handle owns the statement lifecycle. owning: true, session_attribution: SessionAttribution::Current, @@ -391,6 +402,7 @@ impl ExecutedAsyncStatement { valid, closed: Arc::new(AtomicBool::new(true)), owner_released, + volume: None, owning: false, session_attribution, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), @@ -413,16 +425,16 @@ impl ExecutedAsyncStatement { .lock() .map_err(|error| Error::internal().message(format!("Statement status lock: {error}")))? .clone(); - Ok(AsyncStatementReader { - inner: Self::new_read_only( - Arc::clone(&self.session), - self.statement_id.clone(), - self.valid.clone(), - Arc::clone(&self.owner_released), - self.session_attribution, - status, - ), - }) + let mut inner = Self::new_read_only( + Arc::clone(&self.session), + self.statement_id.clone(), + self.valid.clone(), + Arc::clone(&self.owner_released), + self.session_attribution, + status, + ); + inner.volume = self.volume.clone(); + Ok(AsyncStatementReader { inner }) } fn check_owner_available(&self) -> Result<()> { @@ -940,7 +952,16 @@ impl ExecutedAsyncStatement { if result.status.state == crate::types::sea::StatementState::Closed { self.closed.store(true, Ordering::Release); } + let marked = result + .manifest + .as_ref() + .is_some_and(|m| m.is_volume_operation); let mut stream = ResultStream::from_reader(result.reader).await?; + if marked { + if let Some(volume) = &self.volume { + stream.attach_volume(Arc::clone(volume)); + } + } stream.attach_telemetry(self.statement_telemetry.clone()); // SEA carries no row count on the async status either; for a // DML the count rides in the result set. Derive it once @@ -1086,6 +1107,7 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement { submitted it", )); } + self.cancel_volume(); self.session .transport() .cancel_statement(&self.statement_id) @@ -1116,6 +1138,7 @@ impl ExecutedAsyncStatement { async fn close_server_statement(&self) -> Result<()> { if self.owning { + self.cancel_volume(); self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); } @@ -1176,6 +1199,7 @@ impl ExecutedAsyncStatement { // either — otherwise the footgun just moves to the detached // canceller. owning: self.owning, + volume: self.volume.clone(), } } } @@ -1192,6 +1216,7 @@ impl ExecutedAsyncStatement { /// Cheap to [`Clone`] (one `Arc` bump plus a `String` / flag clone). #[derive(Clone)] pub struct AsyncStatementCanceller { + volume: Option>, session: Arc, statement_id: String, valid: ValidityFlag, @@ -1203,6 +1228,15 @@ pub struct AsyncStatementCanceller { } impl AsyncStatementCanceller { + /// Cancel local Volume completion without waiting for a server request. + pub fn cancel_volume_operation(&self) { + if self.owning { + if let Some(volume) = &self.volume { + volume.cancel(); + } + } + } + /// Server-side cancel via `cancel_statement(statement_id)`. /// /// Short-circuits to `InvalidStatementHandle` (no wire round-trip) @@ -1223,6 +1257,7 @@ impl AsyncStatementCanceller { is owned by whoever submitted it", )); } + self.cancel_volume_operation(); self.session .transport() .cancel_statement(&self.statement_id) @@ -1241,6 +1276,7 @@ impl AsyncStatementCanceller { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { if self.owning { + self.cancel_volume(); self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); } diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 34baf1d1..ab286573 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -245,12 +245,17 @@ pub struct Statement { /// new `execute()` / `submit()` so a canceller never targets a /// stale prior statement. inflight_id: InflightId, + /// Volume transfer state of the current execution, shared with any + /// [`StatementCanceller`]. Replaced at the start of each new execution, so + /// a canceller always reaches the current transfer. + volume: Arc>>, } impl Statement { /// Construct a new statement bound to `session`. Crate-private — /// wrappers obtain a `Statement` via `Session::statement()`. pub(crate) fn new(session: Arc) -> Self { + let volume = session.new_volume_state(); Self { session, spec: StatementSpec::new(), @@ -258,6 +263,7 @@ impl Statement { last_valid: None, last_closed: None, inflight_id: Arc::new(Mutex::new(None)), + volume: Arc::new(Mutex::new(volume)), } } @@ -282,6 +288,7 @@ impl Statement { StatementCanceller { session: Arc::clone(&self.session), inflight_id: Arc::clone(&self.inflight_id), + volume: Arc::clone(&self.volume), } } @@ -409,7 +416,14 @@ impl Statement { self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); + let marked = result + .manifest + .as_ref() + .is_some_and(|m| m.is_volume_operation); let mut result_stream = ResultStream::from_reader(result.reader).await?; + if marked { + result_stream.attach_volume(self.volume_state()); + } result_stream.attach_telemetry(telemetry_for_body.clone()); // SEA puts no row count on the status envelope; for a DML it // returns the count as the result set. If the server didn't @@ -549,6 +563,7 @@ impl Statement { response.status, telemetry_for_body, timeout, + self.volume_state(), )) } .instrument(span) @@ -644,7 +659,14 @@ impl Statement { self.last_statement_id = Some(result.statement_id.clone()); self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); + let marked = result + .manifest + .as_ref() + .is_some_and(|m| m.is_volume_operation); let mut result_stream = ResultStream::from_reader(result.reader).await?; + if marked { + result_stream.attach_volume(self.volume_state()); + } result_stream.attach_telemetry(telemetry_for_body.clone()); let mut status = result.status; if status.num_modified_rows.is_none() { @@ -685,6 +707,7 @@ impl Statement { resp.status, telemetry_for_body, ExecutionTimeout::Default, + self.volume_state(), ))) } } @@ -697,6 +720,10 @@ impl Statement { result } + fn volume_state(&self) -> Arc { + Arc::clone(&self.volume.lock().unwrap_or_else(|e| e.into_inner())) + } + fn statement_telemetry(&self, operation_type: OperationType) -> StatementTelemetry { self.session .statement_telemetry_observer(StatementType::Sql, operation_type) @@ -729,6 +756,7 @@ impl Statement { /// for callers that forget to call `close()` explicitly, but /// the explicit path is the supported one. pub async fn close(mut self) -> Result<()> { + self.volume_state().cancel(); let span = self.session.log_span().clone(); async { self.invalidate_prior().await; @@ -759,8 +787,8 @@ impl Statement { build_execute_params(&self.spec, wait_timeout_secs) } - /// Clear the shared in-flight-id slot at the very start of a new - /// dispatch, before any `.await`. + /// Clear the shared in-flight-id slot and replace the Volume transfer + /// state at the very start of a new dispatch, before any `.await`. /// /// The slot still holds the *prior* execution's server statement id /// until this runs. A [`StatementCanceller`] retained across a @@ -775,11 +803,18 @@ impl Statement { /// nothing: a canceller firing before the new id is observed is a /// tolerated no-op (`dispatched = false`), never a hit on the stale id. /// + /// The prior execution's Volume transfer is cancelled and a fresh state + /// installed in the same step, so a retained canceller reaches the new + /// execution's transfer, not the previous one. + /// /// Kept out of [`invalidate_prior`] deliberately — that is also called /// by [`Statement::close`], where the slot must survive so a detached /// canceller can still dispatch against the just-closed statement (its /// cloned session `Arc` keeps the client side alive). fn reset_inflight_slot(&self) { + let mut volume = self.volume.lock().unwrap_or_else(|e| e.into_inner()); + volume.cancel(); + *volume = self.session.new_volume_state(); if let Ok(mut slot) = self.inflight_id.lock() { *slot = None; } @@ -923,19 +958,28 @@ impl Drop for MidExecuteCancelGuard { /// [`Statement`]. Produced by [`Statement::canceller`]. /// /// Holds only the shared session handle and the `Statement`'s shared -/// in-flight-id slot — **not** the `Statement` itself — so a binding -/// can fire a server-side cancel from another thread while `execute()` -/// is blocked. The sync-execute analogue of +/// in-flight-id slot and its Volume transfer state — **not** the `Statement` +/// itself — so a binding can fire a server-side cancel from another thread +/// while `execute()` is blocked. The sync-execute analogue of /// [`AsyncStatementCanceller`](crate::statement::executed_async::AsyncStatementCanceller). /// -/// Cheap to [`Clone`] (two `Arc` bumps). +/// Cheap to [`Clone`] (three `Arc` bumps). #[derive(Clone)] pub struct StatementCanceller { session: Arc, inflight_id: InflightId, + volume: Arc>>, } impl StatementCanceller { + /// Cancel local Volume completion without waiting for a server request. + pub fn cancel_volume_operation(&self) { + self.volume + .lock() + .unwrap_or_else(|e| e.into_inner()) + .cancel(); + } + /// Server-side cancel of the in-flight statement via /// `cancel_statement(statement_id)`. /// @@ -958,8 +1002,10 @@ impl StatementCanceller { /// Idempotent against a server already in a terminal state (the /// kernel's `cancel_statement` is a no-op there). Safe to call /// concurrently with the `execute()` it targets — the two share - /// only the id slot (behind a `Mutex`), no mutable statement state. + /// only the id slot and the Volume state (each behind a `Mutex`), no + /// mutable statement state. pub async fn cancel(&self) -> Result { + self.cancel_volume_operation(); let id = self.inflight_id.lock().ok().and_then(|g| g.clone()); async { // Log both outcomes at the decision point so a host debugging a diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 42505bc7..8ceee6c4 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -292,12 +292,12 @@ fn duration_millis(duration: Duration) -> i64 { mod tests { use super::*; use crate::kernel_error::ErrorCode; - use crate::reader::test_utils::ErrorReader; + use crate::reader::test_utils::{BatchThenErrorReader, ErrorReader, MockReader}; use crate::reader::{ResultReader, ResultReaderMetrics}; use crate::result_stream::ResultStream; use crate::telemetry::models::OperationType; use crate::telemetry::runtime::{ConnectionTelemetry, TelemetrySessionContext}; - use arrow_array::RecordBatch; + use arrow_array::{RecordBatch, RecordBatchOptions}; use arrow_schema::Schema; use async_trait::async_trait; use std::future::Future; @@ -407,6 +407,97 @@ mod tests { ); } + #[tokio::test] + async fn volume_errors_finalize_statement_with_error_before_drop() { + enum Case { + VolumeReader, + Instruction, + } + for case in [Case::VolumeReader, Case::Instruction] { + let connection = Arc::new(CapturingConnectionTelemetry::default()); + let telemetry = StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + ); + let schema = Arc::new(Schema::empty()); + let batch = RecordBatch::try_new_with_options( + schema.clone(), + vec![], + &RecordBatchOptions::new().with_row_count(Some(1)), + ) + .expect("one-row batch"); + let (reader, code, message): (Box, _, _) = match case { + Case::VolumeReader => ( + Box::new(BatchThenErrorReader { + batch: Some(batch), + schema, + }), + ErrorCode::Internal, + "simulated read error after first batch", + ), + Case::Instruction => ( + Box::new(MockReader::new(vec![batch])), + ErrorCode::InvalidArgument, + "Missing Volume instruction column", + ), + }; + let mut stream = ResultStream::from_reader(reader) + .await + .expect("schema succeeds"); + stream.attach_telemetry(telemetry); + + stream.attach_volume(crate::volume::VolumeState::new( + Default::default(), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(None), + ), + Default::default(), + )); + let options = Default::default(); + let error = stream + .complete_volume_operation(&options, None) + .await + .unwrap_err(); + let cached = stream + .complete_volume_operation(&options, None) + .await + .unwrap_err(); + assert_eq!(cached.code, error.code); + assert_eq!(cached.message, error.message); + assert_eq!(error.code, code); + assert_eq!(error.message, message); + let events_before_drop = connection + .statement_events + .lock() + .expect("events mutex") + .len(); + assert_eq!( + events_before_drop, 1, + "terminal error must finalize before Drop" + ); + + drop(stream); + + let events = connection.statement_events.lock().expect("events mutex"); + assert_eq!( + events.len(), + 1, + "terminal error should finalize once; Drop must not overwrite it with success" + ); + let event = &events[0]; + assert_eq!(event.context.statement_type, StatementType::Sql); + assert_eq!(event.error_code, Some(code)); + assert_eq!(event.error_message.as_deref(), Some(message)); + assert!( + event.context.consumption_latency.is_some(), + "failed consumption should still record result-consumption latency" + ); + } + } + #[tokio::test] async fn dropping_result_stream_finalizes_with_reader_metrics() { let connection = Arc::new(CapturingConnectionTelemetry::default()); diff --git a/src/types/sea.rs b/src/types/sea.rs index 8d988dad..62f674ea 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -184,6 +184,8 @@ pub struct ServiceError { /// Manifest describing the result set structure. #[derive(Debug, Clone, Deserialize)] pub struct ResultManifest { + #[serde(default)] + pub is_volume_operation: bool, pub format: String, pub schema: ResultSchema, /// Physical Arrow schema carried by SEA as a schema-only IPC stream. diff --git a/src/volume.rs b/src/volume.rs new file mode 100644 index 00000000..674a8d7a --- /dev/null +++ b/src/volume.rs @@ -0,0 +1,1985 @@ +// 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. + +//! File transfers for Volume PUT, GET and REMOVE statements. +//! +//! The server answers these statements with one row holding a presigned +//! storage URL, request headers and a local path. This module makes that +//! storage request when the caller asks. + +use crate::client::retry::{calculate_backoff, RequestType, RetryConfig, RetryStrategy}; +use crate::kernel_error::{Error, LocalFileError, Result}; +use arrow_array::{Array, LargeStringArray, MapArray, RecordBatch, StringArray, StringViewArray}; +use futures::TryStreamExt; +use reqwest::{header::HeaderMap, Client, Method}; +use std::path::{Component, Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use tokio::io::AsyncWriteExt; +use tokio::sync::OnceCell; +use tokio_util::bytes::Bytes; +use tokio_util::io::ReaderStream; +use tokio_util::sync::CancellationToken; + +/// Caller settings for a Volume file transfer. +#[non_exhaustive] +#[derive(Debug, Clone, Default)] +pub struct VolumeOptions { + /// Local directories a PUT may read from and a GET may write to. Both the + /// path named in the statement and the file it resolves to through + /// symlinks must be inside one of them. Empty allows no local file access. + /// The check runs before the file is opened, so nothing else may swap + /// files or links in these directories during a transfer. + pub allowed_paths: Vec, + /// Report success when REMOVE targets a file that does not exist. + pub remove_not_found_is_success: bool, +} + +impl VolumeOptions { + pub fn new(allowed_paths: Vec, remove_not_found_is_success: bool) -> Self { + Self { + allowed_paths, + remove_not_found_is_success, + } + } +} + +/// Outcome of `ResultStream::complete_volume_operation`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(C)] +pub enum VolumeCompletion { + /// The result is not a Volume statement; nothing was done. + NotVolume = 0, + /// The PUT uploads caller-supplied bytes; call again with `input_bytes`. + NeedsInputStream = 1, + /// The transfer finished. + Completed = 2, +} + +pub(crate) struct VolumeState { + retry: RetryConfig, + storage: Arc, + /// Unset until the transfer reaches a final outcome. A PUT waiting for caller bytes leaves it unset. + pub(crate) completion: OnceCell>, + cancellation: CancellationToken, + started: AtomicBool, +} + +struct Download { + temp: std::fs::File, + existing: Option, + path: PathBuf, + local_file: String, +} + +fn cancelled() -> Error { + Error::cancelled().message("Volume transfer was cancelled") +} + +impl VolumeState { + pub(crate) fn new( + retry: RetryConfig, + storage: Arc, + cancellation: CancellationToken, + ) -> Arc { + Arc::new(Self { + retry, + storage, + cancellation, + completion: OnceCell::new(), + started: AtomicBool::new(false), + }) + } + + pub(crate) fn cancel(&self) { + self.cancellation.cancel(); + } + + pub(crate) async fn complete( + &self, + prepare: impl std::future::Future>, + options: &VolumeOptions, + input_bytes: Option>, + ) -> Result { + match self + .completion + .get_or_try_init(|| async { + // If an earlier call was dropped mid-transfer, do not run the transfer again. + if self.started.swap(true, Ordering::AcqRel) || self.cancellation.is_cancelled() { + return Ok(Err(cancelled())); + } + let transfer = async { + let batch = prepare.await?; + let instruction = Instruction::decode(&batch)?; + if matches!(instruction.operation, Operation::Put(Source::Stream)) + && input_bytes.is_none() + { + return Ok::<_, Error>((VolumeCompletion::NeedsInputStream, None)); + } + let client = self.storage.get().await?; + let destination = self + .transfer(instruction, client, options, input_bytes) + .await?; + Ok((VolumeCompletion::Completed, destination)) + }; + let complete = async { + let (outcome, destination) = tokio::select! { + biased; + result = transfer => result?, + _ = self.cancellation.cancelled() => return Err(cancelled()), + }; + if let Some(Download { + mut temp, + existing, + path, + local_file, + }) = destination + { + let cancellation = self.cancellation.clone(); + tokio::task::spawn_blocking(move || { + if cancellation.is_cancelled() { + return Err(cancelled()); + } + let mut file = match existing { + Some(file) => file, + None => std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|e| local_error(e, &local_file))?, + }; + std::io::Seek::rewind(&mut temp) + .map_err(|e| local_error(e, &local_file))?; + let length = std::io::copy(&mut temp, &mut file) + .map_err(|e| local_error(e, &local_file))?; + file.set_len(length) + .map_err(|e| local_error(e, &local_file)) + }) + .await + .map_err(|e| { + Error::internal() + .message(format!("Volume download copy task failed: {e}")) + })??; + } + Ok(outcome) + }; + let result = complete.await; + if matches!(result, Ok(VolumeCompletion::NeedsInputStream)) { + self.started.store(false, Ordering::Release); + // Leave the cell uninitialized so completion can resume with input bytes. + Err(VolumeCompletion::NeedsInputStream) + } else { + Ok(result) + } + }) + .await + { + Ok(result) => result.clone(), + Err(outcome) => Ok(outcome), + } + } + + async fn transfer( + &self, + instruction: Instruction, + client: &Client, + options: &VolumeOptions, + input_bytes: Option>, + ) -> Result> { + let input = if matches!(instruction.operation, Operation::Put(Source::Stream)) { + Some(Bytes::from( + input_bytes.ok_or_else(|| invalid("Missing input stream"))?, + )) + } else { + None + }; + let mut retry_started = None; + let mut attempt = 0; + loop { + let mut retry_after = None; + let attempt_started = std::time::Instant::now(); + let error = match self + .transfer_once( + &instruction, + client, + options, + input.as_ref(), + &mut retry_after, + ) + .await + { + Ok(completion) => { + tracing::debug!( + target: crate::klog::KERNEL_LOG_TARGET, + attempt = attempt + 1, + attempt_ms = attempt_started.elapsed().as_millis() as u64, + "volume transfer attempt succeeded" + ); + return Ok(completion); + } + Err(error) => error, + }; + tracing::debug!( + target: crate::klog::KERNEL_LOG_TARGET, + attempt = attempt + 1, + attempt_ms = attempt_started.elapsed().as_millis() as u64, + retryable = error.retryable, + error = %error.message, + "volume transfer attempt failed" + ); + // The retry clock starts at the first failure, so a long transfer does not + // use up the retry budget. + let started = retry_started.get_or_insert_with(std::time::Instant::now); + if !error.retryable || attempt >= self.retry.max_retries { + return Err(error.message(format!("after {} attempts", attempt + 1))); + } + let wait = calculate_backoff(&self.retry, attempt, retry_after.as_deref()); + if started.elapsed().saturating_add(wait) >= self.retry.overall_timeout { + return Err(error.message(format!("after {} attempts", attempt + 1))); + } + tracing::debug!( + target: crate::klog::KERNEL_LOG_TARGET, + attempt = attempt + 1, + wait_ms = wait.as_millis() as u64, + "waiting before retrying volume transfer" + ); + tokio::time::sleep(wait).await; + attempt += 1; + } + } + + async fn transfer_once( + &self, + instruction: &Instruction, + client: &Client, + options: &VolumeOptions, + input: Option<&Bytes>, + retry_after: &mut Option, + ) -> Result> { + let (method, local_file, source, mut destination) = + Self::prepare_local(instruction, options).await?; + let upload = method == Method::PUT; + let remove = method == Method::DELETE; + let mut request = client + .request(method, &instruction.url) + .headers(instruction.headers.clone()); + let upload_error = Arc::new(Mutex::new(None)); + let (progress, changed) = tokio::sync::watch::channel(tokio::time::Instant::now()); + let reader: Option<(Box, u64)> = + if let Some((file, length)) = source.as_ref() { + Some(( + Box::new(tokio::fs::File::from_std( + file.try_clone().map_err(|e| local_error(e, &local_file))?, + )), + *length, + )) + } else { + input.map(|bytes| { + ( + Box::new(std::io::Cursor::new(bytes.clone())) as _, + bytes.len() as u64, + ) + }) + }; + if let Some((reader, length)) = reader { + request = request + .headers(HeaderMap::from_iter([( + reqwest::header::CONTENT_LENGTH, + length.into(), + )])) + .body(upload_body( + reader, + local_file.clone(), + Arc::clone(&upload_error), + progress, + )); + } + let mut response = storage_send( + request, + self.storage.read_timeout, + upload, + upload_error, + changed, + ) + .await?; + if matches!(response.status().as_u16(), 307 | 308) { + let bytes = match (input, source) { + (Some(bytes), _) => Some(bytes.clone()), + (None, Some((file, length))) => { + let local_file = local_file.clone(); + Some(Bytes::from( + tokio::task::spawn_blocking(move || { + read_from_start(&file, length).map_err(|e| local_error(e, &local_file)) + }) + .await + .map_err(|e| { + Error::internal() + .message(format!("Volume upload read task failed: {e}")) + })??, + )) + } + _ => None, + }; + if let Some(bytes) = bytes { + // reqwest cannot replay a streamed body on a redirect. Send the original URL again + // with the body in memory so reqwest can follow; this resend has no idle timeout. + response = client + .put(&instruction.url) + .headers(instruction.headers.clone()) + .headers(HeaderMap::from_iter([( + reqwest::header::CONTENT_LENGTH, + bytes.len().into(), + )])) + .body(reqwest::Body::from(bytes)) + .send() + .await + .map_err(storage_error)?; + } + } + let status = response.status(); + if !(status.is_success() + || (remove && status.as_u16() == 404 && options.remove_not_found_is_success)) + { + return Err(self + .storage_failure(&mut response, status, upload, retry_after) + .await); + } + self.download_body(&mut response, upload, &local_file, &mut destination) + .await?; + Ok(destination.map(|(download, writer)| { + drop(writer); + download + })) + } + + async fn prepare_local( + instruction: &Instruction, + options: &VolumeOptions, + ) -> Result<( + Method, + String, + Option<(std::fs::File, u64)>, + Option<(Download, tokio::fs::File)>, + )> { + let operation = instruction.operation.clone(); + let roots = options.allowed_paths.clone(); + let preparation = tokio::task::spawn_blocking(move || { + let mut source = None; + let mut destination = None; + let (method, local_file) = match operation { + Operation::Put(Source::File(path)) => { + let local_file = path.to_string_lossy().into_owned(); + let path = allowed_path(&local_file, &roots)?; + let mut file = + std::fs::File::open(path).map_err(|e| local_error(e, &local_file))?; + let metadata = file.metadata().map_err(|e| local_error(e, &local_file))?; + if metadata.is_dir() { + // A directory opens without error on Unix; reading it produces the OS error to report. + let error = std::io::Read::read(&mut file, &mut [0]) + .err() + .unwrap_or_else(|| std::io::ErrorKind::IsADirectory.into()); + return Err(local_error(error, &local_file)); + } + source = Some((file, metadata.len())); + (Method::PUT, local_file) + } + Operation::Get(path) => { + let local_file = path.to_string_lossy().into_owned(); + let path = allowed_path(&local_file, &roots)?; + let existing = match std::fs::OpenOptions::new().write(true).open(&path) { + Ok(file) => Some(file), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(local_error(error, &local_file)), + }; + let parent = path + .parent() + .ok_or_else(|| invalid("Missing destination parent"))?; + let temp = match tempfile::tempfile_in(parent) { + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + tempfile::tempfile() + } + other => other, + } + .map_err(|e| local_error(e, &local_file))?; + let writer = tokio::fs::File::from_std( + temp.try_clone().map_err(|e| local_error(e, &local_file))?, + ); + destination = Some(( + Download { + temp, + existing, + path, + local_file: local_file.clone(), + }, + writer, + )); + (Method::GET, local_file) + } + Operation::Put(Source::Stream) => (Method::PUT, String::new()), + Operation::Remove => (Method::DELETE, String::new()), + }; + Ok((method, local_file, source, destination)) + }); + preparation.await.map_err(|e| { + Error::internal().message(format!("Volume file preparation task failed: {e}")) + })? + } + + async fn storage_failure( + &self, + response: &mut reqwest::Response, + status: reqwest::StatusCode, + upload: bool, + retry_after: &mut Option, + ) -> Error { + *retry_after = response + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let mut error = Error::from_http_status(status.as_u16()) + .with_error_code("VOLUME_STORAGE_HTTP_ERROR") + .with_retryable( + RetryStrategy::for_request(RequestType::CloudFetchDownload, &self.retry) + .is_retryable_status(status, retry_after.is_some()), + ) + .message(format!( + "Volume storage request failed: HTTP {}", + status.as_u16() + )); + let mut body = Vec::new(); + while body.len() < 4096 { + match storage_read(self.storage.read_timeout, !upload, async { + response.chunk().await.map_err(response_body_error) + }) + .await + { + Ok(Some(chunk)) => { + body.extend_from_slice(&chunk[..chunk.len().min(4096 - body.len())]) + } + _ => break, + } + } + let text = String::from_utf8_lossy(&body); + for tag in ["Code", "Message"] { + if let Some(value) = text + .split_once(&format!("<{tag}>")) + .and_then(|(_, tail)| tail.split_once(&format!(""))) + .map(|(value, _)| value) + .filter(|value| !value.contains(['<', '>'])) + { + error = error.message(format!("{tag}: {value}")); + } + } + for (label, header) in [("RequestId", "x-amz-request-id"), ("HostId", "x-amz-id-2")] { + if let Some(value) = response + .headers() + .get(header) + .and_then(|value| value.to_str().ok()) + { + error = error.message(format!("{label}: {value}")); + } + } + error + } + + async fn download_body( + &self, + response: &mut reqwest::Response, + upload: bool, + local_file: &str, + destination: &mut Option<(Download, tokio::fs::File)>, + ) -> Result<()> { + while let Some(bytes) = storage_read(self.storage.read_timeout, !upload, async { + response.chunk().await.map_err(response_body_error) + }) + .await? + { + if let Some((_, writer)) = destination.as_mut() { + writer + .write_all(&bytes) + .await + .map_err(|e| local_error(e, local_file))?; + } + } + if let Some((_, writer)) = destination.as_mut() { + writer + .flush() + .await + .map_err(|e| local_error(e, local_file))?; + } + Ok(()) + } +} + +fn upload_body( + reader: impl tokio::io::AsyncRead + Unpin + Send + 'static, + path: String, + error: Arc>>, + progress: tokio::sync::watch::Sender, +) -> reqwest::Body { + reqwest::Body::wrap_stream( + ReaderStream::with_capacity(reader, 256 * 1024) + .inspect_ok(move |_| { + progress.send_replace(tokio::time::Instant::now()); + }) + .map_err(move |cause| { + *error.lock().unwrap_or_else(|e| e.into_inner()) = Some(local_error(cause, &path)); + std::io::Error::other("Volume upload source could not be read") + }), + ) +} + +fn invalid(message: &str) -> Error { + Error::invalid_argument() + .with_error_code("VOLUME_INVALID_INSTRUCTION") + .message(message) +} + +async fn storage_send( + request: reqwest::RequestBuilder, + timeout: Option, + upload: bool, + upload_error: Arc>>, + mut progress: tokio::sync::watch::Receiver, +) -> Result { + let send = async { request.send().await.map_err(storage_error) }; + tokio::pin!(send); + let response = if let (true, Some(timeout)) = (upload, timeout) { + loop { + let last = *progress.borrow_and_update(); + let Some(deadline) = last.checked_add(timeout) else { + break (&mut send).await; + }; + // PUT response timeouts may follow a committed write; GET retries only rewrite the temporary file. + tokio::select! { + biased; + response = &mut send => break response, + _ = progress.changed(), if progress.has_changed().is_ok() => {} + _ = tokio::time::sleep_until(deadline) => break Err(Error::network_error() + .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") + .with_retryable(false).message("Volume storage upload or response wait timed out")), + } + } + } else if upload { + send.await + } else { + storage_read(timeout, true, send).await + }; + if let Some(error) = upload_error + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take() + { + return Err(error); + } + response +} + +async fn storage_read( + timeout: Option, + retry_timeout: bool, + read: impl std::future::Future>, +) -> Result { + match timeout { + Some(timeout) => tokio::time::timeout(timeout, read) + .await + .unwrap_or_else(|_| { + Err(Error::network_error() + .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") + .with_retryable(retry_timeout) + .message("Volume storage read timed out")) + }), + None => read.await, + } +} + +fn storage_error(error: reqwest::Error) -> Error { + let retryable = + RetryStrategy::for_request(RequestType::CloudFetchDownload, &RetryConfig::default()) + .is_retryable_error(&error); + let error = error.without_url(); + let mut causes = crate::client::error_chain(&error) + .map(ToString::to_string) + .collect::>(); + causes.dedup(); + Error::network_error() + .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") + .with_retryable(retryable) + .message(format!( + "Volume storage request failed: {}", + causes.join(": ") + )) +} + +fn response_body_error(error: reqwest::Error) -> Error { + let retryable = error.is_body() || error.is_decode(); + let mut error = storage_error(error); + error.retryable |= retryable; + error +} + +/// Reads the first `length` bytes of `file` by offset. The first request's body +/// shares this handle's position and may still be moving it. +fn read_from_start(file: &std::fs::File, length: u64) -> std::io::Result> { + let length = usize::try_from(length).map_err(|_| std::io::ErrorKind::OutOfMemory)?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(length) + .map_err(|_| std::io::ErrorKind::OutOfMemory)?; + bytes.resize(length, 0); + #[cfg(unix)] + { + std::os::unix::fs::FileExt::read_exact_at(file, &mut bytes, 0)?; + Ok(bytes) + } + #[cfg(windows)] + { + use std::os::windows::fs::FileExt; + let mut filled = 0; + while filled < bytes.len() { + match file.seek_read(&mut bytes[filled..], filled as u64)? { + 0 => return Err(std::io::ErrorKind::UnexpectedEof.into()), + read => filled += read, + } + } + Ok(bytes) + } +} + +fn local_error(error: std::io::Error, path: &str) -> Error { + match error.kind() { + std::io::ErrorKind::NotFound => Error::not_found(), + std::io::ErrorKind::PermissionDenied => Error::permission_denied(), + std::io::ErrorKind::InvalidInput + | std::io::ErrorKind::IsADirectory + | std::io::ErrorKind::NotADirectory => Error::invalid_argument(), + _ => Error::io(), + } + .with_error_code("VOLUME_LOCAL_FILE_ERROR") + .with_sql_state("HY000") + .message(format!("{error}: {path}")) + .with_local_error(LocalFileError::new( + error.raw_os_error(), + error.kind(), + path, + )) +} + +fn normalize(path: &Path) -> Result { + let absolute = + std::path::absolute(path).map_err(|e| local_error(e, &path.to_string_lossy()))?; + let mut normalized = PathBuf::new(); + for component in absolute.components() { + match component { + Component::ParentDir => { + normalized.pop(); + } + Component::CurDir => {} + _ => normalized.push(component.as_os_str()), + } + } + Ok(normalized) +} + +const MAX_SYMLINK_RESOLUTIONS: u8 = 40; + +fn resolve_existing_parent( + path: &Path, + requested: &str, + remaining_symlinks: u8, +) -> Result { + match path.canonicalize() { + Ok(path) => Ok(path), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + if std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) { + if remaining_symlinks == 0 { + return Err(local_error(error, requested)); + } + let target = std::fs::read_link(path).map_err(|e| local_error(e, requested))?; + let target = if target.is_absolute() { + target + } else { + path.parent() + .ok_or_else(|| invalid("Invalid local path"))? + .join(target) + }; + return resolve_existing_parent( + &normalize(&target)?, + requested, + remaining_symlinks - 1, + ); + } + let parent = path.parent().ok_or_else(|| local_error(error, requested))?; + let name = path + .file_name() + .ok_or_else(|| invalid("Invalid local path"))?; + Ok(resolve_existing_parent(parent, requested, remaining_symlinks)?.join(name)) + } + Err(error) => Err(local_error(error, requested)), + } +} + +/// Whether `path` is `root` or inside it. The drive or share prefix never +/// depends on case. After resolving links, pass `ignore_name_case: false`: +/// a case-sensitive directory can hold two names that differ only by case. +#[cfg(windows)] +fn within_root(path: &Path, root: &Path, ignore_name_case: bool) -> bool { + let lower = |part: Component<'_>| part.as_os_str().to_string_lossy().to_lowercase(); + let mut path = path.components(); + root.components().all(|root| { + path.next().is_some_and(|part| { + if ignore_name_case || matches!(root, Component::Prefix(_)) { + lower(part) == lower(root) + } else { + part == root + } + }) + }) +} + +#[cfg(not(windows))] +fn within_root(path: &Path, root: &Path, _ignore_name_case: bool) -> bool { + path.starts_with(root) +} + +fn allowed_path(requested: &str, roots: &[PathBuf]) -> Result { + if requested.is_empty() { + return Err(invalid("Local file path is empty")); + } + let path = normalize(Path::new(requested))?; + let roots = roots + .iter() + .filter(|root| !root.as_os_str().is_empty()) + .map(|root| normalize(root)) + .collect::>>()?; + if !roots.iter().any(|root| within_root(&path, root, true)) { + return Err( + invalid("Local file path is outside the configured allowed roots") + .with_error_code("VOLUME_PATH_NOT_ALLOWED"), + ); + } + let resolved = resolve_existing_parent(&path, requested, MAX_SYMLINK_RESOLUTIONS)?; + let mut root_error = None; + for root in roots { + let root = match resolve_existing_parent( + &root, + &root.to_string_lossy(), + MAX_SYMLINK_RESOLUTIONS, + ) { + Ok(root) => root, + Err(error) => { + root_error.get_or_insert(error); + continue; + } + }; + if within_root(&resolved, &root, false) { + return Ok(resolved); + } + } + if let Some(error) = root_error { + return Err(error); + } + Err( + invalid("Resolved local file path is outside the configured allowed roots") + .with_error_code("VOLUME_PATH_NOT_ALLOWED"), + ) +} + +#[derive(Clone)] +enum Source { + File(PathBuf), + Stream, +} + +#[derive(Clone)] +enum Operation { + Put(Source), + Get(PathBuf), + Remove, +} + +struct Instruction { + operation: Operation, + url: String, + headers: HeaderMap, +} + +fn string_at(array: &dyn Array, row: usize) -> Result<&str> { + if array.is_null(row) { + return Err(invalid("Null Volume instruction field")); + } + if let Some(values) = array.as_any().downcast_ref::() { + return Ok(values.value(row)); + } + if let Some(values) = array.as_any().downcast_ref::() { + return Ok(values.value(row)); + } + if let Some(values) = array.as_any().downcast_ref::() { + return Ok(values.value(row)); + } + Err(invalid("Invalid Volume instruction column type")) +} + +impl Instruction { + fn decode(batch: &RecordBatch) -> Result { + if batch.num_rows() != 1 { + return Err(invalid("Expected one Volume instruction row")); + } + let schema = batch.schema(); + let column = |name: &str| -> Result<&dyn Array> { + let index = schema + .fields() + .iter() + .position(|f| f.name() == name) + .ok_or_else(|| invalid("Missing Volume instruction column"))?; + Ok(batch.column(index).as_ref()) + }; + let operation = string_at(column("operation")?, 0)?; + let headers = column("headers")?; + let mut parsed_headers = HeaderMap::new(); + let mut add_header = |name: &str, value: &str| -> Result<()> { + parsed_headers.insert( + reqwest::header::HeaderName::from_bytes(name.as_bytes()) + .map_err(|_| invalid("Invalid Volume storage header name"))?, + value + .parse() + .map_err(|_| invalid("Invalid Volume storage header value"))?, + ); + Ok(()) + }; + if !headers.is_null(0) { + if let Some(map) = headers.as_any().downcast_ref::() { + let entries = map.value(0); + for row in 0..entries.len() { + add_header( + string_at(entries.column(0).as_ref(), row)?, + string_at(entries.column(1).as_ref(), row)?, + )?; + } + } else { + let headers: std::collections::HashMap = + serde_json::from_str(string_at(headers, 0)?) + .map_err(|_| invalid("Invalid Volume storage headers"))?; + for (name, value) in headers { + add_header(&name, &value)?; + } + } + } + let operation = match operation { + "PUT" => match string_at(column("localFile")?, 0)? { + "__input_stream__" => Operation::Put(Source::Stream), + path => Operation::Put(Source::File(path.into())), + }, + "GET" => Operation::Get(string_at(column("localFile")?, 0)?.into()), + "REMOVE" => Operation::Remove, + _ => return Err(invalid("Unsupported Volume operation")), + }; + Ok(Self { + operation, + url: string_at(column("presignedUrl")?, 0)?.to_owned(), + headers: parsed_headers, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::builder::{MapBuilder, StringBuilder}; + use arrow_array::{ArrayRef, RecordBatch}; + use arrow_schema::{Field, Schema}; + #[cfg(unix)] + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + use std::time::Duration; + use wiremock::matchers::{body_bytes, header, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + #[test] + fn replay_read_ignores_the_shared_file_position() { + use std::io::{Seek, SeekFrom}; + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("source"); + let payload = b"0123456789".to_vec(); + std::fs::write(&path, &payload).unwrap(); + let mut file = std::fs::File::open(&path).unwrap(); + file.seek(SeekFrom::Start(3)).unwrap(); + assert_eq!( + read_from_start(&file, payload.len() as u64).unwrap(), + payload + ); + #[cfg(unix)] + assert_eq!(file.stream_position().unwrap(), 3); + assert_eq!( + read_from_start(&file, payload.len() as u64 + 1) + .unwrap_err() + .kind(), + std::io::ErrorKind::UnexpectedEof + ); + } + + fn instruction(operation: &str, url: &str, local: &Path) -> RecordBatch { + let mut headers = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); + headers.keys().append_value("x-storage-token"); + headers.values().append_value("server-token"); + headers.append(true).unwrap(); + let arrays: Vec = vec![ + Arc::new(StringArray::from(vec![operation])), + Arc::new(StringArray::from(vec![url])), + Arc::new(headers.finish()), + Arc::new(StringArray::from(vec![local.to_str().unwrap()])), + ]; + let schema = Schema::new( + ["operation", "presignedUrl", "headers", "localFile"] + .iter() + .zip(&arrays) + .map(|(name, values)| Field::new(*name, values.data_type().clone(), true)) + .collect::>(), + ); + RecordBatch::try_new(Arc::new(schema), arrays).unwrap() + } + + fn options(root: &Path) -> VolumeOptions { + VolumeOptions { + allowed_paths: vec![root.to_owned()], + ..Default::default() + } + } + + fn storage(read_timeout: Option) -> Arc { + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(read_timeout), + ) + } + + fn transfer_state(max_retries: u32) -> Arc { + VolumeState::new( + RetryConfig { + max_retries, + min_wait: Duration::ZERO, + max_wait: Duration::ZERO, + ..Default::default() + }, + storage(None), + Default::default(), + ) + } + + #[tokio::test] + async fn local_upload_read_errors_wrapped_as_request_errors_are_not_retried() { + let server = MockServer::start().await; + struct FailedRead(Option); + impl tokio::io::AsyncRead for FailedRead { + fn poll_read( + mut self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + _: &mut tokio::io::ReadBuf<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Err(self.0.take().unwrap())) + } + } + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("missing"); + let cause = std::fs::File::open(&source).unwrap_err(); + let os_code = cause.raw_os_error(); + let captured = Arc::new(Mutex::new(None)); + let body = upload_body( + FailedRead(Some(cause)), + source.to_str().unwrap().into(), + Arc::clone(&captured), + tokio::sync::watch::channel(tokio::time::Instant::now()).0, + ); + let error = storage_send( + Client::new() + .put(format!("{}/object?secret=hidden", server.uri())) + .body(body), + None, + true, + captured, + tokio::sync::watch::channel(tokio::time::Instant::now()).1, + ) + .await + .unwrap_err(); + assert!(!error.retryable); + assert_eq!(error.code, crate::ErrorCode::NotFound); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + let local = error.local_error.unwrap(); + assert_eq!(local.raw_os_error, os_code); + assert_eq!(local.path, source.to_str().unwrap()); + assert!(!error.message.contains("hidden")); + } + + #[tokio::test] + async fn transient_storage_statuses_replay_full_inputs_and_cache_completion() { + use std::sync::atomic::{AtomicUsize, Ordering}; + for (operation, stream) in [("PUT", false), ("PUT", true), ("GET", false)] { + let requests = 2; + let server = MockServer::start().await; + let attempts = Arc::new(AtomicUsize::new(0)); + let count = Arc::clone(&attempts); + Mock::given(method(operation)) + .and(path("/object")) + .and(header("x-storage-token", "server-token")) + .respond_with(move |request: &wiremock::Request| { + if operation == "PUT" { + assert_eq!(request.body, b"payload"); + } + if count.fetch_add(1, Ordering::SeqCst) == 0 { + ResponseTemplate::new(503) + .insert_header("retry-after", "0") + .set_delay(Duration::from_millis(200)) + } else { + ResponseTemplate::new(200).set_body_bytes(b"payload") + } + }) + .expect(requests) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("file"); + std::fs::write( + &file, + if operation == "GET" { + b"old".as_slice() + } else { + b"payload" + }, + ) + .unwrap(); + let local = if stream { + Path::new("__input_stream__") + } else { + &file + }; + let batch = instruction(operation, &format!("{}/object", server.uri()), local); + let mut state = transfer_state(6); + Arc::get_mut(&mut state).unwrap().retry.overall_timeout = Duration::from_millis(100); + let options = options(dir.path()); + assert_eq!( + state + .complete( + async { Ok(batch.clone()) }, + &options, + stream.then(|| b"payload".to_vec()) + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!( + state + .complete(async { Ok(batch.clone()) }, &options, None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(attempts.load(Ordering::SeqCst), requests as usize); + assert_eq!(std::fs::read(file).unwrap(), b"payload"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + } + } + + #[tokio::test] + async fn storage_statuses_and_retry_limits_preserve_classification() { + for (operation, status, retries, budget, requests, missing_success) in [ + ("PUT", 403, 2, Duration::from_secs(10), 1, true), + ("REMOVE", 403, 2, Duration::from_secs(10), 1, true), + ("REMOVE", 404, 2, Duration::from_secs(10), 1, true), + ("REMOVE", 404, 2, Duration::from_secs(10), 1, false), + ("REMOVE", 503, 0, Duration::from_secs(10), 1, true), + ("REMOVE", 503, 2, Duration::ZERO, 1, true), + ("REMOVE", 503, 2, Duration::from_secs(10), 3, true), + ] { + let server = MockServer::start().await; + Mock::given(method(if operation == "PUT" { "PUT" } else { "DELETE" })) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(status) + .insert_header("retry-after", "0") + .insert_header("location", "/redirected") + .insert_header("x-amz-request-id", "request-1") + .insert_header("x-amz-id-2", "host-1") + .set_body_string("AccessDeniedPermission refusedsecret"), + ) + .expect(requests) + .mount(&server) + .await; + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("source"); + std::fs::write(&file, b"payload").unwrap(); + let options = VolumeOptions { + allowed_paths: vec![directory.path().to_owned()], + remove_not_found_is_success: missing_success, + }; + let state = VolumeState::new( + RetryConfig { + max_retries: retries, + overall_timeout: budget, + min_wait: Duration::ZERO, + max_wait: Duration::ZERO, + ..Default::default() + }, + storage(None), + Default::default(), + ); + let batch = instruction( + operation, + &format!("{}/object?secret=hidden", server.uri()), + &file, + ); + for _ in 0..2 { + let result = state + .complete(async { Ok(batch.clone()) }, &options, None) + .await; + if status == 404 && missing_success { + assert_eq!(result.unwrap(), VolumeCompletion::Completed); + continue; + } + let error = result.unwrap_err(); + assert_eq!(error.http_status, Some(status)); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_HTTP_ERROR") + ); + assert_eq!(error.retryable, status == 503); + assert!(error.message.contains("AccessDenied")); + assert!(error + .message + .contains("RequestId: request-1; HostId: host-1")); + assert!(error + .message + .contains(&format!("after {requests} attempts"))); + assert!(!error.message.contains("secret")); + } + } + } + + #[tokio::test] + async fn cancellation_interrupts_retry_backoff_without_another_request() { + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(503).insert_header("retry-after", "30")) + .expect(1) + .mount(&server) + .await; + let state = VolumeState::new( + RetryConfig { + min_wait: Duration::from_secs(30), + max_wait: Duration::from_secs(30), + ..Default::default() + }, + storage(None), + Default::default(), + ); + let batch = instruction("REMOVE", &server.uri(), Path::new("")); + let options = VolumeOptions::default(); + let complete = state.complete(async { Ok(batch.clone()) }, &options, None); + let cancel = async { + while server.received_requests().await.unwrap().is_empty() { + tokio::task::yield_now().await; + } + tokio::time::sleep(Duration::from_millis(50)).await; + state.cancel(); + }; + let (result, _) = tokio::time::timeout(Duration::from_secs(10), async { + tokio::join!(complete, cancel) + }) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code, crate::ErrorCode::Cancelled); + } + + #[tokio::test] + async fn stream_handshake_accepts_empty_bytes_once_and_keeps_success_after_cancel() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(path("/object")) + .and(body_bytes(Vec::::new())) + .and(header("content-length", "0")) + .and(header("x-storage-token", "server-token")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let batch = instruction( + "PUT", + &format!("{}/object", server.uri()), + Path::new("__input_stream__"), + ); + let state = transfer_state(0); + assert_eq!( + state + .complete(async { Ok(batch.clone()) }, &VolumeOptions::default(), None) + .await + .unwrap(), + VolumeCompletion::NeedsInputStream + ); + assert!(server.received_requests().await.unwrap().is_empty()); + assert_eq!( + state + .complete( + async { Ok(batch.clone()) }, + &VolumeOptions::default(), + Some(vec![]) + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + state.cancel(); + assert_eq!( + state + .complete( + async { Ok(batch.clone()) }, + &VolumeOptions::default(), + Some(vec![1]) + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + } + + #[tokio::test] + async fn get_with_missing_parent_fails_before_downloading() { + let server = MockServer::start().await; + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("missing/download"); + let batch = instruction("GET", &server.uri(), &destination); + let error = transfer_state(0) + .complete(async { Ok(batch) }, &options(directory.path()), None) + .await + .unwrap_err(); + assert_eq!(error.code, crate::ErrorCode::NotFound); + assert!(server.received_requests().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn get_writes_in_place_and_preserves_old_bytes_on_download_failure() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/ok")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"new bytes")) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/fail")) + .respond_with(ResponseTemplate::new(403)) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old bytes").unwrap(); + #[cfg(unix)] + let inode = std::fs::metadata(&dest).unwrap().ino(); + #[cfg(unix)] + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o200)).unwrap(); + let batch = instruction("GET", &format!("{}/ok", server.uri()), &dest); + let completed = transfer_state(0); + completed + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await + .unwrap(); + #[cfg(unix)] + { + assert_eq!(std::fs::metadata(&dest).unwrap().ino(), inode); + assert_eq!( + std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777, + 0o200 + ); + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); + #[cfg(unix)] + { + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o500)).unwrap(); + if tempfile::tempfile_in(dir.path()) + .is_err_and(|error| error.kind() == std::io::ErrorKind::PermissionDenied) + { + std::fs::write(&dest, b"old bytes with a longer tail").unwrap(); + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o200)).unwrap(); + Mock::given(method("GET")) + .and(path("/in-place")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"new bytes")) + .expect(1) + .mount(&server) + .await; + let batch = instruction("GET", &format!("{}/in-place", server.uri()), &dest); + let state = transfer_state(0); + assert_eq!( + state + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!( + std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777, + 0o200 + ); + assert_eq!(std::fs::metadata(&dest).unwrap().ino(), inode); + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); + } else { + eprintln!("SKIP: restricted-directory permissions are not enforced for this user"); + } + } + let state = transfer_state(0); + let batch = instruction( + "GET", + &format!("{}/fail?secret=hidden", server.uri()), + &dest, + ); + let error = state + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await + .unwrap_err(); + assert_eq!(error.http_status, Some(403)); + assert!(!error.message.contains("hidden")); + assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); + #[cfg(unix)] + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + } + + #[tokio::test] + #[cfg(unix)] + async fn cancellation_returns_while_local_preparation_waits_for_a_fifo_writer() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + assert!(std::process::Command::new("mkfifo") + .arg(&source) + .status() + .unwrap() + .success()); + let state = transfer_state(0); + let canceller = Arc::clone(&state); + let batch = instruction("PUT", "http://unused.invalid/object", &source); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(50)).await; + canceller.cancel(); + }); + let result = tokio::time::timeout( + Duration::from_secs(2), + state.complete(async { Ok(batch) }, &options(dir.path()), None), + ) + .await; + let _writer = std::fs::OpenOptions::new() + .write(true) + .open(source) + .unwrap(); + assert_eq!( + result.unwrap().unwrap_err().code, + crate::ErrorCode::Cancelled + ); + } + + #[tokio::test] + async fn abandoned_or_cancelled_get_cannot_publish_or_restart() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .set_body_bytes(b"new") + .set_delay(Duration::from_millis(300)), + ) + .expect(2) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old").unwrap(); + let batch = instruction("GET", &server.uri(), &dest); + let options = options(dir.path()); + for cancel in [false, true] { + let state = transfer_state(0); + let mut future = Box::pin(state.complete(async { Ok(batch.clone()) }, &options, None)); + tokio::select! { + result = &mut future => panic!("unexpected early completion: {result:?}"), + sent = tokio::time::timeout(Duration::from_secs(10), async { + loop { + if server.received_requests().await.unwrap().len() >= if cancel { 2 } else { 1 } { break; } + tokio::task::yield_now().await; + } + }) => sent.expect("storage request was not sent"), + } + if cancel { + state.cancel(); + assert_eq!( + future.as_mut().await.unwrap_err().code, + crate::ErrorCode::Cancelled + ); + } + drop(future); + assert_eq!( + state + .complete(async { Ok(batch.clone()) }, &options, None) + .await + .unwrap_err() + .code, + crate::ErrorCode::Cancelled + ); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + } + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + } + + #[tokio::test] + async fn response_inactivity_bounds_headers_and_body_without_publishing() { + use tokio::io::AsyncReadExt; + for (operation, headers_sent) in [("GET", false), ("GET", true), ("PUT", true)] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let received = Arc::clone(&requests); + let peer = tokio::spawn(async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + received.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + tokio::spawn(async move { + let mut request = Vec::new(); + let mut byte = [0]; + while !request.ends_with(b"\r\n\r\n") { + socket.read_exact(&mut byte).await.unwrap(); + request.push(byte[0]); + } + let size = String::from_utf8(request) + .unwrap() + .lines() + .find_map(|line| { + line.to_lowercase() + .strip_prefix("content-length:") + .map(|size| size.trim().parse::().unwrap()) + }) + .unwrap_or(0); + socket.read_exact(&mut vec![0; size]).await.unwrap(); + if headers_sent { + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\nshort") + .await + .unwrap(); + } + tokio::time::sleep(Duration::from_secs(5)).await; + }); + } + }); + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old").unwrap(); + let state = VolumeState::new( + transfer_state(if operation == "PUT" { 1 } else { 0 }) + .retry + .clone(), + storage(Some(Duration::from_millis(150))), + Default::default(), + ); + let batch = instruction(operation, &url, &dest); + let error = tokio::time::timeout( + Duration::from_secs(2), + state.complete(async { Ok(batch.clone()) }, &options(dir.path()), None), + ) + .await + .unwrap() + .unwrap_err(); + assert_eq!(error.code, crate::ErrorCode::NetworkError); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR") + ); + assert!(error.message.contains("read timed out")); + let repeated = state + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await + .unwrap_err(); + assert_eq!(repeated.message, error.message); + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + peer.abort(); + } + } + + #[tokio::test] + async fn upload_accepts_maximum_idle_timeout() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(body_bytes(b"upload")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let state = VolumeState::new( + transfer_state(0).retry.clone(), + storage(Some(Duration::MAX)), + Default::default(), + ); + assert_eq!( + state + .complete( + async { + Ok(instruction( + "PUT", + &server.uri(), + Path::new("__input_stream__"), + )) + }, + &VolumeOptions::default(), + Some(b"upload".to_vec()), + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + } + + #[tokio::test] + async fn get_progress_and_put_idle_limits() { + use tokio::io::AsyncReadExt; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let peer = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0; 2048]; + assert!(socket.read(&mut request).await.unwrap() > 0); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n") + .await + .unwrap(); + for _ in 0..5 { + tokio::time::sleep(Duration::from_millis(150)).await; + socket.write_all(b"x").await.unwrap(); + } + }); + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + let state = VolumeState::new( + transfer_state(0).retry.clone(), + storage(Some(Duration::from_millis(500))), + Default::default(), + ); + state + .complete( + async { Ok(instruction("GET", &url, &dest)) }, + &options(dir.path()), + None, + ) + .await + .unwrap(); + assert_eq!(std::fs::read(&dest).unwrap(), b"xxxxx"); + peer.await.unwrap(); + + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(body_bytes(b"xxxxx")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let (mut writer, reader) = tokio::io::duplex(1); + let producer = tokio::spawn(async move { + for _ in 0..5 { + tokio::time::sleep(Duration::from_millis(150)).await; + writer.write_all(b"x").await.unwrap(); + } + }); + let error = Arc::new(Mutex::new(None)); + let (progress, changed) = tokio::sync::watch::channel(tokio::time::Instant::now()); + let body = upload_body(reader, "input".into(), Arc::clone(&error), progress); + storage_send( + Client::new() + .put(server.uri()) + .header(reqwest::header::CONTENT_LENGTH, 5) + .body(body), + Some(Duration::from_millis(500)), + true, + error, + changed, + ) + .await + .unwrap(); + producer.await.unwrap(); + + for header_wait in [false, true] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let payload = vec![b'x'; 16 * 1024 * 1024]; + std::fs::write(&dest, &payload).unwrap(); + let length = payload.len(); + let peer = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + if header_wait { + let mut headers = Vec::new(); + while !headers.ends_with(b"\r\n\r\n") { + headers.push(socket.read_u8().await.unwrap()); + } + let mut remaining = length; + let mut buffer = vec![0; 256 * 1024]; + while remaining > 0 { + let n = socket.read(&mut buffer).await.unwrap(); + assert!(n > 0); + remaining -= n; + } + } + std::future::pending::<()>().await; + }); + let state = VolumeState::new( + transfer_state(0).retry.clone(), + storage(Some(Duration::from_millis(150))), + Default::default(), + ); + let error = tokio::time::timeout( + Duration::from_secs(3), + state.complete( + async { Ok(instruction("PUT", &url, &dest)) }, + &options(dir.path()), + None, + ), + ) + .await + .expect("PUT idle watchdog") + .unwrap_err(); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR") + ); + assert!(error.message.contains("timed out")); + peer.abort(); + } + } + + #[tokio::test] + async fn truncated_get_retries_from_clean_temp_and_preserves_destination_on_failure() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + for retries in [0, 1] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let peer = tokio::spawn(async move { + for attempt in 0..=retries { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0; 2048]; + assert!(socket.read(&mut request).await.unwrap() > 0); + let response = if attempt == 0 { + b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\nConnection: close\r\n\r\nshort" + .as_slice() + } else { + b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\ncorrect" + }; + socket.write_all(response).await.unwrap(); + } + }); + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old").unwrap(); + let batch = instruction("GET", &url, &dest); + let result = transfer_state(retries) + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await; + if retries == 0 { + assert_eq!(result.unwrap_err().code, crate::ErrorCode::NetworkError); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + } else { + assert_eq!(result.unwrap(), VolumeCompletion::Completed); + assert_eq!(std::fs::read(&dest).unwrap(), b"correct"); + } + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + peer.await.unwrap(); + } + } + + #[cfg(windows)] + #[test] + fn resolved_names_match_exactly_and_prefix_ignores_case() { + for (path, root, allowed) in [ + (r"\\?\C:\data\safe\x", r"\\?\C:\data\safe", true), + (r"\\?\c:\data\safe\x", r"\\?\C:\data\safe", true), + (r"\\?\C:\data\SAFE\x", r"\\?\C:\data\safe", false), + ( + r"\\?\UNC\server\share\dir\x", + r"\\?\UNC\Server\Share\dir", + true, + ), + ( + r"\\?\UNC\server\share\DIR\x", + r"\\?\UNC\Server\Share\dir", + false, + ), + ] { + assert_eq!( + within_root(Path::new(path), Path::new(root), false), + allowed, + "{path}" + ); + assert!( + within_root(Path::new(path), Path::new(root), true), + "{path}" + ); + } + } + + #[test] + fn symlinks_require_lexical_authority_and_resolved_target_in_any_allowed_root() { + #[cfg(unix)] + use std::os::unix::fs::{symlink as symlink_dir, symlink as symlink_file}; + #[cfg(windows)] + use std::os::windows::fs::{symlink_dir, symlink_file}; + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("root"); + let other = dir.path().join("other"); + std::fs::create_dir(&root).unwrap(); + std::fs::create_dir(&other).unwrap(); + std::fs::write(root.join("file"), b"ok").unwrap(); + #[cfg(windows)] + assert!(allowed_path( + root.join("file").to_str().unwrap(), + &[dir.path().join("ROOT")] + ) + .is_ok()); + symlink_file(root.join("file"), root.join("inside")).unwrap(); + symlink_file(other.join("missing"), root.join("escape")).unwrap(); + symlink_dir(&root, dir.path().join("alias")).unwrap(); + assert_eq!( + allowed_path( + root.join("inside").to_str().unwrap(), + std::slice::from_ref(&root) + ) + .unwrap(), + root.join("file").canonicalize().unwrap() + ); + assert!(allowed_path( + root.join("escape").to_str().unwrap(), + std::slice::from_ref(&root) + ) + .is_err()); + assert_eq!( + allowed_path( + root.join("escape").to_str().unwrap(), + &[root.clone(), other.clone()] + ) + .unwrap(), + other.canonicalize().unwrap().join("missing") + ); + assert!(allowed_path( + dir.path().join("alias/file").to_str().unwrap(), + std::slice::from_ref(&root) + ) + .is_err()); + let looping_root = dir.path().join("loop"); + symlink_dir(&looping_root, &looping_root).unwrap(); + for roots in [ + [looping_root.clone(), root.clone()], + [root.clone(), looping_root.clone()], + ] { + assert_eq!( + allowed_path(root.join("file").to_str().unwrap(), &roots).unwrap(), + root.join("file").canonicalize().unwrap() + ); + } + let error = allowed_path( + root.join("escape").to_str().unwrap(), + &[looping_root.clone(), root.clone()], + ) + .unwrap_err(); + assert_eq!( + error.local_error.unwrap().path, + looping_root.to_string_lossy() + ); + symlink_dir(&other, root.join("link")).unwrap(); + for (name, suffix) in [("cycle", ""), ("nested", "missing")] { + let cycle = root.join(name); + let target = Path::new("link").join("..").join(name).join(suffix); + symlink_file(target, &cycle).unwrap(); + let requested = cycle.to_str().unwrap(); + let error = allowed_path(requested, std::slice::from_ref(&root)).unwrap_err(); + let local = error.local_error.unwrap(); + assert_eq!(local.path, requested); + #[cfg(unix)] + { + assert_eq!(error.code, crate::ErrorCode::NotFound); + assert_eq!(local.kind, std::io::ErrorKind::NotFound); + assert_eq!(local.raw_os_error, Some(2)); + } + } + assert!(allowed_path(root.join("../other/missing").to_str().unwrap(), &[root]).is_err()); + } + + #[tokio::test] + async fn local_errors_retain_os_code_and_requested_filename() { + let dir = tempfile::tempdir().unwrap(); + let server = MockServer::start().await; + for (source, kind, code) in [ + ( + dir.path().join("missing"), + std::io::ErrorKind::NotFound, + crate::ErrorCode::NotFound, + ), + ( + dir.path().to_owned(), + if cfg!(windows) { + std::io::ErrorKind::PermissionDenied + } else { + std::io::ErrorKind::IsADirectory + }, + if cfg!(windows) { + crate::ErrorCode::PermissionDenied + } else { + crate::ErrorCode::InvalidArgument + }, + ), + ] { + let batch = instruction( + "PUT", + &format!("{}/object?secret=hidden", server.uri()), + &source, + ); + let state = transfer_state(1); + let error = state + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await + .unwrap_err(); + assert_eq!(error.code, code); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + assert_eq!(error.sql_state.as_deref(), Some("HY000")); + assert!(!error.retryable); + let local = error.local_error.as_ref().unwrap(); + assert_eq!(local.kind, kind); + assert!(local.raw_os_error.is_some()); + assert_eq!(local.path, source.to_str().unwrap()); + assert!(!error.message.contains("hidden")); + assert_eq!( + state + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await + .unwrap_err() + .local_error + .as_ref() + .unwrap() + .raw_os_error, + local.raw_os_error + ); + } + assert!(server.received_requests().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn storage_network_errors_preserve_causes_without_signed_urls() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + drop(listener); + let url = format!("http://{address}/object?secret=hidden"); + let error = Client::builder() + .no_proxy() + .build() + .unwrap() + .get(&url) + .send() + .await + .unwrap_err(); + let mapped = storage_error(error); + assert_eq!(mapped.code, crate::ErrorCode::NetworkError); + assert_eq!( + mapped.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR") + ); + assert!(mapped.retryable); + assert!( + mapped.message.to_ascii_lowercase().contains("refused"), + "{mapped}" + ); + assert!(!mapped.message.contains(&address.to_string()), "{mapped}"); + assert!(!mapped.message.contains("hidden"), "{mapped}"); + } + + #[tokio::test] + async fn redirected_put_replays_full_bytes() { + for (stream, status) in [(true, 307), (false, 307), (false, 308)] { + let server = MockServer::start().await; + let payload = vec![b'x'; 512 * 1024 + 1]; + let directory = tempfile::tempdir().unwrap(); + let source = directory.path().join("source"); + std::fs::write(&source, &payload).unwrap(); + Mock::given(method("PUT")) + .and(path("/original")) + .and(body_bytes(payload.clone())) + .respond_with(ResponseTemplate::new(status).insert_header("location", "/target")) + .expect(2) + .mount(&server) + .await; + Mock::given(method("PUT")) + .and(path("/target")) + .and(body_bytes(payload.clone())) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let batch = instruction( + "PUT", + &format!("{}/original", server.uri()), + if stream { + Path::new("__input_stream__") + } else { + &source + }, + ); + assert_eq!( + transfer_state(0) + .complete( + async { Ok(batch) }, + &options(directory.path()), + stream.then_some(payload), + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert!(server + .received_requests() + .await + .unwrap() + .iter() + .all(|request| !request.headers.contains_key("referer"))); + } + } + + #[tokio::test] + async fn get_decodes_gzip_content_encoding() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("content-encoding", "gzip") + .set_body_bytes(vec![ + 31, 139, 8, 0, 0, 0, 0, 0, 2, 3, 75, 73, 77, 206, 79, 73, 77, 97, 72, 170, + 44, 73, 45, 6, 0, 196, 224, 211, 9, 13, 0, 0, 0, + ]), + ) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + transfer_state(0) + .complete( + async { Ok(instruction("GET", &server.uri(), &dest)) }, + &options(dir.path()), + None, + ) + .await + .unwrap(); + assert_eq!(std::fs::read(dest).unwrap(), b"decoded\x00bytes"); + } +} diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs new file mode 100644 index 00000000..b134eafe --- /dev/null +++ b/tests/v0_volume_wiremock.rs @@ -0,0 +1,582 @@ +// 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. + +//! Wiremock tests for Volume file transfers through Statement and ResultStream. + +use arrow_array::{RecordBatch, StringArray}; +use arrow_ipc::writer::StreamWriter; +use arrow_schema::{DataType, Field, Schema}; +use base64::{engine::general_purpose::STANDARD, Engine}; +use databricks_sql_kernel::{ + AuthConfig, ConnectionConfig, DirectStatement, ErrorCode, ExecutedStatementHandle, HttpConfig, + ResultBatch, Session, TryNextBatch, VolumeCompletion, VolumeOptions, +}; +use serde_json::json; +use std::sync::Arc; +use std::time::Duration; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +fn response(server: &MockServer, marked: bool, local: &str) -> serde_json::Value { + response_with_batches(server, marked, local, "GET", &[1]) +} + +fn response_with_batches( + server: &MockServer, + marked: bool, + local: &str, + operation: &str, + batch_rows: &[usize], +) -> serde_json::Value { + let names = ["operation", "presignedUrl", "headers", "localFile"]; + let schema = Arc::new(Schema::new( + names + .iter() + .map(|name| Field::new(*name, DataType::Utf8, true)) + .collect::>(), + )); + let values = [ + operation.to_owned(), + format!("{}/object", server.uri()), + "{}".to_owned(), + local.to_owned(), + ]; + let batch = RecordBatch::try_new( + schema, + values + .iter() + .map(|value| Arc::new(StringArray::from(vec![value.as_str()])) as _) + .collect(), + ) + .unwrap(); + let mut ipc = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); + for &rows in batch_rows { + writer.write(&batch.slice(0, rows)).unwrap(); + } + writer.finish().unwrap(); + } + let count: usize = batch_rows.iter().sum(); + json!({ + "statement_id": "volume-stmt", "status": {"state": "CLOSED"}, + "manifest": { + "format": "ARROW_STREAM", "is_volume_operation": marked, + "schema": {"column_count":4,"columns": names.iter().enumerate().map(|(i,name)| json!({"name":name,"type_name":"STRING","type_text":"STRING","position":i})).collect::>()}, + "total_row_count":count,"total_chunk_count":1 + }, + "result": {"chunk_index":0,"row_offset":0,"row_count":count,"attachment":STANDARD.encode(&ipc)} + }) +} + +#[tokio::test] +async fn instruction_batches_preserve_one_row_and_reject_extra_rows() { + for (batch_rows, valid) in [(&[1, 1][..], false), (&[0, 0, 1, 0][..], true)] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"original").unwrap(); + let session = session( + &server, + response_with_batches(&server, true, dest.to_str().unwrap(), "GET", batch_rows), + ) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"replacement")) + .expect(if valid { 1 } else { 0 }) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let mut executed = statement.execute().await.unwrap(); + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + for _ in 0..2 { + let result = executed + .result_stream_mut() + .complete_volume_operation(&options, None) + .await; + if valid { + assert_eq!(result.unwrap(), VolumeCompletion::Completed); + } else { + let error = result.unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_INVALID_INSTRUCTION") + ); + assert_eq!(error.message, "Expected one Volume instruction row"); + } + } + assert_eq!( + std::fs::read(&dest).unwrap(), + if valid { + b"replacement".as_slice() + } else { + b"original".as_slice() + } + ); + let TryNextBatch::Ready(ResultBatch::Arrow(batch)) = + executed.result_stream_mut().try_next_batch().unwrap() + else { + panic!("expected buffered instruction batch"); + }; + assert_eq!(batch.num_rows(), 1); + if !valid { + let Some(ResultBatch::Arrow(batch)) = executed.next_batch().await.unwrap() else { + panic!("expected second instruction batch"); + }; + assert_eq!(batch.num_rows(), 1); + } + assert!(executed.next_batch().await.unwrap().is_none()); + executed.close().await.unwrap(); + session.close().await.unwrap(); + } +} + +async fn session(server: &MockServer, body: serde_json::Value) -> Session { + session_with_http(server, body, HttpConfig::default()).await +} + +async fn session_with_http( + server: &MockServer, + body: serde_json::Value, + http: HttpConfig, +) -> Session { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/wh/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(json!({"session_id":"sess","warehouse_id":"wh"})), + ) + .mount(server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_json(body.clone())) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/volume-stmt")) + .respond_with(ResponseTemplate::new(200).set_body_json(body)) + .mount(server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200)) + .mount(server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/volume-stmt/cancel")) + .respond_with(ResponseTemplate::new(200)) + .mount(server) + .await; + Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/wh").unwrap(), + ) + .auth(AuthConfig::Pat { + token: "workspace-token".into(), + identity_federation_client_id: None, + }) + .http(http) + .open() + .await + .unwrap() +} + +#[tokio::test] +async fn storage_transfers_outlive_rpc_deadline() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("file"); + std::fs::write(&local, b"original").unwrap(); + let mut http = HttpConfig::default(); + http.request_timeout = Duration::from_millis(100); + http.overall_timeout = Duration::from_millis(200); + let session = session_with_http( + &server, + response(&server, true, local.to_str().unwrap()), + http, + ) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_millis(300)) + .set_body_bytes(b"downloaded"), + ) + .expect(1) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let mut executed = statement.execute().await.unwrap(); + assert_eq!( + executed + .result_stream_mut() + .complete_volume_operation( + &VolumeOptions::new(vec![dir.path().to_owned()], false), + None, + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(std::fs::read(&local).unwrap(), b"downloaded"); + executed.close().await.unwrap(); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn sync_and_direct_closed_results_complete_explicitly_and_keep_raw_rows() { + for direct in [false, true] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + let session = session(&server, response(&server, true, dest.to_str().unwrap())).await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"data")) + .expect(1) + .mount(&server) + .await; + let mut stmt = session.statement(); + stmt.spec().sql("server decides the operation"); + let mut exec = if direct { + match stmt.execute_direct().await.unwrap() { + DirectStatement::Completed(exec) => exec, + _ => panic!("expected inline completion"), + } + } else { + stmt.execute().await.unwrap() + }; + assert!(!dest.exists()); + let stream = exec.result_stream_mut(); + assert!(stream.is_volume_operation()); + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + assert_eq!( + stream + .complete_volume_operation(&options, None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(std::fs::read(&dest).unwrap(), b"data"); + let requests = server.received_requests().await.unwrap(); + let storage = requests + .iter() + .find(|request| request.url.path() == "/object") + .unwrap(); + assert!(!storage.headers.contains_key("authorization")); + assert!(exec.next_batch().await.unwrap().is_some()); + assert_eq!( + exec.result_stream_mut() + .complete_volume_operation(&options, None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + exec.close().await.unwrap(); + session.close().await.unwrap(); + } +} + +#[tokio::test] +async fn completion_outlives_parent_statement() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + let session = session( + &server, + response(&server, true, destination.to_str().unwrap()), + ) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"downloaded")) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let mut executed = statement.execute().await.unwrap(); + drop(statement); + assert_eq!( + executed + .result_stream_mut() + .complete_volume_operation( + &VolumeOptions::new(vec![dir.path().to_owned()], false), + None, + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(std::fs::read(&destination).unwrap(), b"downloaded"); + executed.close().await.unwrap(); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn marker_false_and_id_attachment_cannot_initiate_transfer() { + for marked in [false, true] { + let server = MockServer::start().await; + let session = session(&server, response(&server, marked, "/never-created")).await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&server) + .await; + let attached = session.attach_async_statement("volume-stmt").await.unwrap(); + let mut stream = attached.fetch_result().await.unwrap(); + assert_eq!( + stream + .complete_volume_operation(&VolumeOptions::default(), None) + .await + .unwrap(), + VolumeCompletion::NotVolume + ); + assert!(stream.next_batch().await.unwrap().is_some()); + if !marked { + let mut stmt = session.statement(); + stmt.spec().sql("PUT does not authorize local effects"); + let mut exec = stmt.execute().await.unwrap(); + assert!(!exec.result_stream().is_volume_operation()); + assert_eq!( + exec.result_stream_mut() + .complete_volume_operation(&VolumeOptions::default(), None) + .await + .unwrap(), + VolumeCompletion::NotVolume + ); + } + session.close().await.unwrap(); + } +} + +#[tokio::test] +async fn owner_reader_and_repeated_materialization_share_one_completion() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + let session = session(&server, response(&server, true, dest.to_str().unwrap())).await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"data")) + .expect(1) + .mount(&server) + .await; + let mut stmt = session.statement(); + stmt.spec().sql("operation"); + let owner = stmt.submit().await.unwrap(); + let reader = owner.reader().unwrap(); + reader.fetch_result().await.unwrap().close(); + let mut first = reader.fetch_result().await.unwrap(); + let mut second = owner.fetch_result().await.unwrap(); + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + let (a, b) = tokio::join!( + first.complete_volume_operation(&options, None), + second.complete_volume_operation(&options, None) + ); + assert_eq!(a.unwrap(), VolumeCompletion::Completed); + assert_eq!(b.unwrap(), VolumeCompletion::Completed); + drop(reader); + assert_eq!(std::fs::read(&dest).unwrap(), b"data"); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn async_executed_canceller_interrupts_volume_transfer() { + let server = MockServer::start().await; + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("download"); + let session = session( + &server, + response(&server, true, destination.to_str().unwrap()), + ) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_secs(30)) + .set_body_bytes(b"data"), + ) + .expect(1) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let executed = statement.submit().await.unwrap(); + let canceller = executed.canceller(); + let mut stream = executed.fetch_result().await.unwrap(); + let options = VolumeOptions::new(vec![directory.path().to_owned()], false); + let cancel = async { + while !server + .received_requests() + .await + .unwrap() + .iter() + .any(|request| request.url.path() == "/object") + { + tokio::task::yield_now().await; + } + canceller.cancel().await.unwrap(); + }; + let (result, _) = tokio::time::timeout(Duration::from_secs(10), async { + tokio::join!(stream.complete_volume_operation(&options, None), cancel) + }) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); + assert_eq!( + stream + .complete_volume_operation(&options, None) + .await + .unwrap_err() + .code, + ErrorCode::Cancelled + ); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn cancellation_and_session_close_interrupt_instruction_or_storage_after_sql_closed() { + for (instruction_page, close_session) in + [(false, false), (false, true), (true, false), (true, true)] + { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old").unwrap(); + let mut body = response(&server, true, dest.to_str().unwrap()); + let held_path = if instruction_page { + body["manifest"]["total_chunk_count"] = json!(2); + body["result"]["next_chunk_index"] = json!(1); + let mut next = response_with_batches(&server, true, dest.to_str().unwrap(), "GET", &[]) + ["result"] + .clone(); + next["chunk_index"] = json!(1); + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/volume-stmt/result/chunks/1")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_secs(30)) + .set_body_json(next), + ) + .mount(&server) + .await; + "/api/2.0/sql/statements/volume-stmt/result/chunks/1" + } else { + "/object" + }; + let mut session = Some(session(&server, body).await); + Mock::given(method("GET")) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_secs(30)) + .set_body_bytes(b"new"), + ) + .expect(if instruction_page { 0 } else { 1 }) + .mount(&server) + .await; + let mut stmt = session.as_ref().unwrap().statement(); + let canceller = stmt.canceller(); + stmt.spec().sql("operation"); + let mut exec = stmt.execute().await.unwrap(); + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + let complete = exec + .result_stream_mut() + .complete_volume_operation(&options, None); + let cancel = async { + loop { + if server + .received_requests() + .await + .unwrap() + .iter() + .any(|req| req.url.path() == held_path) + { + break; + } + tokio::task::yield_now().await; + } + if close_session { + session.take().unwrap().close().await.unwrap(); + } else { + canceller.cancel().await.unwrap(); + } + }; + let (result, _) = tokio::time::timeout(Duration::from_secs(10), async { + tokio::join!(complete, cancel) + }) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); + assert_eq!( + exec.result_stream_mut() + .complete_volume_operation(&options, None) + .await + .unwrap_err() + .code, + ErrorCode::Cancelled + ); + assert_eq!( + server + .received_requests() + .await + .unwrap() + .iter() + .filter(|req| req.url.path() == held_path) + .count(), + 1 + ); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + if let Some(session) = session { + session.close().await.unwrap(); + } + } +} + +#[tokio::test] +async fn reading_before_volume_completion_returns_invalid_state() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("download"); + let session = session(&server, response(&server, true, local.to_str().unwrap())).await; + let mut statement = session.statement(); + statement.spec().sql("GET"); + let mut executed = statement.execute().await.unwrap(); + assert!(executed.next_batch().await.unwrap().is_some()); + let error = executed + .result_stream_mut() + .complete_volume_operation( + &VolumeOptions::new(vec![dir.path().to_owned()], false), + None, + ) + .await + .unwrap_err(); + assert_eq!( + error.code, + databricks_sql_kernel::Error::invalid_state().code + ); + assert!(error + .message + .contains("complete_volume_operation must be called before reading result rows")); + assert!(!local.exists()); + executed.close().await.unwrap(); + session.close().await.unwrap(); +}