diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 6f421c57..645c73e8 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -167,7 +167,7 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). | Field | Description | Default | |-------|-------------|---------| -| `request_timeout` | Per-request timeout (connect + body). | `120s` | +| `request_timeout` | Per-request timeout (connect + body). For Volume file transfers, an idle limit: a transfer fails after this long without progress. | `120s` | | `overall_timeout` | Maximum total time across retries for one logical RPC. | `900s` | | `pool_max_idle_per_host` | Connection-pool size (max idle warm sockets per host). Raise for bursty concurrent workloads. | `100` | | `retry_min_wait` | Minimum backoff between retries; also the floor for a server `Retry-After` and the base of exponential backoff (`min_wait × 2^attempt`). | `1s` | diff --git a/Cargo.lock b/Cargo.lock index bc909a3e..501a95b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2394,9 +2394,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 14e1e80a..334bd5e9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -105,6 +105,9 @@ lz4_flex = "0.14" # Random number generation (retry jitter) rand = "0.10" +# Temporary files for Volume GET downloads +tempfile = "3.27" + # Concurrent data structures dashmap = "6" moka = { version = "0.12.16", features = ["future"] } @@ -181,7 +184,6 @@ libc = "0.2" [dev-dependencies] tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util"] } wiremock = "0.6" -tempfile = "3" log = "0.4" # Generate JWT test keys in-process to avoid PEM fixtures and an external # `openssl` dependency. `ring` already backs runtime JWT signing. diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 1313dae0..bf48c6c5 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -22,11 +22,19 @@ changes go in their respective binding's NEXT_CHANGELOG. if the host has credentials, a path, query or fragment. - `ProxyConfig.url`, the Rust ADBC driver's `adbc.databricks.proxy.url`, `HTTPS_PROXY` and `ALL_PROXY` accept SOCKS4 and SOCKS5 proxy URLs. +- Volume `PUT`, `GET` and `REMOVE`: with `StatementSpec::volume` set, executing + a statement the server marks as a Volume operation also runs its file + transfer. Local paths, with symlinks resolved, must be inside the caller's + allowed directories. A transfer fails after `HttpConfig::request_timeout` + without progress. On Unix a GET can also write into an existing pipe or + character device as the download arrives. ### Changed - Proxy credentials are redacted from proxy URLs in errors, logs and `Debug` output. +- `Error` and `ResultManifest` have new public fields (`local_error`, + `is_volume_operation`). Code that builds them with struct literals must set them. ### Updated diff --git a/NOTICE b/NOTICE index cdc63bbf..1a5bb418 100644 --- a/NOTICE +++ b/NOTICE @@ -162,6 +162,11 @@ Project URL: https://github.com/jedisct1/rust-siphash Copyright: Copyright 2012-2016 The Rust Project Developers; Copyright 2016-2026 Frank Denis +Package: tempfile +Project URL: https://github.com/Stebalien/tempfile +Copyright: Copyright (c) 2015 Steven Allen + + Package: thiserror Project URL: https://github.com/dtolnay/thiserror Copyright: Copyright thiserror Authors. diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 64db58f1..89294293 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -692,6 +692,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.1", + "tempfile", "thiserror 2.0.21", "tokio", "tokio-util", @@ -2202,9 +2203,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", diff --git a/adbc/NOTICE b/adbc/NOTICE index cdc63bbf..1a5bb418 100644 --- a/adbc/NOTICE +++ b/adbc/NOTICE @@ -162,6 +162,11 @@ Project URL: https://github.com/jedisct1/rust-siphash Copyright: Copyright 2012-2016 The Rust Project Developers; Copyright 2016-2026 Frank Denis +Package: tempfile +Project URL: https://github.com/Stebalien/tempfile +Copyright: Copyright (c) 2015 Steven Allen + + Package: thiserror Project URL: https://github.com/dtolnay/thiserror Copyright: Copyright thiserror Authors. diff --git a/napi/Cargo.lock b/napi/Cargo.lock index dedcf797..c2eec113 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -647,6 +647,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -806,6 +807,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1504,6 +1511,12 @@ dependencies = [ "libc", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.2" @@ -2211,6 +2224,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.46" @@ -2557,6 +2583,19 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index 55bef07f..205684e9 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -643,6 +643,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -779,6 +780,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1434,6 +1441,12 @@ dependencies = [ "libc", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.2" @@ -2123,6 +2136,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.46" @@ -2475,6 +2501,19 @@ version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" diff --git a/src/client/http.rs b/src/client/http.rs index 1211e03e..2a9a9a8c 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -561,8 +561,14 @@ impl DatabricksHttpClient { let revocation = revocation.filter(|_| config.tls.allow_self_signed != Some(true)); // Follow redirects for normal traffic (reqwest's default policy). - let client = - Self::build_reqwest_client(&config, reqwest::redirect::Policy::default(), revocation)?; + // `read_timeout` is a historical name; reqwest applies it as the + // total deadline from connect through response-body completion. + let client = Self::build_reqwest_client( + &config, + reqwest::redirect::Policy::default(), + revocation, + Some(config.read_timeout), + )?; // Surface which TLS backend was compiled in so oncall debugging // a handshake / unknown-CA report can tell at a glance whether @@ -589,7 +595,8 @@ impl DatabricksHttpClient { }) } - /// Build a `reqwest::Client` from `config` with the given redirect policy. + /// Build a `reqwest::Client` from `config` with the given redirect policy + /// and total request timeout. /// /// Factored out of `new()` so tenant discovery can obtain a client that /// does NOT follow redirects (to read the first `/aad/auth` hop's @@ -599,16 +606,17 @@ impl DatabricksHttpClient { config: &HttpClientConfig, redirect: reqwest::redirect::Policy, revocation: Option, + timeout: Option, ) -> Result { check_revocation_support(&config.tls, revocation)?; 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); + if let Some(timeout) = timeout { + builder = builder.timeout(timeout); + } // Apply TLS configuration if config.tls.enabled == Some(false) { @@ -837,6 +845,15 @@ impl DatabricksHttpClient { .expect("Auth provider can only be set once"); } + /// Build the client for Volume storage requests: the session's connection + /// settings without a total deadline or redirect following. + pub(crate) fn storage_client( + config: &HttpClientConfig, + revocation: Option, + ) -> Result { + Self::build_reqwest_client(config, reqwest::redirect::Policy::none(), revocation, None) + } + /// Returns the client configuration. pub fn config(&self) -> &HttpClientConfig { &self.config @@ -926,6 +943,7 @@ impl DatabricksHttpClient { &self.config, reqwest::redirect::Policy::none(), self.revocation, + Some(self.config.read_timeout), )?; 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/mod.rs b/src/client/mod.rs index 0edc69d2..65dff979 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -38,7 +38,7 @@ pub mod sea; pub(crate) mod tls_revocation; 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 42c58990..9c75d0ae 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -2454,6 +2454,7 @@ mod tests { chunks: None, result_compression: Some("LZ4_FRAME".to_string()), is_native_metadata_result: None, + is_volume_operation: false, }), result: None, }; diff --git a/src/config.rs b/src/config.rs index ddea3ce1..06606f84 100644 --- a/src/config.rs +++ b/src/config.rs @@ -941,6 +941,8 @@ 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. + /// For a Volume file transfer it is an idle limit instead: the transfer + /// fails after this long without progress. pub request_timeout: Duration, /// Maximum total time across retries for a single logical RPC. diff --git a/src/kernel_error.rs b/src/kernel_error.rs index ecfb7fb2..38426840 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -43,10 +43,11 @@ //! 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. +//! logging and host-language exception mapping. Build it with +//! `Error::new(...)` and the `with_*(...)` setters, which a new field +//! does not break; code that builds it with a struct literal must set +//! every field. Keeping the marker would block useful pattern-matches +//! for no real benefit. #![allow(dead_code)] @@ -169,9 +170,9 @@ 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). +/// A new field does not break code that uses these setters, but a struct +/// literal must set every field. The type is not `#[non_exhaustive]` +/// because the marker would block the pattern-matching wrappers want. #[derive(Debug, Clone)] pub struct Error { pub code: ErrorCode, @@ -248,6 +249,33 @@ pub struct Error { /// Underlying cause. Boxed to keep the struct stack-friendly. pub cause: Option>, + + /// The OS error behind a failed local file operation. + pub local_error: Option>, +} + +/// The OS error behind a failed local file operation, for mapping to a +/// host-language file error. +#[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 +298,7 @@ impl Error { diagnostic_info: None, error_details_json: None, cause: None, + local_error: None, } } @@ -442,6 +471,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 9b5ebb50..cb525199 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 @@ -161,6 +162,7 @@ pub use telemetry::DriverSystemConfiguration; /// pyo3 crates own. Not a supported API. #[doc(hidden)] pub use util::runtime::block_sigpipe_on_current_thread; +pub use volume::VolumeOptions; // === Compile-time guarantees on auto-traits === // diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 7f6be171..25ab06f8 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1485,6 +1485,7 @@ mod tests { chunks: None, result_compression: None, is_native_metadata_result: None, + is_volume_operation: false, } } @@ -2163,6 +2164,7 @@ mod tests { chunks: None, result_compression: None, is_native_metadata_result: None, + is_volume_operation: false, } } diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index 4c5c82ce..b70de30d 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -482,6 +482,7 @@ mod tests { chunks: None, result_compression: None, is_native_metadata_result: None, + is_volume_operation: false, } } diff --git a/src/result_stream.rs b/src/result_stream.rs index 721424e1..7c6e01ff 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -493,6 +493,8 @@ pub struct ResultStream { close_guard: Option, telemetry: Option, + + is_volume_operation: bool, } struct ResultStreamTelemetry { @@ -608,6 +610,7 @@ impl ResultStream { exhausted: false, close_guard: None, telemetry: None, + is_volume_operation: false, }) } @@ -642,6 +645,35 @@ impl ResultStream { self.telemetry = Some(ResultStreamTelemetry::new(telemetry)); } + /// Records whether the server marked this result as a Volume PUT, GET or + /// REMOVE and, if so, runs the transfer `volume` holds before any row is + /// read. Dropping an `owner` call cancels the transfer. + pub(crate) async fn complete_volume( + &mut self, + manifest: Option<&crate::types::sea::ResultManifest>, + volume: Option<&Arc>, + owner: bool, + ) -> Result<()> { + self.is_volume_operation = manifest.is_some_and(|manifest| manifest.is_volume_operation); + let Some(volume) = volume.filter(|_| self.is_volume_operation) else { + return Ok(()); + }; + let instruction = self + .peek_first_batch() + .await + .map(|batch| batch.map(|ResultBatch::Arrow(batch)| batch.clone())); + let result = volume.complete(instruction, owner).await; + if let Err(error) = &result { + self.finalize_telemetry(Some(error)); + } + result + } + + /// True when the server marked this result as a Volume PUT, GET or REMOVE. + pub fn is_volume_operation(&self) -> bool { + self.is_volume_operation + } + fn reader_metrics(&self) -> Option { self.reader.as_ref().and_then(|reader| reader.metrics()) } @@ -788,10 +820,8 @@ impl ResultStream { /// /// 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. + /// stream. Only valid before any `next_batch` has run (it no-ops if a + /// batch is already current or buffered). pub(crate) async fn peek_first_batch(&mut self) -> Result> { if self.prefetched.is_none() && self.current.is_none() && !self.exhausted { let reader = self diff --git a/src/session.rs b/src/session.rs index bcc691a8..ccfb962c 100644 --- a/src/session.rs +++ b/src/session.rs @@ -155,6 +155,7 @@ pub(crate) struct SessionInner { /// [`DefaultOpts::ignore_transactions`]. Multi-statement transactions are /// a Private Preview feature; setting this `false` opts in. ignore_transactions: bool, + storage: Arc, } impl SessionInner { @@ -165,6 +166,13 @@ impl SessionInner { &self.transport } + pub(crate) fn new_volume_state( + &self, + options: Option, + ) -> Arc { + self.storage.transfer_state(options) + } + /// Crate-internal accessor for the server-issued session ID. pub(crate) fn session_id(&self) -> &str { &self.session_id @@ -375,12 +383,22 @@ impl Session { crate::client::http::check_revocation_support(&http_client_config.tls, revocation)?; validate_revocation_endpoint_scheme(&config, revocation)?; let retry_configs = build_retry_configs_for_session(&config); + // The CloudFetch retry settings disable retries, so Volume transfers + // use the SQL ones. + let storage_retry = retry_configs[&RequestCategory::Sea].clone(); let http_client = Arc::new( DatabricksHttpClient::with_revocation(http_client_config, retry_configs, revocation) .map_err(|e| { Error::network_error().message(format!("Failed to construct HTTP client: {e}")) })?, ); + let storage = Arc::new(crate::volume::Storage::new( + http_client.config().clone(), + http_client.revocation(), + storage_retry, + Some(config.http.request_timeout), + runtime_handle.clone(), + )); // 2. Auth provider — async because OAuth flows hit the OIDC // discovery endpoint. @@ -494,6 +512,7 @@ impl Session { // caller opts into explicit transactions via set_autocommit. autocommit: std::sync::atomic::AtomicBool::new(true), ignore_transactions: defaults.ignore_transactions, + storage, }), }) } @@ -788,6 +807,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.storage.cancel_all(); // 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_async.rs b/src/statement/executed_async.rs index c5739c47..9173f2f7 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -248,6 +248,7 @@ pub struct ExecutedAsyncStatement { /// firing a wasted cancel+close against an already-finished /// statement. terminal_observed: AtomicBool, + volume: Option>, } /// Map an [`ExecutionTimeout`] onto the async handle's two deadline @@ -343,6 +344,7 @@ impl ExecutedAsyncStatement { poll_timeout_disabled, client_timeout_expired: AtomicBool::new(false), terminal_observed: AtomicBool::new(initial_terminal), + volume: None, } } @@ -351,6 +353,17 @@ impl ExecutedAsyncStatement { self } + pub(crate) fn with_volume(mut self, volume: Option>) -> Self { + self.volume = volume; + self + } + + fn cancel_volume(&self) { + if let Some(volume) = self.volume.as_ref().filter(|_| self.owning) { + volume.cancel(); + } + } + /// Crate-internal constructor for a **non-owning** (read-only /// adopt) handle, built by /// [`Session::attach_async_statement`](crate::Session::attach_async_statement). @@ -409,6 +422,7 @@ impl ExecutedAsyncStatement { poll_timeout_disabled: false, client_timeout_expired: AtomicBool::new(false), terminal_observed: AtomicBool::new(initial_terminal), + volume: None, } } @@ -430,7 +444,8 @@ impl ExecutedAsyncStatement { self.session_attribution, status, ) - .with_parameter_set_count(self.parameter_set_count), + .with_parameter_set_count(self.parameter_set_count) + .with_volume(self.volume.clone()), }) } @@ -1006,6 +1021,9 @@ impl ExecutedAsyncStatement { } let mut stream = ResultStream::from_reader(result.reader).await?; stream.attach_telemetry(self.statement_telemetry.clone()); + stream + .complete_volume(result.manifest.as_ref(), self.volume.as_ref(), self.owning) + .await?; // SEA carries no row count on the async status either; for a // DML the count rides in the result set. Derive it once // (non-consuming) and record it onto the latest status so @@ -1078,7 +1096,8 @@ impl AsyncStatementReader { /// Poll until terminal and return a fresh result stream. /// /// The session's polling timeout applies to this read. Timing out or - /// dropping the future leaves the server statement running. + /// dropping the future leaves the server statement and any Volume transfer + /// running. pub async fn await_result(&self) -> Result { self.inner.await_result().await } @@ -1149,6 +1168,7 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement { } async fn cancel(&self) -> Result<()> { + self.cancel_volume(); async { self.valid.check()?; // A non-owning (attached) handle must not cancel a statement @@ -1191,6 +1211,7 @@ impl ExecutedAsyncStatement { } async fn close_server_statement(&self) -> Result<()> { + self.cancel_volume(); if self.owning { self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); @@ -1252,20 +1273,21 @@ impl ExecutedAsyncStatement { // either — otherwise the footgun just moves to the detached // canceller. owning: self.owning, + volume: self.volume.clone().filter(|_| self.owning), } } } /// Detached canceller for an in-flight async statement. /// -/// Holds only the shared session handle, the statement id, and the -/// shared [`ValidityFlag`] — **not** the [`ExecutedAsyncStatement`] -/// itself — so a binding can fire a server-side cancel while the handle +/// Holds only the shared session handle, the statement id, the shared +/// [`ValidityFlag`] and the Volume transfer state, **not** the [`ExecutedAsyncStatement`] +/// itself, so a binding can fire a server-side cancel while the handle /// is borrowed elsewhere (e.g. parked inside a long-running /// [`ExecutedAsyncStatement::await_result`] that a binding-side lock is /// held across). Produced by [`ExecutedAsyncStatement::canceller`]. /// -/// Cheap to [`Clone`] (one `Arc` bump plus a `String` / flag clone). +/// Cheap to [`Clone`] (`Arc` bumps plus a `String` / flag clone). #[derive(Clone)] pub struct AsyncStatementCanceller { session: Arc, @@ -1276,6 +1298,7 @@ pub struct AsyncStatementCanceller { /// cancel a statement it doesn't own. See /// [`ExecutedAsyncStatement::owning`]. owning: bool, + volume: Option>, } impl AsyncStatementCanceller { @@ -1288,8 +1311,12 @@ impl AsyncStatementCanceller { /// there. Byte-for-byte the same operation as /// [`ExecutedAsyncStatement::cancel`]; the two share no mutable /// state, so this can run concurrently with an in-flight - /// `await_result` on the same statement. + /// `await_result` on the same statement. A running Volume transfer + /// stops too. pub async fn cancel(&self) -> Result<()> { + if let Some(volume) = &self.volume { + volume.cancel(); + } async { self.valid.check()?; if !self.owning { @@ -1316,6 +1343,7 @@ impl AsyncStatementCanceller { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { + self.cancel_volume(); if self.owning { self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index c1130b7e..1a0344ce 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -103,6 +103,8 @@ pub enum DirectStatement { /// the binding's `block_on` runs the execute future to completion. type InflightId = Arc>>; +type VolumeSlot = Arc>>; + /// Resolve the SEA `(wait_timeout, on_wait_timeout)` pair for an execute / /// submit dispatch. Pure so the precedence rules are unit-testable without /// a live `Session`. @@ -305,12 +307,16 @@ pub struct Statement { /// new `execute()` / `submit()` so a canceller never targets a /// stale prior statement. inflight_id: InflightId, + /// The current execution's Volume transfer state, shared with + /// [`StatementCanceller`]. + volume: VolumeSlot, } 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 = Arc::new(Mutex::new(session.new_volume_state(None))); Self { session, spec: StatementSpec::new(), @@ -318,6 +324,7 @@ impl Statement { last_valid: None, last_closed: None, inflight_id: Arc::new(Mutex::new(None)), + volume, } } @@ -334,7 +341,7 @@ impl Statement { /// once the server issues the statement id mid-execute, the /// canceller's [`cancel`](StatementCanceller::cancel) reaches it. /// - /// Cheap to clone (two `Arc` bumps). If `cancel()` fires before the + /// Cheap to clone (three `Arc` bumps). If `cancel()` fires before the /// id is observed (query still in the initial submit round-trip) it /// is a no-op; the per-call drop guard still covers the /// future-dropped case. @@ -342,6 +349,7 @@ impl Statement { StatementCanceller { session: Arc::clone(&self.session), inflight_id: Arc::clone(&self.inflight_id), + volume: Arc::clone(&self.volume), } } @@ -407,6 +415,7 @@ impl Statement { // canceller retained across a re-execute can't target the prior // query during the handoff (see `reset_inflight_slot`). self.reset_inflight_slot(); + let volume = self.begin_volume(); let telemetry = self.statement_telemetry(OperationType::ExecuteStatement); let telemetry_for_body = telemetry.clone(); let mut result = async { @@ -472,6 +481,9 @@ impl Statement { let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); + result_stream + .complete_volume(result.manifest.as_ref(), Some(&volume), true) + .await?; // 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 // already supply `num_modified_rows`, derive it from that @@ -503,6 +515,8 @@ impl Statement { .await; if let Err(error) = &mut result { self.finish_failed_batch(error).await; + // A failed execute returns no handle, so close a statement it already ran. + self.invalidate_prior().await; telemetry.finalize(Some(error)); } result @@ -543,6 +557,7 @@ impl Statement { // Clear the shared in-flight-id slot before the first `.await` // (see `reset_inflight_slot`). self.reset_inflight_slot(); + let volume = self.begin_volume(); let telemetry = self.statement_telemetry(OperationType::ExecuteStatementAsync); let telemetry_for_body = telemetry.clone(); let mut result = async { @@ -619,7 +634,8 @@ impl Statement { telemetry_for_body, timeout, ) - .with_parameter_set_count(exec_params.parameter_sets.len())) + .with_parameter_set_count(exec_params.parameter_sets.len()) + .with_volume(Some(volume))) } .instrument(span) .await; @@ -662,6 +678,7 @@ impl Statement { // Clear the shared in-flight-id slot before the first `.await` // (see `reset_inflight_slot`). self.reset_inflight_slot(); + let volume = self.begin_volume(); let telemetry = self.statement_telemetry(OperationType::ExecuteStatement); let telemetry_for_body = telemetry.clone(); let mut result = async { @@ -717,6 +734,9 @@ impl Statement { self.last_closed = Some(Arc::clone(&closed)); let mut result_stream = ResultStream::from_reader(result.reader).await?; result_stream.attach_telemetry(telemetry_for_body.clone()); + result_stream + .complete_volume(result.manifest.as_ref(), Some(&volume), true) + .await?; let mut status = result.status; let parameter_set_count = exec_params.parameter_sets.len(); // Optional count reads must not turn a successful write into an execute error. @@ -768,7 +788,8 @@ impl Statement { telemetry_for_body, ExecutionTimeout::Default, ) - .with_parameter_set_count(exec_params.parameter_sets.len()), + .with_parameter_set_count(exec_params.parameter_sets.len()) + .with_volume(Some(Arc::clone(&volume))), )) } } @@ -777,6 +798,8 @@ impl Statement { .await; if let Err(error) = &mut result { self.finish_failed_batch(error).await; + // A failed execute returns no handle, so close a statement it already ran. + self.invalidate_prior().await; telemetry.finalize(Some(error)); } result @@ -825,6 +848,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.current_volume().cancel(); let span = self.session.log_span().clone(); async { self.invalidate_prior().await; @@ -881,6 +905,24 @@ impl Statement { } } + fn begin_volume(&mut self) -> Arc { + let options = self.spec.volume.as_mut().map(|options| { + let input_bytes = options.input_bytes.take(); + crate::volume::VolumeOptions { + input_bytes, + ..options.clone() + } + }); + let state = self.session.new_volume_state(options); + let mut slot = self.volume.lock().unwrap_or_else(|e| e.into_inner()); + std::mem::replace(&mut *slot, Arc::clone(&state)).cancel(); + state + } + + fn current_volume(&self) -> Arc { + Arc::clone(&self.volume.lock().unwrap_or_else(|e| e.into_inner())) + } + /// Auto-close any prior executed handle this `Statement` produced. /// /// Happy path: by the time the caller is starting a *new* @@ -1024,11 +1066,12 @@ impl Drop for MidExecuteCancelGuard { /// 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: VolumeSlot, } impl StatementCanceller { @@ -1054,8 +1097,13 @@ 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. A running Volume transfer stops too. pub async fn cancel(&self) -> Result { + self.volume + .lock() + .unwrap_or_else(|e| e.into_inner()) + .cancel(); 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 @@ -1097,9 +1145,10 @@ impl Drop for Statement { if let Some(valid) = self.last_valid.take() { valid.invalidate(); } - // `last_statement_id` is left as-is. By construction it is - // only set immediately before `ExecutedStatement::new` - // wraps it; if the caller still holds an `ExecutedStatement`, + self.current_volume().cancel(); + // `last_statement_id` is left as-is. An execute that sets it + // either wraps it in an executed handle or, on failure, closes + // the statement; if the caller still holds an executed handle, // that handle owns the close-on-drop responsibility. If the // caller dropped the handle before this `Statement`, the // handle's own `Drop` already spawned the close. There is no diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 4ff8693a..28392979 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -26,6 +26,7 @@ //! between executions. use crate::kernel_error::{Error, ErrorCode, Result}; +use crate::volume::VolumeOptions; use std::collections::HashMap; /// A typed value bound as a SQL parameter. @@ -232,6 +233,9 @@ pub struct StatementSpec { /// Result wire format. pub result_format: ResultFormat, + + /// Volume transfer settings; see [`VolumeOptions`]. + pub volume: Option, } impl StatementSpec { @@ -245,7 +249,7 @@ impl StatementSpec { /// parameter sets, so each `sql()` begins a fresh set of *bound parameters*. /// /// Scope note: this clears bound parameters and native parameter sets. It does - /// **not** reset `statement_conf` (e.g. query tags) or `row_limit`, which + /// **not** reset `statement_conf` (e.g. query tags), `row_limit` or `volume`, which /// survive a `sql()` call and must be re-set explicitly if a reused handle /// should not carry them into the next query. /// @@ -428,6 +432,12 @@ impl StatementSpec { self.result_format = fmt; self } + + /// Set the Volume transfer settings. + pub fn volume(&mut self, options: Option) -> &mut Self { + self.volume = options; + self + } } /// Serialise a tag map to the comma-separated `key:value` wire shape the diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 88b62b75..51b0f612 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -373,6 +373,49 @@ mod tests { } } + #[tokio::test] + async fn failed_volume_completion_finalizes_statement_with_error() { + let connection = Arc::new(CapturingConnectionTelemetry::default()); + let telemetry = StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + ); + let batch = RecordBatch::try_from_iter([( + "n", + Arc::new(arrow_array::Int64Array::from(vec![1])) as arrow_array::ArrayRef, + )]) + .unwrap(); + let reader = crate::reader::test_utils::MockReader::new(vec![batch]); + let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); + stream.attach_telemetry(telemetry); + let manifest: crate::types::sea::ResultManifest = + serde_json::from_value(serde_json::json!({ + "is_volume_operation": true, + "format": "ARROW_STREAM", + "schema": {"column_count": 1, "columns": []}, + })) + .unwrap(); + let storage = Arc::new(crate::volume::Storage::new( + Default::default(), + None, + Default::default(), + None, + tokio::runtime::Handle::current(), + )); + let volume = storage.transfer_state(Some(Default::default())); + let error = stream + .complete_volume(Some(&manifest), Some(&volume), true) + .await + .unwrap_err(); + + drop(stream); + + let events = connection.statement_events.lock().expect("events mutex"); + assert_eq!(events.len(), 1); + assert_eq!(events[0].error_code, Some(error.code)); + } + #[tokio::test] async fn peek_first_batch_error_finalizes_statement_with_error_before_drop() { let connection = Arc::new(CapturingConnectionTelemetry::default()); diff --git a/src/types/sea.rs b/src/types/sea.rs index 32e18c62..5f303cd8 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -211,6 +211,8 @@ pub struct ResultManifest { /// instead of the SQL statement's raw `SHOW` / information-schema shape. #[serde(default)] pub is_native_metadata_result: Option, + #[serde(default)] + pub is_volume_operation: bool, } /// Schema of the result set. diff --git a/src/volume.rs b/src/volume.rs new file mode 100644 index 00000000..49fcf7cd --- /dev/null +++ b/src/volume.rs @@ -0,0 +1,1835 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Volume PUT, GET and REMOVE file transfers. +//! +//! The server answers these statements with one row holding a presigned +//! storage URL, request headers and, for PUT and GET, a local path. This +//! module makes the storage request that row describes. + +use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; +use crate::client::retry::{calculate_backoff, RequestType, RetryConfig, RetryStrategy}; +use crate::kernel_error::{Error, LocalFileError, Result}; +use arrow_array::cast::AsArray; +use arrow_array::{Array, ArrayRef, RecordBatch}; +use arrow_schema::DataType; +use futures::future::{BoxFuture, Shared}; +use futures::{FutureExt, Stream, StreamExt, TryStreamExt}; +use reqwest::header::{HeaderMap, HeaderName, HeaderValue, CONTENT_LENGTH, RETRY_AFTER}; +use reqwest::{Client, Method, Response, StatusCode, Url}; +use std::io::Seek; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, OnceLock}; +use std::time::{Duration, Instant}; +use tokio::io::{AsyncSeekExt, AsyncWrite, AsyncWriteExt}; +use tokio::sync::{watch, OnceCell}; +use tokio_util::bytes::Bytes; +use tokio_util::sync::CancellationToken; + +const ERROR_BODY_LIMIT: usize = 4096; +const UPLOAD_CHUNK: usize = 256 * 1024; +#[cfg(unix)] +const PIPE_READER_POLL: Duration = Duration::from_millis(50); + +/// Caller settings for Volume file transfers, set on +/// [`StatementSpec::volume`](crate::StatementSpec::volume). +/// +/// With options set, executing a statement whose result the server marks as a +/// Volume PUT, GET or REMOVE also runs its storage transfer, and the execution +/// fails if the transfer does. Without them, the execution returns +/// the instruction row and moves no file. Either way the instruction row stays +/// readable. +/// +/// A PUT reads a regular file, or uploads [`input_bytes`](Self::input_bytes) +/// for `PUT '__input_stream__'`. A GET writes the object's content, decoding +/// a gzip `Content-Encoding`. A GET into a new file removes it if the download +/// fails or is cancelled. A GET into an existing file replaces its content +/// only after the download succeeds; a failure while copying into it can leave +/// it partly written. An existing file whose folder refuses a temporary file +/// is written directly, so there a failed or cancelled download can leave it +/// truncated or partly written. On Unix a GET also writes into an existing +/// pipe or character device as the download arrives: a pipe waits for a +/// reader up to the idle limit, and a failure after the first bytes reach it +/// is not retried. +/// +/// The idle limit is the session's +/// [`HttpConfig::request_timeout`](crate::HttpConfig::request_timeout): a +/// transfer fails after that long without progress. +/// +/// Cancelling the execution stops the transfer, and so does dropping a call +/// that waits on it, unless an [`AsyncStatementReader`](crate::AsyncStatementReader) +/// made the call. Stopping cannot undo a PUT or REMOVE that storage already +/// applied, and a GET whose download is already being copied into an existing +/// file finishes that copy. +#[non_exhaustive] +#[derive(Clone, Default)] +pub struct VolumeOptions { + /// Directories a PUT may read from and a GET may write to. The local path, + /// with symlinks resolved, must be inside one of them when the file is + /// opened or created. The check assumes nothing else swaps files or links in + /// these directories during a transfer. + pub allowed_paths: Vec, + /// Report success when REMOVE targets an object that does not exist. + pub remove_not_found_is_success: bool, + /// The content `PUT '__input_stream__'` uploads. Without it, that PUT fails. + /// On a [`StatementSpec`](crate::StatementSpec), the next execution takes + /// it, even one that fails or is not a Volume PUT. + pub input_bytes: Option, +} + +impl VolumeOptions { + pub fn new(allowed_paths: Vec, remove_not_found_is_success: bool) -> Self { + Self { + allowed_paths, + remove_not_found_is_success, + input_bytes: None, + } + } + + /// Sets the content `PUT '__input_stream__'` uploads. + pub fn with_input_bytes(mut self, input_bytes: impl Into) -> Self { + self.input_bytes = Some(input_bytes.into()); + self + } +} + +impl std::fmt::Debug for VolumeOptions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VolumeOptions") + .field("allowed_paths", &self.allowed_paths) + .field( + "remove_not_found_is_success", + &self.remove_not_found_is_success, + ) + .field("input_bytes", &self.input_bytes.as_ref().map(Bytes::len)) + .finish() + } +} + +pub(crate) struct Storage { + config: HttpClientConfig, + revocation: Option, + client: OnceCell, + retry: RetryConfig, + idle_limit: Option, + cancellation: CancellationToken, + runtime: tokio::runtime::Handle, +} + +impl Storage { + pub(crate) fn new( + config: HttpClientConfig, + revocation: Option, + retry: RetryConfig, + idle_limit: Option, + runtime: tokio::runtime::Handle, + ) -> Self { + Self { + config, + revocation, + client: OnceCell::new(), + retry, + idle_limit: idle_limit.filter(|limit| !limit.is_zero()), + cancellation: CancellationToken::new(), + runtime, + } + } + + pub(crate) fn transfer_state( + self: &Arc, + mut options: Option, + ) -> Arc { + let input_bytes = options + .as_mut() + .and_then(|options| options.input_bytes.take()); + Arc::new(VolumeState { + storage: Arc::clone(self), + options, + input_bytes: std::sync::Mutex::new(input_bytes), + cancellation: self.cancellation.child_token(), + outcome: OnceLock::new(), + }) + } + + pub(crate) fn cancel_all(&self) { + self.cancellation.cancel(); + } + + async fn client(&self) -> Result<&Client> { + self.client + .get_or_try_init(|| async { + DatabricksHttpClient::storage_client(&self.config, self.revocation) + }) + .await + } +} + +type Outcome = Shared>>; + +/// One execution's transfer. Every result stream of the execution shares it, +/// so the transfer runs at most once. +pub(crate) struct VolumeState { + storage: Arc, + options: Option, + /// Taken when the transfer starts, so the upload does not outlive it. + input_bytes: std::sync::Mutex>, + cancellation: CancellationToken, + /// The spawned transfer. Every call waits on it, and only cancellation stops it. + outcome: OnceLock, +} + +impl VolumeState { + pub(crate) fn cancel(&self) { + self.cancellation.cancel(); + } + + /// Runs the transfer `instruction` describes, once per execution. Dropping an + /// `owner` call cancels the transfer; dropping any other call leaves it running. + pub(crate) async fn complete( + self: &Arc, + instruction: Result>, + owner: bool, + ) -> Result<()> { + let Some(options) = &self.options else { + return Ok(()); + }; + let outcome = match self.outcome.get() { + Some(outcome) => outcome.clone(), + None => { + // Nothing before the transfer is kept: another result stream of the + // execution may still read the instruction. + let batch = + instruction?.ok_or_else(|| invalid("Missing Volume instruction row"))?; + let instruction = Instruction::decode(&batch)?; + self.outcome + .get_or_init(|| self.spawn(instruction, options.clone())) + .clone() + } + }; + let cancel_on_drop = owner.then(|| self.cancellation.clone().drop_guard()); + let outcome = outcome.await; + if let Some(guard) = cancel_on_drop { + guard.disarm(); + } + outcome + } + + fn spawn(self: &Arc, instruction: Instruction, options: VolumeOptions) -> Outcome { + let state = Arc::clone(self); + // On the session runtime's threads, which kernel-owned runtimes set to + // block SIGPIPE, a pipe whose reader exits fails the write instead of + // killing the host. + let task = self + .storage + .runtime + .spawn(async move { state.run(instruction, &options).await }); + async move { + task.await.unwrap_or_else(|e| { + Err(Error::internal().message(format!("Volume transfer failed: {e}"))) + }) + } + .boxed() + .shared() + } + + async fn run(&self, instruction: Instruction, options: &VolumeOptions) -> Result<()> { + let input_bytes = self + .input_bytes + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take(); + if matches!(instruction.operation, Operation::Put(None)) && input_bytes.is_none() { + return Err(Error::invalid_argument() + .message("A Volume PUT of __input_stream__ needs input bytes")); + } + // Stopping the transfer drops it, which removes a new GET destination. + let local = tokio::select! { + biased; + _ = self.cancellation.cancelled() => return Err(cancelled()), + local = self.transfer(instruction, options, input_bytes) => local?, + }; + // Copying a download into an existing file cannot be stopped midway, so + // it runs to the end and the outcome reports the file it left. + local.publish().await + } + + async fn transfer( + &self, + instruction: Instruction, + options: &VolumeOptions, + input_bytes: Option, + ) -> Result { + let local = prepare( + instruction.operation.clone(), + options.allowed_paths.clone(), + input_bytes, + ) + .await?; + let client = self.storage.client().await?; + let retry = &self.storage.retry; + let strategy = RetryStrategy::for_request(RequestType::CloudFetchDownload, retry); + let mut first_failure = None; + let mut attempt = 0; + loop { + let (error, retry_after) = match self + .attempt(client, &instruction, &local, options, &strategy) + .await + { + Ok(()) => return Ok(local), + Err(failure) => failure, + }; + let wait = calculate_backoff(retry, attempt, retry_after.as_deref()); + // The retry budget runs from the first failure, so a long transfer that + // is still making progress keeps the whole budget for a late failure. + let waited = first_failure.get_or_insert_with(Instant::now).elapsed(); + if !error.retryable + || attempt >= retry.max_retries + || waited.saturating_add(wait) > retry.overall_timeout + { + return Err(error); + } + crate::klog::debug!( + attempt = attempt + 1, + wait_ms = wait.as_millis() as u64, + error = %error.message, + "retrying Volume storage request" + ); + tokio::time::sleep(wait).await; + attempt += 1; + } + } + + /// One storage request. A failure carries the response's `Retry-After` + /// value. + async fn attempt( + &self, + client: &Client, + instruction: &Instruction, + local: &Local, + options: &VolumeOptions, + strategy: &RetryStrategy, + ) -> std::result::Result<(), (Error, Option)> { + let method = local.method(); + let url = Url::parse(&instruction.url) + .map_err(|_| (invalid("Invalid Volume storage URL"), None))?; + let (progress, mut progressed) = watch::channel(()); + let mut headers = instruction.headers.clone(); + let mut body = None; + if let Some((chunks, length)) = local.upload() { + headers.insert(CONTENT_LENGTH, length.into()); + body = Some(reqwest::Body::wrap_stream(chunks.inspect_ok(move |_| { + progress.send_replace(()); + }))); + } + let mut request = client.request(method.clone(), url).headers(headers); + if let Some(body) = body { + request = request.body(body); + } + let response = self + .idle_bounded(&mut progressed, async { + request.send().await.map_err(|e| storage_error(e, strategy)) + }) + .await + .map_err(|e| (e, None))?; + let status = response.status(); + if status.is_success() + || (method == Method::DELETE + && status == StatusCode::NOT_FOUND + && options.remove_not_found_is_success) + { + return self + .receive(response, local, strategy) + .await + .map_err(|e| (e, None)); + } + Err(self.http_failure(response, strategy).await) + } + + /// Writes a GET response body. Bytes a pipe or device already took cannot + /// be taken back, so a failure after the first write is not retried. + async fn receive( + &self, + mut response: Response, + local: &Local, + strategy: &RetryStrategy, + ) -> Result<()> { + let Local::Download(download) = local else { + return Ok(()); + }; + let local_error = |e| local_error(e, &download.name); + let mut temp_file; + #[cfg(unix)] + let mut stream; + let (sink, rewindable): (&mut (dyn AsyncWrite + Send + Unpin), bool) = + match &download.destination { + Destination::Existing { + temp: Some(target), .. + } + | Destination::Existing { file: target, .. } + | Destination::New { file: target, .. } => { + temp_file = tokio::fs::File::from_std(target.try_clone().map_err(local_error)?); + temp_file.set_len(0).await.map_err(local_error)?; + temp_file.rewind().await.map_err(local_error)?; + (&mut temp_file, true) + } + #[cfg(unix)] + Destination::Stream { + fifo, + requested, + roots, + writer, + } => { + stream = writer.lock().await; + if stream.is_none() { + *stream = Some( + self.open_stream(requested, roots, *fifo, &download.name) + .await?, + ); + } + (stream.as_mut().expect("opened above").as_mut(), false) + } + }; + let mut writing = false; + let result = async { + while let Some(chunk) = self + .bounded(async { + response + .chunk() + .await + .map_err(|e| storage_error(e, strategy)) + }) + .await? + { + // A write cut short may already have reached the pipe or device. + writing = true; + self.bounded(async { sink.write_all(&chunk).await.map_err(local_error) }) + .await?; + } + self.bounded(async { sink.flush().await.map_err(local_error) }) + .await + } + .await; + if result.is_err() && rewindable { + // A write still in flight must land before a retry rewinds the file. + let _ = self + .bounded(async { sink.flush().await.map_err(local_error) }) + .await; + } + result.map_err(|error| { + if writing && !rewindable { + error.with_retryable(false) + } else { + error + } + }) + } + + /// Opens a GET's pipe or device. A pipe refuses a non-blocking open until + /// it has a reader, so the open is retried until one appears, the idle + /// limit passes or the transfer is cancelled. + #[cfg(unix)] + async fn open_stream( + &self, + requested: &Path, + roots: &[PathBuf], + fifo: bool, + name: &str, + ) -> Result> { + let path = allowed_path(requested, roots)?; + let local_error = |e| local_error(e, name); + if !fifo { + let device = tokio::fs::OpenOptions::new() + .write(true) + .open(&path) + .await + .map_err(local_error)?; + return Ok(Box::new(device)); + } + let wait_for_reader = async { + loop { + match tokio::net::unix::pipe::OpenOptions::new().open_sender(&path) { + Err(error) if error.raw_os_error() == Some(libc::ENXIO) => { + tokio::time::sleep(PIPE_READER_POLL).await + } + result => return result, + } + } + }; + let sender = match self.storage.idle_limit { + Some(limit) => tokio::time::timeout(limit, wait_for_reader) + .await + .unwrap_or_else(|_| Err(std::io::Error::from_raw_os_error(libc::ENXIO))), + None => wait_for_reader.await, + } + .map_err(local_error)?; + Ok(Box::new(sender)) + } + + async fn http_failure( + &self, + mut response: Response, + strategy: &RetryStrategy, + ) -> (Error, Option) { + let status = response.status(); + let retry_after = response + .headers() + .get(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(strategy.is_retryable_status(status, retry_after.is_some())) + .message(format!( + "Volume storage request failed: HTTP {}", + status.as_u16() + )); + 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}")); + } + } + let mut body = Vec::new(); + while body.len() < ERROR_BODY_LIMIT { + match self + .bounded(async { + response + .chunk() + .await + .map_err(|e| storage_error(e, strategy)) + }) + .await + { + Ok(Some(chunk)) => body.extend_from_slice(&chunk), + _ => break, + } + } + let body = String::from_utf8_lossy(&body); + for tag in ["Code", "Message"] { + if let Some(value) = xml_value(&body, tag) { + error = error.message(format!("{tag}: {value}")); + } + } + (error, retry_after) + } + + /// Runs `work`, failing once the idle limit passes without `progress` changing. + async fn idle_bounded( + &self, + progress: &mut watch::Receiver<()>, + work: impl std::future::Future>, + ) -> Result { + let Some(limit) = self.storage.idle_limit else { + return work.await; + }; + tokio::pin!(work); + loop { + tokio::select! { + result = &mut work => return result, + Ok(()) = progress.changed() => {} + () = tokio::time::sleep(limit) => return Err(no_progress(limit)), + } + } + } + + async fn bounded(&self, work: impl std::future::Future>) -> Result { + match self.storage.idle_limit { + Some(limit) => tokio::time::timeout(limit, work) + .await + .unwrap_or_else(|_| Err(no_progress(limit))), + None => work.await, + } + } +} + +#[derive(Clone)] +enum Operation { + /// `None` uploads caller-supplied bytes. + Put(Option), + Get(PathBuf), + Remove, +} + +struct Instruction { + operation: Operation, + url: String, + headers: HeaderMap, +} + +impl Instruction { + fn decode(batch: &RecordBatch) -> Result { + if batch.num_rows() != 1 { + return Err(invalid("Expected one Volume instruction row")); + } + let column = |name: &str| { + batch + .column_by_name(name) + .ok_or_else(|| invalid(&format!("Missing Volume instruction column {name}"))) + }; + let text = |name: &str| { + string_value(column(name)?)? + .ok_or_else(|| invalid(&format!("Missing Volume instruction field {name}"))) + }; + let local_path = || match text("localFile")? { + path if path.is_empty() => Err(invalid("Missing Volume instruction field localFile")), + path => Ok(PathBuf::from(path)), + }; + let operation = match text("operation")?.to_ascii_uppercase().as_str() { + "PUT" if text("localFile")? == "__input_stream__" => Operation::Put(None), + "PUT" => Operation::Put(Some(local_path()?)), + "GET" => Operation::Get(local_path()?), + "REMOVE" => Operation::Remove, + _ => return Err(invalid("Unsupported Volume operation")), + }; + Ok(Self { + operation, + url: text("presignedUrl")?, + headers: headers(column("headers")?)?, + }) + } +} + +fn string_value(column: &ArrayRef) -> Result> { + Ok(strings(column)?.into_iter().next().flatten()) +} + +fn strings(column: &ArrayRef) -> Result>> { + let column = arrow_cast::cast(column, &DataType::Utf8) + .map_err(|_| invalid("Invalid Volume instruction column type"))?; + Ok(column + .as_string::() + .iter() + .map(|value| value.map(str::to_owned)) + .collect()) +} + +/// Storage headers arrive as a map or as a JSON object; a blank string means none. +fn headers(column: &ArrayRef) -> Result { + let pairs: Vec<(String, String)> = if column.is_null(0) { + Vec::new() + } else if let Some(map) = column.as_map_opt() { + let entries = map.value(0); + strings(entries.column(0))? + .into_iter() + .zip(strings(entries.column(1))?) + .map(|pair| match pair { + (Some(name), Some(value)) => Ok((name, value)), + _ => Err(invalid("Invalid Volume storage headers")), + }) + .collect::>()? + } else { + match string_value(column)?.unwrap_or_default().trim() { + "" => Vec::new(), + text => serde_json::from_str::>(text) + .map_err(|_| invalid("Invalid Volume storage headers"))? + .into_iter() + .collect(), + } + }; + let mut headers = HeaderMap::new(); + for (name, value) in pairs { + headers.insert( + HeaderName::from_bytes(name.as_bytes()) + .map_err(|_| invalid("Invalid Volume storage header name"))?, + HeaderValue::from_str(&value) + .map_err(|_| invalid("Invalid Volume storage header value"))?, + ); + } + Ok(headers) +} + +enum Local { + Upload(Upload), + Download(Download), + Remove, +} + +enum Upload { + File { + file: Arc, + length: u64, + name: String, + }, + Bytes(Bytes), +} + +struct Download { + destination: Destination, + name: String, +} + +enum Destination { + /// Overwritten with a copy of `temp`, keeping the file itself. Without + /// `temp`, because the folder refuses one, the download writes into it. + Existing { + file: std::fs::File, + temp: Option, + }, + /// Created for this download, and removed unless the download completes. + New { + file: std::fs::File, + path: tempfile::TempPath, + }, + /// A pipe or character device, written as the download arrives. It is + /// opened once, for the first response, and kept open across retries so + /// its reader does not see an early end. + #[cfg(unix)] + Stream { + fifo: bool, + requested: PathBuf, + roots: Vec, + writer: tokio::sync::Mutex>>, + }, +} + +async fn prepare( + operation: Operation, + roots: Vec, + input_bytes: Option, +) -> Result { + tokio::task::spawn_blocking(move || match operation { + Operation::Put(None) => Ok(Local::Upload(Upload::Bytes( + input_bytes.unwrap_or_default(), + ))), + Operation::Put(Some(requested)) => { + let path = allowed_path(&requested, &roots)?; + let name = requested.to_string_lossy().into_owned(); + let local_error = |e| local_error(e, &name); + let metadata = std::fs::metadata(&path).map_err(local_error)?; + if !metadata.is_file() { + return Err(unsupported_file( + &metadata, + &name, + "A Volume PUT reads regular files only", + )); + } + let file = std::fs::File::open(&path).map_err(local_error)?; + Ok(Local::Upload(Upload::File { + file: Arc::new(file), + length: metadata.len(), + name, + })) + } + Operation::Get(requested) => { + let path = allowed_path(&requested, &roots)?; + let name = requested.to_string_lossy().into_owned(); + let local_error = |e| local_error(e, &name); + let parent = path + .parent() + .ok_or_else(|| invalid("Invalid Volume local file"))?; + let destination = match std::fs::metadata(&path) { + Ok(metadata) if metadata.is_file() => { + let file = std::fs::OpenOptions::new() + .write(true) + .open(&path) + .map_err(local_error)?; + let temp = match tempfile::tempfile_in(parent) { + Ok(temp) => Some(temp), + Err(error) + if matches!( + error.kind(), + std::io::ErrorKind::PermissionDenied + | std::io::ErrorKind::ReadOnlyFilesystem + ) => + { + None + } + Err(error) => return Err(local_error(error)), + }; + Destination::Existing { file, temp } + } + #[cfg(unix)] + Ok(metadata) if is_stream(&metadata) => Destination::Stream { + fifo: std::os::unix::fs::FileTypeExt::is_fifo(&metadata.file_type()), + requested, + roots, + writer: tokio::sync::Mutex::new(None), + }, + Ok(metadata) => { + return Err(unsupported_file( + &metadata, + &name, + if cfg!(unix) { + "A Volume GET writes regular files, pipes and character devices only" + } else { + "A Volume GET writes regular files only" + }, + )) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + let file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .map_err(local_error)?; + Destination::New { + file, + path: tempfile::TempPath::try_from_path(path).map_err(local_error)?, + } + } + Err(error) => return Err(local_error(error)), + }; + Ok(Local::Download(Download { destination, name })) + } + Operation::Remove => Ok(Local::Remove), + }) + .await + .map_err(|e| Error::internal().message(format!("Volume file preparation failed: {e}")))? +} + +impl Local { + fn method(&self) -> Method { + match self { + Local::Upload(_) => Method::PUT, + Local::Download(_) => Method::GET, + Local::Remove => Method::DELETE, + } + } + + /// The upload as chunks, each a separate unit of progress, and its length. + fn upload(&self) -> Option<(futures::stream::BoxStream<'static, Result>, u64)> { + Some(match self { + Local::Upload(Upload::File { file, length, name }) => ( + file_chunks(Arc::clone(file), *length, name.clone()).boxed(), + *length, + ), + Local::Upload(Upload::Bytes(bytes)) => { + let all = bytes.clone(); + let chunks = (0..bytes.len()) + .step_by(UPLOAD_CHUNK) + .map(move |start| Ok(all.slice(start..all.len().min(start + UPLOAD_CHUNK)))); + (futures::stream::iter(chunks).boxed(), bytes.len() as u64) + } + Local::Download(_) | Local::Remove => return None, + }) + } + + async fn publish(self) -> Result<()> { + let Local::Download(Download { destination, name }) = self else { + return Ok(()); + }; + tokio::task::spawn_blocking(move || { + let local_error = |e| local_error(e, &name); + match destination { + Destination::Existing { + mut file, + temp: Some(mut temp), + } => { + temp.rewind().map_err(local_error)?; + let length = std::io::copy(&mut temp, &mut file).map_err(local_error)?; + file.set_len(length).map_err(local_error) + } + Destination::Existing { temp: None, .. } => Ok(()), + Destination::New { path, .. } => { + path.keep().map(drop).map_err(|e| local_error(e.error)) + } + #[cfg(unix)] + Destination::Stream { .. } => Ok(()), + } + }) + .await + .map_err(|e| Error::internal().message(format!("Volume download copy failed: {e}")))? + } +} + +/// Reads the first `length` bytes of `file` by offset, so a request never +/// shares a file position with an earlier one that still holds the handle. +fn file_chunks( + file: Arc, + length: u64, + name: String, +) -> impl Stream> + Send + 'static { + futures::stream::try_unfold(0, move |offset| { + let (file, name) = (Arc::clone(&file), name.clone()); + async move { + if offset >= length { + return Ok(None); + } + let size = (length - offset).min(UPLOAD_CHUNK as u64) as usize; + let chunk = tokio::task::spawn_blocking(move || { + let mut chunk = vec![0; size]; + let read = read_at(&file, &mut chunk, offset)?; + chunk.truncate(read); + Ok::<_, std::io::Error>(chunk) + }) + .await + .map_err(|e| Error::internal().message(format!("Volume upload read failed: {e}")))? + .map_err(|e| local_error(e, &name))?; + if chunk.is_empty() { + return Err(local_error(std::io::ErrorKind::UnexpectedEof.into(), &name)); + } + let next = offset + chunk.len() as u64; + Ok(Some((Bytes::from(chunk), next))) + } + }) +} + +fn read_at(file: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result { + #[cfg(unix)] + { + std::os::unix::fs::FileExt::read_at(file, buf, offset) + } + #[cfg(windows)] + { + std::os::windows::fs::FileExt::seek_read(file, buf, offset) + } +} + +fn xml_value<'a>(body: &'a str, tag: &str) -> Option<&'a str> { + let (_, rest) = body.split_once(&format!("<{tag}>"))?; + let (value, _) = rest.split_once(&format!(""))?; + (!value.contains(['<', '>'])).then_some(value) +} + +fn allowed_path(requested: &Path, roots: &[PathBuf]) -> Result { + let name = requested.to_string_lossy(); + let path = resolve(requested).map_err(|e| local_error(e, &name))?; + if roots + .iter() + .filter(|root| !root.as_os_str().is_empty()) + .filter_map(|root| resolve(root).ok()) + .any(|root| path.starts_with(root)) + { + Ok(path) + } else { + Err(Error::invalid_argument() + .with_error_code("VOLUME_PATH_NOT_ALLOWED") + .message(format!( + "Local file path is outside the configured allowed roots: {name}" + ))) + } +} + +fn unsupported_file(metadata: &std::fs::Metadata, name: &str, allowed: &str) -> Error { + let error = if metadata.is_dir() { + #[cfg(unix)] + let error = std::io::Error::from_raw_os_error(libc::EISDIR); + #[cfg(not(unix))] + let error = std::io::Error::from(std::io::ErrorKind::IsADirectory); + error + } else { + std::io::Error::new(std::io::ErrorKind::InvalidInput, allowed) + }; + local_error(error, name) +} + +#[cfg(unix)] +fn is_stream(metadata: &std::fs::Metadata) -> bool { + use std::os::unix::fs::FileTypeExt; + let file_type = metadata.file_type(); + file_type.is_fifo() || file_type.is_char_device() +} + +/// `path` made absolute with symlinks resolved. Trailing components that do +/// not exist yet are kept as written; a dangling symlink is an error. +fn resolve(path: &Path) -> std::io::Result { + let absolute = std::path::absolute(path)?; + let mut existing = absolute.as_path(); + let mut missing = Vec::new(); + loop { + match existing.canonicalize() { + Ok(resolved) => { + return Ok(missing + .iter() + .rev() + .fold(resolved, |path, name| path.join(name))) + } + Err(error) + if error.kind() == std::io::ErrorKind::NotFound + && existing.symlink_metadata().is_err() => + { + match (existing.parent(), existing.file_name()) { + (Some(parent), Some(name)) => { + missing.push(name); + existing = parent; + } + _ => return Err(error), + } + } + Err(error) => return Err(error), + } + } +} + +fn invalid(message: &str) -> Error { + Error::invalid_argument() + .with_error_code("VOLUME_INVALID_INSTRUCTION") + .message(message) +} + +fn cancelled() -> Error { + Error::cancelled().message("Volume transfer was cancelled") +} + +fn no_progress(limit: Duration) -> Error { + network(format!( + "Volume storage transfer made no progress for {} seconds", + limit.as_secs_f64() + )) +} + +fn network(message: impl AsRef) -> Error { + Error::network_error() + .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") + .message(message) +} + +fn storage_error(error: reqwest::Error, strategy: &RetryStrategy) -> Error { + // The upload body reports a failed read of the local source as a local error. + if let Some(local) = + crate::client::error_chain(&error).find_map(|cause| cause.downcast_ref::()) + { + return local.clone(); + } + let retryable = error.is_body() || error.is_decode() || strategy.is_retryable_error(&error); + // The URL is presigned; it must not reach the message. + let error = error.without_url(); + let mut causes = crate::client::error_chain(&error) + .map(ToString::to_string) + .collect::>(); + causes.dedup(); + network(format!( + "Volume storage request failed: {}", + causes.join(": ") + )) + .with_retryable(retryable) +} + +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") + .message(format!("{error}: {path}")) + .with_local_error(LocalFileError::new( + error.raw_os_error(), + error.kind(), + path, + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ErrorCode; + use arrow_array::builder::{MapBuilder, StringBuilder}; + use arrow_array::StringArray; + use tokio::io::AsyncReadExt; + use wiremock::matchers::{body_bytes, header, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + fn storage(max_retries: u32, idle_limit: Option) -> Arc { + let retry = RetryConfig { + max_retries, + min_wait: Duration::ZERO, + max_wait: Duration::ZERO, + ..Default::default() + }; + Arc::new(Storage::new( + HttpClientConfig::default(), + None, + retry, + idle_limit, + tokio::runtime::Handle::current(), + )) + } + + fn state(storage: &Arc, root: &Path) -> Arc { + storage.transfer_state(Some(VolumeOptions::new(vec![root.to_owned()], false))) + } + + async fn run(storage: &Arc, batch: RecordBatch, root: &Path) -> Result<()> { + state(storage, root).complete(Ok(Some(batch)), true).await + } + + /// An instruction row as the server sends it, with headers as a map. + fn instruction(operation: &str, url: &str, local: &Path) -> RecordBatch { + instruction_with_headers(operation, url, Some(local), &[("x-test", "yes")]) + } + + /// A REMOVE instruction row, which has no `localFile` column. + fn remove(url: &str) -> RecordBatch { + instruction_with_headers("REMOVE", url, None, &[]) + } + + fn instruction_with_headers( + operation: &str, + url: &str, + local: Option<&Path>, + headers: &[(&str, &str)], + ) -> RecordBatch { + let mut map = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); + for (name, value) in headers { + map.keys().append_value(name); + map.values().append_value(value); + } + map.append(true).unwrap(); + let mut columns = vec![ + ( + "operation", + Arc::new(StringArray::from(vec![operation])) as ArrayRef, + ), + ("presignedUrl", Arc::new(StringArray::from(vec![url])) as _), + ("headers", Arc::new(map.finish()) as _), + ]; + if let Some(local) = local { + columns.push(( + "localFile", + Arc::new(StringArray::from(vec![local.to_str().unwrap()])) as _, + )); + } + RecordBatch::try_from_iter(columns).unwrap() + } + + async fn mount(server: &MockServer, verb: &str, route: &str, response: ResponseTemplate) { + Mock::given(method(verb)) + .and(path(route)) + .respond_with(response) + .expect(1) + .mount(server) + .await; + } + + async fn requested(server: &MockServer) { + while server.received_requests().await.unwrap().is_empty() { + tokio::task::yield_now().await; + } + } + + #[cfg(unix)] + fn privileged() -> bool { + unsafe { libc::geteuid() == 0 } + } + + #[tokio::test] + async fn put_get_and_remove_move_exact_bytes() { + let payload = b"\0\xffvolume bytes".to_vec(); + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(path("/put")) + .and(header("x-test", "yes")) + .and(body_bytes(payload.clone())) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let get = ResponseTemplate::new(200).set_body_bytes(payload.clone()); + mount(&server, "GET", "/get", get).await; + mount(&server, "DELETE", "/remove", ResponseTemplate::new(200)).await; + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + std::fs::write(&source, &payload).unwrap(); + // An existing destination ends with exactly the download, even if it was longer. + let destination = dir.path().join("destination"); + std::fs::write(&destination, b"an older and longer file").unwrap(); + let url = |name: &str| format!("{}/{name}", server.uri()); + let storage = storage(0, None); + + run( + &storage, + instruction("PUT", &url("put"), &source), + dir.path(), + ) + .await + .unwrap(); + let get = instruction("GET", &url("get"), &destination); + run(&storage, get, dir.path()).await.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), payload); + run(&storage, remove(&url("remove")), dir.path()) + .await + .unwrap(); + } + + #[tokio::test] + async fn the_upload_length_replaces_an_instruction_content_length() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(header("content-length", "7")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + std::fs::write(&source, b"payload").unwrap(); + let headers = [("Content-Length", "1")]; + let put = instruction_with_headers("PUT", &server.uri(), Some(&source), &headers); + run(&storage(0, None), put, dir.path()).await.unwrap(); + } + + #[tokio::test] + async fn an_input_stream_put_uploads_the_input_bytes() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(body_bytes(b"caller bytes".to_vec())) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let put = instruction("PUT", &server.uri(), Path::new("__input_stream__")); + let storage = storage(0, None); + let without = storage.transfer_state(Some(VolumeOptions::default())); + let error = without + .complete(Ok(Some(put.clone())), true) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + let bytes = Bytes::from(b"caller bytes".to_vec()); + let options = VolumeOptions::default().with_input_bytes(bytes.clone()); + let with = storage.transfer_state(Some(options)); + with.complete(Ok(Some(put)), true).await.unwrap(); + // The finished transfer no longer holds the upload. + assert!(bytes.is_unique()); + } + + #[tokio::test] + async fn a_failed_get_into_a_new_file_leaves_no_file() { + let server = MockServer::start().await; + mount(&server, "GET", "/", ResponseTemplate::new(500)).await; + let dir = tempfile::tempdir().unwrap(); + let get = instruction("GET", &server.uri(), &dir.path().join("new")); + run(&storage(0, None), get, dir.path()).await.unwrap_err(); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0); + } + + #[tokio::test] + async fn a_gzip_encoded_download_is_written_decoded() { + // gzip of "decoded content". + const GZIP: [u8; 35] = [ + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x4b, 0x49, 0x4d, 0xce, + 0x4f, 0x49, 0x4d, 0x51, 0x48, 0xce, 0xcf, 0x2b, 0x49, 0xcd, 0x2b, 0x01, 0x00, 0x6d, + 0xf0, 0x83, 0xb2, 0x0f, 0x00, 0x00, 0x00, + ]; + let server = MockServer::start().await; + let get = ResponseTemplate::new(200) + .insert_header("content-encoding", "gzip") + .set_body_bytes(GZIP.to_vec()); + mount(&server, "GET", "/", get).await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("destination"); + let get = instruction("GET", &server.uri(), &destination); + run(&storage(0, None), get, dir.path()).await.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), b"decoded content"); + } + + #[tokio::test] + async fn a_failed_instruction_read_is_not_kept_for_the_execution() { + let server = MockServer::start().await; + mount(&server, "DELETE", "/", ResponseTemplate::new(200)).await; + let dir = tempfile::tempdir().unwrap(); + let state = state(&storage(0, None), dir.path()); + let read = state.complete(Err(Error::network_error()), true).await; + assert!(read.is_err()); + state + .complete(Ok(Some(remove(&server.uri()))), true) + .await + .unwrap(); + } + + #[tokio::test] + async fn storage_failures_keep_local_files_and_report_storage_details() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(404) + .insert_header("x-amz-request-id", "request-1") + .set_body_string( + "NoSuchKeygone", + ), + ) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let existing = dir.path().join("existing"); + std::fs::write(&existing, b"old").unwrap(); + let missing = dir.path().join("missing"); + let storage = storage(0, None); + for destination in [&existing, &missing] { + let get = instruction("GET", &server.uri(), destination); + let error = run(&storage, get, dir.path()).await.unwrap_err(); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_HTTP_ERROR") + ); + assert_eq!(error.http_status, Some(404)); + assert_eq!( + error.message, + "Volume storage request failed: HTTP 404; RequestId: request-1; \ + Code: NoSuchKey; Message: gone" + ); + } + assert_eq!(std::fs::read(&existing).unwrap(), b"old"); + assert!(!missing.exists()); + } + + #[tokio::test] + async fn a_remove_answered_with_not_found_succeeds_only_when_allowed() { + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(404)) + .mount(&server) + .await; + let storage = storage(0, None); + for remove_not_found_is_success in [true, false] { + let options = VolumeOptions::new(Vec::new(), remove_not_found_is_success); + let result = storage + .transfer_state(Some(options)) + .complete(Ok(Some(remove(&server.uri()))), true) + .await; + assert_eq!(result.is_ok(), remove_not_found_is_success); + } + } + + #[tokio::test] + async fn only_transient_storage_failures_are_retried() { + let server = MockServer::start().await; + Mock::given(path("/flaky")) + .respond_with(ResponseTemplate::new(503)) + .up_to_n_times(1) + .mount(&server) + .await; + Mock::given(path("/flaky")) + .respond_with(ResponseTemplate::new(200).set_body_string("recovered")) + .mount(&server) + .await; + let denied = ResponseTemplate::new(403); + mount(&server, "GET", "/denied", denied).await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("destination"); + let storage = storage(1, None); + let flaky = instruction("GET", &format!("{}/flaky", server.uri()), &destination); + run(&storage, flaky, dir.path()).await.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), b"recovered"); + let denied = instruction("GET", &format!("{}/denied", server.uri()), &destination); + let error = run(&storage, denied, dir.path()).await.unwrap_err(); + assert_eq!(error.code, ErrorCode::PermissionDenied); + } + + #[tokio::test] + async fn a_redirect_fails_without_being_followed() { + let server = MockServer::start().await; + let see_other = ResponseTemplate::new(303).insert_header("location", "/object"); + mount(&server, "PUT", "/", see_other).await; + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + std::fs::write(&source, b"payload").unwrap(); + let put = instruction("PUT", &server.uri(), &source); + let error = run(&storage(0, None), put, dir.path()).await.unwrap_err(); + assert_eq!(error.http_status, Some(303)); + assert_eq!(server.received_requests().await.unwrap().len(), 1); + } + + #[tokio::test] + async fn storage_connections_apply_the_session_revocation_policy() { + let storage = Storage::new( + HttpClientConfig::default(), + Some(false), + RetryConfig::default(), + None, + tokio::runtime::Handle::current(), + ); + let unsupported = crate::client::http::revocation_unsupported_message( + cfg!(windows), + cfg!(feature = "tls-rustls"), + ); + assert_eq!( + storage.client().await.err().map(|error| error.message), + unsupported.map(String::from) + ); + } + + #[tokio::test] + async fn idle_limit_fails_stalled_transfers_but_not_slow_ones() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + std::fs::write(&source, vec![b'x'; 16 * 1024 * 1024]).unwrap(); + let destination = dir.path().join("destination"); + // (operation, scheme, bytes the peer trickles before stalling, idle limit in ms, + // expected to finish). Zero sets no limit. The peer never answers a TLS + // handshake, so the https row stalls connection setup. + for (operation, scheme, sent, limit, finishes) in [ + ("GET", "http", 15, 500, true), + ("GET", "http", 15, 0, true), + ("GET", "http", 1, 500, false), + ("PUT", "http", 0, 500, false), + ("GET", "https", 0, 500, false), + ] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("{scheme}://{}", listener.local_addr().unwrap()); + let peer = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + if sent > 0 { + assert!(socket.read(&mut [0; 4096]).await.unwrap() > 0); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 15\r\n\r\n") + .await + .unwrap(); + for _ in 0..sent { + tokio::time::sleep(Duration::from_millis(50)).await; + socket.write_all(b"x").await.unwrap(); + } + } + std::future::pending::<()>().await; + drop(socket); + }); + let local = if operation == "PUT" { + &source + } else { + &destination + }; + let transfer = instruction(operation, &url, local); + let storage = storage(0, Some(Duration::from_millis(limit))); + let result = run(&storage, transfer, dir.path()).await; + peer.abort(); + if finishes { + result.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), vec![b'x'; 15]); + } else { + let error = result.unwrap_err(); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR"), + "{operation}" + ); + assert!(error.message.contains("made no progress"), "{operation}"); + } + } + } + + #[tokio::test] + async fn storage_error_reports_a_failed_upload_read_as_local() { + let server = MockServer::start().await; + let body = reqwest::Body::wrap_stream(futures::stream::once(async { + Err::(local_error(std::io::ErrorKind::Other.into(), "source")) + })); + let error = Client::new() + .put(server.uri()) + .body(body) + .send() + .await + .unwrap_err(); + let strategy = + RetryStrategy::for_request(RequestType::CloudFetchDownload, &RetryConfig::default()); + let error = storage_error(error, &strategy); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + assert!(!error.retryable); + } + + #[test] + fn local_paths_must_resolve_inside_an_allowed_root() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("root"); + let outside = dir.path().join("outside"); + std::fs::create_dir(&root).unwrap(); + std::fs::create_dir(&outside).unwrap(); + let roots = [root.clone()]; + let not_allowed = |path: PathBuf, roots: &[PathBuf]| { + allowed_path(&path, roots) + .unwrap_err() + .error_code + .as_deref() + == Some("VOLUME_PATH_NOT_ALLOWED") + }; + assert!(allowed_path(&root.join("new"), &roots).is_ok()); + assert!(not_allowed(outside.join("file"), &roots)); + assert!(not_allowed(root.join("../outside/file"), &roots)); + assert!(not_allowed(root.join("file"), &[])); + #[cfg(unix)] + { + use std::os::unix::fs::symlink; + symlink(&outside, root.join("out")).unwrap(); + assert!(not_allowed(root.join("out/file"), &roots)); + symlink(&root, outside.join("in")).unwrap(); + assert!(allowed_path(&outside.join("in/file"), &roots).is_ok()); + symlink(root.join("missing"), root.join("dangling")).unwrap(); + assert_eq!( + allowed_path(&root.join("dangling"), &roots) + .unwrap_err() + .code, + ErrorCode::NotFound + ); + } + } + + #[cfg(unix)] + fn mkfifo(path: &Path) { + assert!(std::process::Command::new("mkfifo") + .arg(path) + .status() + .unwrap() + .success()); + } + + #[tokio::test] + #[cfg(unix)] + async fn a_get_writes_into_a_pipe_whose_reader_arrives_later() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_string("content")) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let fifo = dir.path().join("fifo"); + mkfifo(&fifo); + let reader = async { + requested(&server).await; + let fifo = fifo.clone(); + tokio::task::spawn_blocking(move || std::fs::read(fifo).unwrap()) + .await + .unwrap() + }; + let get = instruction("GET", &server.uri(), &fifo); + let storage = storage(0, None); + let (result, content) = tokio::join!(run(&storage, get, dir.path()), reader); + result.unwrap(); + assert_eq!(content, b"content"); + } + + #[tokio::test] + #[cfg(unix)] + async fn a_get_writes_into_a_character_device() { + let server = MockServer::start().await; + mount( + &server, + "GET", + "/", + ResponseTemplate::new(200).set_body_string("content"), + ) + .await; + let get = instruction("GET", &server.uri(), Path::new("/dev/null")); + run(&storage(0, None), get, Path::new("/dev")) + .await + .unwrap(); + } + + #[tokio::test] + #[cfg(unix)] + async fn a_get_into_a_pipe_without_a_reader_stops_at_the_idle_limit() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_string("content")) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let fifo = dir.path().join("fifo"); + mkfifo(&fifo); + let get = instruction("GET", &server.uri(), &fifo); + let storage = storage(0, Some(Duration::from_millis(300))); + let started = Instant::now(); + let error = run(&storage, get, dir.path()).await.unwrap_err(); + // It waited for a reader before giving up. + assert!(started.elapsed() >= Duration::from_millis(300)); + assert_eq!(error.local_error.unwrap().raw_os_error, Some(libc::ENXIO)); + } + + #[tokio::test] + #[cfg(unix)] + async fn a_stalled_pipe_reader_stops_the_transfer_without_a_retry() { + use std::os::unix::fs::OpenOptionsExt; + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![b'x'; 1 << 20])) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let fifo = dir.path().join("fifo"); + mkfifo(&fifo); + let stalled = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NONBLOCK) + .open(&fifo) + .unwrap(); + // A small pipe buffer makes the first write stall partway. + #[cfg(target_os = "linux")] + assert!( + unsafe { + libc::fcntl( + std::os::fd::AsRawFd::as_raw_fd(&stalled), + libc::F_SETPIPE_SZ, + 4096, + ) + } >= 0 + ); + let get = instruction("GET", &server.uri(), &fifo); + let storage = storage(2, Some(Duration::from_millis(300))); + let error = run(&storage, get, dir.path()).await.unwrap_err(); + assert!( + error.message.contains("made no progress"), + "{}", + error.message + ); + assert_eq!(server.received_requests().await.unwrap().len(), 1); + drop(stalled); + } + + #[tokio::test] + async fn a_download_cut_off_mid_body_is_retried_into_a_file() { + let dir = tempfile::tempdir().unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let peer = tokio::spawn({ + let accepted = Arc::clone(&accepted); + async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + accepted.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + assert!(socket.read(&mut [0; 4096]).await.unwrap() > 0); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc") + .await + .unwrap(); + } + } + }); + let get = instruction("GET", &url, &dir.path().join("file")); + run(&storage(2, None), get, dir.path()).await.unwrap_err(); + peer.abort(); + assert_eq!(accepted.load(std::sync::atomic::Ordering::SeqCst), 3); + assert!(!dir.path().join("file").exists()); + } + + #[tokio::test] + async fn local_failures_happen_before_any_storage_request() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let url = format!("{}/object?signature=secret", server.uri()); + let storage = storage(0, None); + let missing = dir.path().join("missing"); + let no_parent = dir.path().join("no-dir/file"); + for (operation, local) in [("PUT", &missing), ("GET", &no_parent)] { + let transfer = instruction(operation, &url, local); + let error = run(&storage, transfer, dir.path()).await.unwrap_err(); + assert_eq!(error.code, ErrorCode::NotFound, "{operation}"); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + assert!(!error.message.contains("secret"), "{operation}"); + let details = error.local_error.unwrap(); + assert_eq!(details.kind, std::io::ErrorKind::NotFound, "{operation}"); + #[cfg(unix)] + assert_eq!(details.raw_os_error, Some(libc::ENOENT), "{operation}"); + assert_eq!(details.path, local.to_str().unwrap(), "{operation}"); + } + for operation in ["PUT", "GET"] { + let transfer = instruction(operation, &url, dir.path()); + let error = run(&storage, transfer, dir.path()).await.unwrap_err(); + let local = error.local_error.unwrap(); + assert_eq!(local.kind, std::io::ErrorKind::IsADirectory, "{operation}"); + #[cfg(unix)] + assert_eq!(local.raw_os_error, Some(libc::EISDIR), "{operation}"); + } + // A PUT needs the source's length, so it refuses a pipe without opening it. + #[cfg(unix)] + { + let fifo = dir.path().join("fifo"); + mkfifo(&fifo); + let put = instruction("PUT", &url, &fifo); + let error = run(&storage, put, dir.path()).await.unwrap_err(); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + } + #[cfg(unix)] + if !privileged() { + use std::os::unix::fs::PermissionsExt; + let locked = dir.path().join("locked"); + std::fs::create_dir(&locked).unwrap(); + std::fs::set_permissions(&locked, PermissionsExt::from_mode(0o555)).unwrap(); + let new = locked.join("new"); + let get = instruction("GET", &url, &new); + let error = run(&storage, get, dir.path()).await.unwrap_err(); + std::fs::set_permissions(&locked, PermissionsExt::from_mode(0o755)).unwrap(); + let details = error.local_error.unwrap(); + assert_eq!(details.raw_os_error, Some(libc::EACCES)); + assert_eq!(details.path, new.to_str().unwrap()); + } + assert!(server.received_requests().await.unwrap().is_empty()); + } + + #[tokio::test] + #[cfg(unix)] + async fn an_existing_file_in_a_folder_that_refuses_files_is_still_replaced() { + use std::os::unix::fs::PermissionsExt; + if privileged() { + return; + } + let server = MockServer::start().await; + mount( + &server, + "GET", + "/", + ResponseTemplate::new(200).set_body_string("new"), + ) + .await; + let dir = tempfile::tempdir().unwrap(); + let existing = dir.path().join("existing"); + std::fs::write(&existing, b"old content").unwrap(); + std::fs::set_permissions(dir.path(), PermissionsExt::from_mode(0o555)).unwrap(); + let get = instruction("GET", &server.uri(), &existing); + let result = run(&storage(0, None), get, dir.path()).await; + std::fs::set_permissions(dir.path(), PermissionsExt::from_mode(0o755)).unwrap(); + result.unwrap(); + assert_eq!(std::fs::read(&existing).unwrap(), b"new"); + } + + #[tokio::test] + async fn a_cancel_while_a_download_is_put_in_place_lets_it_finish() { + let body = vec![b'x'; 32 << 20]; + let server = MockServer::start().await; + let get = ResponseTemplate::new(200).set_body_bytes(body.clone()); + mount(&server, "GET", "/", get).await; + let dir = tempfile::tempdir().unwrap(); + // An existing empty file changes length only once the download is copied into it. + let destination = dir.path().join("destination"); + std::fs::write(&destination, b"").unwrap(); + let state = state(&storage(0, None), dir.path()); + let watcher = { + let (state, destination) = (Arc::clone(&state), destination.clone()); + std::thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(30); + while std::fs::metadata(&destination).map_or(0, |m| m.len()) == 0 + && Instant::now() < deadline + { + std::thread::sleep(Duration::from_millis(1)); + } + state.cancel(); + }) + }; + let get = instruction("GET", &server.uri(), &destination); + state.complete(Ok(Some(get)), true).await.unwrap(); + watcher.join().unwrap(); + assert_eq!(std::fs::read(&destination).unwrap().len(), body.len()); + } + + #[tokio::test] + async fn cancelled_or_abandoned_transfers_do_not_run_again() { + for abandon in [false, true] { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string("new") + .set_delay(Duration::from_secs(30)), + ) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("destination"); + std::fs::write(&destination, b"old").unwrap(); + let get = instruction("GET", &server.uri(), &destination); + let state = state(&storage(0, None), dir.path()); + let requested = requested(&server); + tokio::time::timeout(Duration::from_secs(10), async { + let transfer = state.complete(Ok(Some(get.clone())), true); + if abandon { + tokio::select! { + result = transfer => panic!("transfer finished early: {result:?}"), + () = requested => {} + } + } else { + let (result, ()) = tokio::join!(transfer, async { + requested.await; + state.cancel(); + }); + assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); + } + }) + .await + .unwrap(); + let repeated = state.complete(Ok(Some(get)), true).await.unwrap_err(); + assert_eq!(repeated.code, ErrorCode::Cancelled, "abandon={abandon}"); + assert_eq!(std::fs::read(&destination).unwrap(), b"old"); + } + } + + #[tokio::test] + async fn uploads_are_chunked_and_each_read_covers_the_whole_source() { + let payload: Vec = (0..3 * UPLOAD_CHUNK + 1).map(|i| i as u8).collect(); + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + std::fs::write(&source, &payload).unwrap(); + let file = Upload::File { + file: Arc::new(std::fs::File::open(&source).unwrap()), + length: payload.len() as u64, + name: "source".into(), + }; + let bytes = Upload::Bytes(payload.clone().into()); + let joined = |chunks: &[Bytes]| chunks.iter().flat_map(|c| c.to_vec()).collect::>(); + for upload in [Local::Upload(file), Local::Upload(bytes)] { + // A retry starts a new read while an earlier one may still be open. + let (mut first, length) = upload.upload().unwrap(); + let head = first.try_next().await.unwrap().unwrap(); + let (second, _) = upload.upload().unwrap(); + let second: Vec = second.try_collect().await.unwrap(); + let mut rest: Vec = first.try_collect().await.unwrap(); + rest.insert(0, head); + assert_eq!(length, payload.len() as u64); + assert_eq!(second.len(), 4); + assert_eq!(joined(&second), payload); + assert_eq!(joined(&rest), payload); + } + } + + #[test] + fn instructions_must_be_one_well_formed_row() { + let removed = Instruction::decode(&remove("https://storage")).unwrap(); + assert!(matches!(removed.operation, Operation::Remove)); + let valid = instruction("GET", "https://storage", Path::new("/tmp/file")); + assert_eq!( + Instruction::decode(&valid).unwrap().headers["x-test"], + "yes" + ); + let replace = |name: &str, value: &str| { + let schema = valid.schema(); + RecordBatch::try_from_iter(schema.fields().iter().zip(valid.columns()).map( + |(field, column)| { + let column = if field.name() == name { + Arc::new(StringArray::from(vec![value])) as ArrayRef + } else { + Arc::clone(column) + }; + (field.name().clone(), column) + }, + )) + .unwrap() + }; + let json = Instruction::decode(&replace("headers", r#"{"x-test":"yes"}"#)).unwrap(); + assert_eq!(json.headers["x-test"], "yes"); + let blank = Instruction::decode(&replace("headers", " ")).unwrap(); + assert!(blank.headers.is_empty()); + let invalid = [ + arrow_select::concat::concat_batches(&valid.schema(), [&valid, &valid]).unwrap(), + valid.project(&[0, 1, 2]).unwrap(), + replace("operation", "COPY"), + replace("headers", "not json"), + replace("localFile", ""), + ]; + for batch in invalid { + assert_eq!( + Instruction::decode(&batch) + .err() + .unwrap() + .error_code + .as_deref(), + Some("VOLUME_INVALID_INSTRUCTION") + ); + } + } +} diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs new file mode 100644 index 00000000..8de5bc84 --- /dev/null +++ b/tests/v0_volume_wiremock.rs @@ -0,0 +1,440 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Volume transfers through sessions and statements, against a mock server. + +use arrow_array::builder::{MapBuilder, StringBuilder}; +use arrow_array::{ArrayRef, RecordBatch, StringArray}; +use arrow_ipc::writer::StreamWriter; +use base64::{engine::general_purpose::STANDARD, Engine}; +use databricks_sql_kernel::{ + AuthConfig, ConnectionConfig, DirectStatement, ErrorCode, ExecutedStatementHandle, HttpConfig, + ResultStream, Session, VolumeOptions, +}; +use serde_json::json; +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; +use tokio_util::bytes::Bytes; +use wiremock::matchers::{body_bytes, method, path, path_regex}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +async fn session(server: &MockServer, http: HttpConfig) -> Session { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/test_wh/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-test","warehouse_id":"test_wh"}"#), + ) + .mount(server) + .await; + Mock::given(method("POST")) + .and(path_regex("/cancel$")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(server) + .await; + Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh").unwrap(), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .http(http) + .open() + .await + .unwrap() +} + +/// Answers every statement with one `operation` instruction for `local`, the +/// way the server does: headers as a map, and `is_volume_operation` when marked. +async fn mount_volume_result(server: &MockServer, operation: &str, local: &str, marked: bool) { + let mut headers = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); + headers.append(true).unwrap(); + let batch = RecordBatch::try_from_iter([ + ( + "operation", + Arc::new(StringArray::from(vec![operation])) as ArrayRef, + ), + ( + "presignedUrl", + Arc::new(StringArray::from(vec![format!("{}/object", server.uri())])) as _, + ), + ("headers", Arc::new(headers.finish()) as _), + ("localFile", Arc::new(StringArray::from(vec![local])) as _), + ]) + .unwrap(); + let mut ipc = Vec::new(); + let mut writer = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + let columns: Vec<_> = batch + .schema() + .fields() + .iter() + .enumerate() + .map(|(position, field)| { + let (type_name, type_text) = match field.name().as_str() { + "headers" => ("MAP", "MAP"), + _ => ("STRING", "STRING"), + }; + json!({"name": field.name(), "type_name": type_name, "type_text": type_text, "position": position}) + }) + .collect(); + let body = json!({ + "statement_id": "stmt-volume", + "status": {"state": "SUCCEEDED"}, + "manifest": { + "is_volume_operation": marked, + "format": "ARROW_STREAM", + "schema": {"column_count": 4, "columns": columns}, + "total_chunk_count": 1, + "total_row_count": 1, + "total_byte_count": ipc.len(), + "truncated": false, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": 1, + "byte_count": ipc.len(), + "attachment": STANDARD.encode(&ipc), + }, + }); + for (verb, route) in [ + ("POST", "/api/2.0/sql/statements"), + ("GET", "/api/2.0/sql/statements/stmt-volume"), + ] { + Mock::given(method(verb)) + .and(path(route)) + .respond_with(ResponseTemplate::new(200).set_body_string(body.to_string())) + .mount(server) + .await; + } +} + +async fn mount_object(server: &MockServer, delay: Duration, expected_requests: u64) { + Mock::given(method("GET")) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string("data") + .set_delay(delay), + ) + .expect(expected_requests) + .mount(server) + .await; +} + +async fn object_requested(server: &MockServer) { + while !server + .received_requests() + .await + .unwrap() + .iter() + .any(|request| request.url.path() == "/object") + { + tokio::task::yield_now().await; + } +} + +fn options(root: &Path) -> Option { + Some(VolumeOptions::new(vec![root.to_owned()], false)) +} + +async fn instruction_rows(stream: &mut ResultStream) -> usize { + match stream.next_batch().await.unwrap().unwrap() { + databricks_sql_kernel::ResultBatch::Arrow(row) => row.num_rows(), + _ => unreachable!(), + } +} + +#[tokio::test] +async fn execution_with_options_transfers_and_keeps_the_instruction_row() { + for direct in [false, true] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + mount_object(&server, Duration::ZERO, 1).await; + mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; + let session = session(&server, HttpConfig::default()).await; + let mut statement = session.statement(); + statement.spec().sql("GET").volume(options(dir.path())); + let mut executed = if direct { + match statement.execute_direct().await.unwrap() { + DirectStatement::Completed(executed) => executed, + DirectStatement::Running(_) => panic!("the mock answers inline"), + } + } else { + statement.execute().await.unwrap() + }; + assert_eq!( + std::fs::read(&destination).unwrap(), + b"data", + "direct={direct}" + ); + let stream = executed.result_stream_mut(); + assert!(stream.is_volume_operation()); + assert_eq!(instruction_rows(stream).await, 1); + } +} + +#[tokio::test] +async fn only_a_marked_result_with_options_transfers() { + for (marked, with_options) in [(false, true), (true, false)] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + mount_object(&server, Duration::ZERO, 0).await; + mount_volume_result(&server, "GET", destination.to_str().unwrap(), marked).await; + let session = session(&server, HttpConfig::default()).await; + let mut statement = session.statement(); + statement + .spec() + .sql("GET") + .volume(options(dir.path()).filter(|_| with_options)); + let mut executed = statement.execute().await.unwrap(); + let stream = executed.result_stream_mut(); + assert_eq!(stream.is_volume_operation(), marked); + assert_eq!(instruction_rows(stream).await, 1); + assert!(!destination.exists()); + } +} + +#[tokio::test] +async fn input_bytes_apply_to_one_execution() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(path("/object")) + .and(body_bytes(b"caller bytes".to_vec())) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + mount_volume_result(&server, "PUT", "__input_stream__", true).await; + let session = session(&server, HttpConfig::default()).await; + let mut statement = session.statement(); + let options = VolumeOptions::default().with_input_bytes(Bytes::from_static(b"caller bytes")); + statement.spec().sql("PUT").volume(Some(options)); + statement.execute().await.unwrap(); + let error = statement.execute().await.err().unwrap(); + assert_eq!(error.code, ErrorCode::InvalidArgument); +} + +#[tokio::test] +async fn async_results_of_one_execution_share_one_transfer() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + mount_object(&server, Duration::ZERO, 1).await; + mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; + let session = session(&server, HttpConfig::default()).await; + let mut statement = session.statement(); + statement.spec().sql("GET").volume(options(dir.path())); + let executed = statement.submit().await.unwrap(); + let reader = executed.reader().unwrap(); + executed.await_result().await.unwrap(); + reader.fetch_result().await.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), b"data"); +} + +#[tokio::test] +async fn a_dropped_reader_call_leaves_the_transfer_to_the_owner() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + mount_object(&server, Duration::from_millis(500), 1).await; + mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; + let session = session(&server, HttpConfig::default()).await; + let mut statement = session.statement(); + statement.spec().sql("GET").volume(options(dir.path())); + let executed = statement.submit().await.unwrap(); + let reader = executed.reader().unwrap(); + tokio::select! { + result = reader.await_result() => panic!("the reader finished early: {:?}", result.err()), + () = object_requested(&server) => {} + } + executed.await_result().await.unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), b"data"); +} + +#[tokio::test] +async fn a_failed_transfer_closes_the_server_statement() { + for direct in [false, true] { + let server = MockServer::start().await; + let (root, elsewhere) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + let destination = elsewhere.path().join("download"); + mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; + let session = session(&server, HttpConfig::default()).await; + let mut statement = session.statement(); + statement.spec().sql("GET").volume(options(root.path())); + let failed = if direct { + statement.execute_direct().await.is_err() + } else { + statement.execute().await.is_err() + }; + assert!(failed, "a GET outside the allowed root fails"); + drop(statement); + tokio::time::timeout(Duration::from_secs(5), async { + while !server + .received_requests() + .await + .unwrap() + .iter() + .any(|request| { + request.method.as_str() == "DELETE" + && request.url.path() == "/api/2.0/sql/statements/stmt-volume" + }) + { + tokio::task::yield_now().await; + } + }) + .await + .unwrap_or_else(|_| panic!("no CloseStatement (direct={direct})")); + } +} + +#[tokio::test] +async fn an_attached_handle_returns_the_instruction_row_without_transferring() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + mount_object(&server, Duration::ZERO, 0).await; + mount_volume_result( + &server, + "GET", + dir.path().join("download").to_str().unwrap(), + true, + ) + .await; + let session = session(&server, HttpConfig::default()).await; + let attached = session.attach_async_statement("stmt-volume").await.unwrap(); + let mut observed = attached.fetch_result().await.unwrap(); + assert!(observed.is_volume_operation()); + assert_eq!(instruction_rows(&mut observed).await, 1); +} + +#[tokio::test] +async fn cancellers_and_session_close_stop_a_running_transfer() { + for case in [ + "statement canceller", + "async canceller", + "async handle", + "async close", + "owner dropped", + "statement close", + "statement dropped", + "re-execute", + "session close", + ] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + mount_object(&server, Duration::from_secs(30), 1).await; + mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; + let session = session(&server, HttpConfig::default()).await; + let mut statement = session.statement(); + statement.spec().sql("GET").volume(options(dir.path())); + let execution = async { + match case { + "statement canceller" => { + let canceller = statement.canceller(); + let stop = async { + object_requested(&server).await; + canceller.cancel().await.unwrap(); + }; + tokio::join!(statement.execute(), stop).0.map(drop) + } + "async canceller" | "async handle" | "async close" => { + let executed = statement.submit().await.unwrap(); + let canceller = executed.canceller(); + let stop = async { + object_requested(&server).await; + let _ = match case { + "async handle" => executed.cancel().await, + "async close" => ExecutedStatementHandle::close(&executed).await, + _ => canceller.cancel().await, + }; + }; + tokio::join!(executed.await_result(), stop).0.map(drop) + } + "owner dropped" => { + let executed = statement.submit().await.unwrap(); + let reader = executed.reader().unwrap(); + let server = &server; + let stop = async move { + object_requested(server).await; + drop(executed); + }; + tokio::join!(reader.fetch_result(), stop).0.map(drop) + } + "statement close" | "statement dropped" | "re-execute" => { + let executed = statement.submit().await.unwrap(); + let stop = async { + object_requested(&server).await; + match case { + "statement close" => statement.close().await.unwrap(), + "statement dropped" => drop(statement), + _ => { + statement.spec().volume(None); + statement.execute().await.unwrap(); + } + } + }; + tokio::join!(executed.await_result(), stop).0.map(drop) + } + _ => { + let stop = async { + object_requested(&server).await; + session.close().await.unwrap(); + }; + tokio::join!(statement.execute(), stop).0.map(drop) + } + } + }; + let result = tokio::time::timeout(Duration::from_secs(10), execution) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled, "{case}"); + assert!(!destination.exists(), "{case}"); + } +} + +#[tokio::test] +async fn the_sql_request_timeout_is_the_transfer_idle_limit() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + mount_object(&server, Duration::from_secs(2), 1).await; + mount_volume_result(&server, "GET", destination.to_str().unwrap(), true).await; + let mut http = HttpConfig::default(); + http.request_timeout = Duration::from_secs(1); + http.retry_max_retries = 0; + let session = session(&server, http).await; + let mut statement = session.statement(); + statement.spec().sql("GET").volume(options(dir.path())); + let Err(error) = statement.execute().await else { + panic!("a stalled transfer succeeded"); + }; + assert!( + error.message.contains("made no progress"), + "{}", + error.message + ); +}