diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a84f66..ffa7b6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ All notable changes to this project will be documented in this file. +## Unreleased + +### Added + +- `ONEIO_S3_MAX_CONCURRENCY` - number of multipart parts uploaded in parallel + (default 4, capped at 16). +- `ONEIO_S3_REQUEST_TIMEOUT_SECS` - per-request timeout for S3 upload requests + (default 300, the previous hardcoded value). + +### Changed + +- S3 multipart uploads now run parts in parallel, reading each part's byte + range from a single open handle before uploading it. Previously parts were + uploaded one at a time, so a single TCP stream set the ceiling and one stalled part blocked + everything until the request timeout. Part retries, abort-on-failure and + part ordering are unchanged. +- Peak memory for a multipart upload is `concurrency * part_size` (4 x 8 MiB + with the defaults). +- Multipart parts are read from one open handle instead of reopening the path + in each worker, so a file replaced at the same path mid-upload can no longer + contribute bytes from two versions to a single object. + ## v0.26.1 -- 2026-09-09 ### Changed diff --git a/README.md b/README.md index 7244c6e..7577f8f 100644 --- a/README.md +++ b/README.md @@ -270,7 +270,8 @@ Note: Async compression is limited to gz, bz, zstd. LZ4/XZ return `NotSupported` use oneio::s3::*; // Upload file to S3 -// Files < 8MB use single PUT; larger files use multipart upload +// Files under the multipart threshold (5MB by default) use a single PUT; +// larger files are uploaded as parallel parts s3_upload("my-bucket", "path/to/file.txt", "local/file.txt")?; // Download file from S3 @@ -306,6 +307,8 @@ Optional environment variables for S3: - `AWS_SESSION_TOKEN` - Temporary session token - `ONEIO_S3_CHUNK_SIZE` - Multipart part size in bytes (default: 8MB) - `ONEIO_S3_MULTIPART_THRESHOLD` - File size threshold for multipart upload (default: 5MB) +- `ONEIO_S3_MAX_CONCURRENCY` - Multipart parts uploaded in parallel (default: 4, max: 16) +- `ONEIO_S3_REQUEST_TIMEOUT_SECS` - Per-request timeout for upload requests (default: 300) ### Error Handling diff --git a/specs/04-s3-concurrent-multipart/README.md b/specs/04-s3-concurrent-multipart/README.md new file mode 100644 index 0000000..46af498 --- /dev/null +++ b/specs/04-s3-concurrent-multipart/README.md @@ -0,0 +1,100 @@ +# Spec: Concurrent S3 multipart upload + +**Status**: Complete +**Author**: Mingwei Zhang +**Created**: 2026-10-23 +**Target Branch**: `dev/s3-concurrent-multipart` + +## 1. Overview + +- Goal: make `oneio::s3_upload` upload multi-GB files at link speed instead of + one part at a time, and stop a single stalled part request from costing the + caller a 300 s timeout before anything is retried. +- Non-goals: async API, conditional writes, progress callbacks, changing + `s3_upload`'s signature or the `S3Config` struct. +- Success criteria: + - [x] 4.3 GB upload to Cloudflare R2 completes in well under the 6 minutes + the sequential path needs (measured 90 s with 4 workers, 420 s with 1) + - [x] part order in `CompleteMultipartUpload` is always part-number order + - [x] one failing part aborts the multipart upload and returns that error + - [x] `cargo fmt --check`, `cargo clippy --all-features -- -D warnings`, + `cargo test --all-features` all pass + - [x] no new dependency + +## 2. Current State + +`upload_multipart` uploads parts strictly sequentially, one 8 MiB part per +request, each with a hardcoded 300 s request timeout. Measured against +Cloudflare R2, one TCP stream caps at about 12 MiB/s while four concurrent +streams reach about 90 MiB/s, so the sequential loop leaves most of the link +idle. When a part request stalls, +nothing else is in flight, so the whole upload waits for the timeout. + +## 3. Proposed Solution + +- Keep the blocking design. Concurrency comes from `std::thread::scope`. +- N worker threads (default 4) share an `AtomicUsize` part counter and read + their part ranges from one open handle. Reads are serialized through that + handle's lock; the uploads that follow run in parallel. +- Each worker signs its own part URL and uploads with the existing retry + helper; the ETag is written into a pre-sized slot `Vec>` at the + part index, so the completion list is ordered by construction. +- On the first unrecoverable error a shared `AtomicBool` stops the other + workers at their next part boundary; after all workers join, the multipart + upload is aborted exactly once and the first error is returned. +- Tuning is read from the environment through cached `OnceLock`s, mirroring the + existing `s3_retry_config` pattern, so no public struct or signature changes: + - `ONEIO_S3_MAX_CONCURRENCY` (default 4, clamped to 1..=16) + - `ONEIO_S3_REQUEST_TIMEOUT_SECS` (default 300, unchanged behavior) +- Memory: peak per upload is `concurrency * part_size` (4 x 8 MiB default). + +## 4. Implementation Plan + +1. Add `s3_upload_tuning()` (concurrency + request timeout) next to + `s3_retry_config`; replace the `S3_UPLOAD_REQUEST_TIMEOUT` constant uses. +2. Rewrite `upload_multipart` around a scoped worker pool; extract + `collect_part_etags` so ordering and missing-part handling are unit-testable. +3. Unit tests: concurrency clamp, ETag ordering, missing part error. +4. Verify against R2 with a 4.3 GB local file. + +## 5. Testing Strategy + +- Unit: pure helpers only (no network). +- Integration: `tests/s3_integration.rs` multipart cases (5 MB, 10 MB, 80 MB) + already cover correctness against R2; they now exercise the concurrent path. +- Manual: 4.3 GB upload, compare wall clock with the sequential measurement + (420 s) and check the object size with a HEAD (both runs stored exactly + 4,334,649,344 bytes). + +## 6. Risks + +- More sockets per upload: default 4, bounded, and only for multipart. +- A part failing late can leave other parts already uploaded: acceptable, the + upload is aborted and S3 bills parts only until then. +- `thread::scope` panics propagate: workers return `Result` instead of panicking + so the abort path always runs. +- Env-based tuning is cached: a test or embedding process cannot change it after + the first upload, same as the existing retry settings. + +## 7. Decision Log + +- 2026-10-23: kept the blocking API; concurrency via `thread::scope` rather than + adding tokio, because oneio's S3 path has no async runtime and pulling one in + would be a much larger change than the problem requires. +- 2026-10-23: tuned via environment rather than new `S3Config` fields, because + `S3Config` has public fields and adding one breaks struct literals. +- 2026-10-23: no per-part logging in the library; oneio has no logging facade in + library code today, so callers time the whole call instead. +- 2026-10-23: workers report failure and cancellation themselves through shared + state, because the coordinator joins them in creation order and would + otherwise keep uploading queued parts behind a failure. +- 2026-10-23: workers are started with `Builder::spawn_scoped`; a thread the OS + refuses is reported as an error so the multipart upload is still aborted, + instead of panicking out of `Scope::spawn` and leaving it behind. +- 2026-10-23: the source file is opened once and each part reads a range from + that handle under a lock. Opening the path in each worker could mix two + versions of the file into one object when a writer swaps the path atomically + between worker startups, and cloned handles would share a seek position. +- 2026-10-23: four workers by default, 16 as the ceiling; a failing part is + reported after the other workers stop at their next part boundary, so the + caller never waits for parts queued behind a failure. diff --git a/src/lib.rs b/src/lib.rs index 5e5ee92..5708762 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -193,10 +193,15 @@ Optional: - `AWS_SESSION_TOKEN` - Temporary session token - `ONEIO_S3_CHUNK_SIZE` - Multipart part size in bytes (default: 8MB) - `ONEIO_S3_MULTIPART_THRESHOLD` - File size threshold for multipart upload (default: 5MB) - -R2 supports single PUT uploads up to 300 MiB. The default threshold of 5MB -(the S3 minimum part size) uses single-PUT for small files and multipart -for larger files where retry-per-part improves reliability. +- `ONEIO_S3_MAX_CONCURRENCY` - Multipart parts uploaded in parallel (default: 4, max: 16) +- `ONEIO_S3_REQUEST_TIMEOUT_SECS` - Per-request timeout for upload requests (default: 300) +- `ONEIO_S3_MAX_RETRIES` - Retry attempts after the initial request (default: 3) +- `ONEIO_S3_RETRY_BACKOFF_MS` - Initial retry backoff in ms, doubles each attempt (default: 1000) + +The default threshold of 5MB (the S3 minimum part size) uses single PUT for +small files and multipart for larger ones, where parts are uploaded in +parallel and each part retries independently. Peak memory for a multipart +upload is `concurrency * part_size`. # TLS and Corporate Proxies diff --git a/src/s3/mod.rs b/src/s3/mod.rs index 65b00a4..11797aa 100644 --- a/src/s3/mod.rs +++ b/src/s3/mod.rs @@ -14,12 +14,15 @@ //! - `ONEIO_S3_MULTIPART_THRESHOLD` - File size threshold for multipart upload (default: 5MB) //! - `ONEIO_S3_MAX_RETRIES` - Retry attempts after the initial request for transient transport errors (default: 3) //! - `ONEIO_S3_RETRY_BACKOFF_MS` - Initial retry backoff in ms, doubles each attempt (default: 1000) +//! - `ONEIO_S3_MAX_CONCURRENCY` - Multipart parts uploaded in parallel (default: 4, max: 16) +//! - `ONEIO_S3_REQUEST_TIMEOUT_SECS` - Per-request timeout for upload requests (default: 300) //! //! # Upload Behavior //! //! Files smaller than the multipart threshold use a single PUT request. //! Larger files are uploaded via multipart with auto-calculated part sizing -//! to stay within S3's 10,000 part limit. +//! to stay within S3's 10,000 part limit, and with parts uploaded in parallel. +//! Peak memory for a multipart upload is `concurrency * part_size`. pub mod config; @@ -33,12 +36,18 @@ use reqwest::blocking::Response; use rusty_s3::S3Action; use sha2::{Digest, Sha256}; use std::io::{Read, Seek, SeekFrom}; -use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock}; use std::time::Duration; type HmacSha256 = Hmac; -const S3_UPLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(300); +/// Multipart parts uploaded in parallel when the caller does not override it. +const DEFAULT_MULTIPART_CONCURRENCY: usize = 4; +/// Upper bound on multipart workers, so one upload cannot exhaust the caller. +const MAX_MULTIPART_CONCURRENCY: usize = 16; +/// Per-request timeout for S3 upload requests (single PUT, part, initiate, complete). +const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 300; const COPY_SOURCE_ENCODE_SET: &AsciiSet = &CONTROLS .add(b':') @@ -315,7 +324,7 @@ pub fn s3_upload(bucket: &str, key: &str, file_path: &str) -> Result<(), OneIoEr if size < config.multipart_threshold { upload_single(&config, key, file_path) } else { - upload_multipart(&config, key, file_path, size) + upload_multipart(&config, key, file_path) } } @@ -329,7 +338,7 @@ fn upload_single(config: &config::S3Config, key: &str, file_path: &str) -> Resul ensure_s3_success( get_s3_client() .put(url) - .timeout(S3_UPLOAD_REQUEST_TIMEOUT) + .timeout(upload_request_timeout()) .body(file) .send()?, )?; @@ -365,6 +374,106 @@ fn s3_retry_config() -> (u32, u64) { }) } +/// Concurrency and request timeout for S3 uploads, read once from the +/// environment so repeated uploads in one process behave identically. +fn s3_upload_tuning() -> (usize, Duration) { + static S3_UPLOAD_CONFIG: OnceLock<(usize, Duration)> = OnceLock::new(); + *S3_UPLOAD_CONFIG.get_or_init(|| { + let concurrency = std::env::var("ONEIO_S3_MAX_CONCURRENCY") + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(DEFAULT_MULTIPART_CONCURRENCY); + let timeout_secs = std::env::var("ONEIO_S3_REQUEST_TIMEOUT_SECS") + .ok() + .and_then(|value| value.parse().ok()) + .filter(|value| *value > 0) + .unwrap_or(DEFAULT_REQUEST_TIMEOUT_SECS); + (concurrency, Duration::from_secs(timeout_secs)) + }) +} + +fn upload_request_timeout() -> Duration { + s3_upload_tuning().1 +} + +/// Number of parts to keep in flight. Bounded by the configured value, the +/// per-upload ceiling and the number of parts there are to send. +fn multipart_concurrency(requested: usize, total_parts: usize) -> usize { + requested + .clamp(1, MAX_MULTIPART_CONCURRENCY) + .min(total_parts.max(1)) +} + +/// Turn per-part ETag slots into the ordered part list for +/// CompleteMultipartUpload. A missing slot means a worker never succeeded. +fn collect_part_etags(slots: &[Option]) -> Result, OneIoError> { + slots + .iter() + .enumerate() + .map(|(index, slot)| { + slot.clone().ok_or_else(|| { + OneIoError::NotSupported(format!("Missing ETag for multipart part {}", index + 1)) + }) + }) + .collect() +} + +/// Shared state of one multipart part pool: which part to take next, whether a +/// worker has already failed, and which error to report. +struct PartUploadState { + next_part: AtomicUsize, + stop: AtomicBool, + first_error: Mutex>, +} + +impl PartUploadState { + fn new() -> Self { + Self { + next_part: AtomicUsize::new(0), + stop: AtomicBool::new(false), + first_error: Mutex::new(None), + } + } + + /// Claim the next part, or `None` once every part is taken or the pool has + /// already failed. + fn claim(&self, total_parts: usize) -> Option { + if self.stop.load(Ordering::Relaxed) { + return None; + } + let index = self.next_part.fetch_add(1, Ordering::Relaxed); + (index < total_parts).then_some(index) + } + + #[cfg(test)] + fn cancelled(&self) -> bool { + self.stop.load(Ordering::Relaxed) + } + + /// Record a failure and stop the pool. + /// + /// Workers call this themselves: the coordinator joins them in creation + /// order, so signalling from the join loop would let a failure in a later + /// worker go unnoticed while the remaining parts are still uploaded. + fn fail(&self, error: OneIoError) { + let mut slot = self + .first_error + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if slot.is_none() { + *slot = Some(error); + } + self.stop.store(true, Ordering::Relaxed); + } + + /// The first error reported by any worker, if one was. + fn into_error(self) -> Option { + self.first_error + .into_inner() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } +} + /// Execute an S3 request with retry on transient transport errors. /// /// S3-compatible services (especially Cloudflare R2) occasionally reset @@ -409,48 +518,82 @@ fn is_retryable_error(err: &reqwest::Error) -> bool { false } +/// Single open handle for the multipart source, read under a lock. +/// +/// Reopening the path in each worker would let an atomic replacement of the +/// file between two opens mix bytes from two versions into one object: the +/// per-part length checks still pass when both versions have the same size. +/// Handles cloned from one open would share a seek position instead, so reads +/// go through this lock rather than a raw file per worker. +struct PartSource { + file: Mutex, +} + +impl PartSource { + fn open(path: &str) -> Result { + Ok(Self { + file: Mutex::new(std::fs::File::open(path)?), + }) + } + + /// Size of the open file, not of whatever the path resolves to now. + fn len(&self) -> Result { + let file = self + .file + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + Ok(file.metadata()?.len()) + } + + /// Read exactly `len` bytes at `offset` from the open file. + fn read_range(&self, offset: u64, len: u64) -> Result, OneIoError> { + let mut file = self + .file + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut buf = Vec::with_capacity(len as usize); + file.seek(SeekFrom::Start(offset))?; + file.by_ref().take(len).read_to_end(&mut buf)?; + if buf.len() as u64 != len { + return Err(OneIoError::Io(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + format!( + "multipart part read was short: expected {len} bytes, got {}", + buf.len() + ), + ))); + } + Ok(buf) + } +} + /// Upload a single multipart part with retry, avoiding unnecessary clones. /// /// On the first attempt, `body` is moved into the request with zero copy. /// On retry (transient transport error), the part bytes are re-read from -/// `file` at `offset` to reconstruct the request body. This avoids cloning -/// the full chunk on every attempt — the happy path has no extra allocation. +/// `source` at `offset` to reconstruct the request body. fn upload_part_with_retry( url: &reqwest::Url, body: Vec, - file: &mut std::fs::File, + source: &PartSource, offset: u64, part_len: u64, ) -> Result { let (max_retries, mut backoff_ms) = s3_retry_config(); // First attempt: move the body, no clone. - // Retry attempts: re-read from file at the recorded offset. + // Retry attempts: re-read the same range from the open source. let mut body = Some(body); for _attempt in 0..=max_retries { let request_body = match body.take() { Some(b) => b, - None => { - let mut buf = Vec::with_capacity(part_len as usize); - file.seek(SeekFrom::Start(offset))?; - file.by_ref().take(part_len).read_to_end(&mut buf)?; - if buf.len() as u64 != part_len { - return Err(OneIoError::Io(std::io::Error::new( - std::io::ErrorKind::UnexpectedEof, - format!( - "S3 retry part read was short: expected {part_len} bytes, got {}", - buf.len() - ), - ))); - } - buf - } + None => source.read_range(offset, part_len)?, }; match get_s3_client() .put(url.clone()) - .timeout(S3_UPLOAD_REQUEST_TIMEOUT) + .timeout(upload_request_timeout()) .body(request_body) .send() { @@ -469,8 +612,11 @@ fn upload_multipart( config: &config::S3Config, key: &str, file_path: &str, - size: u64, ) -> Result<(), OneIoError> { + // One open handle covers the part ranges, the total size and the retry + // reads, so every part comes from the same file version. + let source = PartSource::open(file_path)?; + let size = source.len()?; let (chunk_size, total_parts) = calculate_chunk_size(size, config.multipart_chunk_size); let bucket = config.rusty_bucket()?; @@ -482,7 +628,7 @@ fn upload_multipart( let response = ensure_s3_success(send_with_retry(|| { get_s3_client() .post(url.clone()) - .timeout(S3_UPLOAD_REQUEST_TIMEOUT) + .timeout(upload_request_timeout()) .send() })?)?; let init_response = @@ -490,57 +636,100 @@ fn upload_multipart( .map_err(|e| OneIoError::Network(Box::new(e)))?; let upload_id = init_response.upload_id().to_string(); - // 2. Upload parts with abort-on-failure guard - let mut parts: Vec = Vec::with_capacity(total_parts); - let mut file = std::fs::File::open(file_path)?; - let mut chunk = Vec::with_capacity(chunk_size as usize); - - let upload_result = (|| -> Result<(), OneIoError> { - for part_number in 1..=total_parts { - chunk.clear(); - let bytes_read = file.by_ref().take(chunk_size).read_to_end(&mut chunk)?; - if bytes_read == 0 { - break; + // 2. Upload parts concurrently. Part ranges are read from the one open + // source, serialized by its lock, and each part is then uploaded after + // the read returns. One stalled part therefore no longer stops the whole + // upload: the other workers keep filling the pipe with parts they have + // already read. + let concurrency = multipart_concurrency(s3_upload_tuning().0, total_parts); + let state = PartUploadState::new(); + let slots: Mutex>> = Mutex::new(vec![None; total_parts]); + + std::thread::scope(|scope| { + let mut handles = Vec::with_capacity(concurrency); + for _ in 0..concurrency { + // `Scope::spawn` panics when the OS refuses a thread, which would + // unwind past the abort path below and leave the multipart upload + // behind. Report the failure through the pool state instead. + let spawned = std::thread::Builder::new() + .name("oneio-s3-part".to_string()) + .spawn_scoped(scope, || { + let outcome = (|| -> Result<(), OneIoError> { + while let Some(index) = state.claim(total_parts) { + let offset = index as u64 * chunk_size; + let part_len = (size - offset).min(chunk_size); + let body = source.read_range(offset, part_len)?; + + let action = bucket.upload_part( + Some(&creds), + key, + (index + 1) as u16, + &upload_id, + ); + + let url = repair_leading_slash_action_url( + action.sign(config.ttl), + config, + key, + "PUT", + )?; + + // On retry this re-reads the same range from the + // shared source; the read is taken under the source + // lock, outside the network wait. + let response = ensure_s3_success(upload_part_with_retry( + &url, body, &source, offset, part_len, + )?)?; + let etag = extract_etag(response.headers()).ok_or_else(|| { + OneIoError::NotSupported( + "Missing ETag in UploadPart response".into(), + ) + })?; + slots + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner())[index] = + Some(etag); + } + Ok(()) + })(); + if let Err(e) = outcome { + state.fail(e); + } + }); + + match spawned { + Ok(handle) => handles.push(handle), + Err(e) => { + // Keep whatever workers already started; they stop at the + // next part boundary because `fail` sets the stop flag. + state.fail(OneIoError::Io(e)); + break; + } } + } - let action = bucket.upload_part(Some(&creds), key, part_number as u16, &upload_id); - let url = repair_leading_slash_action_url(action.sign(config.ttl), config, key, "PUT")?; - let part_data = std::mem::replace(&mut chunk, Vec::with_capacity(chunk_size as usize)); - let part_len = part_data.len() as u64; - let part_offset = file - .stream_position()? - .checked_sub(part_len) - .ok_or_else(|| { - OneIoError::Io(std::io::Error::new( - std::io::ErrorKind::InvalidData, - "multipart part offset exceeds file position", - )) - })?; - - // Upload this part with retry. On the first attempt, move the - // body to avoid cloning the full chunk. On retry (transient - // transport error), re-read the same bytes from the file. - let response = ensure_s3_success(upload_part_with_retry( - &url, - part_data, - &mut file, - part_offset, - part_len, - )?)?; - - let etag = extract_etag(response.headers()).ok_or_else(|| { - OneIoError::NotSupported("Missing ETag in UploadPart response".into()) - })?; - parts.push(etag); + // Workers stop themselves through `state.fail`; joining is only needed + // to surface a panic, which cannot report through that path. + for handle in handles { + if handle.join().is_err() { + state.fail(OneIoError::NotSupported( + "multipart part worker panicked".to_string(), + )); + } } - Ok(()) - })(); + }); - if let Err(e) = upload_result { + if let Some(e) = state.into_error() { abort_multipart_upload(&bucket, &creds, config, key, &upload_id); return Err(e); } + let parts = collect_part_etags( + &slots + .into_inner() + .unwrap_or_else(|poisoned| poisoned.into_inner()), + )?; + // 3. Complete multipart upload let action = bucket.complete_multipart_upload( Some(&creds), @@ -553,7 +742,7 @@ fn upload_multipart( let response = match send_with_retry(|| { get_s3_client() .post(url.clone()) - .timeout(S3_UPLOAD_REQUEST_TIMEOUT) + .timeout(upload_request_timeout()) .header("content-type", "application/xml") .body(body.clone()) .send() @@ -1223,4 +1412,145 @@ mod tests { assert!(cs >= 8 * 1024 * 1024); assert_eq!(tp, ((hundred_gb + cs - 1) / cs) as usize); } + + #[test] + fn test_multipart_concurrency_bounds() { + // Requested value is used when there is enough work. + assert_eq!(multipart_concurrency(4, 100), 4); + // Never more workers than parts. + assert_eq!(multipart_concurrency(4, 2), 2); + // At least one worker, even for a single-part upload. + assert_eq!(multipart_concurrency(4, 1), 1); + assert_eq!(multipart_concurrency(0, 10), 1); + // Never above the per-upload ceiling. + assert_eq!( + multipart_concurrency(1_000, 10_000), + MAX_MULTIPART_CONCURRENCY + ); + } + + #[test] + fn test_collect_part_etags_preserves_part_order() { + let slots = vec![ + Some("etag-1".to_string()), + Some("etag-2".to_string()), + Some("etag-3".to_string()), + ]; + assert_eq!( + collect_part_etags(&slots).map_err(|e| e.to_string()), + Ok(vec![ + "etag-1".to_string(), + "etag-2".to_string(), + "etag-3".to_string() + ]) + ); + } + + #[test] + fn test_collect_part_etags_rejects_missing_part() { + let slots = vec![Some("etag-1".to_string()), None]; + match collect_part_etags(&slots) { + Ok(parts) => panic!("expected a missing-part error, got {parts:?}"), + Err(crate::OneIoError::NotSupported(message)) => { + assert_eq!(message, "Missing ETag for multipart part 2"); + } + Err(e) => panic!("unexpected error: {e}"), + } + } + + fn temp_path(name: &str) -> std::path::PathBuf { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + std::env::temp_dir().join(format!("oneio-{}-{nanos}-{name}", std::process::id())) + } + + #[test] + fn part_source_reads_exact_ranges() { + let path = temp_path("ranges.bin"); + std::fs::write(&path, b"0123456789abcdef").unwrap(); + let source = PartSource::open(path.to_str().unwrap()).unwrap(); + + assert_eq!(source.len().unwrap(), 16); + assert_eq!(source.read_range(0, 4).unwrap(), b"0123".to_vec()); + assert_eq!(source.read_range(10, 6).unwrap(), b"abcdef".to_vec()); + // A range past the end is an error, not a short body. + assert!(source.read_range(10, 7).is_err()); + + let _ = std::fs::remove_file(&path); + } + + /// A rotating writer replaces the path atomically; the upload must keep + /// reading the file version it opened, not whichever version the path + /// resolves to now. Equal sizes make a mixed upload otherwise invisible. + #[cfg(unix)] + #[test] + fn part_source_keeps_the_opened_file_after_path_replacement() { + let path = temp_path("replace.bin"); + let replacement = temp_path("replacement.bin"); + std::fs::write(&path, b"AAAAAAAAAAAA").unwrap(); + std::fs::write(&replacement, b"BBBBBBBBBBBB").unwrap(); + + let source = PartSource::open(path.to_str().unwrap()).unwrap(); + std::fs::rename(&replacement, &path).unwrap(); + + assert_eq!(source.len().unwrap(), 12); + assert_eq!(source.read_range(0, 12).unwrap(), b"AAAAAAAAAAAA".to_vec()); + + let _ = std::fs::remove_file(&path); + } + + #[test] + fn part_state_claims_each_part_once() { + let state = PartUploadState::new(); + let claimed: Vec = std::iter::from_fn(|| state.claim(3)).collect(); + assert_eq!(claimed, vec![0, 1, 2]); + assert_eq!(state.claim(3), None); + } + + #[test] + fn part_state_keeps_first_failure_and_stops_claims() { + let state = PartUploadState::new(); + assert_eq!(state.claim(10), Some(0)); + state.fail(crate::OneIoError::NotSupported("part 2 failed".into())); + state.fail(crate::OneIoError::NotSupported("part 5 failed".into())); + assert!(state.cancelled()); + assert_eq!(state.claim(10), None); + match state.into_error() { + Some(crate::OneIoError::NotSupported(message)) => assert_eq!(message, "part 2 failed"), + other => panic!("expected the first failure, got {other:?}"), + } + } + + /// The coordinator joins workers in creation order, so a failing worker has + /// to publish cancellation itself. Otherwise a failure in a later worker + /// waits behind a slow earlier worker while the remaining parts keep + /// uploading. + #[test] + fn part_state_failure_is_visible_while_another_worker_runs() { + let state = PartUploadState::new(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + + std::thread::scope(|scope| { + let blocked = scope.spawn(move || { + let _ = release_rx.recv_timeout(std::time::Duration::from_secs(10)); + }); + let failing = scope.spawn(|| { + state.fail(crate::OneIoError::NotSupported("part 2 failed".into())); + }); + + let _ = failing.join(); + let cancelled_while_blocked = state.cancelled(); + let _ = release_tx.send(()); + let _ = blocked.join(); + + assert!( + cancelled_while_blocked, + "a failing worker must set the stop flag before other workers finish" + ); + }); + + assert!(state.into_error().is_some()); + } }