From 37dd3bd1e2e37cf9c338f018218f99001f7d4a98 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 30 Nov 2026 03:01:30 +0000 Subject: [PATCH 1/7] feat(volume): complete Volume file transfers in the kernel core Signed-off-by: Aakash Saravanan --- .github/workflows/pr-checks.yml | 26 + CONNECTION_PARAMETERS.md | 3 +- Cargo.lock | 4 +- Cargo.toml | 6 +- NEXT_CHANGELOG.md | 9 + NOTICE | 5 + README.md | 8 + adbc/Cargo.lock | 5 +- adbc/NOTICE | 5 + napi/Cargo.lock | 39 + pyo3/Cargo.lock | 39 + src/client/http.rs | 72 +- src/client/http_tls_tests.rs | 113 ++ src/client/mod.rs | 2 +- src/client/sea.rs | 1 + src/config.rs | 7 + src/kernel_error.rs | 49 +- src/lib.rs | 4 +- src/reader/mod.rs | 2 + src/reader/post_processor/mod.rs | 1 + src/result_stream.rs | 155 ++- src/session.rs | 22 + src/statement/executed.rs | 7 + src/statement/executed_async.rs | 64 +- src/statement/mutable.rs | 60 +- src/telemetry/statement.rs | 95 +- src/types/sea.rs | 2 + src/volume.rs | 2074 ++++++++++++++++++++++++++++++ tests/v0_volume_wiremock.rs | 674 ++++++++++ 29 files changed, 3474 insertions(+), 79 deletions(-) create mode 100644 src/volume.rs create mode 100644 tests/v0_volume_wiremock.rs diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index ffaa60bd..a8f6d728 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -131,6 +131,32 @@ jobs: # a live workspace; `rust-e2e.yml` runs them separately. run: cargo test --workspace + volume-windows: + name: Volume tests (Windows) + runs-on: + group: databricks-protected-runner-group + labels: [windows-server-latest] + timeout-minutes: 45 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: ./.github/actions/setup-public-package-proxies + with: + cargo: "true" + + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: stable + + - name: Set up MSVC environment + uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1 + with: + arch: x64 + + - name: Volume file and cancellation tests + shell: pwsh + run: cargo test --locked --lib volume::tests + c-abi: name: C ABI smoke test runs-on: diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 2a11227d..3a8ba972 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -127,7 +127,8 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). | Field | Description | Default | |-------|-------------|---------| -| `request_timeout` | Per-request timeout (connect + body). | `120s` | +| `request_timeout` | Per-request timeout (connect + body) for SQL requests. Volume file transfers are limited by storage_read_timeout instead. | `120s` | +| `storage_read_timeout` | Idle limit for Volume file transfers: a transfer fails after this long without progress. | `None` (no limit) | | `overall_timeout` | Maximum total time across retries for one logical RPC. | `900s` | | `pool_max_idle_per_host` | Connection-pool size (max idle warm sockets per host). Raise for bursty concurrent workloads. | `100` | | `retry_min_wait` | Minimum backoff between retries; also the floor for a server `Retry-After` and the base of exponential backoff (`min_wait × 2^attempt`). | `1s` | diff --git a/Cargo.lock b/Cargo.lock index c4fa1986..28d34ed2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2384,9 +2384,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 66898c45..12a21cd8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -105,9 +105,12 @@ moka = { version = "0.12.16", features = ["future"] } # Async utilities futures = "0.3" -tokio-util = "0.7" +tokio-util = { version = "0.7", features = ["io"] } async-trait = "0.1" +# Temporary file that holds a Volume GET download before it is copied into place +tempfile = "3" + # Error handling thiserror = "2" @@ -167,7 +170,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 f80d0401..0d9dd98b 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,8 +11,17 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- Volume `PUT`, `GET` and `REMOVE`: `ResultStream::complete_volume_operation` + runs the file transfer. Local paths, and the files they resolve to through + symlinks, must be inside the caller's allowed directories. A `PUT` can also + upload bytes the caller supplies. + ### Changed +- Adds public fields to `Error` and `ResultManifest`. Code that builds these + structs with struct literals must be updated. Supported consumers are the PyO3, + NAPI, C ABI and ADBC bindings. + ### Updated ### Fixed diff --git a/NOTICE b/NOTICE index 7cda1ab7..55dd3e4b 100644 --- a/NOTICE +++ b/NOTICE @@ -142,6 +142,11 @@ Project URL: https://github.com/serde-rs/json Copyright: Copyright serde_json Authors. +Package: tempfile +Project URL: https://github.com/Stebalien/tempfile +Copyright: Copyright (c) 2015 Steven Allen + + Package: thiserror Project URL: https://github.com/dtolnay/thiserror Copyright: Copyright thiserror Authors. diff --git a/README.md b/README.md index ba83c9f1..c7b02315 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,14 @@ and security vulnerabilities should be reported according to [SECURITY.md](SECURITY.md). For other project questions, contact [eng-oss-sql-driver@databricks.com](mailto:eng-oss-sql-driver@databricks.com). +## Volume file operations + +For a Volume `PUT`, `GET` or `REMOVE`, call +`ResultStream::complete_volume_operation` before reading rows. It runs the +file transfer; without it the result is only the server's instruction row. +See [`ResultStream::complete_volume_operation`](https://docs.rs/databricks-sql-kernel/latest/databricks_sql_kernel/struct.ResultStream.html#method.complete_volume_operation) +for transfer behavior. + ## License Apache 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE). diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index fa0db928..95f5e23d 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -679,6 +679,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.1", + "tempfile", "thiserror 2.0.21", "tokio", "tokio-util", @@ -2170,9 +2171,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 7cda1ab7..55dd3e4b 100644 --- a/adbc/NOTICE +++ b/adbc/NOTICE @@ -142,6 +142,11 @@ Project URL: https://github.com/serde-rs/json Copyright: Copyright serde_json Authors. +Package: tempfile +Project URL: https://github.com/Stebalien/tempfile +Copyright: Copyright (c) 2015 Steven Allen + + Package: thiserror Project URL: https://github.com/dtolnay/thiserror Copyright: Copyright thiserror Authors. diff --git a/napi/Cargo.lock b/napi/Cargo.lock index 9446836c..f013d66b 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -639,6 +639,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -797,6 +798,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1494,6 +1501,12 @@ dependencies = [ "libc", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.2" @@ -2201,6 +2214,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.46" @@ -2547,6 +2573,19 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index 2faffe7c..d89035ac 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -635,6 +635,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.0", + "tempfile", "thiserror 2.0.19", "tokio", "tokio-util", @@ -770,6 +771,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" @@ -1424,6 +1431,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" @@ -2113,6 +2126,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" @@ -2465,6 +2491,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 cac2243b..33c9b502 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -388,6 +388,39 @@ pub struct DatabricksHttpClient { retry_configs: HashMap, } +pub(crate) struct StorageClient { + pub(crate) read_timeout: Option, + config: HttpClientConfig, + client: tokio::sync::OnceCell, +} + +impl StorageClient { + pub(crate) async fn get(&self) -> Result<&Client> { + self.client + .get_or_try_init(|| async { + DatabricksHttpClient::build_reqwest_client( + &self.config, + reqwest::redirect::Policy::custom(|attempt| { + if attempt.url().scheme() == "http" + && attempt + .previous() + .last() + .is_some_and(|url| url.scheme() == "https") + { + attempt.error("Volume storage redirect cannot downgrade HTTPS to HTTP") + } else { + reqwest::redirect::Policy::default().redirect(attempt) + } + }), + None, + // No Referer on redirects: it would carry the presigned URL. + false, + ) + }) + .await + } +} + impl DatabricksHttpClient { /// Creates a new HTTP client with the given configuration and per-category retry configs. /// @@ -479,7 +512,13 @@ impl DatabricksHttpClient { } // Follow redirects for normal traffic (reqwest's default policy). - let client = Self::build_reqwest_client(&config, reqwest::redirect::Policy::default())?; + let client = Self::build_reqwest_client( + &config, + reqwest::redirect::Policy::default(), + // `read_timeout` is historical: reqwest applies it as a total SQL deadline. + Some(config.read_timeout), + true, + )?; // Surface which TLS backend was compiled in so oncall debugging // a handshake / unknown-CA report can tell at a glance whether @@ -514,15 +553,18 @@ impl DatabricksHttpClient { fn build_reqwest_client( config: &HttpClientConfig, redirect: reqwest::redirect::Policy, + request_timeout: Option, + referer: bool, ) -> Result { let mut builder = Client::builder() .connect_timeout(config.connect_timeout) - // `read_timeout` is a historical name; reqwest applies this as - // the total deadline from connect through response-body completion. - .timeout(config.read_timeout) .pool_max_idle_per_host(config.max_connections_per_host) .user_agent(&config.user_agent) - .redirect(redirect); + .redirect(redirect) + .referer(referer); + if let Some(timeout) = request_timeout { + builder = builder.timeout(timeout); + } // Apply TLS configuration if config.tls.enabled == Some(false) { @@ -736,6 +778,19 @@ impl DatabricksHttpClient { &self.client } + /// Storage transfers can outlive SQL RPCs, so retain connection settings without their deadline. + pub(crate) fn storage_client(&self, storage_read_timeout: Option) -> StorageClient { + let mut config = self.config.clone(); + if let Some(timeout) = storage_read_timeout { + config.connect_timeout = config.connect_timeout.min(timeout); + } + StorageClient { + read_timeout: storage_read_timeout, + config, + client: tokio::sync::OnceCell::new(), + } + } + /// Get the authorization header value. /// /// Returns an error if the auth provider has not been set via `set_auth_provider()`. @@ -805,7 +860,12 @@ impl DatabricksHttpClient { /// `azure_tenant_id` (which skips discovery entirely). A single hop is /// sufficient for discovery, so no retry is attempted here. pub async fn first_redirect_location(&self, url: &str) -> Result> { - let client = Self::build_reqwest_client(&self.config, reqwest::redirect::Policy::none())?; + let client = Self::build_reqwest_client( + &self.config, + reqwest::redirect::Policy::none(), + Some(self.config.read_timeout), + true, + )?; let response = client.get(url).send().await.map_err(|e| { Error::network_error().message(format!("Redirect-probe request to {url} failed: {e}")) })?; diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs index b4b2d8c3..5d326292 100644 --- a/src/client/http_tls_tests.rs +++ b/src/client/http_tls_tests.rs @@ -288,6 +288,119 @@ async fn expired_certificate_fails_once_with_certificate_cause() { assert_certificate_failure(CertificateFailure::Expired).await; } +#[tokio::test] +async fn storage_redirect_rejects_https_to_http_on_the_same_port() { + let key = KeyPair::generate().unwrap(); + let certificate = CertificateParams::new(vec!["127.0.0.1".to_string()]) + .unwrap() + .self_signed(&key) + .unwrap(); + let tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![certificate.der().clone()], + PrivatePkcs8KeyDer::from(key.serialize_der()).into(), + ) + .unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let socket = listener.accept().await.unwrap().0; + let mut stream = TlsAcceptor::from(Arc::new(tls)) + .accept(socket) + .await + .unwrap(); + let mut request = [0; 4096]; + assert!(stream.read(&mut request).await.unwrap() > 0); + stream + .write_all( + format!( + "HTTP/1.1 302 Found\r\nLocation: http://{address}/plain\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) + .as_bytes(), + ) + .await + .unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(150), listener.accept()) + .await + .is_err() + ); + }); + let client = test_client( + HttpClientConfig { + tls: TlsConfig { + allow_self_signed: Some(true), + ..Default::default() + }, + ..Default::default() + }, + Duration::from_secs(2), + ); + let storage = client.storage_client(None); + let error = storage + .get() + .await + .unwrap() + .get(format!("https://{address}/object")) + .send() + .await + .unwrap_err(); + assert!(error.is_redirect(), "{error}"); + server.await.unwrap(); +} + +#[tokio::test] +async fn storage_idle_timeout_also_bounds_connection_setup() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (shutdown, mut stopped) = oneshot::channel(); + let server = tokio::spawn(async move { + let mut sockets = Vec::new(); + loop { + tokio::select! { + _ = &mut stopped => return sockets.len(), + accepted = listener.accept() => sockets.push(accepted.unwrap().0), + } + } + }); + let client = test_client( + HttpClientConfig { + connect_timeout: Duration::from_secs(2), + read_timeout: Duration::from_millis(10), + ..Default::default() + }, + Duration::from_secs(10), + ); + for timeout in [None, Some(Duration::from_millis(100))] { + let storage = client.storage_client(timeout); + let storage = storage.get().await.unwrap(); + let deadline = if timeout.is_some() { + Duration::from_millis(500) + } else { + Duration::from_secs(3) + }; + let result = tokio::time::timeout( + deadline, + storage + .put(format!("https://{address}/object")) + .body("bytes") + .send(), + ) + .await; + let error = result + .expect("storage connection timeout must finish") + .unwrap_err(); + assert!(error.is_connect() && error.is_timeout(), "{error}"); + } + shutdown.send(()).unwrap(); + assert_eq!(server.await.unwrap(), 2); +} + #[tokio::test] async fn tls_handshake_timeout_still_retries() { for request_type in [RequestType::CreateSession, RequestType::ExecuteStatement] { diff --git a/src/client/mod.rs b/src/client/mod.rs index af553abf..4205b276 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -36,7 +36,7 @@ pub mod retry; pub mod sea; pub(crate) mod transport; -fn error_chain<'a>( +pub(crate) fn error_chain<'a>( error: &'a (dyn std::error::Error + 'static), ) -> impl Iterator { std::iter::successors(Some(error), |error| { diff --git a/src/client/sea.rs b/src/client/sea.rs index db9b2ebf..29a812e4 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -2431,6 +2431,7 @@ mod tests { error_details_json: None, }, manifest: Some(ResultManifest { + is_volume_operation: false, format: "ARROW_STREAM".to_string(), schema: ResultSchema { column_count: 0, diff --git a/src/config.rs b/src/config.rs index 9c1eb0a9..4457382b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -755,8 +755,14 @@ pub struct HttpConfig { /// Total timeout for one HTTP request, from connection start through /// response-body completion. A separate 30-second connection timeout also /// applies, so connection establishment is bounded by the shorter limit. + /// Does not apply to Volume file transfers; see the storage read timeout. pub request_timeout: Duration, + /// Idle limit for Volume file transfers: a transfer fails after this long + /// without progress. Also caps connection setup. None sets no limit. + /// Exception: a PUT that storage redirects is resent without this limit. + pub storage_read_timeout: Option, + /// Maximum total time across retries for a single logical RPC. /// Retrying stops once cumulative elapsed time exceeds this. pub overall_timeout: Duration, @@ -836,6 +842,7 @@ impl Default for HttpConfig { Self { sea_response_compression_enabled: false, request_timeout: Duration::from_secs(120), + storage_read_timeout: None, overall_timeout: Duration::from_secs(900), pool_max_idle_per_host: 100, // Mirror `RetryConfig::default()` so a stock `HttpConfig` diff --git a/src/kernel_error.rs b/src/kernel_error.rs index ecfb7fb2..a5126853 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -41,12 +41,10 @@ //! Aborted, Unimplemented, …) lands in a follow-on PR. External //! `match` arms get a forced `_ =>` fallback — they keep compiling //! when the enum grows. -//! - `Error` **is not** `#[non_exhaustive]`: wrappers want to -//! pattern-match (`let Error { code, message, sql_state, .. }`) for -//! logging and host-language exception mapping. New fields go -//! through `Error::new(...).with_*(...)`, so adding a field is -//! non-breaking without the marker. Keeping the marker would block -//! useful pattern-matches for no real benefit. +//! - `Error` **is not** `#[non_exhaustive]`, so wrappers can pattern-match +//! (`let Error { code, message, sql_state, .. }`). Build it with +//! `Error::new(...).with_*(...)`: a struct literal stops compiling when a +//! field is added. #![allow(dead_code)] @@ -169,9 +167,6 @@ impl ErrorCode { /// chain `with_*` setters. **Pattern-matching is supported** — /// wrappers writing a comprehensive logger or host-language exception /// adapter can do `let Error { code, message, sql_state, .. } = err;`. -/// New fields land through additive setters, so the type does not -/// need `#[non_exhaustive]` (and the marker would block the -/// pattern-matching wrappers actually want). #[derive(Debug, Clone)] pub struct Error { pub code: ErrorCode, @@ -180,8 +175,8 @@ pub struct Error { /// 5-character SQLSTATE if the server returned one. pub sql_state: Option, - /// Databricks-specific error identifier from the SEA - /// `ServiceError.error_code` envelope — a stable string slug like + /// Stable error identifier from the kernel or the SEA + /// `ServiceError.error_code` envelope, such as /// `STATEMENT_NOT_FOUND` or `WAREHOUSE_STOPPED` that wrappers can /// branch on to map to host-language exceptions (PySQL's /// `OperationalError` taxonomy, JDBC's `SQLException` subclasses). @@ -248,6 +243,32 @@ pub struct Error { /// Underlying cause. Boxed to keep the struct stack-friendly. pub cause: Option>, + + /// Original local filesystem failure, for host-language OS error mapping. + pub local_error: Option>, +} + +/// The OS error behind a failed local file operation. +#[non_exhaustive] +#[derive(Debug, Clone)] +pub struct LocalFileError { + pub raw_os_error: Option, + pub kind: std::io::ErrorKind, + pub path: String, +} + +impl LocalFileError { + pub fn new( + raw_os_error: Option, + kind: std::io::ErrorKind, + path: impl Into, + ) -> Self { + Self { + raw_os_error, + kind, + path: path.into(), + } + } } impl Error { @@ -270,6 +291,7 @@ impl Error { diagnostic_info: None, error_details_json: None, cause: None, + local_error: None, } } @@ -442,6 +464,11 @@ impl Error { self } + pub fn with_local_error(mut self, local_error: LocalFileError) -> Self { + self.local_error = Some(Box::new(local_error)); + self + } + pub fn with_vendor_code(mut self, vendor_code: i32) -> Self { self.vendor_code = Some(vendor_code); self diff --git a/src/lib.rs b/src/lib.rs index 00340e94..4a189d3f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -127,6 +127,7 @@ pub mod metadata_v0; pub mod result_stream; pub mod session; pub(crate) mod util; +mod volume; // Custom C ABI for ODBC / Go consumers (lives in the core crate; see // `c_abi` module docs for why it is not a separate crate like pyo3 / napi). @@ -138,7 +139,7 @@ pub use config::{ LoggingConfig, ProxyConfig, ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, TokenCacheConfig, TransportMode, }; -pub use kernel_error::{Error, ErrorCode, Result}; +pub use kernel_error::{Error, ErrorCode, LocalFileError, Result}; /// The `tracing` target string stamped on every kernel log event. /// Binding crates (pyo3, napi) reference this constant directly so the /// logger name they expose to users can never drift from what the @@ -157,6 +158,7 @@ pub use statement::params_codec::parse_typed_value; pub use statement::spec::{ResultFormat, StatementSpec, TypedValue}; pub use statement::{MAX_CLIENT_QUERY_TIMEOUT, MAX_CLIENT_QUERY_TIMEOUT_MS}; pub use telemetry::DriverSystemConfiguration; +pub use volume::{VolumeCompletion, VolumeOptions}; // === Compile-time guarantees on auto-traits === // diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 7f6be171..709ccaf3 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1472,6 +1472,7 @@ mod tests { fn make_manifest(columns: Vec) -> ResultManifest { ResultManifest { + is_volume_operation: false, format: "ARROW_STREAM".to_string(), schema: ResultSchema { column_count: columns.len() as i32, @@ -2150,6 +2151,7 @@ mod tests { fn minimal_manifest(total_chunk_count: Option) -> ResultManifest { ResultManifest { + is_volume_operation: false, format: "ARROW_STREAM".to_string(), schema: ResultSchema { column_count: 0, diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index 4c5c82ce..cc3f80cf 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -469,6 +469,7 @@ mod tests { fn make_manifest(columns: Vec) -> ResultManifest { ResultManifest { + is_volume_operation: false, format: "ARROW_STREAM".to_string(), schema: ResultSchema { column_count: columns.len() as i32, diff --git a/src/result_stream.rs b/src/result_stream.rs index 721424e1..749d610c 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -58,6 +58,7 @@ use arrow_array::types::{ use arrow_array::{Array, RecordBatch}; use arrow_schema::{DataType, Schema, TimeUnit}; use chrono::{NaiveDate, NaiveDateTime}; +use std::collections::VecDeque; use std::sync::Arc; /// Cheap-clone reference to a result schema. The kernel hands one @@ -90,7 +91,7 @@ pub enum TryNextBatch<'a> { End, } -type Prefetched = Option>>; +type Prefetched = VecDeque>>; // `ResultBatch::into_arrow()` was deliberately removed: the // `#[non_exhaustive]` envelope is the right escape hatch already. @@ -466,7 +467,7 @@ pub struct ResultStream { /// until the next call to `next_batch` replaces it. current: Option, - /// A peek must preserve both data and read errors for the caller's fetch. + /// Batches and read errors already pulled from the reader but not yet returned to the caller. prefetched: Prefetched, /// Row cursor inside [`current`](Self::current). Reset to `0` @@ -493,6 +494,7 @@ pub struct ResultStream { close_guard: Option, telemetry: Option, + volume: Option>, } struct ResultStreamTelemetry { @@ -603,11 +605,12 @@ impl ResultStream { reader: Some(reader), schema, current: None, - prefetched: None, + prefetched: VecDeque::new(), current_row_idx: 0, exhausted: false, close_guard: None, telemetry: None, + volume: None, }) } @@ -638,6 +641,99 @@ impl ResultStream { Ok(stream) } + pub(crate) fn attach_volume(&mut self, state: Arc) { + self.volume = Some(state); + } + + /// True when the server marked this result as a Volume PUT, GET or REMOVE. + pub fn is_volume_operation(&self) -> bool { + self.volume.is_some() + } + + /// Runs the file transfer for a Volume PUT, GET or REMOVE result. + /// + /// Call before reading rows; the rows stay readable afterwards. The outcome, + /// success or failure, is cached, so a repeat call does not transfer again. + /// A GET downloads to a temporary file and then copies it over the destination, + /// so a failed download leaves an existing file unchanged. + /// A failure during that copy can leave the destination partly written. + /// A PUT source must be a regular file that reports its size. + /// A file PUT that storage redirects with 307 or 308 is resent from memory, + /// so that upload needs memory equal to the file size. + /// Cancelling does not undo work already done: a PUT or REMOVE may already + /// have reached storage, and a copy that has started runs to the end. + /// Results from [`Session::attach_async_statement`](crate::Session::attach_async_statement) + /// cannot run transfers and return `NotVolume`. + pub async fn complete_volume_operation( + &mut self, + options: &crate::volume::VolumeOptions, + input_bytes: Option>, + ) -> Result { + let Some(state) = self.volume.clone() else { + return Ok(crate::volume::VolumeCompletion::NotVolume); + }; + if !state.completion.initialized() + && (self.current.is_some() || (self.exhausted && self.prefetched.is_empty())) + { + return Err(Error::invalid_state() + .message("complete_volume_operation must be called before reading result rows")); + } + let result = state + .complete( + async { + let batch = loop { + let batch = self.peek_first_batch().await?.ok_or_else(|| { + Error::invalid_argument() + .with_error_code("VOLUME_INVALID_INSTRUCTION") + .message("Missing Volume instruction row") + })?; + let ResultBatch::Arrow(batch) = batch; + if batch.num_rows() != 0 { + break batch.clone(); + } + self.prefetched.pop_front(); + }; + // Read to the end before transferring: a result with more than one row is rejected. + while !self.exhausted { + match self + .reader + .as_mut() + .expect("Volume completion retains its reader") + .next_batch() + .await + { + Err(error) => { + self.prefetched.push_back(Err(Box::new(error.clone()))); + return Err(error); + } + Ok(Some(batch)) if batch.num_rows() != 0 => { + self.prefetched.push_back(Ok(ResultBatch::Arrow(batch))); + return Err(Error::invalid_argument() + .with_error_code("VOLUME_INVALID_INSTRUCTION") + .message("Expected one Volume instruction row")); + } + Ok(Some(_)) => {} + Ok(None) => self.exhausted = true, + } + } + Ok(batch) + }, + options, + input_bytes, + ) + .await; + if let Err(error) = &result { + self.finalize_telemetry(Some(error)); + } + result + } + + pub(crate) fn cancel_volume(&self) { + if let Some(state) = &self.volume { + state.cancel(); + } + } + pub(crate) fn attach_telemetry(&mut self, telemetry: StatementTelemetry) { self.telemetry = Some(ResultStreamTelemetry::new(telemetry)); } @@ -711,9 +807,9 @@ impl ResultStream { /// performed on this path, so calling from a tokio runtime /// (napi-rs, PyO3 async) is safe. pub async fn next_batch(&mut self) -> Result> { - // A batch buffered by `peek_first_batch` is replayed here first, - // so a non-consuming peek doesn't steal it from the caller. - if let Some(batch) = self.prefetched.take() { + // Return buffered batches first, so rows read ahead by a peek or by Volume + // completion still reach the caller. + if let Some(batch) = self.prefetched.pop_front() { self.set_current_batch(batch.map_err(|error| *error)?); return Ok(self.current.as_ref()); } @@ -747,7 +843,7 @@ impl ResultStream { /// Return the next batch if it is already available without waiting for /// network or background-prefetch progress. pub fn try_next_batch(&mut self) -> Result> { - if let Some(batch) = self.prefetched.take() { + if let Some(batch) = self.prefetched.pop_front() { self.set_current_batch(batch.map_err(|error| *error)?); return Ok(TryNextBatch::Ready( self.current.as_ref().expect("batch was just installed"), @@ -784,23 +880,17 @@ impl ResultStream { } } - /// Non-consuming peek at the **first** batch of the stream. - /// - /// Buffers the first batch or error so the caller's next read observes - /// the same outcome. Returns `None` for an empty - /// stream. Only valid before any `next_batch`/`peek_first_batch` has - /// run (it no-ops if a batch is already current or buffered), which is - /// the only context it's used in: deriving a DML row-count off the - /// terminal result at statement-construction time. + /// Before the first next_batch, returns the first batch without consuming it. + /// The following next_batch returns the same batch or error. pub(crate) async fn peek_first_batch(&mut self) -> Result> { - if self.prefetched.is_none() && self.current.is_none() && !self.exhausted { + if self.prefetched.is_empty() && self.current.is_none() && !self.exhausted { let reader = self .reader .as_mut() .expect("ResultStream reader is present until into_owned_batches consumes it"); match reader.next_batch().await { Ok(Some(rb)) => { - self.prefetched = Some(Ok(ResultBatch::Arrow(rb))); + self.prefetched.push_back(Ok(ResultBatch::Arrow(rb))); // Stamp first-batch (result-set-ready) latency at fetch // time, not when the caller later consumes the prefetched // batch via `next_batch`. `record_result_batch` is @@ -810,7 +900,7 @@ impl ResultStream { // result set became ready rather than the caller's // think-time before the first `next_batch` pull. if let (Some(telemetry), Some(Ok(batch))) = - (&self.telemetry, self.prefetched.as_ref()) + (&self.telemetry, self.prefetched.front()) { telemetry.record_batch(batch); } @@ -818,12 +908,12 @@ impl ResultStream { Ok(None) => self.exhausted = true, Err(e) => { self.finalize_telemetry(Some(&e)); - self.prefetched = Some(Err(Box::new(e.clone()))); + self.prefetched.push_back(Err(Box::new(e.clone()))); return Err(e); } } } - match self.prefetched.as_ref() { + match self.prefetched.front() { Some(Ok(batch)) => Ok(Some(batch)), Some(Err(error)) => Err((**error).clone()), None => Ok(None), @@ -916,13 +1006,11 @@ impl ResultStream { /// runtime at all. Errors are surfaced once; subsequent calls /// after an `Err` keep returning `None`. pub fn into_owned_batches(mut self) -> OwnedBatchIter { - // Preserve a peeked-but-not-yet-consumed first batch: it was - // pulled from the reader, so it must be yielded ahead of the - // reader's remaining batches or it would be silently dropped. - let prefetched = self - .prefetched - .take() - .map(|outcome| outcome.map(|ResultBatch::Arrow(rb)| rb)); + // Buffered batches were read first, so yield them first to keep row order. + let prefetched = std::mem::take(&mut self.prefetched) + .into_iter() + .map(|outcome| outcome.map(|ResultBatch::Arrow(rb)| rb)) + .collect(); OwnedBatchIter { reader: self .reader @@ -969,7 +1057,7 @@ impl Iterator for OwnedBatchIter { if self.done { return None; } - if let Some(outcome) = self.prefetched.take() { + if let Some(outcome) = self.prefetched.pop_front() { return match outcome { Ok(batch) => { if let Some(telemetry) = &self.telemetry { @@ -1401,16 +1489,19 @@ mod tests { let schema = schema_for(vec![Field::new("a", DataType::Int32, false)]); let b1 = RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![1, 2]))]) .unwrap(); - let b2 = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![3]))]).unwrap(); - let reader = InMemoryReader::new(b1.schema(), vec![b1.clone(), b2.clone()]); + let b2 = RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![3]))]) + .unwrap(); + let b3 = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![4]))]).unwrap(); + let reader = InMemoryReader::new(b1.schema(), vec![b1.clone(), b2.clone(), b3.clone()]); let mut stream = ResultStream::from_reader(Box::new(reader)).await.unwrap(); assert!(stream.peek_first_batch().await.unwrap().is_some()); let mut iter = stream.into_owned_batches(); let first = iter.next().unwrap().unwrap(); - assert_eq!(first.num_rows(), 2); + assert_eq!(first, b1); let second = iter.next().unwrap().unwrap(); - assert_eq!(second.num_rows(), 1); + assert_eq!(second, b2); + assert_eq!(iter.next().unwrap().unwrap(), b3); assert!(iter.next().is_none(), "exhausted iterator returns None"); assert!(iter.next().is_none(), "still None on subsequent calls"); } diff --git a/src/session.rs b/src/session.rs index ac2f462f..8824c02f 100644 --- a/src/session.rs +++ b/src/session.rs @@ -97,6 +97,9 @@ pub(crate) struct SessionInner { /// behind the trait object; future variants slot in via /// `TransportMode`. transport: Arc, + storage_client: Arc, + storage_retry: RetryConfig, + volume_cancellation: tokio_util::sync::CancellationToken, /// Server-issued session identifier. session_id: String, @@ -158,6 +161,18 @@ pub(crate) struct SessionInner { } impl SessionInner { + pub(crate) fn new_volume_state(&self) -> Arc { + crate::volume::VolumeState::new( + self.storage_retry.clone(), + Arc::clone(&self.storage_client), + self.volume_cancellation.child_token(), + ) + } + + fn cancel_volume_operations(&self) { + self.volume_cancellation.cancel(); + } + /// Crate-internal accessor for the session's transport. Used by /// `Metadata` (and PR 4's `Statement`) to drive RPCs without /// reaching into private fields. @@ -226,6 +241,7 @@ impl SessionInner { /// explicit close genuinely *initiates* the delete rather than /// deferring it to an idle-timeout. pub(crate) fn initiate_delete(&self) { + self.cancel_volume_operations(); if self .closed .compare_exchange( @@ -367,11 +383,13 @@ impl Session { // it for OIDC discovery / token endpoint calls. let http_client_config = build_http_client_config(&config, org_id); let retry_configs = build_retry_configs_for_session(&config); + let storage_retry = retry_configs[&RequestCategory::Sea].clone(); let http_client = Arc::new( DatabricksHttpClient::new(http_client_config, retry_configs).map_err(|e| { Error::network_error().message(format!("Failed to construct HTTP client: {e}")) })?, ); + let storage_client = Arc::new(http_client.storage_client(config.http.storage_read_timeout)); // 2. Auth provider — async because OAuth flows hit the OIDC // discovery endpoint. @@ -472,6 +490,9 @@ impl Session { Ok(Session { inner: Arc::new(SessionInner { transport, + storage_client, + storage_retry, + volume_cancellation: tokio_util::sync::CancellationToken::new(), session_id: session_info.session_id, config, runtime_handle, @@ -778,6 +799,7 @@ impl Session { /// race): flag stays false, [`Drop`] picks up the slack. /// - On `Ok`: flag flips, [`Drop`] is a no-op. pub async fn close(self) -> Result<()> { + self.inner.cancel_volume_operations(); // Bail early if a concurrent caller already finished a // successful close — no point hitting the wire twice. if self.inner.closed.load(std::sync::atomic::Ordering::Acquire) { diff --git a/src/statement/executed.rs b/src/statement/executed.rs index 025db78e..49054d9e 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -189,6 +189,7 @@ impl ExecutedStatement { } async fn close_server_statement(&self) -> Result<()> { + self.result_stream.cancel_volume(); // Idempotent on success: a prior successful close sets // `closed=true` and subsequent calls short-circuit. // @@ -348,12 +349,17 @@ impl ExecutedStatementHandle for ExecutedStatement { } async fn cancel(&self) -> Result<()> { + self.result_stream.cancel_volume(); // Local validity short-circuits a wire call against an // already-closed/superseded handle. `instrument` (rather // than `.entered()`) so the future stays `Send` per the // `ExecutedStatementHandle` trait bound. async { self.valid.check()?; + // A closed statement has nothing left to cancel on the server. + if self.closed.load(Ordering::Acquire) { + return Ok(()); + } self.session .transport() .cancel_statement(&self.statement_id) @@ -370,6 +376,7 @@ impl ExecutedStatementHandle for ExecutedStatement { impl Drop for ExecutedStatement { fn drop(&mut self) { + self.result_stream.cancel_volume(); // Backstop for the not-fully-drained case (partial fetch / // abandoned result / early error): if the stream was drained, // `next_batch`'s auto-close already fired and flipped `closed`, diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index c5739c47..388a30c6 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -172,6 +172,7 @@ impl StatementStatus { /// Async-consumption executed handle. pub struct ExecutedAsyncStatement { + volume: Option>, session: Arc, statement_id: String, /// Shared with the parent `Statement`; flipped on re-execute or @@ -277,10 +278,17 @@ fn deadline_policy(timeout: ExecutionTimeout) -> (Option, bo } impl ExecutedAsyncStatement { + fn cancel_volume(&self) { + if let Some(volume) = &self.volume { + volume.cancel(); + } + } + /// Produce the stable client query-timeout error and schedule bounded, /// best-effort server cleanup when a deadline retained across /// caller-driven status polls expires. pub(crate) fn expire_client_query_timeout(&self) -> Error { + self.cancel_volume(); self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); if !self.client_timeout_expired.swap(true, Ordering::AcqRel) { @@ -314,6 +322,7 @@ impl ExecutedAsyncStatement { /// deadline and the transport's default `poll_timeout` ceiling; /// `Default` keeps the `poll_timeout` ceiling with no client /// deadline. + #[allow(clippy::too_many_arguments)] pub(crate) fn new( session: Arc, statement_id: String, @@ -322,6 +331,7 @@ impl ExecutedAsyncStatement { initial_status: crate::types::sea::StatementStatus, statement_telemetry: StatementTelemetry, timeout: ExecutionTimeout, + volume: Arc, ) -> Self { let (client_deadline, poll_timeout_disabled) = deadline_policy(timeout); let initial_terminal = initial_status.state.is_terminal(); @@ -331,6 +341,7 @@ impl ExecutedAsyncStatement { valid, closed, owner_released: Arc::new(AtomicBool::new(false)), + volume: Some(volume), // The submitting handle owns the statement lifecycle. owning: true, session_attribution: SessionAttribution::Current, @@ -398,6 +409,7 @@ impl ExecutedAsyncStatement { valid, closed: Arc::new(AtomicBool::new(true)), owner_released, + volume: None, owning: false, session_attribution, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), @@ -421,17 +433,17 @@ impl ExecutedAsyncStatement { .lock() .map_err(|error| Error::internal().message(format!("Statement status lock: {error}")))? .clone(); - Ok(AsyncStatementReader { - inner: Self::new_read_only( - Arc::clone(&self.session), - self.statement_id.clone(), - self.valid.clone(), - Arc::clone(&self.owner_released), - self.session_attribution, - status, - ) - .with_parameter_set_count(self.parameter_set_count), - }) + let mut inner = Self::new_read_only( + Arc::clone(&self.session), + self.statement_id.clone(), + self.valid.clone(), + Arc::clone(&self.owner_released), + self.session_attribution, + status, + ) + .with_parameter_set_count(self.parameter_set_count); + inner.volume = self.volume.clone(); + Ok(AsyncStatementReader { inner }) } fn check_owner_available(&self) -> Result<()> { @@ -1004,7 +1016,16 @@ impl ExecutedAsyncStatement { if result.status.state == crate::types::sea::StatementState::Closed { self.closed.store(true, Ordering::Release); } + let marked = result + .manifest + .as_ref() + .is_some_and(|m| m.is_volume_operation); let mut stream = ResultStream::from_reader(result.reader).await?; + if marked { + if let Some(volume) = &self.volume { + stream.attach_volume(Arc::clone(volume)); + } + } stream.attach_telemetry(self.statement_telemetry.clone()); // SEA carries no row count on the async status either; for a // DML the count rides in the result set. Derive it once @@ -1149,6 +1170,10 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement { } async fn cancel(&self) -> Result<()> { + // Stops a running transfer even after the parent `Statement` is dropped. + if self.owning { + self.cancel_volume(); + } async { self.valid.check()?; // A non-owning (attached) handle must not cancel a statement @@ -1192,6 +1217,7 @@ impl ExecutedAsyncStatement { async fn close_server_statement(&self) -> Result<()> { if self.owning { + self.cancel_volume(); self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); } @@ -1252,6 +1278,7 @@ impl ExecutedAsyncStatement { // either — otherwise the footgun just moves to the detached // canceller. owning: self.owning, + volume: self.volume.clone(), } } } @@ -1268,6 +1295,7 @@ impl ExecutedAsyncStatement { /// Cheap to [`Clone`] (one `Arc` bump plus a `String` / flag clone). #[derive(Clone)] pub struct AsyncStatementCanceller { + volume: Option>, session: Arc, statement_id: String, valid: ValidityFlag, @@ -1279,17 +1307,28 @@ pub struct AsyncStatementCanceller { } impl AsyncStatementCanceller { + /// Cancel local Volume completion without waiting for a server request. + pub fn cancel_volume_operation(&self) { + if self.owning { + if let Some(volume) = &self.volume { + volume.cancel(); + } + } + } + /// Server-side cancel via `cancel_statement(statement_id)`. /// /// Short-circuits to `InvalidStatementHandle` (no wire round-trip) /// if the parent handle was invalidated (re-execute / parent - /// `Statement` drop). Idempotent against a server already in a + /// `Statement` drop); a running Volume transfer is cancelled first + /// in that case too. Idempotent against a server already in a /// terminal state — the kernel's `cancel_statement` is a no-op /// 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. pub async fn cancel(&self) -> Result<()> { + self.cancel_volume_operation(); async { self.valid.check()?; if !self.owning { @@ -1317,6 +1356,7 @@ impl AsyncStatementCanceller { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { if self.owning { + self.cancel_volume(); self.owner_released.store(true, Ordering::Release); self.clear_pending_result(); } diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 630a04fe..eeaa459d 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -268,12 +268,17 @@ pub struct Statement { /// new `execute()` / `submit()` so a canceller never targets a /// stale prior statement. inflight_id: InflightId, + /// Volume transfer state of the current execution, shared with any + /// [`StatementCanceller`]. Replaced at the start of each new execution, so + /// a canceller always reaches the current transfer. + volume: Arc>>, } impl Statement { /// Construct a new statement bound to `session`. Crate-private — /// wrappers obtain a `Statement` via `Session::statement()`. pub(crate) fn new(session: Arc) -> Self { + let volume = session.new_volume_state(); Self { session, spec: StatementSpec::new(), @@ -281,6 +286,7 @@ impl Statement { last_valid: None, last_closed: None, inflight_id: Arc::new(Mutex::new(None)), + volume: Arc::new(Mutex::new(volume)), } } @@ -305,6 +311,7 @@ impl Statement { StatementCanceller { session: Arc::clone(&self.session), inflight_id: Arc::clone(&self.inflight_id), + volume: Arc::clone(&self.volume), } } @@ -432,7 +439,14 @@ impl Statement { self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); + let marked = result + .manifest + .as_ref() + .is_some_and(|m| m.is_volume_operation); let mut result_stream = ResultStream::from_reader(result.reader).await?; + if marked { + result_stream.attach_volume(self.volume_state()); + } result_stream.attach_telemetry(telemetry_for_body.clone()); // SEA puts no row count on the status envelope; for a DML it // returns the count as the result set. If the server didn't @@ -580,6 +594,7 @@ impl Statement { response.status, telemetry_for_body, timeout, + self.volume_state(), ) .with_parameter_set_count(exec_params.parameter_sets.len())) } @@ -677,7 +692,14 @@ impl Statement { self.last_statement_id = Some(result.statement_id.clone()); self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); + let marked = result + .manifest + .as_ref() + .is_some_and(|m| m.is_volume_operation); let mut result_stream = ResultStream::from_reader(result.reader).await?; + if marked { + result_stream.attach_volume(self.volume_state()); + } result_stream.attach_telemetry(telemetry_for_body.clone()); let mut status = result.status; let parameter_set_count = exec_params.parameter_sets.len(); @@ -729,6 +751,7 @@ impl Statement { resp.status, telemetry_for_body, ExecutionTimeout::Default, + self.volume_state(), ) .with_parameter_set_count(exec_params.parameter_sets.len()), )) @@ -755,6 +778,10 @@ impl Statement { self.invalidate_prior().await; } + fn volume_state(&self) -> Arc { + Arc::clone(&self.volume.lock().unwrap_or_else(|e| e.into_inner())) + } + fn statement_telemetry(&self, operation_type: OperationType) -> StatementTelemetry { self.session .statement_telemetry_observer(StatementType::Sql, operation_type) @@ -787,6 +814,7 @@ impl Statement { /// for callers that forget to call `close()` explicitly, but /// the explicit path is the supported one. pub async fn close(mut self) -> Result<()> { + self.volume_state().cancel(); let span = self.session.log_span().clone(); async { self.invalidate_prior().await; @@ -817,8 +845,8 @@ impl Statement { build_execute_params(&self.spec, wait_timeout_secs) } - /// Clear the shared in-flight-id slot at the very start of a new - /// dispatch, before any `.await`. + /// Clear the shared in-flight-id slot and replace the Volume transfer + /// state at the very start of a new dispatch, before any `.await`. /// /// The slot still holds the *prior* execution's server statement id /// until this runs. A [`StatementCanceller`] retained across a @@ -833,11 +861,18 @@ impl Statement { /// nothing: a canceller firing before the new id is observed is a /// tolerated no-op (`dispatched = false`), never a hit on the stale id. /// + /// The prior execution's Volume transfer is cancelled and a fresh state + /// installed in the same step, so a retained canceller reaches the new + /// execution's transfer, not the previous one. + /// /// Kept out of [`invalidate_prior`] deliberately — that is also called /// by [`Statement::close`], where the slot must survive so a detached /// canceller can still dispatch against the just-closed statement (its /// cloned session `Arc` keeps the client side alive). fn reset_inflight_slot(&self) { + let mut volume = self.volume.lock().unwrap_or_else(|e| e.into_inner()); + volume.cancel(); + *volume = self.session.new_volume_state(); if let Ok(mut slot) = self.inflight_id.lock() { *slot = None; } @@ -981,19 +1016,28 @@ impl Drop for MidExecuteCancelGuard { /// [`Statement`]. Produced by [`Statement::canceller`]. /// /// Holds only the shared session handle and the `Statement`'s shared -/// in-flight-id slot — **not** the `Statement` itself — so a binding -/// can fire a server-side cancel from another thread while `execute()` -/// is blocked. The sync-execute analogue of +/// in-flight-id slot and its Volume transfer state — **not** the `Statement` +/// itself — so a binding can fire a server-side cancel from another thread +/// while `execute()` is blocked. The sync-execute analogue of /// [`AsyncStatementCanceller`](crate::statement::executed_async::AsyncStatementCanceller). /// -/// Cheap to [`Clone`] (two `Arc` bumps). +/// Cheap to [`Clone`] (three `Arc` bumps). #[derive(Clone)] pub struct StatementCanceller { session: Arc, inflight_id: InflightId, + volume: Arc>>, } impl StatementCanceller { + /// Cancel local Volume completion without waiting for a server request. + pub fn cancel_volume_operation(&self) { + self.volume + .lock() + .unwrap_or_else(|e| e.into_inner()) + .cancel(); + } + /// Server-side cancel of the in-flight statement via /// `cancel_statement(statement_id)`. /// @@ -1016,8 +1060,10 @@ impl StatementCanceller { /// Idempotent against a server already in a terminal state (the /// kernel's `cancel_statement` is a no-op there). Safe to call /// concurrently with the `execute()` it targets — the two share - /// only the id slot (behind a `Mutex`), no mutable statement state. + /// only the id slot and the Volume state (each behind a `Mutex`), no + /// mutable statement state. pub async fn cancel(&self) -> Result { + self.cancel_volume_operation(); let id = self.inflight_id.lock().ok().and_then(|g| g.clone()); async { // Log both outcomes at the decision point so a host debugging a diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 42505bc7..8ceee6c4 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -292,12 +292,12 @@ fn duration_millis(duration: Duration) -> i64 { mod tests { use super::*; use crate::kernel_error::ErrorCode; - use crate::reader::test_utils::ErrorReader; + use crate::reader::test_utils::{BatchThenErrorReader, ErrorReader, MockReader}; use crate::reader::{ResultReader, ResultReaderMetrics}; use crate::result_stream::ResultStream; use crate::telemetry::models::OperationType; use crate::telemetry::runtime::{ConnectionTelemetry, TelemetrySessionContext}; - use arrow_array::RecordBatch; + use arrow_array::{RecordBatch, RecordBatchOptions}; use arrow_schema::Schema; use async_trait::async_trait; use std::future::Future; @@ -407,6 +407,97 @@ mod tests { ); } + #[tokio::test] + async fn volume_errors_finalize_statement_with_error_before_drop() { + enum Case { + VolumeReader, + Instruction, + } + for case in [Case::VolumeReader, Case::Instruction] { + let connection = Arc::new(CapturingConnectionTelemetry::default()); + let telemetry = StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + ); + let schema = Arc::new(Schema::empty()); + let batch = RecordBatch::try_new_with_options( + schema.clone(), + vec![], + &RecordBatchOptions::new().with_row_count(Some(1)), + ) + .expect("one-row batch"); + let (reader, code, message): (Box, _, _) = match case { + Case::VolumeReader => ( + Box::new(BatchThenErrorReader { + batch: Some(batch), + schema, + }), + ErrorCode::Internal, + "simulated read error after first batch", + ), + Case::Instruction => ( + Box::new(MockReader::new(vec![batch])), + ErrorCode::InvalidArgument, + "Missing Volume instruction column", + ), + }; + let mut stream = ResultStream::from_reader(reader) + .await + .expect("schema succeeds"); + stream.attach_telemetry(telemetry); + + stream.attach_volume(crate::volume::VolumeState::new( + Default::default(), + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(None), + ), + Default::default(), + )); + let options = Default::default(); + let error = stream + .complete_volume_operation(&options, None) + .await + .unwrap_err(); + let cached = stream + .complete_volume_operation(&options, None) + .await + .unwrap_err(); + assert_eq!(cached.code, error.code); + assert_eq!(cached.message, error.message); + assert_eq!(error.code, code); + assert_eq!(error.message, message); + let events_before_drop = connection + .statement_events + .lock() + .expect("events mutex") + .len(); + assert_eq!( + events_before_drop, 1, + "terminal error must finalize before Drop" + ); + + drop(stream); + + let events = connection.statement_events.lock().expect("events mutex"); + assert_eq!( + events.len(), + 1, + "terminal error should finalize once; Drop must not overwrite it with success" + ); + let event = &events[0]; + assert_eq!(event.context.statement_type, StatementType::Sql); + assert_eq!(event.error_code, Some(code)); + assert_eq!(event.error_message.as_deref(), Some(message)); + assert!( + event.context.consumption_latency.is_some(), + "failed consumption should still record result-consumption latency" + ); + } + } + #[tokio::test] async fn dropping_result_stream_finalizes_with_reader_metrics() { let connection = Arc::new(CapturingConnectionTelemetry::default()); diff --git a/src/types/sea.rs b/src/types/sea.rs index 32e18c62..2dd34b85 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -184,6 +184,8 @@ pub struct ServiceError { /// Manifest describing the result set structure. #[derive(Debug, Clone, Deserialize)] pub struct ResultManifest { + #[serde(default)] + pub is_volume_operation: bool, pub format: String, pub schema: ResultSchema, /// Physical Arrow schema carried by SEA as a schema-only IPC stream. diff --git a/src/volume.rs b/src/volume.rs new file mode 100644 index 00000000..c2042b2a --- /dev/null +++ b/src/volume.rs @@ -0,0 +1,2074 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! File transfers for Volume PUT, GET and REMOVE statements. +//! +//! The server answers these statements with one row holding a presigned +//! storage URL, request headers and a local path. This module makes that +//! storage request when the caller asks. + +use crate::client::retry::{calculate_backoff, RequestType, RetryConfig, RetryStrategy}; +use crate::kernel_error::{Error, LocalFileError, Result}; +use arrow_array::{Array, LargeStringArray, MapArray, RecordBatch, StringArray, StringViewArray}; +use futures::TryStreamExt; +use reqwest::{header::HeaderMap, Client, Method}; +use std::path::{Component, Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use tokio::io::AsyncWriteExt; +use tokio::sync::OnceCell; +use tokio_util::bytes::Bytes; +use tokio_util::io::ReaderStream; +use tokio_util::sync::CancellationToken; + +/// Caller settings for a Volume file transfer. +#[non_exhaustive] +#[derive(Debug, Clone, Default)] +pub struct VolumeOptions { + /// Local directories a PUT may read from and a GET may write to. Both the + /// path named in the statement and the file it resolves to through + /// symlinks must be inside one of them. Empty allows no local file access. + /// The check runs before the file is opened, so nothing else may swap + /// files or links in these directories during a transfer. + pub allowed_paths: Vec, + /// Report success when REMOVE targets a file that does not exist. + pub remove_not_found_is_success: bool, +} + +impl VolumeOptions { + pub fn new(allowed_paths: Vec, remove_not_found_is_success: bool) -> Self { + Self { + allowed_paths, + remove_not_found_is_success, + } + } +} + +/// Outcome of `ResultStream::complete_volume_operation`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(C)] +pub enum VolumeCompletion { + /// The result is not a Volume statement; nothing was done. + NotVolume = 0, + /// The PUT uploads caller-supplied bytes; call again with `input_bytes`. + NeedsInputStream = 1, + /// The transfer finished. + Completed = 2, +} + +pub(crate) struct VolumeState { + retry: RetryConfig, + storage: Arc, + /// Unset until the transfer reaches a final outcome. A PUT waiting for caller bytes leaves it unset. + pub(crate) completion: OnceCell>, + cancellation: CancellationToken, + started: AtomicBool, +} + +struct Download { + temp: std::fs::File, + existing: Option, + path: PathBuf, + local_file: String, +} + +fn cancelled() -> Error { + Error::cancelled().message("Volume transfer was cancelled") +} + +impl VolumeState { + pub(crate) fn new( + retry: RetryConfig, + storage: Arc, + cancellation: CancellationToken, + ) -> Arc { + Arc::new(Self { + retry, + storage, + cancellation, + completion: OnceCell::new(), + started: AtomicBool::new(false), + }) + } + + pub(crate) fn cancel(&self) { + self.cancellation.cancel(); + } + + pub(crate) async fn complete( + &self, + prepare: impl std::future::Future>, + options: &VolumeOptions, + input_bytes: Option>, + ) -> Result { + match self + .completion + .get_or_try_init(|| async { + // If an earlier call was dropped mid-transfer, do not run the transfer again. + if self.started.swap(true, Ordering::AcqRel) || self.cancellation.is_cancelled() { + return Ok(Err(cancelled())); + } + let transfer = async { + let batch = prepare.await?; + let instruction = Instruction::decode(&batch)?; + if matches!(instruction.operation, Operation::Put(Source::Stream)) + && input_bytes.is_none() + { + return Ok::<_, Error>((VolumeCompletion::NeedsInputStream, None)); + } + let client = self.storage.get().await?; + let destination = self + .transfer(instruction, client, options, input_bytes) + .await?; + Ok((VolumeCompletion::Completed, destination)) + }; + let complete = async { + let (outcome, destination) = tokio::select! { + biased; + result = transfer => result?, + _ = self.cancellation.cancelled() => return Err(cancelled()), + }; + if let Some(Download { + mut temp, + existing, + path, + local_file, + }) = destination + { + let cancellation = self.cancellation.clone(); + tokio::task::spawn_blocking(move || { + if cancellation.is_cancelled() { + return Err(cancelled()); + } + let mut file = match existing { + Some(file) => file, + None => std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|e| local_error(e, &local_file))?, + }; + std::io::Seek::rewind(&mut temp) + .map_err(|e| local_error(e, &local_file))?; + let length = std::io::copy(&mut temp, &mut file) + .map_err(|e| local_error(e, &local_file))?; + file.set_len(length) + .map_err(|e| local_error(e, &local_file)) + }) + .await + .map_err(|e| { + Error::internal() + .message(format!("Volume download copy task failed: {e}")) + })??; + } + Ok(outcome) + }; + let result = complete.await; + if matches!(result, Ok(VolumeCompletion::NeedsInputStream)) { + self.started.store(false, Ordering::Release); + // Leave the cell uninitialized so completion can resume with input bytes. + Err(VolumeCompletion::NeedsInputStream) + } else { + Ok(result) + } + }) + .await + { + Ok(result) => result.clone(), + Err(outcome) => Ok(outcome), + } + } + + async fn transfer( + &self, + instruction: Instruction, + client: &Client, + options: &VolumeOptions, + input_bytes: Option>, + ) -> Result> { + let input = if matches!(instruction.operation, Operation::Put(Source::Stream)) { + Some(Bytes::from( + input_bytes.ok_or_else(|| invalid("Missing input stream"))?, + )) + } else { + None + }; + let mut retry_started = None; + let mut attempt = 0; + loop { + let mut retry_after = None; + let attempt_started = std::time::Instant::now(); + let error = match self + .transfer_once( + &instruction, + client, + options, + input.as_ref(), + &mut retry_after, + ) + .await + { + Ok(completion) => { + tracing::debug!( + target: crate::klog::KERNEL_LOG_TARGET, + attempt = attempt + 1, + attempt_ms = attempt_started.elapsed().as_millis() as u64, + "volume transfer attempt succeeded" + ); + return Ok(completion); + } + Err(error) => error, + }; + tracing::debug!( + target: crate::klog::KERNEL_LOG_TARGET, + attempt = attempt + 1, + attempt_ms = attempt_started.elapsed().as_millis() as u64, + retryable = error.retryable, + error = %error.message, + "volume transfer attempt failed" + ); + // The retry clock starts at the first failure, so a long transfer does not + // use up the retry budget. + let started = retry_started.get_or_insert_with(std::time::Instant::now); + if !error.retryable || attempt >= self.retry.max_retries { + return Err(error.message(format!("after {} attempts", attempt + 1))); + } + let wait = calculate_backoff(&self.retry, attempt, retry_after.as_deref()); + if started.elapsed().saturating_add(wait) >= self.retry.overall_timeout { + return Err(error.message(format!("after {} attempts", attempt + 1))); + } + tracing::debug!( + target: crate::klog::KERNEL_LOG_TARGET, + attempt = attempt + 1, + wait_ms = wait.as_millis() as u64, + "waiting before retrying volume transfer" + ); + tokio::time::sleep(wait).await; + attempt += 1; + } + } + + async fn transfer_once( + &self, + instruction: &Instruction, + client: &Client, + options: &VolumeOptions, + input: Option<&Bytes>, + retry_after: &mut Option, + ) -> Result> { + let (method, local_file, source, mut destination) = + Self::prepare_local(instruction, options).await?; + let upload = method == Method::PUT; + let remove = method == Method::DELETE; + let mut request = client + .request(method, &instruction.url) + .headers(instruction.headers.clone()); + let upload_error = Arc::new(Mutex::new(None)); + let (progress, changed) = tokio::sync::watch::channel(tokio::time::Instant::now()); + let reader: Option<(Box, u64)> = + if let Some((file, length)) = source.as_ref() { + Some(( + Box::new(tokio::fs::File::from_std( + file.try_clone().map_err(|e| local_error(e, &local_file))?, + )), + *length, + )) + } else { + input.map(|bytes| { + ( + Box::new(std::io::Cursor::new(bytes.clone())) as _, + bytes.len() as u64, + ) + }) + }; + if let Some((reader, length)) = reader { + request = request + .headers(HeaderMap::from_iter([( + reqwest::header::CONTENT_LENGTH, + length.into(), + )])) + .body(upload_body( + reader, + local_file.clone(), + Arc::clone(&upload_error), + progress, + )); + } + let mut response = storage_send( + request, + self.storage.read_timeout, + upload, + upload_error, + changed, + ) + .await?; + if matches!(response.status().as_u16(), 307 | 308) { + let bytes = match (input, source) { + (Some(bytes), _) => Some(bytes.clone()), + (None, Some((file, length))) => { + let local_file = local_file.clone(); + Some(Bytes::from( + tokio::task::spawn_blocking(move || { + read_from_start(&file, length).map_err(|e| local_error(e, &local_file)) + }) + .await + .map_err(|e| { + Error::internal() + .message(format!("Volume upload read task failed: {e}")) + })??, + )) + } + _ => None, + }; + if let Some(bytes) = bytes { + // reqwest cannot replay a streamed body on a redirect. Send the original URL again + // with the body in memory so reqwest can follow; this resend has no idle timeout. + response = client + .put(&instruction.url) + .headers(instruction.headers.clone()) + .headers(HeaderMap::from_iter([( + reqwest::header::CONTENT_LENGTH, + bytes.len().into(), + )])) + .body(reqwest::Body::from(bytes)) + .send() + .await + .map_err(storage_error)?; + } + } + let status = response.status(); + if !(status.is_success() + || (remove && status.as_u16() == 404 && options.remove_not_found_is_success)) + { + return Err(self + .storage_failure(&mut response, status, upload, retry_after) + .await); + } + self.download_body(&mut response, upload, &local_file, &mut destination) + .await?; + Ok(destination.map(|(download, writer)| { + drop(writer); + download + })) + } + + async fn prepare_local( + instruction: &Instruction, + options: &VolumeOptions, + ) -> Result<( + Method, + String, + Option<(std::fs::File, u64)>, + Option<(Download, tokio::fs::File)>, + )> { + let operation = instruction.operation.clone(); + let roots = options.allowed_paths.clone(); + let preparation = tokio::task::spawn_blocking(move || { + let mut source = None; + let mut destination = None; + let (method, local_file) = match operation { + Operation::Put(Source::File(path)) => { + let local_file = path.to_string_lossy().into_owned(); + let path = allowed_path(&local_file, &roots)?; + // Checked before opening because opening a FIFO waits for a writer. + if std::fs::metadata(&path).is_ok_and(|m| !m.is_file() && !m.is_dir()) { + return Err(unsupported_source("not a regular file", &local_file)); + } + let mut file = + std::fs::File::open(path).map_err(|e| local_error(e, &local_file))?; + let metadata = file.metadata().map_err(|e| local_error(e, &local_file))?; + if metadata.is_dir() { + // A directory opens without error on Unix; reading it produces the OS error to report. + let error = std::io::Read::read(&mut file, &mut [0]) + .err() + .unwrap_or_else(|| std::io::ErrorKind::IsADirectory.into()); + return Err(local_error(error, &local_file)); + } + if !metadata.is_file() { + return Err(unsupported_source("not a regular file", &local_file)); + } + // procfs files are regular files that report size 0 but are not empty. + if metadata.len() == 0 { + match read_from_start(&file, 1) { + Ok(_) => { + return Err(unsupported_source( + "reports size 0 but is not empty", + &local_file, + )) + } + Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => {} + Err(error) => return Err(local_error(error, &local_file)), + } + } + source = Some((file, metadata.len())); + (Method::PUT, local_file) + } + Operation::Get(path) => { + let local_file = path.to_string_lossy().into_owned(); + let path = allowed_path(&local_file, &roots)?; + let existing = match std::fs::OpenOptions::new().write(true).open(&path) { + Ok(file) => Some(file), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(local_error(error, &local_file)), + }; + let parent = path + .parent() + .ok_or_else(|| invalid("Missing destination parent"))?; + let temp = match tempfile::tempfile_in(parent) { + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + tempfile::tempfile() + } + other => other, + } + .map_err(|e| local_error(e, &local_file))?; + let writer = tokio::fs::File::from_std( + temp.try_clone().map_err(|e| local_error(e, &local_file))?, + ); + destination = Some(( + Download { + temp, + existing, + path, + local_file: local_file.clone(), + }, + writer, + )); + (Method::GET, local_file) + } + Operation::Put(Source::Stream) => (Method::PUT, String::new()), + Operation::Remove => (Method::DELETE, String::new()), + }; + Ok((method, local_file, source, destination)) + }); + preparation.await.map_err(|e| { + Error::internal().message(format!("Volume file preparation task failed: {e}")) + })? + } + + async fn storage_failure( + &self, + response: &mut reqwest::Response, + status: reqwest::StatusCode, + upload: bool, + retry_after: &mut Option, + ) -> Error { + *retry_after = response + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let mut error = Error::from_http_status(status.as_u16()) + .with_error_code("VOLUME_STORAGE_HTTP_ERROR") + .with_retryable( + RetryStrategy::for_request(RequestType::CloudFetchDownload, &self.retry) + .is_retryable_status(status, retry_after.is_some()), + ) + .message(format!( + "Volume storage request failed: HTTP {}", + status.as_u16() + )); + let mut body = Vec::new(); + while body.len() < 4096 { + match storage_read(self.storage.read_timeout, !upload, async { + response.chunk().await.map_err(response_body_error) + }) + .await + { + Ok(Some(chunk)) => { + body.extend_from_slice(&chunk[..chunk.len().min(4096 - body.len())]) + } + _ => break, + } + } + let text = String::from_utf8_lossy(&body); + for tag in ["Code", "Message"] { + if let Some(value) = text + .split_once(&format!("<{tag}>")) + .and_then(|(_, tail)| tail.split_once(&format!(""))) + .map(|(value, _)| value) + .filter(|value| !value.contains(['<', '>'])) + { + error = error.message(format!("{tag}: {value}")); + } + } + for (label, header) in [("RequestId", "x-amz-request-id"), ("HostId", "x-amz-id-2")] { + if let Some(value) = response + .headers() + .get(header) + .and_then(|value| value.to_str().ok()) + { + error = error.message(format!("{label}: {value}")); + } + } + error + } + + async fn download_body( + &self, + response: &mut reqwest::Response, + upload: bool, + local_file: &str, + destination: &mut Option<(Download, tokio::fs::File)>, + ) -> Result<()> { + while let Some(bytes) = storage_read(self.storage.read_timeout, !upload, async { + response.chunk().await.map_err(response_body_error) + }) + .await? + { + if let Some((_, writer)) = destination.as_mut() { + writer + .write_all(&bytes) + .await + .map_err(|e| local_error(e, local_file))?; + } + } + if let Some((_, writer)) = destination.as_mut() { + writer + .flush() + .await + .map_err(|e| local_error(e, local_file))?; + } + Ok(()) + } +} + +fn upload_body( + reader: impl tokio::io::AsyncRead + Unpin + Send + 'static, + path: String, + error: Arc>>, + progress: tokio::sync::watch::Sender, +) -> reqwest::Body { + reqwest::Body::wrap_stream( + ReaderStream::with_capacity(reader, 256 * 1024) + .inspect_ok(move |_| { + progress.send_replace(tokio::time::Instant::now()); + }) + .map_err(move |cause| { + *error.lock().unwrap_or_else(|e| e.into_inner()) = Some(local_error(cause, &path)); + std::io::Error::other("Volume upload source could not be read") + }), + ) +} + +fn invalid(message: &str) -> Error { + Error::invalid_argument() + .with_error_code("VOLUME_INVALID_INSTRUCTION") + .message(message) +} + +async fn storage_send( + request: reqwest::RequestBuilder, + timeout: Option, + upload: bool, + upload_error: Arc>>, + mut progress: tokio::sync::watch::Receiver, +) -> Result { + let send = async { request.send().await.map_err(storage_error) }; + tokio::pin!(send); + let response = if let (true, Some(timeout)) = (upload, timeout) { + loop { + let last = *progress.borrow_and_update(); + let Some(deadline) = last.checked_add(timeout) else { + break (&mut send).await; + }; + // PUT response timeouts may follow a committed write; GET retries only rewrite the temporary file. + tokio::select! { + biased; + response = &mut send => break response, + _ = progress.changed(), if progress.has_changed().is_ok() => {} + _ = tokio::time::sleep_until(deadline) => break Err(Error::network_error() + .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") + .with_retryable(false).message("Volume storage upload or response wait timed out")), + } + } + } else if upload { + send.await + } else { + storage_read(timeout, true, send).await + }; + if let Some(error) = upload_error + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take() + { + return Err(error); + } + response +} + +async fn storage_read( + timeout: Option, + retry_timeout: bool, + read: impl std::future::Future>, +) -> Result { + match timeout { + Some(timeout) => tokio::time::timeout(timeout, read) + .await + .unwrap_or_else(|_| { + Err(Error::network_error() + .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") + .with_retryable(retry_timeout) + .message("Volume storage read timed out")) + }), + None => read.await, + } +} + +fn storage_error(error: reqwest::Error) -> Error { + let retryable = + RetryStrategy::for_request(RequestType::CloudFetchDownload, &RetryConfig::default()) + .is_retryable_error(&error); + let error = error.without_url(); + let mut causes = crate::client::error_chain(&error) + .map(ToString::to_string) + .collect::>(); + causes.dedup(); + Error::network_error() + .with_error_code("VOLUME_STORAGE_NETWORK_ERROR") + .with_retryable(retryable) + .message(format!( + "Volume storage request failed: {}", + causes.join(": ") + )) +} + +fn response_body_error(error: reqwest::Error) -> Error { + let retryable = error.is_body() || error.is_decode(); + let mut error = storage_error(error); + error.retryable |= retryable; + error +} + +/// Reads the first `length` bytes of `file` by offset. The first request's body +/// shares this handle's position and may still be moving it. +fn read_from_start(file: &std::fs::File, length: u64) -> std::io::Result> { + let length = usize::try_from(length).map_err(|_| std::io::ErrorKind::OutOfMemory)?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(length) + .map_err(|_| std::io::ErrorKind::OutOfMemory)?; + bytes.resize(length, 0); + #[cfg(unix)] + { + std::os::unix::fs::FileExt::read_exact_at(file, &mut bytes, 0)?; + Ok(bytes) + } + #[cfg(windows)] + { + use std::os::windows::fs::FileExt; + let mut filled = 0; + while filled < bytes.len() { + match file.seek_read(&mut bytes[filled..], filled as u64)? { + 0 => return Err(std::io::ErrorKind::UnexpectedEof.into()), + read => filled += read, + } + } + Ok(bytes) + } +} + +fn local_error(error: std::io::Error, path: &str) -> Error { + match error.kind() { + std::io::ErrorKind::NotFound => Error::not_found(), + std::io::ErrorKind::PermissionDenied => Error::permission_denied(), + std::io::ErrorKind::InvalidInput + | std::io::ErrorKind::IsADirectory + | std::io::ErrorKind::NotADirectory => Error::invalid_argument(), + _ => Error::io(), + } + .with_error_code("VOLUME_LOCAL_FILE_ERROR") + .with_sql_state("HY000") + .message(format!("{error}: {path}")) + .with_local_error(LocalFileError::new( + error.raw_os_error(), + error.kind(), + path, + )) +} + +fn unsupported_source(reason: &'static str, path: &str) -> Error { + local_error( + std::io::Error::new(std::io::ErrorKind::InvalidInput, reason), + path, + ) +} + +fn normalize(path: &Path) -> Result { + let absolute = + std::path::absolute(path).map_err(|e| local_error(e, &path.to_string_lossy()))?; + let mut normalized = PathBuf::new(); + for component in absolute.components() { + match component { + Component::ParentDir => { + normalized.pop(); + } + Component::CurDir => {} + _ => normalized.push(component.as_os_str()), + } + } + Ok(normalized) +} + +const MAX_SYMLINK_RESOLUTIONS: u8 = 40; + +fn resolve_existing_parent( + path: &Path, + requested: &str, + remaining_symlinks: u8, +) -> Result { + match path.canonicalize() { + Ok(path) => Ok(path), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + if std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) { + if remaining_symlinks == 0 { + return Err(local_error(error, requested)); + } + let target = std::fs::read_link(path).map_err(|e| local_error(e, requested))?; + let target = if target.is_absolute() { + target + } else { + path.parent() + .ok_or_else(|| invalid("Invalid local path"))? + .join(target) + }; + return resolve_existing_parent( + &normalize(&target)?, + requested, + remaining_symlinks - 1, + ); + } + let parent = path.parent().ok_or_else(|| local_error(error, requested))?; + let name = path + .file_name() + .ok_or_else(|| invalid("Invalid local path"))?; + Ok(resolve_existing_parent(parent, requested, remaining_symlinks)?.join(name)) + } + Err(error) => Err(local_error(error, requested)), + } +} + +/// Whether `path` is `root` or inside it. The drive or share prefix never +/// depends on case. After resolving links, pass `ignore_name_case: false`: +/// a case-sensitive directory can hold two names that differ only by case. +#[cfg(windows)] +fn within_root(path: &Path, root: &Path, ignore_name_case: bool) -> bool { + let lower = |part: Component<'_>| part.as_os_str().to_string_lossy().to_lowercase(); + let mut path = path.components(); + root.components().all(|root| { + path.next().is_some_and(|part| { + if ignore_name_case || matches!(root, Component::Prefix(_)) { + lower(part) == lower(root) + } else { + part == root + } + }) + }) +} + +#[cfg(not(windows))] +fn within_root(path: &Path, root: &Path, _ignore_name_case: bool) -> bool { + path.starts_with(root) +} + +fn allowed_path(requested: &str, roots: &[PathBuf]) -> Result { + if requested.is_empty() { + return Err(invalid("Local file path is empty")); + } + let path = normalize(Path::new(requested))?; + let roots = roots + .iter() + .filter(|root| !root.as_os_str().is_empty()) + .map(|root| normalize(root)) + .collect::>>()?; + if !roots.iter().any(|root| within_root(&path, root, true)) { + return Err( + invalid("Local file path is outside the configured allowed roots") + .with_error_code("VOLUME_PATH_NOT_ALLOWED"), + ); + } + let resolved = resolve_existing_parent(&path, requested, MAX_SYMLINK_RESOLUTIONS)?; + let mut root_error = None; + for root in roots { + let root = match resolve_existing_parent( + &root, + &root.to_string_lossy(), + MAX_SYMLINK_RESOLUTIONS, + ) { + Ok(root) => root, + Err(error) => { + root_error.get_or_insert(error); + continue; + } + }; + if within_root(&resolved, &root, false) { + return Ok(resolved); + } + } + if let Some(error) = root_error { + return Err(error); + } + Err( + invalid("Resolved local file path is outside the configured allowed roots") + .with_error_code("VOLUME_PATH_NOT_ALLOWED"), + ) +} + +#[derive(Clone)] +enum Source { + File(PathBuf), + Stream, +} + +#[derive(Clone)] +enum Operation { + Put(Source), + Get(PathBuf), + Remove, +} + +struct Instruction { + operation: Operation, + url: String, + headers: HeaderMap, +} + +fn string_at(array: &dyn Array, row: usize) -> Result<&str> { + if array.is_null(row) { + return Err(invalid("Null Volume instruction field")); + } + if let Some(values) = array.as_any().downcast_ref::() { + return Ok(values.value(row)); + } + if let Some(values) = array.as_any().downcast_ref::() { + return Ok(values.value(row)); + } + if let Some(values) = array.as_any().downcast_ref::() { + return Ok(values.value(row)); + } + Err(invalid("Invalid Volume instruction column type")) +} + +impl Instruction { + fn decode(batch: &RecordBatch) -> Result { + if batch.num_rows() != 1 { + return Err(invalid("Expected one Volume instruction row")); + } + let schema = batch.schema(); + let column = |name: &str| -> Result<&dyn Array> { + let index = schema + .fields() + .iter() + .position(|f| f.name() == name) + .ok_or_else(|| invalid("Missing Volume instruction column"))?; + Ok(batch.column(index).as_ref()) + }; + let operation = string_at(column("operation")?, 0)?; + let headers = column("headers")?; + let mut parsed_headers = HeaderMap::new(); + let mut add_header = |name: &str, value: &str| -> Result<()> { + parsed_headers.insert( + reqwest::header::HeaderName::from_bytes(name.as_bytes()) + .map_err(|_| invalid("Invalid Volume storage header name"))?, + value + .parse() + .map_err(|_| invalid("Invalid Volume storage header value"))?, + ); + Ok(()) + }; + if !headers.is_null(0) { + if let Some(map) = headers.as_any().downcast_ref::() { + let entries = map.value(0); + for row in 0..entries.len() { + add_header( + string_at(entries.column(0).as_ref(), row)?, + string_at(entries.column(1).as_ref(), row)?, + )?; + } + } else { + let headers: std::collections::HashMap = + serde_json::from_str(string_at(headers, 0)?) + .map_err(|_| invalid("Invalid Volume storage headers"))?; + for (name, value) in headers { + add_header(&name, &value)?; + } + } + } + let operation = match operation { + "PUT" => match string_at(column("localFile")?, 0)? { + "__input_stream__" => Operation::Put(Source::Stream), + path => Operation::Put(Source::File(path.into())), + }, + "GET" => Operation::Get(string_at(column("localFile")?, 0)?.into()), + "REMOVE" => Operation::Remove, + _ => return Err(invalid("Unsupported Volume operation")), + }; + Ok(Self { + operation, + url: string_at(column("presignedUrl")?, 0)?.to_owned(), + headers: parsed_headers, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::builder::{MapBuilder, StringBuilder}; + use arrow_array::{ArrayRef, RecordBatch}; + use arrow_schema::{Field, Schema}; + #[cfg(unix)] + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + use std::time::Duration; + use wiremock::matchers::{body_bytes, header, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + #[test] + fn replay_read_ignores_the_shared_file_position() { + use std::io::{Seek, SeekFrom}; + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("source"); + let payload = b"0123456789".to_vec(); + std::fs::write(&path, &payload).unwrap(); + let mut file = std::fs::File::open(&path).unwrap(); + file.seek(SeekFrom::Start(3)).unwrap(); + assert_eq!( + read_from_start(&file, payload.len() as u64).unwrap(), + payload + ); + #[cfg(unix)] + assert_eq!(file.stream_position().unwrap(), 3); + assert_eq!( + read_from_start(&file, payload.len() as u64 + 1) + .unwrap_err() + .kind(), + std::io::ErrorKind::UnexpectedEof + ); + } + + fn instruction(operation: &str, url: &str, local: &Path) -> RecordBatch { + let mut headers = MapBuilder::new(None, StringBuilder::new(), StringBuilder::new()); + headers.keys().append_value("x-storage-token"); + headers.values().append_value("server-token"); + headers.append(true).unwrap(); + let arrays: Vec = vec![ + Arc::new(StringArray::from(vec![operation])), + Arc::new(StringArray::from(vec![url])), + Arc::new(headers.finish()), + Arc::new(StringArray::from(vec![local.to_str().unwrap()])), + ]; + let schema = Schema::new( + ["operation", "presignedUrl", "headers", "localFile"] + .iter() + .zip(&arrays) + .map(|(name, values)| Field::new(*name, values.data_type().clone(), true)) + .collect::>(), + ); + RecordBatch::try_new(Arc::new(schema), arrays).unwrap() + } + + fn options(root: &Path) -> VolumeOptions { + VolumeOptions { + allowed_paths: vec![root.to_owned()], + ..Default::default() + } + } + + fn storage(read_timeout: Option) -> Arc { + Arc::new( + crate::client::DatabricksHttpClient::with_default_retry(Default::default()) + .unwrap() + .storage_client(read_timeout), + ) + } + + fn transfer_state(max_retries: u32) -> Arc { + VolumeState::new( + RetryConfig { + max_retries, + min_wait: Duration::ZERO, + max_wait: Duration::ZERO, + ..Default::default() + }, + storage(None), + Default::default(), + ) + } + + #[tokio::test] + async fn local_upload_read_errors_wrapped_as_request_errors_are_not_retried() { + let server = MockServer::start().await; + struct FailedRead(Option); + impl tokio::io::AsyncRead for FailedRead { + fn poll_read( + mut self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + _: &mut tokio::io::ReadBuf<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Err(self.0.take().unwrap())) + } + } + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("missing"); + let cause = std::fs::File::open(&source).unwrap_err(); + let os_code = cause.raw_os_error(); + let captured = Arc::new(Mutex::new(None)); + let body = upload_body( + FailedRead(Some(cause)), + source.to_str().unwrap().into(), + Arc::clone(&captured), + tokio::sync::watch::channel(tokio::time::Instant::now()).0, + ); + let error = storage_send( + Client::new() + .put(format!("{}/object?secret=hidden", server.uri())) + .body(body), + None, + true, + captured, + tokio::sync::watch::channel(tokio::time::Instant::now()).1, + ) + .await + .unwrap_err(); + assert!(!error.retryable); + assert_eq!(error.code, crate::ErrorCode::NotFound); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + let local = error.local_error.unwrap(); + assert_eq!(local.raw_os_error, os_code); + assert_eq!(local.path, source.to_str().unwrap()); + assert!(!error.message.contains("hidden")); + } + + #[tokio::test] + async fn transient_storage_statuses_replay_full_inputs_and_cache_completion() { + use std::sync::atomic::{AtomicUsize, Ordering}; + for (operation, stream) in [("PUT", false), ("PUT", true), ("GET", false)] { + let requests = 2; + let server = MockServer::start().await; + let attempts = Arc::new(AtomicUsize::new(0)); + let count = Arc::clone(&attempts); + Mock::given(method(operation)) + .and(path("/object")) + .and(header("x-storage-token", "server-token")) + .respond_with(move |request: &wiremock::Request| { + if operation == "PUT" { + assert_eq!(request.body, b"payload"); + } + if count.fetch_add(1, Ordering::SeqCst) == 0 { + ResponseTemplate::new(503) + .insert_header("retry-after", "0") + .set_delay(Duration::from_millis(200)) + } else { + ResponseTemplate::new(200).set_body_bytes(b"payload") + } + }) + .expect(requests) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("file"); + std::fs::write( + &file, + if operation == "GET" { + b"old".as_slice() + } else { + b"payload" + }, + ) + .unwrap(); + let local = if stream { + Path::new("__input_stream__") + } else { + &file + }; + let batch = instruction(operation, &format!("{}/object", server.uri()), local); + let mut state = transfer_state(6); + Arc::get_mut(&mut state).unwrap().retry.overall_timeout = Duration::from_millis(100); + let options = options(dir.path()); + assert_eq!( + state + .complete( + async { Ok(batch.clone()) }, + &options, + stream.then(|| b"payload".to_vec()) + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!( + state + .complete(async { Ok(batch.clone()) }, &options, None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(attempts.load(Ordering::SeqCst), requests as usize); + assert_eq!(std::fs::read(file).unwrap(), b"payload"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + } + } + + #[tokio::test] + async fn storage_statuses_and_retry_limits_preserve_classification() { + for (operation, status, retries, budget, requests, missing_success) in [ + ("PUT", 403, 2, Duration::from_secs(10), 1, true), + ("REMOVE", 403, 2, Duration::from_secs(10), 1, true), + ("REMOVE", 404, 2, Duration::from_secs(10), 1, true), + ("REMOVE", 404, 2, Duration::from_secs(10), 1, false), + ("REMOVE", 503, 0, Duration::from_secs(10), 1, true), + ("REMOVE", 503, 2, Duration::ZERO, 1, true), + ("REMOVE", 503, 2, Duration::from_secs(10), 3, true), + ] { + let server = MockServer::start().await; + Mock::given(method(if operation == "PUT" { "PUT" } else { "DELETE" })) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(status) + .insert_header("retry-after", "0") + .insert_header("location", "/redirected") + .insert_header("x-amz-request-id", "request-1") + .insert_header("x-amz-id-2", "host-1") + .set_body_string("AccessDeniedPermission refusedsecret"), + ) + .expect(requests) + .mount(&server) + .await; + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("source"); + std::fs::write(&file, b"payload").unwrap(); + let options = VolumeOptions { + allowed_paths: vec![directory.path().to_owned()], + remove_not_found_is_success: missing_success, + }; + let state = VolumeState::new( + RetryConfig { + max_retries: retries, + overall_timeout: budget, + min_wait: Duration::ZERO, + max_wait: Duration::ZERO, + ..Default::default() + }, + storage(None), + Default::default(), + ); + let batch = instruction( + operation, + &format!("{}/object?secret=hidden", server.uri()), + &file, + ); + for _ in 0..2 { + let result = state + .complete(async { Ok(batch.clone()) }, &options, None) + .await; + if status == 404 && missing_success { + assert_eq!(result.unwrap(), VolumeCompletion::Completed); + continue; + } + let error = result.unwrap_err(); + assert_eq!(error.http_status, Some(status)); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_HTTP_ERROR") + ); + assert_eq!(error.retryable, status == 503); + assert!(error.message.contains("AccessDenied")); + assert!(error + .message + .contains("RequestId: request-1; HostId: host-1")); + assert!(error + .message + .contains(&format!("after {requests} attempts"))); + assert!(!error.message.contains("secret")); + } + } + } + + #[tokio::test] + async fn cancellation_interrupts_retry_backoff_without_another_request() { + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(503).insert_header("retry-after", "30")) + .expect(1) + .mount(&server) + .await; + let state = VolumeState::new( + RetryConfig { + min_wait: Duration::from_secs(30), + max_wait: Duration::from_secs(30), + ..Default::default() + }, + storage(None), + Default::default(), + ); + let batch = instruction("REMOVE", &server.uri(), Path::new("")); + let options = VolumeOptions::default(); + let complete = state.complete(async { Ok(batch.clone()) }, &options, None); + let cancel = async { + while server.received_requests().await.unwrap().is_empty() { + tokio::task::yield_now().await; + } + tokio::time::sleep(Duration::from_millis(50)).await; + state.cancel(); + }; + let (result, _) = tokio::time::timeout(Duration::from_secs(10), async { + tokio::join!(complete, cancel) + }) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code, crate::ErrorCode::Cancelled); + } + + #[tokio::test] + async fn stream_handshake_accepts_empty_bytes_once_and_keeps_success_after_cancel() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(path("/object")) + .and(body_bytes(Vec::::new())) + .and(header("content-length", "0")) + .and(header("x-storage-token", "server-token")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let batch = instruction( + "PUT", + &format!("{}/object", server.uri()), + Path::new("__input_stream__"), + ); + let state = transfer_state(0); + assert_eq!( + state + .complete(async { Ok(batch.clone()) }, &VolumeOptions::default(), None) + .await + .unwrap(), + VolumeCompletion::NeedsInputStream + ); + assert!(server.received_requests().await.unwrap().is_empty()); + assert_eq!( + state + .complete( + async { Ok(batch.clone()) }, + &VolumeOptions::default(), + Some(vec![]) + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + state.cancel(); + assert_eq!( + state + .complete( + async { Ok(batch.clone()) }, + &VolumeOptions::default(), + Some(vec![1]) + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + } + + #[tokio::test] + async fn get_with_missing_parent_fails_before_downloading() { + let server = MockServer::start().await; + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("missing/download"); + let batch = instruction("GET", &server.uri(), &destination); + let error = transfer_state(0) + .complete(async { Ok(batch) }, &options(directory.path()), None) + .await + .unwrap_err(); + assert_eq!(error.code, crate::ErrorCode::NotFound); + assert!(server.received_requests().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn get_writes_in_place_and_preserves_old_bytes_on_download_failure() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/ok")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"new bytes")) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/fail")) + .respond_with(ResponseTemplate::new(403)) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old bytes").unwrap(); + #[cfg(unix)] + let inode = std::fs::metadata(&dest).unwrap().ino(); + #[cfg(unix)] + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o200)).unwrap(); + let batch = instruction("GET", &format!("{}/ok", server.uri()), &dest); + let completed = transfer_state(0); + completed + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await + .unwrap(); + #[cfg(unix)] + { + assert_eq!(std::fs::metadata(&dest).unwrap().ino(), inode); + assert_eq!( + std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777, + 0o200 + ); + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); + #[cfg(unix)] + { + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o500)).unwrap(); + if tempfile::tempfile_in(dir.path()) + .is_err_and(|error| error.kind() == std::io::ErrorKind::PermissionDenied) + { + std::fs::write(&dest, b"old bytes with a longer tail").unwrap(); + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o200)).unwrap(); + Mock::given(method("GET")) + .and(path("/in-place")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"new bytes")) + .expect(1) + .mount(&server) + .await; + let batch = instruction("GET", &format!("{}/in-place", server.uri()), &dest); + let state = transfer_state(0); + assert_eq!( + state + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!( + std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777, + 0o200 + ); + assert_eq!(std::fs::metadata(&dest).unwrap().ino(), inode); + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); + } else { + eprintln!("SKIP: restricted-directory permissions are not enforced for this user"); + } + } + let state = transfer_state(0); + let batch = instruction( + "GET", + &format!("{}/fail?secret=hidden", server.uri()), + &dest, + ); + let error = state + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await + .unwrap_err(); + assert_eq!(error.http_status, Some(403)); + assert!(!error.message.contains("hidden")); + assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes"); + #[cfg(unix)] + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + } + + #[tokio::test] + #[cfg(unix)] + async fn cancellation_returns_while_local_preparation_waits_for_a_fifo_reader() { + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("destination"); + assert!(std::process::Command::new("mkfifo") + .arg(&destination) + .status() + .unwrap() + .success()); + let state = transfer_state(0); + let canceller = Arc::clone(&state); + let batch = instruction("GET", "http://unused.invalid/object", &destination); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(50)).await; + canceller.cancel(); + }); + let result = tokio::time::timeout( + Duration::from_secs(2), + state.complete(async { Ok(batch) }, &options(dir.path()), None), + ) + .await; + let _reader = std::fs::OpenOptions::new() + .read(true) + .open(destination) + .unwrap(); + assert_eq!( + result.unwrap().unwrap_err().code, + crate::ErrorCode::Cancelled + ); + } + + #[tokio::test] + #[cfg(unix)] + async fn put_rejects_a_source_that_is_not_a_regular_file() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + assert!(std::process::Command::new("mkfifo") + .arg(&source) + .status() + .unwrap() + .success()); + let batch = instruction("PUT", "http://unused.invalid/object", &source); + let error = tokio::time::timeout( + Duration::from_secs(2), + transfer_state(0).complete(async { Ok(batch) }, &options(dir.path()), None), + ) + .await + .unwrap() + .unwrap_err(); + assert_eq!(error.code, crate::ErrorCode::InvalidArgument); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + } + + #[tokio::test] + #[cfg(target_os = "linux")] + async fn put_rejects_a_source_that_reports_size_zero_but_has_content() { + let batch = instruction( + "PUT", + "http://unused.invalid/object", + Path::new("/proc/version"), + ); + let error = transfer_state(0) + .complete(async { Ok(batch) }, &options(Path::new("/proc")), None) + .await + .unwrap_err(); + assert_eq!(error.code, crate::ErrorCode::InvalidArgument); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + } + + #[tokio::test] + async fn put_uploads_an_empty_file() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(path("/object")) + .and(body_bytes(Vec::::new())) + .and(header("content-length", "0")) + .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"").unwrap(); + let batch = instruction("PUT", &format!("{}/object", server.uri()), &source); + assert_eq!( + transfer_state(0) + .complete(async { Ok(batch) }, &options(dir.path()), None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + } + + #[tokio::test] + async fn abandoned_or_cancelled_get_cannot_publish_or_restart() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .set_body_bytes(b"new") + .set_delay(Duration::from_millis(300)), + ) + .expect(2) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old").unwrap(); + let batch = instruction("GET", &server.uri(), &dest); + let options = options(dir.path()); + for cancel in [false, true] { + let state = transfer_state(0); + let mut future = Box::pin(state.complete(async { Ok(batch.clone()) }, &options, None)); + tokio::select! { + result = &mut future => panic!("unexpected early completion: {result:?}"), + sent = tokio::time::timeout(Duration::from_secs(10), async { + loop { + if server.received_requests().await.unwrap().len() >= if cancel { 2 } else { 1 } { break; } + tokio::task::yield_now().await; + } + }) => sent.expect("storage request was not sent"), + } + if cancel { + state.cancel(); + assert_eq!( + future.as_mut().await.unwrap_err().code, + crate::ErrorCode::Cancelled + ); + } + drop(future); + assert_eq!( + state + .complete(async { Ok(batch.clone()) }, &options, None) + .await + .unwrap_err() + .code, + crate::ErrorCode::Cancelled + ); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + } + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + } + + #[tokio::test] + async fn response_inactivity_bounds_headers_and_body_without_publishing() { + use tokio::io::AsyncReadExt; + for (operation, headers_sent) in [("GET", false), ("GET", true), ("PUT", true)] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let received = Arc::clone(&requests); + let peer = tokio::spawn(async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + received.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + tokio::spawn(async move { + let mut request = Vec::new(); + let mut byte = [0]; + while !request.ends_with(b"\r\n\r\n") { + socket.read_exact(&mut byte).await.unwrap(); + request.push(byte[0]); + } + let size = String::from_utf8(request) + .unwrap() + .lines() + .find_map(|line| { + line.to_lowercase() + .strip_prefix("content-length:") + .map(|size| size.trim().parse::().unwrap()) + }) + .unwrap_or(0); + socket.read_exact(&mut vec![0; size]).await.unwrap(); + if headers_sent { + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\nshort") + .await + .unwrap(); + } + tokio::time::sleep(Duration::from_secs(5)).await; + }); + } + }); + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old").unwrap(); + let state = VolumeState::new( + transfer_state(if operation == "PUT" { 1 } else { 0 }) + .retry + .clone(), + storage(Some(Duration::from_millis(150))), + Default::default(), + ); + let batch = instruction(operation, &url, &dest); + let error = tokio::time::timeout( + Duration::from_secs(2), + state.complete(async { Ok(batch.clone()) }, &options(dir.path()), None), + ) + .await + .unwrap() + .unwrap_err(); + assert_eq!(error.code, crate::ErrorCode::NetworkError); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR") + ); + assert!(error.message.contains("read timed out")); + let repeated = state + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await + .unwrap_err(); + assert_eq!(repeated.message, error.message); + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + peer.abort(); + } + } + + #[tokio::test] + async fn upload_accepts_maximum_idle_timeout() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(body_bytes(b"upload")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let state = VolumeState::new( + transfer_state(0).retry.clone(), + storage(Some(Duration::MAX)), + Default::default(), + ); + assert_eq!( + state + .complete( + async { + Ok(instruction( + "PUT", + &server.uri(), + Path::new("__input_stream__"), + )) + }, + &VolumeOptions::default(), + Some(b"upload".to_vec()), + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + } + + #[tokio::test] + async fn get_progress_and_put_idle_limits() { + use tokio::io::AsyncReadExt; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let peer = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0; 2048]; + assert!(socket.read(&mut request).await.unwrap() > 0); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n") + .await + .unwrap(); + for _ in 0..5 { + tokio::time::sleep(Duration::from_millis(150)).await; + socket.write_all(b"x").await.unwrap(); + } + }); + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + let state = VolumeState::new( + transfer_state(0).retry.clone(), + storage(Some(Duration::from_millis(500))), + Default::default(), + ); + state + .complete( + async { Ok(instruction("GET", &url, &dest)) }, + &options(dir.path()), + None, + ) + .await + .unwrap(); + assert_eq!(std::fs::read(&dest).unwrap(), b"xxxxx"); + peer.await.unwrap(); + + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(body_bytes(b"xxxxx")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let (mut writer, reader) = tokio::io::duplex(1); + let producer = tokio::spawn(async move { + for _ in 0..5 { + tokio::time::sleep(Duration::from_millis(150)).await; + writer.write_all(b"x").await.unwrap(); + } + }); + let error = Arc::new(Mutex::new(None)); + let (progress, changed) = tokio::sync::watch::channel(tokio::time::Instant::now()); + let body = upload_body(reader, "input".into(), Arc::clone(&error), progress); + storage_send( + Client::new() + .put(server.uri()) + .header(reqwest::header::CONTENT_LENGTH, 5) + .body(body), + Some(Duration::from_millis(500)), + true, + error, + changed, + ) + .await + .unwrap(); + producer.await.unwrap(); + + for header_wait in [false, true] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let payload = vec![b'x'; 16 * 1024 * 1024]; + std::fs::write(&dest, &payload).unwrap(); + let length = payload.len(); + let peer = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + if header_wait { + let mut headers = Vec::new(); + while !headers.ends_with(b"\r\n\r\n") { + headers.push(socket.read_u8().await.unwrap()); + } + let mut remaining = length; + let mut buffer = vec![0; 256 * 1024]; + while remaining > 0 { + let n = socket.read(&mut buffer).await.unwrap(); + assert!(n > 0); + remaining -= n; + } + } + std::future::pending::<()>().await; + }); + let state = VolumeState::new( + transfer_state(0).retry.clone(), + storage(Some(Duration::from_millis(150))), + Default::default(), + ); + let error = tokio::time::timeout( + Duration::from_secs(3), + state.complete( + async { Ok(instruction("PUT", &url, &dest)) }, + &options(dir.path()), + None, + ), + ) + .await + .expect("PUT idle watchdog") + .unwrap_err(); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR") + ); + assert!(error.message.contains("timed out")); + peer.abort(); + } + } + + #[tokio::test] + async fn truncated_get_retries_from_clean_temp_and_preserves_destination_on_failure() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + for retries in [0, 1] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let peer = tokio::spawn(async move { + for attempt in 0..=retries { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0; 2048]; + assert!(socket.read(&mut request).await.unwrap() > 0); + let response = if attempt == 0 { + b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\nConnection: close\r\n\r\nshort" + .as_slice() + } else { + b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\ncorrect" + }; + socket.write_all(response).await.unwrap(); + } + }); + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old").unwrap(); + let batch = instruction("GET", &url, &dest); + let result = transfer_state(retries) + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await; + if retries == 0 { + assert_eq!(result.unwrap_err().code, crate::ErrorCode::NetworkError); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + } else { + assert_eq!(result.unwrap(), VolumeCompletion::Completed); + assert_eq!(std::fs::read(&dest).unwrap(), b"correct"); + } + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + peer.await.unwrap(); + } + } + + #[cfg(windows)] + #[test] + fn resolved_names_match_exactly_and_prefix_ignores_case() { + for (path, root, allowed) in [ + (r"\\?\C:\data\safe\x", r"\\?\C:\data\safe", true), + (r"\\?\c:\data\safe\x", r"\\?\C:\data\safe", true), + (r"\\?\C:\data\SAFE\x", r"\\?\C:\data\safe", false), + ( + r"\\?\UNC\server\share\dir\x", + r"\\?\UNC\Server\Share\dir", + true, + ), + ( + r"\\?\UNC\server\share\DIR\x", + r"\\?\UNC\Server\Share\dir", + false, + ), + ] { + assert_eq!( + within_root(Path::new(path), Path::new(root), false), + allowed, + "{path}" + ); + assert!( + within_root(Path::new(path), Path::new(root), true), + "{path}" + ); + } + } + + #[test] + fn symlinks_require_lexical_authority_and_resolved_target_in_any_allowed_root() { + #[cfg(unix)] + use std::os::unix::fs::{symlink as symlink_dir, symlink as symlink_file}; + #[cfg(windows)] + use std::os::windows::fs::{symlink_dir, symlink_file}; + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("root"); + let other = dir.path().join("other"); + std::fs::create_dir(&root).unwrap(); + std::fs::create_dir(&other).unwrap(); + std::fs::write(root.join("file"), b"ok").unwrap(); + #[cfg(windows)] + assert!(allowed_path( + root.join("file").to_str().unwrap(), + &[dir.path().join("ROOT")] + ) + .is_ok()); + symlink_file(root.join("file"), root.join("inside")).unwrap(); + symlink_file(other.join("missing"), root.join("escape")).unwrap(); + symlink_dir(&root, dir.path().join("alias")).unwrap(); + assert_eq!( + allowed_path( + root.join("inside").to_str().unwrap(), + std::slice::from_ref(&root) + ) + .unwrap(), + root.join("file").canonicalize().unwrap() + ); + assert!(allowed_path( + root.join("escape").to_str().unwrap(), + std::slice::from_ref(&root) + ) + .is_err()); + assert_eq!( + allowed_path( + root.join("escape").to_str().unwrap(), + &[root.clone(), other.clone()] + ) + .unwrap(), + other.canonicalize().unwrap().join("missing") + ); + assert!(allowed_path( + dir.path().join("alias/file").to_str().unwrap(), + std::slice::from_ref(&root) + ) + .is_err()); + let looping_root = dir.path().join("loop"); + symlink_dir(&looping_root, &looping_root).unwrap(); + for roots in [ + [looping_root.clone(), root.clone()], + [root.clone(), looping_root.clone()], + ] { + assert_eq!( + allowed_path(root.join("file").to_str().unwrap(), &roots).unwrap(), + root.join("file").canonicalize().unwrap() + ); + } + let error = allowed_path( + root.join("escape").to_str().unwrap(), + &[looping_root.clone(), root.clone()], + ) + .unwrap_err(); + assert_eq!( + error.local_error.unwrap().path, + looping_root.to_string_lossy() + ); + symlink_dir(&other, root.join("link")).unwrap(); + for (name, suffix) in [("cycle", ""), ("nested", "missing")] { + let cycle = root.join(name); + let target = Path::new("link").join("..").join(name).join(suffix); + symlink_file(target, &cycle).unwrap(); + let requested = cycle.to_str().unwrap(); + let error = allowed_path(requested, std::slice::from_ref(&root)).unwrap_err(); + let local = error.local_error.unwrap(); + assert_eq!(local.path, requested); + #[cfg(unix)] + { + assert_eq!(error.code, crate::ErrorCode::NotFound); + assert_eq!(local.kind, std::io::ErrorKind::NotFound); + assert_eq!(local.raw_os_error, Some(2)); + } + } + assert!(allowed_path(root.join("../other/missing").to_str().unwrap(), &[root]).is_err()); + } + + #[tokio::test] + async fn local_errors_retain_os_code_and_requested_filename() { + let dir = tempfile::tempdir().unwrap(); + let server = MockServer::start().await; + for (source, kind, code) in [ + ( + dir.path().join("missing"), + std::io::ErrorKind::NotFound, + crate::ErrorCode::NotFound, + ), + ( + dir.path().to_owned(), + if cfg!(windows) { + std::io::ErrorKind::PermissionDenied + } else { + std::io::ErrorKind::IsADirectory + }, + if cfg!(windows) { + crate::ErrorCode::PermissionDenied + } else { + crate::ErrorCode::InvalidArgument + }, + ), + ] { + let batch = instruction( + "PUT", + &format!("{}/object?secret=hidden", server.uri()), + &source, + ); + let state = transfer_state(1); + let error = state + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await + .unwrap_err(); + assert_eq!(error.code, code); + assert_eq!(error.error_code.as_deref(), Some("VOLUME_LOCAL_FILE_ERROR")); + assert_eq!(error.sql_state.as_deref(), Some("HY000")); + assert!(!error.retryable); + let local = error.local_error.as_ref().unwrap(); + assert_eq!(local.kind, kind); + assert!(local.raw_os_error.is_some()); + assert_eq!(local.path, source.to_str().unwrap()); + assert!(!error.message.contains("hidden")); + assert_eq!( + state + .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) + .await + .unwrap_err() + .local_error + .as_ref() + .unwrap() + .raw_os_error, + local.raw_os_error + ); + } + assert!(server.received_requests().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn storage_network_errors_preserve_causes_without_signed_urls() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + drop(listener); + let url = format!("http://{address}/object?secret=hidden"); + let error = Client::builder() + .no_proxy() + .build() + .unwrap() + .get(&url) + .send() + .await + .unwrap_err(); + let mapped = storage_error(error); + assert_eq!(mapped.code, crate::ErrorCode::NetworkError); + assert_eq!( + mapped.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR") + ); + assert!(mapped.retryable); + assert!( + mapped.message.to_ascii_lowercase().contains("refused"), + "{mapped}" + ); + assert!(!mapped.message.contains(&address.to_string()), "{mapped}"); + assert!(!mapped.message.contains("hidden"), "{mapped}"); + } + + #[tokio::test] + async fn redirected_put_replays_full_bytes() { + for (stream, status) in [(true, 307), (false, 307), (false, 308)] { + let server = MockServer::start().await; + let payload = vec![b'x'; 512 * 1024 + 1]; + let directory = tempfile::tempdir().unwrap(); + let source = directory.path().join("source"); + std::fs::write(&source, &payload).unwrap(); + Mock::given(method("PUT")) + .and(path("/original")) + .and(body_bytes(payload.clone())) + .respond_with(ResponseTemplate::new(status).insert_header("location", "/target")) + .expect(2) + .mount(&server) + .await; + Mock::given(method("PUT")) + .and(path("/target")) + .and(body_bytes(payload.clone())) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + let batch = instruction( + "PUT", + &format!("{}/original", server.uri()), + if stream { + Path::new("__input_stream__") + } else { + &source + }, + ); + assert_eq!( + transfer_state(0) + .complete( + async { Ok(batch) }, + &options(directory.path()), + stream.then_some(payload), + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert!(server + .received_requests() + .await + .unwrap() + .iter() + .all(|request| !request.headers.contains_key("referer"))); + } + } + + #[tokio::test] + async fn get_decodes_gzip_content_encoding() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("content-encoding", "gzip") + .set_body_bytes(vec![ + 31, 139, 8, 0, 0, 0, 0, 0, 2, 3, 75, 73, 77, 206, 79, 73, 77, 97, 72, 170, + 44, 73, 45, 6, 0, 196, 224, 211, 9, 13, 0, 0, 0, + ]), + ) + .expect(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + transfer_state(0) + .complete( + async { Ok(instruction("GET", &server.uri(), &dest)) }, + &options(dir.path()), + None, + ) + .await + .unwrap(); + assert_eq!(std::fs::read(dest).unwrap(), b"decoded\x00bytes"); + } +} diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs new file mode 100644 index 00000000..773c459f --- /dev/null +++ b/tests/v0_volume_wiremock.rs @@ -0,0 +1,674 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Wiremock tests for Volume file transfers through Statement and ResultStream. + +use arrow_array::{RecordBatch, StringArray}; +use arrow_ipc::writer::StreamWriter; +use arrow_schema::{DataType, Field, Schema}; +use base64::{engine::general_purpose::STANDARD, Engine}; +use databricks_sql_kernel::{ + AuthConfig, ConnectionConfig, DirectStatement, ErrorCode, ExecutedStatementHandle, HttpConfig, + ResultBatch, Session, TryNextBatch, VolumeCompletion, VolumeOptions, +}; +use serde_json::json; +use std::sync::Arc; +use std::time::Duration; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +fn response(server: &MockServer, marked: bool, local: &str) -> serde_json::Value { + response_with_batches(server, marked, local, "GET", &[1]) +} + +fn response_with_batches( + server: &MockServer, + marked: bool, + local: &str, + operation: &str, + batch_rows: &[usize], +) -> serde_json::Value { + let names = ["operation", "presignedUrl", "headers", "localFile"]; + let schema = Arc::new(Schema::new( + names + .iter() + .map(|name| Field::new(*name, DataType::Utf8, true)) + .collect::>(), + )); + let values = [ + operation.to_owned(), + format!("{}/object", server.uri()), + "{}".to_owned(), + local.to_owned(), + ]; + let batch = RecordBatch::try_new( + schema, + values + .iter() + .map(|value| Arc::new(StringArray::from(vec![value.as_str()])) as _) + .collect(), + ) + .unwrap(); + let mut ipc = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); + for &rows in batch_rows { + writer.write(&batch.slice(0, rows)).unwrap(); + } + writer.finish().unwrap(); + } + let count: usize = batch_rows.iter().sum(); + json!({ + "statement_id": "volume-stmt", "status": {"state": "CLOSED"}, + "manifest": { + "format": "ARROW_STREAM", "is_volume_operation": marked, + "schema": {"column_count":4,"columns": names.iter().enumerate().map(|(i,name)| json!({"name":name,"type_name":"STRING","type_text":"STRING","position":i})).collect::>()}, + "total_row_count":count,"total_chunk_count":1 + }, + "result": {"chunk_index":0,"row_offset":0,"row_count":count,"attachment":STANDARD.encode(&ipc)} + }) +} + +#[tokio::test] +async fn instruction_batches_preserve_one_row_and_reject_extra_rows() { + for (batch_rows, valid) in [(&[1, 1][..], false), (&[0, 0, 1, 0][..], true)] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"original").unwrap(); + let session = session( + &server, + response_with_batches(&server, true, dest.to_str().unwrap(), "GET", batch_rows), + ) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"replacement")) + .expect(if valid { 1 } else { 0 }) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let mut executed = statement.execute().await.unwrap(); + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + for _ in 0..2 { + let result = executed + .result_stream_mut() + .complete_volume_operation(&options, None) + .await; + if valid { + assert_eq!(result.unwrap(), VolumeCompletion::Completed); + } else { + let error = result.unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_INVALID_INSTRUCTION") + ); + assert_eq!(error.message, "Expected one Volume instruction row"); + } + } + assert_eq!( + std::fs::read(&dest).unwrap(), + if valid { + b"replacement".as_slice() + } else { + b"original".as_slice() + } + ); + let TryNextBatch::Ready(ResultBatch::Arrow(batch)) = + executed.result_stream_mut().try_next_batch().unwrap() + else { + panic!("expected buffered instruction batch"); + }; + assert_eq!(batch.num_rows(), 1); + if !valid { + let Some(ResultBatch::Arrow(batch)) = executed.next_batch().await.unwrap() else { + panic!("expected second instruction batch"); + }; + assert_eq!(batch.num_rows(), 1); + } + assert!(executed.next_batch().await.unwrap().is_none()); + executed.close().await.unwrap(); + session.close().await.unwrap(); + } +} + +async fn session(server: &MockServer, body: serde_json::Value) -> Session { + session_with_http(server, body, HttpConfig::default()).await +} + +async fn session_with_http( + server: &MockServer, + body: serde_json::Value, + http: HttpConfig, +) -> Session { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/warehouses/wh/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(json!({"session_id":"sess","warehouse_id":"wh"})), + ) + .mount(server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_json(body.clone())) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/volume-stmt")) + .respond_with(ResponseTemplate::new(200).set_body_json(body)) + .mount(server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200)) + .mount(server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/volume-stmt/cancel")) + .respond_with(ResponseTemplate::new(200)) + .mount(server) + .await; + Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/wh").unwrap(), + ) + .auth(AuthConfig::Pat { + token: "workspace-token".into(), + identity_federation_client_id: None, + }) + .http(http) + .open() + .await + .unwrap() +} + +#[tokio::test] +async fn storage_transfers_outlive_rpc_deadline() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("file"); + std::fs::write(&local, b"original").unwrap(); + let mut http = HttpConfig::default(); + http.request_timeout = Duration::from_millis(100); + http.overall_timeout = Duration::from_millis(200); + let session = session_with_http( + &server, + response(&server, true, local.to_str().unwrap()), + http, + ) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_millis(300)) + .set_body_bytes(b"downloaded"), + ) + .expect(1) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let mut executed = statement.execute().await.unwrap(); + assert_eq!( + executed + .result_stream_mut() + .complete_volume_operation( + &VolumeOptions::new(vec![dir.path().to_owned()], false), + None, + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(std::fs::read(&local).unwrap(), b"downloaded"); + executed.close().await.unwrap(); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn sync_and_direct_closed_results_complete_explicitly_and_keep_raw_rows() { + for direct in [false, true] { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + let session = session(&server, response(&server, true, dest.to_str().unwrap())).await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"data")) + .expect(1) + .mount(&server) + .await; + let mut stmt = session.statement(); + stmt.spec().sql("server decides the operation"); + let mut exec = if direct { + match stmt.execute_direct().await.unwrap() { + DirectStatement::Completed(exec) => exec, + _ => panic!("expected inline completion"), + } + } else { + stmt.execute().await.unwrap() + }; + assert!(!dest.exists()); + let stream = exec.result_stream_mut(); + assert!(stream.is_volume_operation()); + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + assert_eq!( + stream + .complete_volume_operation(&options, None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(std::fs::read(&dest).unwrap(), b"data"); + let requests = server.received_requests().await.unwrap(); + let storage = requests + .iter() + .find(|request| request.url.path() == "/object") + .unwrap(); + assert!(!storage.headers.contains_key("authorization")); + assert!(exec.next_batch().await.unwrap().is_some()); + assert_eq!( + exec.result_stream_mut() + .complete_volume_operation(&options, None) + .await + .unwrap(), + VolumeCompletion::Completed + ); + exec.close().await.unwrap(); + session.close().await.unwrap(); + } +} + +#[tokio::test] +async fn completion_outlives_parent_statement() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("download"); + let session = session( + &server, + response(&server, true, destination.to_str().unwrap()), + ) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"downloaded")) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let mut executed = statement.execute().await.unwrap(); + drop(statement); + assert_eq!( + executed + .result_stream_mut() + .complete_volume_operation( + &VolumeOptions::new(vec![dir.path().to_owned()], false), + None, + ) + .await + .unwrap(), + VolumeCompletion::Completed + ); + assert_eq!(std::fs::read(&destination).unwrap(), b"downloaded"); + executed.close().await.unwrap(); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn marker_false_and_id_attachment_cannot_initiate_transfer() { + for marked in [false, true] { + let server = MockServer::start().await; + let session = session(&server, response(&server, marked, "/never-created")).await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&server) + .await; + let attached = session.attach_async_statement("volume-stmt").await.unwrap(); + let mut stream = attached.fetch_result().await.unwrap(); + assert_eq!( + stream + .complete_volume_operation(&VolumeOptions::default(), None) + .await + .unwrap(), + VolumeCompletion::NotVolume + ); + assert!(stream.next_batch().await.unwrap().is_some()); + if !marked { + let mut stmt = session.statement(); + stmt.spec().sql("PUT does not authorize local effects"); + let mut exec = stmt.execute().await.unwrap(); + assert!(!exec.result_stream().is_volume_operation()); + assert_eq!( + exec.result_stream_mut() + .complete_volume_operation(&VolumeOptions::default(), None) + .await + .unwrap(), + VolumeCompletion::NotVolume + ); + } + session.close().await.unwrap(); + } +} + +#[tokio::test] +async fn owner_reader_and_repeated_materialization_share_one_completion() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + let session = session(&server, response(&server, true, dest.to_str().unwrap())).await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"data")) + .expect(1) + .mount(&server) + .await; + let mut stmt = session.statement(); + stmt.spec().sql("operation"); + let owner = stmt.submit().await.unwrap(); + let reader = owner.reader().unwrap(); + reader.fetch_result().await.unwrap().close(); + let mut first = reader.fetch_result().await.unwrap(); + let mut second = owner.fetch_result().await.unwrap(); + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + let (a, b) = tokio::join!( + first.complete_volume_operation(&options, None), + second.complete_volume_operation(&options, None) + ); + assert_eq!(a.unwrap(), VolumeCompletion::Completed); + assert_eq!(b.unwrap(), VolumeCompletion::Completed); + drop(reader); + assert_eq!(std::fs::read(&dest).unwrap(), b"data"); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn async_executed_canceller_interrupts_volume_transfer() { + let server = MockServer::start().await; + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("download"); + let session = session( + &server, + response(&server, true, destination.to_str().unwrap()), + ) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_secs(30)) + .set_body_bytes(b"data"), + ) + .expect(1) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let executed = statement.submit().await.unwrap(); + let canceller = executed.canceller(); + let mut stream = executed.fetch_result().await.unwrap(); + let options = VolumeOptions::new(vec![directory.path().to_owned()], false); + let cancel = async { + while !server + .received_requests() + .await + .unwrap() + .iter() + .any(|request| request.url.path() == "/object") + { + tokio::task::yield_now().await; + } + canceller.cancel().await.unwrap(); + }; + let (result, _) = tokio::time::timeout(Duration::from_secs(10), async { + tokio::join!(stream.complete_volume_operation(&options, None), cancel) + }) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); + assert_eq!( + stream + .complete_volume_operation(&options, None) + .await + .unwrap_err() + .code, + ErrorCode::Cancelled + ); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn async_cancel_stops_a_transfer_after_the_parent_statement_is_dropped() { + for through_canceller in [false, true] { + let server = MockServer::start().await; + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("download"); + let session = session( + &server, + response(&server, true, destination.to_str().unwrap()), + ) + .await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_secs(30)) + .set_body_bytes(b"data"), + ) + .expect(1) + .mount(&server) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let executed = statement.submit().await.unwrap(); + let canceller = executed.canceller(); + let mut stream = executed.await_result().await.unwrap(); + drop(statement); + let options = VolumeOptions::new(vec![directory.path().to_owned()], false); + let cancel = async { + while !server + .received_requests() + .await + .unwrap() + .iter() + .any(|request| request.url.path() == "/object") + { + tokio::task::yield_now().await; + } + let result = if through_canceller { + canceller.cancel().await + } else { + executed.cancel().await + }; + assert_eq!(result.unwrap_err().code, ErrorCode::InvalidStatementHandle); + }; + let (result, _) = tokio::time::timeout(Duration::from_secs(10), async { + tokio::join!(stream.complete_volume_operation(&options, None), cancel) + }) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); + assert!(!destination.exists()); + session.close().await.unwrap(); + } +} + +#[tokio::test] +async fn cancel_on_a_closed_volume_result_sends_no_request() { + let server = MockServer::start().await; + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("download"); + let session = session( + &server, + response(&server, true, destination.to_str().unwrap()), + ) + .await; + let mut statement = session.statement(); + statement.spec().sql("operation"); + let mut executed = statement.execute().await.unwrap(); + executed.cancel().await.unwrap(); + assert_eq!( + executed + .result_stream_mut() + .complete_volume_operation( + &VolumeOptions::new(vec![directory.path().to_owned()], false), + None, + ) + .await + .unwrap_err() + .code, + ErrorCode::Cancelled + ); + assert!(!server + .received_requests() + .await + .unwrap() + .iter() + .any(|request| request.url.path().ends_with("/cancel"))); + executed.close().await.unwrap(); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn cancellation_and_session_close_interrupt_instruction_or_storage_after_sql_closed() { + for (instruction_page, close_session) in + [(false, false), (false, true), (true, false), (true, true)] + { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("download"); + std::fs::write(&dest, b"old").unwrap(); + let mut body = response(&server, true, dest.to_str().unwrap()); + let held_path = if instruction_page { + body["manifest"]["total_chunk_count"] = json!(2); + body["result"]["next_chunk_index"] = json!(1); + let mut next = response_with_batches(&server, true, dest.to_str().unwrap(), "GET", &[]) + ["result"] + .clone(); + next["chunk_index"] = json!(1); + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/volume-stmt/result/chunks/1")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_secs(30)) + .set_body_json(next), + ) + .mount(&server) + .await; + "/api/2.0/sql/statements/volume-stmt/result/chunks/1" + } else { + "/object" + }; + let mut session = Some(session(&server, body).await); + Mock::given(method("GET")) + .and(path("/object")) + .respond_with( + ResponseTemplate::new(200) + .set_delay(Duration::from_secs(30)) + .set_body_bytes(b"new"), + ) + .expect(if instruction_page { 0 } else { 1 }) + .mount(&server) + .await; + let mut stmt = session.as_ref().unwrap().statement(); + let canceller = stmt.canceller(); + stmt.spec().sql("operation"); + let mut exec = stmt.execute().await.unwrap(); + let options = VolumeOptions::new(vec![dir.path().to_owned()], false); + let complete = exec + .result_stream_mut() + .complete_volume_operation(&options, None); + let cancel = async { + loop { + if server + .received_requests() + .await + .unwrap() + .iter() + .any(|req| req.url.path() == held_path) + { + break; + } + tokio::task::yield_now().await; + } + if close_session { + session.take().unwrap().close().await.unwrap(); + } else { + canceller.cancel().await.unwrap(); + } + }; + let (result, _) = tokio::time::timeout(Duration::from_secs(10), async { + tokio::join!(complete, cancel) + }) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); + assert_eq!( + exec.result_stream_mut() + .complete_volume_operation(&options, None) + .await + .unwrap_err() + .code, + ErrorCode::Cancelled + ); + assert_eq!( + server + .received_requests() + .await + .unwrap() + .iter() + .filter(|req| req.url.path() == held_path) + .count(), + 1 + ); + assert_eq!(std::fs::read(&dest).unwrap(), b"old"); + if let Some(session) = session { + session.close().await.unwrap(); + } + } +} + +#[tokio::test] +async fn reading_before_volume_completion_returns_invalid_state() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("download"); + let session = session(&server, response(&server, true, local.to_str().unwrap())).await; + let mut statement = session.statement(); + statement.spec().sql("GET"); + let mut executed = statement.execute().await.unwrap(); + assert!(executed.next_batch().await.unwrap().is_some()); + let error = executed + .result_stream_mut() + .complete_volume_operation( + &VolumeOptions::new(vec![dir.path().to_owned()], false), + None, + ) + .await + .unwrap_err(); + assert_eq!( + error.code, + databricks_sql_kernel::Error::invalid_state().code + ); + assert!(error + .message + .contains("complete_volume_operation must be called before reading result rows")); + assert!(!local.exists()); + executed.close().await.unwrap(); + session.close().await.unwrap(); +} From 2c1f14691d8a46bfad8987fe6285c7c8dab5b1a0 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 30 Nov 2026 18:58:51 +0000 Subject: [PATCH 2/7] fix(volume): replay PUT bodies on 301 and 302 redirects Signed-off-by: Aakash Saravanan --- src/result_stream.rs | 2 +- src/volume.rs | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/result_stream.rs b/src/result_stream.rs index 749d610c..1f3d26bb 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -658,7 +658,7 @@ impl ResultStream { /// so a failed download leaves an existing file unchanged. /// A failure during that copy can leave the destination partly written. /// A PUT source must be a regular file that reports its size. - /// A file PUT that storage redirects with 307 or 308 is resent from memory, + /// A file PUT that storage redirects with 301, 302, 307 or 308 is resent from memory, /// so that upload needs memory equal to the file size. /// Cancelling does not undo work already done: a PUT or REMOVE may already /// have reached storage, and a copy that has started runs to the end. diff --git a/src/volume.rs b/src/volume.rs index c2042b2a..7e48eb67 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -313,7 +313,7 @@ impl VolumeState { changed, ) .await?; - if matches!(response.status().as_u16(), 307 | 308) { + if matches!(response.status().as_u16(), 301 | 302 | 307 | 308) { let bytes = match (input, source) { (Some(bytes), _) => Some(bytes.clone()), (None, Some((file, length))) => { @@ -1995,7 +1995,13 @@ mod tests { #[tokio::test] async fn redirected_put_replays_full_bytes() { - for (stream, status) in [(true, 307), (false, 307), (false, 308)] { + for (stream, status) in [ + (true, 307), + (false, 301), + (false, 302), + (false, 307), + (false, 308), + ] { let server = MockServer::start().await; let payload = vec![b'x'; 512 * 1024 + 1]; let directory = tempfile::tempdir().unwrap(); From 98b8c2855ff8efe258d1708f4c10b2e671c134ba Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 30 Nov 2026 18:58:51 +0000 Subject: [PATCH 3/7] fix(volume): copy GET downloads into pipes Signed-off-by: Aakash Saravanan --- src/volume.rs | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 7e48eb67..372ff529 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -163,8 +163,14 @@ impl VolumeState { .map_err(|e| local_error(e, &local_file))?; let length = std::io::copy(&mut temp, &mut file) .map_err(|e| local_error(e, &local_file))?; - file.set_len(length) - .map_err(|e| local_error(e, &local_file)) + // Only a regular file has a length to set; a pipe takes the bytes as written. + let metadata = + file.metadata().map_err(|e| local_error(e, &local_file))?; + if metadata.is_file() { + file.set_len(length) + .map_err(|e| local_error(e, &local_file))?; + } + Ok(()) }) .await .map_err(|e| { @@ -1416,6 +1422,35 @@ mod tests { ); } + #[tokio::test] + #[cfg(unix)] + async fn get_writes_into_a_pipe_that_has_a_reader() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/object")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"downloaded")) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("pipe"); + assert!(std::process::Command::new("mkfifo") + .arg(&destination) + .status() + .unwrap() + .success()); + let pipe = destination.clone(); + let reader = std::thread::spawn(move || std::fs::read(pipe).unwrap()); + let batch = instruction("GET", &format!("{}/object", server.uri()), &destination); + let result = tokio::time::timeout( + Duration::from_secs(10), + transfer_state(0).complete(async { Ok(batch) }, &options(dir.path()), None), + ) + .await + .unwrap(); + assert_eq!(result.unwrap(), VolumeCompletion::Completed); + assert_eq!(reader.join().unwrap(), b"downloaded"); + } + #[tokio::test] #[cfg(unix)] async fn put_rejects_a_source_that_is_not_a_regular_file() { From 5fc6588cfc86191ef803529776afcac2aa6252eb Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 30 Nov 2026 18:58:51 +0000 Subject: [PATCH 4/7] fix(volume): reject storage 303 redirects Signed-off-by: Aakash Saravanan --- src/client/http.rs | 5 ++++- src/result_stream.rs | 1 + src/volume.rs | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/client/http.rs b/src/client/http.rs index 33c9b502..e9e7edef 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -401,7 +401,10 @@ impl StorageClient { DatabricksHttpClient::build_reqwest_client( &self.config, reqwest::redirect::Policy::custom(|attempt| { - if attempt.url().scheme() == "http" + if attempt.status() == reqwest::StatusCode::SEE_OTHER { + // A 303 turns PUT and DELETE into GET, and the policy cannot see the method. + attempt.stop() + } else if attempt.url().scheme() == "http" && attempt .previous() .last() diff --git a/src/result_stream.rs b/src/result_stream.rs index 1f3d26bb..a3a92d15 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -660,6 +660,7 @@ impl ResultStream { /// A PUT source must be a regular file that reports its size. /// A file PUT that storage redirects with 301, 302, 307 or 308 is resent from memory, /// so that upload needs memory equal to the file size. + /// A 303 redirect from storage fails the transfer, including a GET. /// Cancelling does not undo work already done: a PUT or REMOVE may already /// have reached storage, and a copy that has started runs to the end. /// Results from [`Session::attach_async_statement`](crate::Session::attach_async_statement) diff --git a/src/volume.rs b/src/volume.rs index 372ff529..f5bedb7d 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -2085,6 +2085,39 @@ mod tests { } } + #[tokio::test] + async fn see_other_redirect_is_not_followed() { + for operation in ["PUT", "REMOVE", "GET"] { + let server = MockServer::start().await; + Mock::given(path("/original")) + .respond_with(ResponseTemplate::new(303).insert_header("location", "/target")) + .expect(1) + .mount(&server) + .await; + Mock::given(path("/target")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&server) + .await; + let directory = tempfile::tempdir().unwrap(); + let local = directory.path().join("file"); + if operation == "PUT" { + std::fs::write(&local, b"payload").unwrap(); + } + let batch = instruction(operation, &format!("{}/original", server.uri()), &local); + let error = transfer_state(0) + .complete(async { Ok(batch) }, &options(directory.path()), None) + .await + .unwrap_err(); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_HTTP_ERROR"), + "{operation}" + ); + assert_eq!(error.http_status, Some(303), "{operation}"); + } + } + #[tokio::test] async fn get_decodes_gzip_content_encoding() { let server = MockServer::start().await; From 0aca707c8c1e40737924f5f8e70fa53b59205c49 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 30 Nov 2026 18:59:45 +0000 Subject: [PATCH 5/7] refactor(volume): consolidate transfer checks and retry logging A transfer that succeeds first time no longer logs its duration. Keep both telemetry failure cases and assert the expected timeout text for each idle-test case. Signed-off-by: Aakash Saravanan --- src/result_stream.rs | 7 +- src/telemetry/statement.rs | 6 - src/volume.rs | 299 ++++++++++++++---------------------- tests/v0_volume_wiremock.rs | 124 +++++---------- 4 files changed, 163 insertions(+), 273 deletions(-) diff --git a/src/result_stream.rs b/src/result_stream.rs index a3a92d15..60eaefa1 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -881,8 +881,11 @@ impl ResultStream { } } - /// Before the first next_batch, returns the first batch without consuming it. - /// The following next_batch returns the same batch or error. + /// Returns the first unread batch without consuming it, or `None` at the end + /// of the stream; the following `next_batch` returns the same batch or error. + /// Reads from the reader only when nothing is buffered. Call it before the + /// first `next_batch`: once a batch is current it reads nothing more, so it + /// can return `None` before the stream ends. pub(crate) async fn peek_first_batch(&mut self) -> Result> { if self.prefetched.is_empty() && self.current.is_none() && !self.exhausted { let reader = self diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index 8ceee6c4..5316d574 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -461,12 +461,6 @@ mod tests { .complete_volume_operation(&options, None) .await .unwrap_err(); - let cached = stream - .complete_volume_operation(&options, None) - .await - .unwrap_err(); - assert_eq!(cached.code, error.code); - assert_eq!(cached.message, error.message); assert_eq!(error.code, code); assert_eq!(error.message, message); let events_before_drop = connection diff --git a/src/volume.rs b/src/volume.rs index f5bedb7d..7155e9ea 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -226,24 +226,17 @@ impl VolumeState { .await { Ok(completion) => { - tracing::debug!( - target: crate::klog::KERNEL_LOG_TARGET, - attempt = attempt + 1, - attempt_ms = attempt_started.elapsed().as_millis() as u64, - "volume transfer attempt succeeded" - ); + if attempt > 0 { + tracing::debug!( + target: crate::klog::KERNEL_LOG_TARGET, + attempts = attempt + 1, + "volume transfer succeeded after retrying" + ); + } return Ok(completion); } Err(error) => error, }; - tracing::debug!( - target: crate::klog::KERNEL_LOG_TARGET, - attempt = attempt + 1, - attempt_ms = attempt_started.elapsed().as_millis() as u64, - retryable = error.retryable, - error = %error.message, - "volume transfer attempt failed" - ); // The retry clock starts at the first failure, so a long transfer does not // use up the retry budget. let started = retry_started.get_or_insert_with(std::time::Instant::now); @@ -257,8 +250,10 @@ impl VolumeState { tracing::debug!( target: crate::klog::KERNEL_LOG_TARGET, attempt = attempt + 1, + attempt_ms = attempt_started.elapsed().as_millis() as u64, wait_ms = wait.as_millis() as u64, - "waiting before retrying volume transfer" + error = %error.message, + "retrying volume transfer" ); tokio::time::sleep(wait).await; attempt += 1; @@ -1564,149 +1559,136 @@ mod tests { } #[tokio::test] - async fn response_inactivity_bounds_headers_and_body_without_publishing() { + async fn idle_limit_stops_stalled_transfers_and_resets_on_progress() { + use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::io::AsyncReadExt; - for (operation, headers_sent) in [("GET", false), ("GET", true), ("PUT", true)] { + #[derive(Clone, Copy, Debug)] + enum Peer { + // Holds the connection without reading the request. + Unread, + // Reads the request and never responds. + Silent, + // Reads the request, then sends headers and part of the body. + Partial, + // Reads the request, then sends a 5-byte body one byte every 150 ms. + Trickle, + // Reads the request, then responds with an empty body. + Respond, + } + let stall = Duration::from_millis(150); + for (operation, idle, retries, peer_mode, expected_error) in [ + ("GET", stall, 0, Peer::Silent, Some("read timed out")), + ("GET", stall, 0, Peer::Partial, Some("read timed out")), + ( + "PUT", + stall, + 1, + Peer::Unread, + Some("upload or response wait timed out"), + ), + ( + "PUT", + stall, + 1, + Peer::Silent, + Some("upload or response wait timed out"), + ), + ("PUT", stall, 1, Peer::Partial, Some("read timed out")), + ("GET", Duration::from_millis(500), 0, Peer::Trickle, None), + ("PUT", Duration::MAX, 0, Peer::Respond, None), + ] { + let case = format!("{operation} {peer_mode:?}"); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("http://{}", listener.local_addr().unwrap()); - let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let received = Arc::clone(&requests); + let connections = Arc::new(AtomicUsize::new(0)); + let accepted = Arc::clone(&connections); let peer = tokio::spawn(async move { loop { let (mut socket, _) = listener.accept().await.unwrap(); - received.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + accepted.fetch_add(1, Ordering::SeqCst); tokio::spawn(async move { - let mut request = Vec::new(); - let mut byte = [0]; - while !request.ends_with(b"\r\n\r\n") { - socket.read_exact(&mut byte).await.unwrap(); - request.push(byte[0]); + if !matches!(peer_mode, Peer::Unread) { + let mut head = Vec::new(); + while !head.ends_with(b"\r\n\r\n") { + head.push(socket.read_u8().await.unwrap()); + } + let length: usize = String::from_utf8_lossy(&head) + .to_lowercase() + .split_once("content-length:") + .map_or(0, |(_, rest)| { + rest.lines().next().unwrap().trim().parse().unwrap() + }); + socket.read_exact(&mut vec![0; length]).await.unwrap(); } - let size = String::from_utf8(request) - .unwrap() - .lines() - .find_map(|line| { - line.to_lowercase() - .strip_prefix("content-length:") - .map(|size| size.trim().parse::().unwrap()) - }) - .unwrap_or(0); - socket.read_exact(&mut vec![0; size]).await.unwrap(); - if headers_sent { - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\nshort") - .await - .unwrap(); + let response: &[u8] = match peer_mode { + Peer::Partial => b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\nshort", + Peer::Trickle => b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n", + Peer::Respond => b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + Peer::Unread | Peer::Silent => b"", + }; + socket.write_all(response).await.unwrap(); + if matches!(peer_mode, Peer::Trickle) { + for _ in 0..5 { + tokio::time::sleep(Duration::from_millis(150)).await; + socket.write_all(b"x").await.unwrap(); + } } - tokio::time::sleep(Duration::from_secs(5)).await; + std::future::pending::<()>().await; }); } }); let dir = tempfile::tempdir().unwrap(); let dest = dir.path().join("download"); + let source = dir.path().join("source"); std::fs::write(&dest, b"old").unwrap(); + // An unread upload stalls only after it fills the socket buffers. + let size = if matches!(peer_mode, Peer::Unread) { + 16 << 20 + } else { + 5 + }; + std::fs::write(&source, vec![b'x'; size]).unwrap(); let state = VolumeState::new( - transfer_state(if operation == "PUT" { 1 } else { 0 }) - .retry - .clone(), - storage(Some(Duration::from_millis(150))), + transfer_state(retries).retry.clone(), + storage(Some(idle)), Default::default(), ); - let batch = instruction(operation, &url, &dest); - let error = tokio::time::timeout( - Duration::from_secs(2), - state.complete(async { Ok(batch.clone()) }, &options(dir.path()), None), + let local = if operation == "GET" { &dest } else { &source }; + let batch = instruction(operation, &url, local); + let options = options(dir.path()); + let result = tokio::time::timeout( + Duration::from_secs(3), + state.complete(async { Ok(batch.clone()) }, &options, None), ) .await - .unwrap() - .unwrap_err(); - assert_eq!(error.code, crate::ErrorCode::NetworkError); - assert_eq!( - error.error_code.as_deref(), - Some("VOLUME_STORAGE_NETWORK_ERROR") - ); - assert!(error.message.contains("read timed out")); - let repeated = state - .complete(async { Ok(batch.clone()) }, &options(dir.path()), None) - .await - .unwrap_err(); - assert_eq!(repeated.message, error.message); - assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1); - assert_eq!(std::fs::read(&dest).unwrap(), b"old"); - assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + .expect(&case); + if let Some(expected_error) = expected_error { + let error = result.expect_err(&case); + assert_eq!(error.code, crate::ErrorCode::NetworkError, "{case}"); + assert_eq!( + error.error_code.as_deref(), + Some("VOLUME_STORAGE_NETWORK_ERROR"), + "{case}" + ); + assert!(error.message.contains(expected_error), "{case}: {error}"); + let repeated = state + .complete(async { Ok(batch.clone()) }, &options, None) + .await + .expect_err(&case); + assert_eq!(repeated.message, error.message, "{case}"); + assert_eq!(std::fs::read(&dest).unwrap(), b"old", "{case}"); + } else { + assert_eq!(result.expect(&case), VolumeCompletion::Completed, "{case}"); + if operation == "GET" { + assert_eq!(std::fs::read(&dest).unwrap(), b"xxxxx", "{case}"); + } + } + assert_eq!(connections.load(Ordering::SeqCst), 1, "{case}"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 2, "{case}"); peer.abort(); } - } - - #[tokio::test] - async fn upload_accepts_maximum_idle_timeout() { - let server = MockServer::start().await; - Mock::given(method("PUT")) - .and(body_bytes(b"upload")) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&server) - .await; - let state = VolumeState::new( - transfer_state(0).retry.clone(), - storage(Some(Duration::MAX)), - Default::default(), - ); - assert_eq!( - state - .complete( - async { - Ok(instruction( - "PUT", - &server.uri(), - Path::new("__input_stream__"), - )) - }, - &VolumeOptions::default(), - Some(b"upload".to_vec()), - ) - .await - .unwrap(), - VolumeCompletion::Completed - ); - } - - #[tokio::test] - async fn get_progress_and_put_idle_limits() { - use tokio::io::AsyncReadExt; - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}", listener.local_addr().unwrap()); - let peer = tokio::spawn(async move { - let (mut socket, _) = listener.accept().await.unwrap(); - let mut request = [0; 2048]; - assert!(socket.read(&mut request).await.unwrap() > 0); - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n") - .await - .unwrap(); - for _ in 0..5 { - tokio::time::sleep(Duration::from_millis(150)).await; - socket.write_all(b"x").await.unwrap(); - } - }); - let dir = tempfile::tempdir().unwrap(); - let dest = dir.path().join("download"); - let state = VolumeState::new( - transfer_state(0).retry.clone(), - storage(Some(Duration::from_millis(500))), - Default::default(), - ); - state - .complete( - async { Ok(instruction("GET", &url, &dest)) }, - &options(dir.path()), - None, - ) - .await - .unwrap(); - assert_eq!(std::fs::read(&dest).unwrap(), b"xxxxx"); - peer.await.unwrap(); + // An upload that keeps producing bytes outlasts the idle limit. let server = MockServer::start().await; Mock::given(method("PUT")) .and(body_bytes(b"xxxxx")) @@ -1737,53 +1719,6 @@ mod tests { .await .unwrap(); producer.await.unwrap(); - - for header_wait in [false, true] { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}", listener.local_addr().unwrap()); - let payload = vec![b'x'; 16 * 1024 * 1024]; - std::fs::write(&dest, &payload).unwrap(); - let length = payload.len(); - let peer = tokio::spawn(async move { - let (mut socket, _) = listener.accept().await.unwrap(); - if header_wait { - let mut headers = Vec::new(); - while !headers.ends_with(b"\r\n\r\n") { - headers.push(socket.read_u8().await.unwrap()); - } - let mut remaining = length; - let mut buffer = vec![0; 256 * 1024]; - while remaining > 0 { - let n = socket.read(&mut buffer).await.unwrap(); - assert!(n > 0); - remaining -= n; - } - } - std::future::pending::<()>().await; - }); - let state = VolumeState::new( - transfer_state(0).retry.clone(), - storage(Some(Duration::from_millis(150))), - Default::default(), - ); - let error = tokio::time::timeout( - Duration::from_secs(3), - state.complete( - async { Ok(instruction("PUT", &url, &dest)) }, - &options(dir.path()), - None, - ), - ) - .await - .expect("PUT idle watchdog") - .unwrap_err(); - assert_eq!( - error.error_code.as_deref(), - Some("VOLUME_STORAGE_NETWORK_ERROR") - ); - assert!(error.message.contains("timed out")); - peer.abort(); - } } #[tokio::test] diff --git a/tests/v0_volume_wiremock.rs b/tests/v0_volume_wiremock.rs index 773c459f..7f98b09b 100644 --- a/tests/v0_volume_wiremock.rs +++ b/tests/v0_volume_wiremock.rs @@ -195,6 +195,18 @@ async fn session_with_http( .unwrap() } +async fn wait_for_request(server: &MockServer, request_path: &str) { + while !server + .received_requests() + .await + .unwrap() + .iter() + .any(|request| request.url.path() == request_path) + { + tokio::task::yield_now().await; + } +} + #[tokio::test] async fn storage_transfers_outlive_rpc_deadline() { let server = MockServer::start().await; @@ -398,63 +410,11 @@ async fn owner_reader_and_repeated_materialization_share_one_completion() { } #[tokio::test] -async fn async_executed_canceller_interrupts_volume_transfer() { - let server = MockServer::start().await; - let directory = tempfile::tempdir().unwrap(); - let destination = directory.path().join("download"); - let session = session( - &server, - response(&server, true, destination.to_str().unwrap()), - ) - .await; - Mock::given(method("GET")) - .and(path("/object")) - .respond_with( - ResponseTemplate::new(200) - .set_delay(Duration::from_secs(30)) - .set_body_bytes(b"data"), - ) - .expect(1) - .mount(&server) - .await; - let mut statement = session.statement(); - statement.spec().sql("operation"); - let executed = statement.submit().await.unwrap(); - let canceller = executed.canceller(); - let mut stream = executed.fetch_result().await.unwrap(); - let options = VolumeOptions::new(vec![directory.path().to_owned()], false); - let cancel = async { - while !server - .received_requests() - .await - .unwrap() - .iter() - .any(|request| request.url.path() == "/object") - { - tokio::task::yield_now().await; - } - canceller.cancel().await.unwrap(); - }; - let (result, _) = tokio::time::timeout(Duration::from_secs(10), async { - tokio::join!(stream.complete_volume_operation(&options, None), cancel) - }) - .await - .unwrap(); - assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); - assert_eq!( - stream - .complete_volume_operation(&options, None) - .await - .unwrap_err() - .code, - ErrorCode::Cancelled - ); - session.close().await.unwrap(); -} - -#[tokio::test] -async fn async_cancel_stops_a_transfer_after_the_parent_statement_is_dropped() { - for through_canceller in [false, true] { +async fn async_cancel_stops_a_transfer_whether_or_not_the_parent_is_dropped() { + for (drop_parent, through_canceller) in + [(false, false), (false, true), (true, false), (true, true)] + { + let case = format!("drop_parent={drop_parent} through_canceller={through_canceller}"); let server = MockServer::start().await; let directory = tempfile::tempdir().unwrap(); let destination = directory.path().join("download"); @@ -478,32 +438,41 @@ async fn async_cancel_stops_a_transfer_after_the_parent_statement_is_dropped() { let executed = statement.submit().await.unwrap(); let canceller = executed.canceller(); let mut stream = executed.await_result().await.unwrap(); - drop(statement); + if drop_parent { + drop(statement); + } let options = VolumeOptions::new(vec![directory.path().to_owned()], false); let cancel = async { - while !server - .received_requests() - .await - .unwrap() - .iter() - .any(|request| request.url.path() == "/object") - { - tokio::task::yield_now().await; - } + wait_for_request(&server, "/object").await; let result = if through_canceller { canceller.cancel().await } else { executed.cancel().await }; - assert_eq!(result.unwrap_err().code, ErrorCode::InvalidStatementHandle); + if drop_parent { + let error = result.expect_err(&case); + assert_eq!(error.code, ErrorCode::InvalidStatementHandle, "{case}"); + } else { + result.expect(&case); + } }; let (result, _) = tokio::time::timeout(Duration::from_secs(10), async { tokio::join!(stream.complete_volume_operation(&options, None), cancel) }) .await - .unwrap(); - assert_eq!(result.unwrap_err().code, ErrorCode::Cancelled); - assert!(!destination.exists()); + .expect(&case); + assert_eq!( + result.expect_err(&case).code, + ErrorCode::Cancelled, + "{case}" + ); + let repeated = stream.complete_volume_operation(&options, None).await; + assert_eq!( + repeated.expect_err(&case).code, + ErrorCode::Cancelled, + "{case}" + ); + assert!(!destination.exists(), "{case}"); session.close().await.unwrap(); } } @@ -594,18 +563,7 @@ async fn cancellation_and_session_close_interrupt_instruction_or_storage_after_s .result_stream_mut() .complete_volume_operation(&options, None); let cancel = async { - loop { - if server - .received_requests() - .await - .unwrap() - .iter() - .any(|req| req.url.path() == held_path) - { - break; - } - tokio::task::yield_now().await; - } + wait_for_request(&server, held_path).await; if close_session { session.take().unwrap().close().await.unwrap(); } else { From b73fbdf262509d9b1ac229399e75cc1ab442df03 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 30 Nov 2026 21:00:54 +0000 Subject: [PATCH 6/7] fix(volume): preserve filesystem paths and bound idle transfers by default Signed-off-by: Aakash Saravanan --- NEXT_CHANGELOG.md | 2 + src/client/http.rs | 19 ++++-- src/client/http_tls_tests.rs | 4 +- src/config.rs | 5 +- src/result_stream.rs | 2 +- src/volume.rs | 118 +++++++++++++++++++++++++++-------- 6 files changed, 114 insertions(+), 36 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 0d9dd98b..8dec540c 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -18,6 +18,8 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed +- Volume file transfers default to a 15-minute idle limit. Set + `HttpConfig::storage_read_timeout` to `None` for no limit. - Adds public fields to `Error` and `ResultManifest`. Code that builds these structs with struct literals must be updated. Supported consumers are the PyO3, NAPI, C ABI and ADBC bindings. diff --git a/src/client/http.rs b/src/client/http.rs index e9e7edef..99688edf 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -391,17 +391,23 @@ pub struct DatabricksHttpClient { pub(crate) struct StorageClient { pub(crate) read_timeout: Option, config: HttpClientConfig, - client: tokio::sync::OnceCell, + get_client: tokio::sync::OnceCell, + write_client: tokio::sync::OnceCell, } impl StorageClient { - pub(crate) async fn get(&self) -> Result<&Client> { - self.client + pub(crate) async fn get(&self, follow_see_other: bool) -> Result<&Client> { + let client = if follow_see_other { + &self.get_client + } else { + &self.write_client + }; + client .get_or_try_init(|| async { DatabricksHttpClient::build_reqwest_client( &self.config, - reqwest::redirect::Policy::custom(|attempt| { - if attempt.status() == reqwest::StatusCode::SEE_OTHER { + reqwest::redirect::Policy::custom(move |attempt| { + if !follow_see_other && attempt.status() == reqwest::StatusCode::SEE_OTHER { // A 303 turns PUT and DELETE into GET, and the policy cannot see the method. attempt.stop() } else if attempt.url().scheme() == "http" @@ -790,7 +796,8 @@ impl DatabricksHttpClient { StorageClient { read_timeout: storage_read_timeout, config, - client: tokio::sync::OnceCell::new(), + get_client: tokio::sync::OnceCell::new(), + write_client: tokio::sync::OnceCell::new(), } } diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs index 5d326292..f746a207 100644 --- a/src/client/http_tls_tests.rs +++ b/src/client/http_tls_tests.rs @@ -343,7 +343,7 @@ async fn storage_redirect_rejects_https_to_http_on_the_same_port() { ); let storage = client.storage_client(None); let error = storage - .get() + .get(true) .await .unwrap() .get(format!("https://{address}/object")) @@ -378,7 +378,7 @@ async fn storage_idle_timeout_also_bounds_connection_setup() { ); for timeout in [None, Some(Duration::from_millis(100))] { let storage = client.storage_client(timeout); - let storage = storage.get().await.unwrap(); + let storage = storage.get(true).await.unwrap(); let deadline = if timeout.is_some() { Duration::from_millis(500) } else { diff --git a/src/config.rs b/src/config.rs index 4457382b..f5481ab5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -759,7 +759,8 @@ pub struct HttpConfig { pub request_timeout: Duration, /// Idle limit for Volume file transfers: a transfer fails after this long - /// without progress. Also caps connection setup. None sets no limit. + /// without progress. Defaults to 15 minutes. Also caps connection setup. + /// None sets no limit. /// Exception: a PUT that storage redirects is resent without this limit. pub storage_read_timeout: Option, @@ -842,7 +843,7 @@ impl Default for HttpConfig { Self { sea_response_compression_enabled: false, request_timeout: Duration::from_secs(120), - storage_read_timeout: None, + storage_read_timeout: Some(Duration::from_secs(900)), overall_timeout: Duration::from_secs(900), pool_max_idle_per_host: 100, // Mirror `RetryConfig::default()` so a stock `HttpConfig` diff --git a/src/result_stream.rs b/src/result_stream.rs index 60eaefa1..4c534f41 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -660,7 +660,7 @@ impl ResultStream { /// A PUT source must be a regular file that reports its size. /// A file PUT that storage redirects with 301, 302, 307 or 308 is resent from memory, /// so that upload needs memory equal to the file size. - /// A 303 redirect from storage fails the transfer, including a GET. + /// A 303 fails a PUT or REMOVE; a GET follows it. /// Cancelling does not undo work already done: a PUT or REMOVE may already /// have reached storage, and a copy that has started runs to the end. /// Results from [`Session::attach_async_statement`](crate::Session::attach_async_statement) diff --git a/src/volume.rs b/src/volume.rs index 7155e9ea..649d17ff 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -39,6 +39,7 @@ pub struct VolumeOptions { /// Local directories a PUT may read from and a GET may write to. Both the /// path named in the statement and the file it resolves to through /// symlinks must be inside one of them. Empty allows no local file access. + /// The first check collapses `..`; the resolved check follows symlinks before applying `..`. /// The check runs before the file is opened, so nothing else may swap /// files or links in these directories during a transfer. pub allowed_paths: Vec, @@ -127,7 +128,10 @@ impl VolumeState { { return Ok::<_, Error>((VolumeCompletion::NeedsInputStream, None)); } - let client = self.storage.get().await?; + let client = self + .storage + .get(matches!(instruction.operation, Operation::Get(_))) + .await?; let destination = self .transfer(instruction, client, options, input_bytes) .await?; @@ -427,7 +431,10 @@ impl VolumeState { .parent() .ok_or_else(|| invalid("Missing destination parent"))?; let temp = match tempfile::tempfile_in(parent) { - Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + Err(error) + if error.kind() == std::io::ErrorKind::PermissionDenied + && existing.is_some() => + { tempfile::tempfile() } other => other, @@ -743,16 +750,11 @@ fn resolve_existing_parent( .ok_or_else(|| invalid("Invalid local path"))? .join(target) }; - return resolve_existing_parent( - &normalize(&target)?, - requested, - remaining_symlinks - 1, - ); + return resolve_existing_parent(&target, requested, remaining_symlinks - 1); } - let parent = path.parent().ok_or_else(|| local_error(error, requested))?; - let name = path - .file_name() - .ok_or_else(|| invalid("Invalid local path"))?; + let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else { + return Err(local_error(error, requested)); + }; Ok(resolve_existing_parent(parent, requested, remaining_symlinks)?.join(name)) } Err(error) => Err(local_error(error, requested)), @@ -798,7 +800,8 @@ fn allowed_path(requested: &str, roots: &[PathBuf]) -> Result { .with_error_code("VOLUME_PATH_NOT_ALLOWED"), ); } - let resolved = resolve_existing_parent(&path, requested, MAX_SYMLINK_RESOLUTIONS)?; + let absolute = std::path::absolute(requested).map_err(|e| local_error(e, requested))?; + let resolved = resolve_existing_parent(&absolute, requested, MAX_SYMLINK_RESOLUTIONS)?; let mut root_error = None; for root in roots { let root = match resolve_existing_parent( @@ -1295,6 +1298,29 @@ mod tests { assert!(server.received_requests().await.unwrap().is_empty()); } + #[tokio::test] + #[cfg(unix)] + async fn get_in_read_only_directory_fails_before_downloading() { + let server = MockServer::start().await; + let directory = tempfile::tempdir().unwrap(); + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o500)).unwrap(); + if tempfile::tempfile_in(directory.path()).is_ok() { + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)) + .unwrap(); + eprintln!("SKIP: directory permissions are not enforced for this user"); + return; + } + let destination = directory.path().join("download"); + let batch = instruction("GET", &server.uri(), &destination); + let result = transfer_state(0) + .complete(async { Ok(batch) }, &options(directory.path()), None) + .await; + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + assert_eq!(result.unwrap_err().code, crate::ErrorCode::PermissionDenied); + assert!(!destination.exists()); + assert!(server.received_requests().await.unwrap().is_empty()); + } + #[tokio::test] async fn get_writes_in_place_and_preserves_old_bytes_on_download_failure() { let server = MockServer::start().await; @@ -1596,6 +1622,7 @@ mod tests { ("PUT", stall, 1, Peer::Partial, Some("read timed out")), ("GET", Duration::from_millis(500), 0, Peer::Trickle, None), ("PUT", Duration::MAX, 0, Peer::Respond, None), + ("GET", Duration::MAX, 0, Peer::Respond, None), ] { let case = format!("{operation} {peer_mode:?}"); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -1680,7 +1707,12 @@ mod tests { } else { assert_eq!(result.expect(&case), VolumeCompletion::Completed, "{case}"); if operation == "GET" { - assert_eq!(std::fs::read(&dest).unwrap(), b"xxxxx", "{case}"); + let expected: &[u8] = if matches!(peer_mode, Peer::Trickle) { + b"xxxxx" + } else { + b"" + }; + assert_eq!(std::fs::read(&dest).unwrap(), expected, "{case}"); } } assert_eq!(connections.load(Ordering::SeqCst), 1, "{case}"); @@ -1858,20 +1890,52 @@ mod tests { looping_root.to_string_lossy() ); symlink_dir(&other, root.join("link")).unwrap(); + let through_parent = root.join("link/../file"); + std::fs::write(dir.path().join("file"), b"beside target").unwrap(); + assert_eq!( + allowed_path( + through_parent.to_str().unwrap(), + std::slice::from_ref(&root) + ) + .unwrap_err() + .error_code + .as_deref(), + Some("VOLUME_PATH_NOT_ALLOWED") + ); + assert_eq!( + allowed_path( + through_parent.to_str().unwrap(), + &[root.clone(), dir.path().to_owned()] + ) + .unwrap(), + dir.path().join("file").canonicalize().unwrap() + ); + let missing_parent = root.join("missing/../file"); + let error = allowed_path( + missing_parent.to_str().unwrap(), + std::slice::from_ref(&root), + ) + .unwrap_err(); + assert_eq!(error.code, crate::ErrorCode::NotFound); + assert_eq!( + error.local_error.unwrap().kind, + std::io::ErrorKind::NotFound + ); for (name, suffix) in [("cycle", ""), ("nested", "missing")] { let cycle = root.join(name); - let target = Path::new("link").join("..").join(name).join(suffix); + let target = Path::new("link") + .join("..") + .join("root") + .join(name) + .join(suffix); symlink_file(target, &cycle).unwrap(); + let os_error = cycle.canonicalize().unwrap_err(); let requested = cycle.to_str().unwrap(); let error = allowed_path(requested, std::slice::from_ref(&root)).unwrap_err(); let local = error.local_error.unwrap(); assert_eq!(local.path, requested); - #[cfg(unix)] - { - assert_eq!(error.code, crate::ErrorCode::NotFound); - assert_eq!(local.kind, std::io::ErrorKind::NotFound); - assert_eq!(local.raw_os_error, Some(2)); - } + assert_eq!(local.kind, os_error.kind()); + assert_eq!(local.raw_os_error, os_error.raw_os_error()); } assert!(allowed_path(root.join("../other/missing").to_str().unwrap(), &[root]).is_err()); } @@ -2021,7 +2085,7 @@ mod tests { } #[tokio::test] - async fn see_other_redirect_is_not_followed() { + async fn see_other_redirect_is_followed_only_for_get() { for operation in ["PUT", "REMOVE", "GET"] { let server = MockServer::start().await; Mock::given(path("/original")) @@ -2031,7 +2095,7 @@ mod tests { .await; Mock::given(path("/target")) .respond_with(ResponseTemplate::new(200)) - .expect(0) + .expect(if operation == "GET" { 1 } else { 0 }) .mount(&server) .await; let directory = tempfile::tempdir().unwrap(); @@ -2040,10 +2104,14 @@ mod tests { std::fs::write(&local, b"payload").unwrap(); } let batch = instruction(operation, &format!("{}/original", server.uri()), &local); - let error = transfer_state(0) + let result = transfer_state(0) .complete(async { Ok(batch) }, &options(directory.path()), None) - .await - .unwrap_err(); + .await; + if operation == "GET" { + assert_eq!(result.unwrap(), VolumeCompletion::Completed); + continue; + } + let error = result.unwrap_err(); assert_eq!( error.error_code.as_deref(), Some("VOLUME_STORAGE_HTTP_ERROR"), From 49d63ed1aaf2899aef3a7e7845ae56eea9bb22aa Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 30 Nov 2026 21:01:43 +0000 Subject: [PATCH 7/7] docs(volume): state the default storage idle limit Signed-off-by: Aakash Saravanan --- CONNECTION_PARAMETERS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 3a8ba972..e51eed3d 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -128,7 +128,7 @@ until implemented) and `External` (a caller-supplied `TokenProvider`). | Field | Description | Default | |-------|-------------|---------| | `request_timeout` | Per-request timeout (connect + body) for SQL requests. Volume file transfers are limited by storage_read_timeout instead. | `120s` | -| `storage_read_timeout` | Idle limit for Volume file transfers: a transfer fails after this long without progress. | `None` (no limit) | +| `storage_read_timeout` | Idle limit for Volume file transfers: a transfer fails after this long without progress. | `Some(900s)` (15 minutes); `None` disables the limit | | `overall_timeout` | Maximum total time across retries for one logical RPC. | `900s` | | `pool_max_idle_per_host` | Connection-pool size (max idle warm sockets per host). Raise for bursty concurrent workloads. | `100` | | `retry_min_wait` | Minimum backoff between retries; also the floor for a server `Retry-After` and the base of exponential backoff (`min_wait × 2^attempt`). | `1s` |