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 96fca350..f4588c8e 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/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/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..7ba9f9cd 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,100 @@ 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. + /// 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 +808,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 +844,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 +881,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 +901,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 +909,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 +1007,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 +1058,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 +1490,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..4774a9f8 --- /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:?}"), + _ = async { + loop { + if server.received_requests().await.unwrap().len() >= if cancel { 2 } else { 1 } { break; } + tokio::task::yield_now().await; + } + } => {} + } + 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(); +}