use std::io::{Read, Seek, SeekFrom, Write};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use bytes::Bytes;
use futures::StreamExt;
use futures::stream::FuturesUnordered;
use object_store::path::Path;
use object_store::{
CopyMode, CopyOptions, MultipartUpload, ObjectStore, ObjectStoreExt, PutMode, PutOptions,
PutPayload,
};
use serde::{Deserialize, Serialize};
use crate::cpu::{self, Cost, Lane};
use crate::error::{ItzmaError, Result};
pub const DEFAULT_STREAM_ABOVE: u64 = 64 * 1024 * 1024;
pub const DEFAULT_PART_SIZE: usize = 8 * 1024 * 1024;
pub const MIN_PART_SIZE: usize = 5 * 1024 * 1024;
pub const DEFAULT_UPLOAD_CONCURRENCY: usize = 4;
pub const DEFAULT_FALLBACK_MAX: u64 = 256 * 1024 * 1024;
const COMPARE_PIECE: u64 = 8 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct UploadOptions {
pub stream_above: u64,
pub part_size: usize,
pub concurrency: usize,
pub fallback_max: u64,
pub spill_dir: Option<PathBuf>,
}
impl Default for UploadOptions {
fn default() -> Self {
Self {
stream_above: DEFAULT_STREAM_ABOVE,
part_size: DEFAULT_PART_SIZE,
concurrency: DEFAULT_UPLOAD_CONCURRENCY,
fallback_max: DEFAULT_FALLBACK_MAX,
spill_dir: None,
}
}
}
impl UploadOptions {
pub fn stream_above(mut self, bytes: u64) -> Self {
self.stream_above = bytes;
self
}
pub fn part_size(mut self, bytes: usize) -> Self {
self.part_size = bytes;
self
}
pub fn concurrency(mut self, parts: usize) -> Self {
self.concurrency = parts;
self
}
pub fn fallback_max(mut self, bytes: u64) -> Self {
self.fallback_max = bytes;
self
}
pub fn spill_dir(mut self, dir: Option<PathBuf>) -> Self {
self.spill_dir = dir;
self
}
pub fn validate(&self) -> Result<()> {
if self.part_size < MIN_PART_SIZE {
return Err(ItzmaError::InvalidConfig(
"an upload's part_size must be at least 5 MiB, S3's smallest part",
));
}
if self.concurrency == 0 {
return Err(ItzmaError::InvalidConfig(
"an upload's concurrency must be at least 1",
));
}
Ok(())
}
pub(crate) fn spill(&self) -> Spill {
let dir = self
.spill_dir
.clone()
.unwrap_or_else(|| std::env::temp_dir().join(format!("itzma-{}", std::process::id())));
Spill { dir }
}
}
#[derive(Default)]
pub(crate) struct Body {
pieces: Vec<Piece>,
len: u64,
}
enum Piece {
Memory(Bytes),
Spilled {
file: Arc<SpillFile>,
offset: u64,
len: u64,
},
}
impl Body {
pub(crate) fn push(&mut self, bytes: Bytes) {
if !bytes.is_empty() {
self.len += bytes.len() as u64;
self.pieces.push(Piece::Memory(bytes));
}
}
pub(crate) fn push_spilled(&mut self, file: &Arc<SpillFile>, offset: u64, len: u64) {
if len > 0 {
self.len += len;
self.pieces.push(Piece::Spilled {
file: file.clone(),
offset,
len,
});
}
}
pub(crate) fn len(&self) -> u64 {
self.len
}
fn spans(&self, size: u64) -> Vec<Span> {
let size = size.max(1);
let mut spans = Vec::new();
for piece in &self.pieces {
let len = piece.len();
let mut at = 0;
while at < len {
let n = (len - at).min(size);
spans.push(match piece {
Piece::Memory(bytes) => {
Span::Memory(bytes.slice(at as usize..(at + n) as usize))
}
Piece::Spilled { file, offset, .. } => Span::Spilled {
file: file.clone(),
offset: offset + at,
len: n,
},
});
at += n;
}
}
spans
}
pub(crate) fn into_memory(self) -> Result<PutPayload> {
self.pieces
.into_iter()
.map(|piece| match piece {
Piece::Memory(bytes) => Ok(bytes),
Piece::Spilled { .. } => Err(ItzmaError::CorruptSegment {
path: "(encoding)".into(),
reason: "a spilled section read as if in memory".into(),
}),
})
.collect::<Result<Vec<Bytes>>>()
.map(|parts| parts.into_iter().collect())
}
#[cfg(test)]
pub(crate) fn spilled(&self) -> bool {
self.pieces
.iter()
.any(|p| matches!(p, Piece::Spilled { .. }))
}
pub(crate) async fn into_payload(self) -> Result<PutPayload> {
if self.pieces.iter().all(|p| matches!(p, Piece::Memory(_))) {
return Ok(self
.pieces
.into_iter()
.filter_map(|p| match p {
Piece::Memory(bytes) => Some(bytes),
Piece::Spilled { .. } => None,
})
.collect());
}
let len = self.len;
let spans = self.spans(u64::MAX);
cpu::run(Lane::Maintenance, bytes_cost(len), move || {
spans
.into_iter()
.map(Span::read)
.collect::<Result<Vec<Bytes>>>()
.map(|parts| parts.into_iter().collect())
})
.await
}
}
impl From<PutPayload> for Body {
fn from(payload: PutPayload) -> Self {
let mut body = Body::default();
for bytes in payload.iter() {
body.push(bytes.clone());
}
body
}
}
enum Span {
Memory(Bytes),
Spilled {
file: Arc<SpillFile>,
offset: u64,
len: u64,
},
}
impl Span {
fn len(&self) -> u64 {
match self {
Span::Memory(bytes) => bytes.len() as u64,
Span::Spilled { len, .. } => *len,
}
}
fn read(self) -> Result<Bytes> {
match self {
Span::Memory(bytes) => Ok(bytes),
Span::Spilled { file, offset, len } => file.read_at(offset, len),
}
}
}
impl Piece {
fn len(&self) -> u64 {
match self {
Piece::Memory(bytes) => bytes.len() as u64,
Piece::Spilled { len, .. } => *len,
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct Spill {
dir: PathBuf,
}
impl Spill {
pub(crate) fn file(&self) -> Result<Arc<SpillFile>> {
static NEXT: AtomicU64 = AtomicU64::new(0);
std::fs::create_dir_all(&self.dir).map_err(spill_error)?;
let path = self.dir.join(format!(
"{}-{}.spill",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(&path)
.map_err(spill_error)?;
#[cfg(unix)]
let path = {
std::fs::remove_file(&path).map_err(spill_error)?;
None
};
#[cfg(not(unix))]
let path = Some(path);
Ok(Arc::new(SpillFile {
path,
file: Mutex::new(file),
len: AtomicU64::new(0),
}))
}
}
pub(crate) struct SpillFile {
path: Option<PathBuf>,
file: Mutex<std::fs::File>,
len: AtomicU64,
}
impl SpillFile {
pub(crate) fn append(&self, bytes: &[u8]) -> Result<u64> {
let mut file = self.file.lock().unwrap_or_else(PoisonError::into_inner);
let offset = self.len.load(Ordering::Relaxed);
file.seek(SeekFrom::Start(offset)).map_err(spill_error)?;
file.write_all(bytes).map_err(spill_error)?;
self.len
.store(offset + bytes.len() as u64, Ordering::Relaxed);
Ok(offset)
}
fn read_at(&self, offset: u64, len: u64) -> Result<Bytes> {
let mut file = self.file.lock().unwrap_or_else(PoisonError::into_inner);
file.seek(SeekFrom::Start(offset)).map_err(spill_error)?;
let mut out = vec![0; usize::try_from(len).map_err(|_| spill_error("too large"))?];
file.read_exact(&mut out).map_err(spill_error)?;
Ok(Bytes::from(out))
}
}
impl Drop for SpillFile {
fn drop(&mut self) {
if let Some(path) = &self.path {
let _ = std::fs::remove_file(path);
}
}
}
fn bytes_cost(len: u64) -> Cost {
Cost::Bytes(usize::try_from(len).unwrap_or(usize::MAX))
}
fn spill_error(source: impl std::fmt::Display) -> ItzmaError {
ItzmaError::Storage(object_store::Error::Generic {
store: "spill",
source: format!("a merge's spill file: {source}").into(),
})
}
pub(crate) struct Refusal {
pub(crate) missing: fn(&Path) -> ItzmaError,
pub(crate) differs: &'static str,
}
#[derive(Debug, Default)]
pub(crate) struct Uploader {
pub(crate) options: UploadOptions,
no_conditional_copy: AtomicBool,
}
impl Uploader {
pub(crate) fn new(options: UploadOptions) -> Self {
Self {
options,
no_conditional_copy: AtomicBool::new(false),
}
}
}
pub(crate) async fn write(
store: &dyn ObjectStore,
path: &Path,
body: Body,
uploader: &Uploader,
refusal: &Refusal,
) -> Result<()> {
let options = &uploader.options;
if body.len() <= options.stream_above {
return write_whole(store, path, body, refusal).await;
}
if uploader.no_conditional_copy.load(Ordering::Relaxed) {
if body.len() <= options.fallback_max {
return write_whole(store, path, body, refusal).await;
}
return Err(no_conditional_copy());
}
let staging = staging_path(path);
stage(store, &staging, &body, options).await?;
let copied = store
.copy_opts(
&staging,
path,
CopyOptions {
mode: CopyMode::Create,
..CopyOptions::default()
},
)
.await;
let outcome = match copied {
Ok(()) => Ok(()),
Err(
object_store::Error::AlreadyExists { .. } | object_store::Error::Precondition { .. },
) => reuse_or_refuse(store, path, &body, refusal).await,
Err(object_store::Error::NotSupported { .. })
| Err(object_store::Error::NotImplemented { .. }) => {
uploader.no_conditional_copy.store(true, Ordering::Relaxed);
let _ = store.delete(&staging).await;
return if body.len() <= options.fallback_max {
write_whole(store, path, body, refusal).await
} else {
Err(no_conditional_copy())
};
}
Err(e) => Err(e.into()),
};
let _ = store.delete(&staging).await;
outcome
}
fn no_conditional_copy() -> ItzmaError {
ItzmaError::Storage(object_store::Error::NotSupported {
source: "the store cannot copy with put-if-absent, and the object is over \
UploadOptions::fallback_max"
.into(),
})
}
async fn write_whole(
store: &dyn ObjectStore,
path: &Path,
body: Body,
refusal: &Refusal,
) -> Result<()> {
let payload = body.into_payload().await?;
match store
.put_opts(path, payload.clone(), PutOptions::from(PutMode::Create))
.await
{
Ok(_) => Ok(()),
Err(object_store::Error::AlreadyExists { .. }) => {
reuse_or_refuse(store, path, &Body::from(payload), refusal).await
}
Err(e) => Err(e.into()),
}
}
async fn reuse_or_refuse(
store: &dyn ObjectStore,
path: &Path,
body: &Body,
refusal: &Refusal,
) -> Result<()> {
match same_object(store, path, body).await {
Ok(true) => Ok(()),
Ok(false) => Err(ItzmaError::CorruptSegment {
path: path.to_string(),
reason: refusal.differs.into(),
}),
Err(object_store::Error::NotFound { .. }) => Err((refusal.missing)(path)),
Err(e) => Err(e.into()),
}
}
async fn stage(
store: &dyn ObjectStore,
staging: &Path,
body: &Body,
options: &UploadOptions,
) -> Result<()> {
let mut upload = store
.put_multipart_opts(staging, Default::default())
.await?;
match send_parts(&mut *upload, body, options).await {
Ok(()) => {
upload.complete().await?;
Ok(())
}
Err(e) => {
let _ = upload.abort().await;
Err(e)
}
}
}
async fn send_parts(
upload: &mut dyn MultipartUpload,
body: &Body,
options: &UploadOptions,
) -> Result<()> {
let size = options.part_size.max(1);
let mut in_flight = FuturesUnordered::new();
let mut part: Vec<Bytes> = Vec::new();
let mut part_len = 0usize;
let mut sent = 0usize;
for span in body.spans(size as u64) {
let len = span.len();
let mut bytes = cpu::run(Lane::Maintenance, bytes_cost(len), move || span.read()).await?;
while !bytes.is_empty() {
let take = (size - part_len).min(bytes.len());
part.push(bytes.split_to(take));
part_len += take;
if part_len == size {
while in_flight.len() >= options.concurrency.max(1) {
if let Some(done) = in_flight.next().await {
done?;
}
}
in_flight.push(upload.put_part(std::mem::take(&mut part).into_iter().collect()));
part_len = 0;
sent += 1;
}
}
}
if part_len > 0 || sent == 0 {
in_flight.push(upload.put_part(part.into_iter().collect()));
}
while let Some(done) = in_flight.next().await {
done?;
}
Ok(())
}
fn staging_path(path: &Path) -> Path {
static NEXT: AtomicU64 = AtomicU64::new(0);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
let name = format!(
"staging-{:x}-{nanos:x}-{:x}.bin",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
);
let parent = path.as_ref().rsplit_once('/').map_or("", |(dir, _)| dir);
Path::from(format!("{parent}/{name}"))
}
pub(crate) fn is_staging(name: &str) -> bool {
name.starts_with("staging-") && name.ends_with(".bin")
}
async fn same_object(
store: &dyn ObjectStore,
path: &Path,
body: &Body,
) -> object_store::Result<bool> {
if store.head(path).await?.size != body.len() {
return Ok(false);
}
let mut at = 0u64;
for span in body.spans(COMPARE_PIECE) {
let len = span.len();
let mine = cpu::run(Lane::Maintenance, bytes_cost(len), move || span.read())
.await
.map_err(|e| object_store::Error::Generic {
store: "spill",
source: e.to_string().into(),
})?;
if store.get_range(path, at..at + len).await?.as_ref() != mine.as_ref() {
return Ok(false);
}
at += len;
}
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
use object_store::PutPayloadMut;
use object_store::memory::InMemory;
const REFUSAL: Refusal = Refusal {
missing: crate::segment::missing,
differs: "differs",
};
fn bytes(n: usize, seed: u8) -> Vec<u8> {
(0..n)
.map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed))
.collect()
}
fn body_of(chunks: &[&[u8]]) -> Body {
let mut body = Body::default();
for c in chunks {
body.push(Bytes::copy_from_slice(c));
}
body
}
fn small() -> Uploader {
Uploader::new(UploadOptions {
stream_above: 100,
part_size: 64,
..UploadOptions::default()
})
}
async fn listing(store: &InMemory) -> Vec<String> {
use futures::TryStreamExt;
let mut names: Vec<String> = store
.list(None)
.map_ok(|m| m.location.to_string())
.try_collect()
.await
.unwrap();
names.sort();
names
}
#[tokio::test]
async fn a_large_body_lands_at_its_key_with_the_bytes_a_put_writes() {
let store = InMemory::new();
let data = bytes(1000, 3);
let path = Path::from("ns/segments/1-2/data.bin");
let body = body_of(&[&data[..300], &data[300..]]);
write(&store, &path, body, &small(), &REFUSAL)
.await
.unwrap();
let stored = store.get(&path).await.unwrap().bytes().await.unwrap();
assert_eq!(stored.as_ref(), &data[..]);
assert_eq!(
listing(&store).await,
["ns/segments/1-2/data.bin"],
"staging gone"
);
}
#[tokio::test]
async fn a_spilled_body_reads_back_in_order() {
let dir = tempfile::tempdir().unwrap();
let spill = UploadOptions::default()
.spill_dir(Some(dir.path().to_owned()))
.spill();
let file = spill.file().unwrap();
let data = bytes(500, 9);
let a = file.append(&data[..200]).unwrap();
let b = file.append(&data[200..]).unwrap();
let mut body = Body::default();
body.push(Bytes::from_static(b"head"));
body.push_spilled(&file, a, 200);
body.push_spilled(&file, b, 300);
#[cfg(unix)]
assert_eq!(
std::fs::read_dir(dir.path()).unwrap().count(),
0,
"a spill file in use has no name, so a killed process leaves nothing"
);
let store = InMemory::new();
let path = Path::from("ns/segments/1-2/data.bin");
write(&store, &path, body, &small(), &REFUSAL)
.await
.unwrap();
let stored = store.get(&path).await.unwrap().bytes().await.unwrap();
assert_eq!(&stored[..4], b"head");
assert_eq!(&stored[4..], &data[..]);
drop(file);
let left = std::fs::read_dir(dir.path())
.map(|d| d.count())
.unwrap_or_default();
assert_eq!(
left, 0,
"a spill file has no name once dropped, or none at all"
);
}
#[tokio::test]
async fn an_identical_object_at_the_key_is_reused_and_another_is_refused() {
let store = InMemory::new();
let path = Path::from("ns/segments/1-2/data.bin");
let data = bytes(1000, 1);
store.put(&path, data.clone().into()).await.unwrap();
write(&store, &path, body_of(&[&data]), &small(), &REFUSAL)
.await
.unwrap();
let other = bytes(1000, 2);
let err = write(&store, &path, body_of(&[&other]), &small(), &REFUSAL)
.await
.unwrap_err();
assert!(matches!(err, ItzmaError::CorruptSegment { .. }), "{err:?}");
assert_eq!(listing(&store).await, ["ns/segments/1-2/data.bin"]);
let stored = store.get(&path).await.unwrap().bytes().await.unwrap();
assert_eq!(stored.as_ref(), &data[..], "nothing overwritten");
}
#[tokio::test]
async fn a_small_body_is_one_put() {
let store = InMemory::new();
let path = Path::from("ns/segments/1-2/data.bin");
let mut payload = PutPayloadMut::new();
payload.extend_from_slice(b"small");
let body = Body::from(payload.freeze());
write(&store, &path, body, &small(), &REFUSAL)
.await
.unwrap();
assert_eq!(
store
.get(&path)
.await
.unwrap()
.bytes()
.await
.unwrap()
.as_ref(),
b"small"
);
}
#[derive(Debug, Default)]
struct TestStore {
inner: InMemory,
no_copy: bool,
parts: Arc<Mutex<Vec<usize>>>,
starts: AtomicU64,
}
#[derive(Debug)]
struct Recorded {
inner: Box<dyn MultipartUpload>,
parts: Arc<Mutex<Vec<usize>>>,
}
#[async_trait::async_trait]
impl MultipartUpload for Recorded {
fn put_part(&mut self, data: PutPayload) -> object_store::UploadPart {
self.parts.lock().unwrap().push(data.content_length());
self.inner.put_part(data)
}
async fn complete(&mut self) -> object_store::Result<object_store::PutResult> {
self.inner.complete().await
}
async fn abort(&mut self) -> object_store::Result<()> {
self.inner.abort().await
}
}
impl std::fmt::Display for TestStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "TestStore")
}
}
#[async_trait::async_trait]
impl ObjectStore for TestStore {
async fn put_opts(
&self,
location: &Path,
payload: PutPayload,
opts: PutOptions,
) -> object_store::Result<object_store::PutResult> {
self.inner.put_opts(location, payload, opts).await
}
async fn put_multipart_opts(
&self,
location: &Path,
opts: object_store::PutMultipartOptions,
) -> object_store::Result<Box<dyn MultipartUpload>> {
self.starts.fetch_add(1, Ordering::SeqCst);
Ok(Box::new(Recorded {
inner: self.inner.put_multipart_opts(location, opts).await?,
parts: self.parts.clone(),
}))
}
async fn get_opts(
&self,
location: &Path,
options: object_store::GetOptions,
) -> object_store::Result<object_store::GetResult> {
self.inner.get_opts(location, options).await
}
fn delete_stream(
&self,
locations: futures::stream::BoxStream<'static, object_store::Result<Path>>,
) -> futures::stream::BoxStream<'static, object_store::Result<Path>> {
self.inner.delete_stream(locations)
}
fn list(
&self,
prefix: Option<&Path>,
) -> futures::stream::BoxStream<'static, object_store::Result<object_store::ObjectMeta>>
{
self.inner.list(prefix)
}
async fn list_with_delimiter(
&self,
prefix: Option<&Path>,
) -> object_store::Result<object_store::ListResult> {
self.inner.list_with_delimiter(prefix).await
}
async fn copy_opts(
&self,
from: &Path,
to: &Path,
options: CopyOptions,
) -> object_store::Result<()> {
match options.mode {
CopyMode::Create if self.no_copy => Err(object_store::Error::NotSupported {
source: "no conditional copy".into(),
}),
_ => self.inner.copy_opts(from, to, options).await,
}
}
}
#[tokio::test]
async fn parts_are_cut_at_part_size_across_pieces() {
let store = TestStore::default();
let data = bytes(1000, 4);
let body = body_of(&[&data[..3], &data[3..500], &data[500..501], &data[501..]]);
let path = Path::from("ns/segments/1-2/data.bin");
write(&store, &path, body, &small(), &REFUSAL)
.await
.unwrap();
let parts = store.parts.lock().unwrap().clone();
let (last, middle) = parts.split_last().unwrap();
assert!(middle.iter().all(|&n| n == 64), "{parts:?}");
assert_eq!(middle.len() * 64 + last, 1000);
assert_eq!(
store
.inner
.get(&path)
.await
.unwrap()
.bytes()
.await
.unwrap()
.as_ref(),
&data[..]
);
}
#[tokio::test]
async fn without_a_conditional_copy_a_body_falls_back_or_fails() {
let store = TestStore {
no_copy: true,
..TestStore::default()
};
let path = Path::from("ns/segments/1-2/data.bin");
let data = bytes(1000, 5);
let uploader = Uploader::new(UploadOptions {
fallback_max: 1000,
..small().options
});
write(&store, &path, body_of(&[&data]), &uploader, &REFUSAL)
.await
.unwrap();
assert_eq!(
store
.inner
.get(&path)
.await
.unwrap()
.bytes()
.await
.unwrap()
.as_ref(),
&data[..]
);
assert_eq!(store.starts.load(Ordering::SeqCst), 1);
let other = Path::from("ns/segments/3-4/data.bin");
let err = write(
&store,
&other,
body_of(&[&bytes(1001, 6)]),
&uploader,
&REFUSAL,
)
.await
.unwrap_err();
assert!(
matches!(
err,
ItzmaError::Storage(object_store::Error::NotSupported { .. })
),
"{err:?}"
);
let third = Path::from("ns/segments/5-6/data.bin");
write(
&store,
&third,
body_of(&[&bytes(900, 7)]),
&uploader,
&REFUSAL,
)
.await
.unwrap();
assert_eq!(
store.starts.load(Ordering::SeqCst),
1,
"no upload staged again"
);
assert_eq!(
listing(&store.inner).await,
["ns/segments/1-2/data.bin", "ns/segments/5-6/data.bin"]
);
}
#[test]
fn a_streamed_write_runs_on_any_executor() {
let store = InMemory::new();
let path = Path::from("ns/segments/1-2/data.bin");
let data = bytes(1000, 8);
futures::executor::block_on(write(&store, &path, body_of(&[&data]), &small(), &REFUSAL))
.unwrap();
let stored = futures::executor::block_on(async {
store.get(&path).await.unwrap().bytes().await.unwrap()
});
assert_eq!(stored.as_ref(), &data[..]);
}
#[test]
fn staging_names_are_unique_and_recognised() {
let path = Path::from("ns/segments/1-2/data.bin");
let (a, b) = (staging_path(&path), staging_path(&path));
assert_ne!(a, b);
assert!(a.as_ref().starts_with("ns/segments/1-2/staging-"));
assert!(is_staging(a.filename().unwrap()));
assert!(!is_staging("data.bin"));
}
#[test]
fn a_part_under_s3s_minimum_or_zero_concurrency_is_refused() {
assert!(UploadOptions::default().part_size(0).validate().is_err());
let under = UploadOptions::default().part_size(MIN_PART_SIZE - 1);
assert!(under.validate().is_err());
UploadOptions::default()
.part_size(MIN_PART_SIZE)
.validate()
.unwrap();
assert!(UploadOptions::default().concurrency(0).validate().is_err());
UploadOptions::default().validate().unwrap();
}
}