1use std::io::{Read, Seek, SeekFrom, Write};
17use std::path::PathBuf;
18use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
19use std::sync::{Arc, Mutex, PoisonError};
20
21use bytes::Bytes;
22use futures::StreamExt;
23use futures::stream::FuturesUnordered;
24use object_store::path::Path;
25use object_store::{
26 CopyMode, CopyOptions, MultipartUpload, ObjectStore, ObjectStoreExt, PutMode, PutOptions,
27 PutPayload,
28};
29use serde::{Deserialize, Serialize};
30
31use crate::cpu::{self, Cost, Lane};
32use crate::error::{ItzmaError, Result};
33
34pub const DEFAULT_STREAM_ABOVE: u64 = 64 * 1024 * 1024;
36pub const DEFAULT_PART_SIZE: usize = 8 * 1024 * 1024;
39pub const MIN_PART_SIZE: usize = 5 * 1024 * 1024;
41pub const DEFAULT_UPLOAD_CONCURRENCY: usize = 4;
43pub const DEFAULT_FALLBACK_MAX: u64 = 256 * 1024 * 1024;
45
46const COMPARE_PIECE: u64 = 8 * 1024 * 1024;
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(default)]
70#[non_exhaustive]
71pub struct UploadOptions {
72 pub stream_above: u64,
74 pub part_size: usize,
76 pub concurrency: usize,
78 pub fallback_max: u64,
81 pub spill_dir: Option<PathBuf>,
84}
85
86impl Default for UploadOptions {
87 fn default() -> Self {
88 Self {
89 stream_above: DEFAULT_STREAM_ABOVE,
90 part_size: DEFAULT_PART_SIZE,
91 concurrency: DEFAULT_UPLOAD_CONCURRENCY,
92 fallback_max: DEFAULT_FALLBACK_MAX,
93 spill_dir: None,
94 }
95 }
96}
97
98impl UploadOptions {
99 pub fn stream_above(mut self, bytes: u64) -> Self {
101 self.stream_above = bytes;
102 self
103 }
104
105 pub fn part_size(mut self, bytes: usize) -> Self {
107 self.part_size = bytes;
108 self
109 }
110
111 pub fn concurrency(mut self, parts: usize) -> Self {
113 self.concurrency = parts;
114 self
115 }
116
117 pub fn fallback_max(mut self, bytes: u64) -> Self {
119 self.fallback_max = bytes;
120 self
121 }
122
123 pub fn spill_dir(mut self, dir: Option<PathBuf>) -> Self {
125 self.spill_dir = dir;
126 self
127 }
128
129 pub fn validate(&self) -> Result<()> {
138 if self.part_size < MIN_PART_SIZE {
139 return Err(ItzmaError::InvalidConfig(
140 "an upload's part_size must be at least 5 MiB, S3's smallest part",
141 ));
142 }
143 if self.concurrency == 0 {
144 return Err(ItzmaError::InvalidConfig(
145 "an upload's concurrency must be at least 1",
146 ));
147 }
148 Ok(())
149 }
150
151 pub(crate) fn spill(&self) -> Spill {
153 let dir = self
154 .spill_dir
155 .clone()
156 .unwrap_or_else(|| std::env::temp_dir().join(format!("itzma-{}", std::process::id())));
157 Spill { dir }
158 }
159}
160
161#[derive(Default)]
163pub(crate) struct Body {
164 pieces: Vec<Piece>,
165 len: u64,
166}
167
168enum Piece {
169 Memory(Bytes),
170 Spilled {
171 file: Arc<SpillFile>,
172 offset: u64,
173 len: u64,
174 },
175}
176
177impl Body {
178 pub(crate) fn push(&mut self, bytes: Bytes) {
179 if !bytes.is_empty() {
180 self.len += bytes.len() as u64;
181 self.pieces.push(Piece::Memory(bytes));
182 }
183 }
184
185 pub(crate) fn push_spilled(&mut self, file: &Arc<SpillFile>, offset: u64, len: u64) {
186 if len > 0 {
187 self.len += len;
188 self.pieces.push(Piece::Spilled {
189 file: file.clone(),
190 offset,
191 len,
192 });
193 }
194 }
195
196 pub(crate) fn len(&self) -> u64 {
198 self.len
199 }
200
201 fn spans(&self, size: u64) -> Vec<Span> {
205 let size = size.max(1);
206 let mut spans = Vec::new();
207 for piece in &self.pieces {
208 let len = piece.len();
209 let mut at = 0;
210 while at < len {
211 let n = (len - at).min(size);
212 spans.push(match piece {
213 Piece::Memory(bytes) => {
214 Span::Memory(bytes.slice(at as usize..(at + n) as usize))
215 }
216 Piece::Spilled { file, offset, .. } => Span::Spilled {
217 file: file.clone(),
218 offset: offset + at,
219 len: n,
220 },
221 });
222 at += n;
223 }
224 }
225 spans
226 }
227
228 pub(crate) fn into_memory(self) -> Result<PutPayload> {
235 self.pieces
236 .into_iter()
237 .map(|piece| match piece {
238 Piece::Memory(bytes) => Ok(bytes),
239 Piece::Spilled { .. } => Err(ItzmaError::CorruptSegment {
240 path: "(encoding)".into(),
241 reason: "a spilled section read as if in memory".into(),
242 }),
243 })
244 .collect::<Result<Vec<Bytes>>>()
245 .map(|parts| parts.into_iter().collect())
246 }
247
248 #[cfg(test)]
250 pub(crate) fn spilled(&self) -> bool {
251 self.pieces
252 .iter()
253 .any(|p| matches!(p, Piece::Spilled { .. }))
254 }
255
256 pub(crate) async fn into_payload(self) -> Result<PutPayload> {
258 if self.pieces.iter().all(|p| matches!(p, Piece::Memory(_))) {
259 return Ok(self
260 .pieces
261 .into_iter()
262 .filter_map(|p| match p {
263 Piece::Memory(bytes) => Some(bytes),
264 Piece::Spilled { .. } => None,
265 })
266 .collect());
267 }
268 let len = self.len;
269 let spans = self.spans(u64::MAX);
270 cpu::run(Lane::Maintenance, bytes_cost(len), move || {
271 spans
272 .into_iter()
273 .map(Span::read)
274 .collect::<Result<Vec<Bytes>>>()
275 .map(|parts| parts.into_iter().collect())
276 })
277 .await
278 }
279}
280
281impl From<PutPayload> for Body {
282 fn from(payload: PutPayload) -> Self {
283 let mut body = Body::default();
284 for bytes in payload.iter() {
285 body.push(bytes.clone());
286 }
287 body
288 }
289}
290
291enum Span {
293 Memory(Bytes),
294 Spilled {
295 file: Arc<SpillFile>,
296 offset: u64,
297 len: u64,
298 },
299}
300
301impl Span {
302 fn len(&self) -> u64 {
303 match self {
304 Span::Memory(bytes) => bytes.len() as u64,
305 Span::Spilled { len, .. } => *len,
306 }
307 }
308
309 fn read(self) -> Result<Bytes> {
311 match self {
312 Span::Memory(bytes) => Ok(bytes),
313 Span::Spilled { file, offset, len } => file.read_at(offset, len),
314 }
315 }
316}
317
318impl Piece {
319 fn len(&self) -> u64 {
320 match self {
321 Piece::Memory(bytes) => bytes.len() as u64,
322 Piece::Spilled { len, .. } => *len,
323 }
324 }
325}
326
327#[derive(Debug, Clone)]
329pub(crate) struct Spill {
330 dir: PathBuf,
331}
332
333impl Spill {
334 pub(crate) fn file(&self) -> Result<Arc<SpillFile>> {
336 static NEXT: AtomicU64 = AtomicU64::new(0);
337 std::fs::create_dir_all(&self.dir).map_err(spill_error)?;
338 let path = self.dir.join(format!(
339 "{}-{}.spill",
340 std::process::id(),
341 NEXT.fetch_add(1, Ordering::Relaxed)
342 ));
343 let file = std::fs::OpenOptions::new()
344 .read(true)
345 .write(true)
346 .create_new(true)
347 .open(&path)
348 .map_err(spill_error)?;
349 #[cfg(unix)]
354 let path = {
355 std::fs::remove_file(&path).map_err(spill_error)?;
356 None
357 };
358 #[cfg(not(unix))]
359 let path = Some(path);
360 Ok(Arc::new(SpillFile {
361 path,
362 file: Mutex::new(file),
363 len: AtomicU64::new(0),
364 }))
365 }
366}
367
368pub(crate) struct SpillFile {
371 path: Option<PathBuf>,
373 file: Mutex<std::fs::File>,
374 len: AtomicU64,
375}
376
377impl SpillFile {
378 pub(crate) fn append(&self, bytes: &[u8]) -> Result<u64> {
380 let mut file = self.file.lock().unwrap_or_else(PoisonError::into_inner);
381 let offset = self.len.load(Ordering::Relaxed);
382 file.seek(SeekFrom::Start(offset)).map_err(spill_error)?;
383 file.write_all(bytes).map_err(spill_error)?;
384 self.len
385 .store(offset + bytes.len() as u64, Ordering::Relaxed);
386 Ok(offset)
387 }
388
389 fn read_at(&self, offset: u64, len: u64) -> Result<Bytes> {
390 let mut file = self.file.lock().unwrap_or_else(PoisonError::into_inner);
391 file.seek(SeekFrom::Start(offset)).map_err(spill_error)?;
392 let mut out = vec![0; usize::try_from(len).map_err(|_| spill_error("too large"))?];
393 file.read_exact(&mut out).map_err(spill_error)?;
394 Ok(Bytes::from(out))
395 }
396}
397
398impl Drop for SpillFile {
399 fn drop(&mut self) {
400 if let Some(path) = &self.path {
401 let _ = std::fs::remove_file(path);
402 }
403 }
404}
405
406fn bytes_cost(len: u64) -> Cost {
408 Cost::Bytes(usize::try_from(len).unwrap_or(usize::MAX))
409}
410
411fn spill_error(source: impl std::fmt::Display) -> ItzmaError {
412 ItzmaError::Storage(object_store::Error::Generic {
413 store: "spill",
414 source: format!("a merge's spill file: {source}").into(),
415 })
416}
417
418pub(crate) struct Refusal {
420 pub(crate) missing: fn(&Path) -> ItzmaError,
422 pub(crate) differs: &'static str,
424}
425
426#[derive(Debug, Default)]
430pub(crate) struct Uploader {
431 pub(crate) options: UploadOptions,
432 no_conditional_copy: AtomicBool,
433}
434
435impl Uploader {
436 pub(crate) fn new(options: UploadOptions) -> Self {
437 Self {
438 options,
439 no_conditional_copy: AtomicBool::new(false),
440 }
441 }
442}
443
444pub(crate) async fn write(
456 store: &dyn ObjectStore,
457 path: &Path,
458 body: Body,
459 uploader: &Uploader,
460 refusal: &Refusal,
461) -> Result<()> {
462 let options = &uploader.options;
463 if body.len() <= options.stream_above {
464 return write_whole(store, path, body, refusal).await;
465 }
466 if uploader.no_conditional_copy.load(Ordering::Relaxed) {
467 if body.len() <= options.fallback_max {
468 return write_whole(store, path, body, refusal).await;
469 }
470 return Err(no_conditional_copy());
471 }
472 let staging = staging_path(path);
473 stage(store, &staging, &body, options).await?;
474 let copied = store
475 .copy_opts(
476 &staging,
477 path,
478 CopyOptions {
479 mode: CopyMode::Create,
480 ..CopyOptions::default()
481 },
482 )
483 .await;
484 let outcome = match copied {
485 Ok(()) => Ok(()),
486 Err(
487 object_store::Error::AlreadyExists { .. } | object_store::Error::Precondition { .. },
488 ) => reuse_or_refuse(store, path, &body, refusal).await,
489 Err(object_store::Error::NotSupported { .. })
490 | Err(object_store::Error::NotImplemented { .. }) => {
491 uploader.no_conditional_copy.store(true, Ordering::Relaxed);
492 let _ = store.delete(&staging).await;
493 return if body.len() <= options.fallback_max {
494 write_whole(store, path, body, refusal).await
495 } else {
496 Err(no_conditional_copy())
497 };
498 }
499 Err(e) => Err(e.into()),
500 };
501 let _ = store.delete(&staging).await;
502 outcome
503}
504
505fn no_conditional_copy() -> ItzmaError {
506 ItzmaError::Storage(object_store::Error::NotSupported {
507 source: "the store cannot copy with put-if-absent, and the object is over \
508 UploadOptions::fallback_max"
509 .into(),
510 })
511}
512
513async fn write_whole(
515 store: &dyn ObjectStore,
516 path: &Path,
517 body: Body,
518 refusal: &Refusal,
519) -> Result<()> {
520 let payload = body.into_payload().await?;
521 match store
522 .put_opts(path, payload.clone(), PutOptions::from(PutMode::Create))
523 .await
524 {
525 Ok(_) => Ok(()),
526 Err(object_store::Error::AlreadyExists { .. }) => {
527 reuse_or_refuse(store, path, &Body::from(payload), refusal).await
528 }
529 Err(e) => Err(e.into()),
530 }
531}
532
533async fn reuse_or_refuse(
535 store: &dyn ObjectStore,
536 path: &Path,
537 body: &Body,
538 refusal: &Refusal,
539) -> Result<()> {
540 match same_object(store, path, body).await {
541 Ok(true) => Ok(()),
542 Ok(false) => Err(ItzmaError::CorruptSegment {
543 path: path.to_string(),
544 reason: refusal.differs.into(),
545 }),
546 Err(object_store::Error::NotFound { .. }) => Err((refusal.missing)(path)),
547 Err(e) => Err(e.into()),
548 }
549}
550
551async fn stage(
557 store: &dyn ObjectStore,
558 staging: &Path,
559 body: &Body,
560 options: &UploadOptions,
561) -> Result<()> {
562 let mut upload = store
563 .put_multipart_opts(staging, Default::default())
564 .await?;
565 match send_parts(&mut *upload, body, options).await {
566 Ok(()) => {
567 upload.complete().await?;
568 Ok(())
569 }
570 Err(e) => {
571 let _ = upload.abort().await;
572 Err(e)
573 }
574 }
575}
576
577async fn send_parts(
578 upload: &mut dyn MultipartUpload,
579 body: &Body,
580 options: &UploadOptions,
581) -> Result<()> {
582 let size = options.part_size.max(1);
583 let mut in_flight = FuturesUnordered::new();
584 let mut part: Vec<Bytes> = Vec::new();
585 let mut part_len = 0usize;
586 let mut sent = 0usize;
587 for span in body.spans(size as u64) {
588 let len = span.len();
589 let mut bytes = cpu::run(Lane::Maintenance, bytes_cost(len), move || span.read()).await?;
590 while !bytes.is_empty() {
591 let take = (size - part_len).min(bytes.len());
592 part.push(bytes.split_to(take));
593 part_len += take;
594 if part_len == size {
595 while in_flight.len() >= options.concurrency.max(1) {
596 if let Some(done) = in_flight.next().await {
597 done?;
598 }
599 }
600 in_flight.push(upload.put_part(std::mem::take(&mut part).into_iter().collect()));
601 part_len = 0;
602 sent += 1;
603 }
604 }
605 }
606 if part_len > 0 || sent == 0 {
607 in_flight.push(upload.put_part(part.into_iter().collect()));
608 }
609 while let Some(done) = in_flight.next().await {
610 done?;
611 }
612 Ok(())
613}
614
615fn staging_path(path: &Path) -> Path {
618 static NEXT: AtomicU64 = AtomicU64::new(0);
619 let nanos = std::time::SystemTime::now()
620 .duration_since(std::time::UNIX_EPOCH)
621 .map_or(0, |d| d.as_nanos());
622 let name = format!(
623 "staging-{:x}-{nanos:x}-{:x}.bin",
624 std::process::id(),
625 NEXT.fetch_add(1, Ordering::Relaxed)
626 );
627 let parent = path.as_ref().rsplit_once('/').map_or("", |(dir, _)| dir);
628 Path::from(format!("{parent}/{name}"))
629}
630
631pub(crate) fn is_staging(name: &str) -> bool {
633 name.starts_with("staging-") && name.ends_with(".bin")
634}
635
636async fn same_object(
639 store: &dyn ObjectStore,
640 path: &Path,
641 body: &Body,
642) -> object_store::Result<bool> {
643 if store.head(path).await?.size != body.len() {
644 return Ok(false);
645 }
646 let mut at = 0u64;
647 for span in body.spans(COMPARE_PIECE) {
648 let len = span.len();
649 let mine = cpu::run(Lane::Maintenance, bytes_cost(len), move || span.read())
650 .await
651 .map_err(|e| object_store::Error::Generic {
652 store: "spill",
653 source: e.to_string().into(),
654 })?;
655 if store.get_range(path, at..at + len).await?.as_ref() != mine.as_ref() {
656 return Ok(false);
657 }
658 at += len;
659 }
660 Ok(true)
661}
662
663#[cfg(test)]
664mod tests {
665 use super::*;
666 use object_store::PutPayloadMut;
667 use object_store::memory::InMemory;
668
669 const REFUSAL: Refusal = Refusal {
670 missing: crate::segment::missing,
671 differs: "differs",
672 };
673
674 fn bytes(n: usize, seed: u8) -> Vec<u8> {
675 (0..n)
676 .map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed))
677 .collect()
678 }
679
680 fn body_of(chunks: &[&[u8]]) -> Body {
681 let mut body = Body::default();
682 for c in chunks {
683 body.push(Bytes::copy_from_slice(c));
684 }
685 body
686 }
687
688 fn small() -> Uploader {
691 Uploader::new(UploadOptions {
692 stream_above: 100,
693 part_size: 64,
694 ..UploadOptions::default()
695 })
696 }
697
698 async fn listing(store: &InMemory) -> Vec<String> {
699 use futures::TryStreamExt;
700 let mut names: Vec<String> = store
701 .list(None)
702 .map_ok(|m| m.location.to_string())
703 .try_collect()
704 .await
705 .unwrap();
706 names.sort();
707 names
708 }
709
710 #[tokio::test]
711 async fn a_large_body_lands_at_its_key_with_the_bytes_a_put_writes() {
712 let store = InMemory::new();
713 let data = bytes(1000, 3);
714 let path = Path::from("ns/segments/1-2/data.bin");
715 let body = body_of(&[&data[..300], &data[300..]]);
716 write(&store, &path, body, &small(), &REFUSAL)
717 .await
718 .unwrap();
719 let stored = store.get(&path).await.unwrap().bytes().await.unwrap();
720 assert_eq!(stored.as_ref(), &data[..]);
721 assert_eq!(
722 listing(&store).await,
723 ["ns/segments/1-2/data.bin"],
724 "staging gone"
725 );
726 }
727
728 #[tokio::test]
729 async fn a_spilled_body_reads_back_in_order() {
730 let dir = tempfile::tempdir().unwrap();
731 let spill = UploadOptions::default()
732 .spill_dir(Some(dir.path().to_owned()))
733 .spill();
734 let file = spill.file().unwrap();
735 let data = bytes(500, 9);
736 let a = file.append(&data[..200]).unwrap();
737 let b = file.append(&data[200..]).unwrap();
738 let mut body = Body::default();
739 body.push(Bytes::from_static(b"head"));
740 body.push_spilled(&file, a, 200);
741 body.push_spilled(&file, b, 300);
742 #[cfg(unix)]
743 assert_eq!(
744 std::fs::read_dir(dir.path()).unwrap().count(),
745 0,
746 "a spill file in use has no name, so a killed process leaves nothing"
747 );
748 let store = InMemory::new();
749 let path = Path::from("ns/segments/1-2/data.bin");
750 write(&store, &path, body, &small(), &REFUSAL)
751 .await
752 .unwrap();
753 let stored = store.get(&path).await.unwrap().bytes().await.unwrap();
754 assert_eq!(&stored[..4], b"head");
755 assert_eq!(&stored[4..], &data[..]);
756 drop(file);
757 let left = std::fs::read_dir(dir.path())
758 .map(|d| d.count())
759 .unwrap_or_default();
760 assert_eq!(
761 left, 0,
762 "a spill file has no name once dropped, or none at all"
763 );
764 }
765
766 #[tokio::test]
767 async fn an_identical_object_at_the_key_is_reused_and_another_is_refused() {
768 let store = InMemory::new();
769 let path = Path::from("ns/segments/1-2/data.bin");
770 let data = bytes(1000, 1);
771 store.put(&path, data.clone().into()).await.unwrap();
772 write(&store, &path, body_of(&[&data]), &small(), &REFUSAL)
773 .await
774 .unwrap();
775 let other = bytes(1000, 2);
776 let err = write(&store, &path, body_of(&[&other]), &small(), &REFUSAL)
777 .await
778 .unwrap_err();
779 assert!(matches!(err, ItzmaError::CorruptSegment { .. }), "{err:?}");
780 assert_eq!(listing(&store).await, ["ns/segments/1-2/data.bin"]);
781 let stored = store.get(&path).await.unwrap().bytes().await.unwrap();
782 assert_eq!(stored.as_ref(), &data[..], "nothing overwritten");
783 }
784
785 #[tokio::test]
786 async fn a_small_body_is_one_put() {
787 let store = InMemory::new();
788 let path = Path::from("ns/segments/1-2/data.bin");
789 let mut payload = PutPayloadMut::new();
790 payload.extend_from_slice(b"small");
791 let body = Body::from(payload.freeze());
792 write(&store, &path, body, &small(), &REFUSAL)
793 .await
794 .unwrap();
795 assert_eq!(
796 store
797 .get(&path)
798 .await
799 .unwrap()
800 .bytes()
801 .await
802 .unwrap()
803 .as_ref(),
804 b"small"
805 );
806 }
807
808 #[derive(Debug, Default)]
812 struct TestStore {
813 inner: InMemory,
814 no_copy: bool,
815 parts: Arc<Mutex<Vec<usize>>>,
816 starts: AtomicU64,
817 }
818
819 #[derive(Debug)]
820 struct Recorded {
821 inner: Box<dyn MultipartUpload>,
822 parts: Arc<Mutex<Vec<usize>>>,
823 }
824
825 #[async_trait::async_trait]
826 impl MultipartUpload for Recorded {
827 fn put_part(&mut self, data: PutPayload) -> object_store::UploadPart {
828 self.parts.lock().unwrap().push(data.content_length());
829 self.inner.put_part(data)
830 }
831
832 async fn complete(&mut self) -> object_store::Result<object_store::PutResult> {
833 self.inner.complete().await
834 }
835
836 async fn abort(&mut self) -> object_store::Result<()> {
837 self.inner.abort().await
838 }
839 }
840
841 impl std::fmt::Display for TestStore {
842 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
843 write!(f, "TestStore")
844 }
845 }
846
847 #[async_trait::async_trait]
848 impl ObjectStore for TestStore {
849 async fn put_opts(
850 &self,
851 location: &Path,
852 payload: PutPayload,
853 opts: PutOptions,
854 ) -> object_store::Result<object_store::PutResult> {
855 self.inner.put_opts(location, payload, opts).await
856 }
857
858 async fn put_multipart_opts(
859 &self,
860 location: &Path,
861 opts: object_store::PutMultipartOptions,
862 ) -> object_store::Result<Box<dyn MultipartUpload>> {
863 self.starts.fetch_add(1, Ordering::SeqCst);
864 Ok(Box::new(Recorded {
865 inner: self.inner.put_multipart_opts(location, opts).await?,
866 parts: self.parts.clone(),
867 }))
868 }
869
870 async fn get_opts(
871 &self,
872 location: &Path,
873 options: object_store::GetOptions,
874 ) -> object_store::Result<object_store::GetResult> {
875 self.inner.get_opts(location, options).await
876 }
877
878 fn delete_stream(
879 &self,
880 locations: futures::stream::BoxStream<'static, object_store::Result<Path>>,
881 ) -> futures::stream::BoxStream<'static, object_store::Result<Path>> {
882 self.inner.delete_stream(locations)
883 }
884
885 fn list(
886 &self,
887 prefix: Option<&Path>,
888 ) -> futures::stream::BoxStream<'static, object_store::Result<object_store::ObjectMeta>>
889 {
890 self.inner.list(prefix)
891 }
892
893 async fn list_with_delimiter(
894 &self,
895 prefix: Option<&Path>,
896 ) -> object_store::Result<object_store::ListResult> {
897 self.inner.list_with_delimiter(prefix).await
898 }
899
900 async fn copy_opts(
901 &self,
902 from: &Path,
903 to: &Path,
904 options: CopyOptions,
905 ) -> object_store::Result<()> {
906 match options.mode {
907 CopyMode::Create if self.no_copy => Err(object_store::Error::NotSupported {
908 source: "no conditional copy".into(),
909 }),
910 _ => self.inner.copy_opts(from, to, options).await,
911 }
912 }
913 }
914
915 #[tokio::test]
918 async fn parts_are_cut_at_part_size_across_pieces() {
919 let store = TestStore::default();
920 let data = bytes(1000, 4);
921 let body = body_of(&[&data[..3], &data[3..500], &data[500..501], &data[501..]]);
922 let path = Path::from("ns/segments/1-2/data.bin");
923 write(&store, &path, body, &small(), &REFUSAL)
924 .await
925 .unwrap();
926 let parts = store.parts.lock().unwrap().clone();
927 let (last, middle) = parts.split_last().unwrap();
928 assert!(middle.iter().all(|&n| n == 64), "{parts:?}");
929 assert_eq!(middle.len() * 64 + last, 1000);
930 assert_eq!(
931 store
932 .inner
933 .get(&path)
934 .await
935 .unwrap()
936 .bytes()
937 .await
938 .unwrap()
939 .as_ref(),
940 &data[..]
941 );
942 }
943
944 #[tokio::test]
948 async fn without_a_conditional_copy_a_body_falls_back_or_fails() {
949 let store = TestStore {
950 no_copy: true,
951 ..TestStore::default()
952 };
953 let path = Path::from("ns/segments/1-2/data.bin");
954 let data = bytes(1000, 5);
955 let uploader = Uploader::new(UploadOptions {
956 fallback_max: 1000,
957 ..small().options
958 });
959 write(&store, &path, body_of(&[&data]), &uploader, &REFUSAL)
960 .await
961 .unwrap();
962 assert_eq!(
963 store
964 .inner
965 .get(&path)
966 .await
967 .unwrap()
968 .bytes()
969 .await
970 .unwrap()
971 .as_ref(),
972 &data[..]
973 );
974 assert_eq!(store.starts.load(Ordering::SeqCst), 1);
975 let other = Path::from("ns/segments/3-4/data.bin");
976 let err = write(
977 &store,
978 &other,
979 body_of(&[&bytes(1001, 6)]),
980 &uploader,
981 &REFUSAL,
982 )
983 .await
984 .unwrap_err();
985 assert!(
986 matches!(
987 err,
988 ItzmaError::Storage(object_store::Error::NotSupported { .. })
989 ),
990 "{err:?}"
991 );
992 let third = Path::from("ns/segments/5-6/data.bin");
993 write(
994 &store,
995 &third,
996 body_of(&[&bytes(900, 7)]),
997 &uploader,
998 &REFUSAL,
999 )
1000 .await
1001 .unwrap();
1002 assert_eq!(
1003 store.starts.load(Ordering::SeqCst),
1004 1,
1005 "no upload staged again"
1006 );
1007 assert_eq!(
1008 listing(&store.inner).await,
1009 ["ns/segments/1-2/data.bin", "ns/segments/5-6/data.bin"]
1010 );
1011 }
1012
1013 #[test]
1016 fn a_streamed_write_runs_on_any_executor() {
1017 let store = InMemory::new();
1018 let path = Path::from("ns/segments/1-2/data.bin");
1019 let data = bytes(1000, 8);
1020 futures::executor::block_on(write(&store, &path, body_of(&[&data]), &small(), &REFUSAL))
1021 .unwrap();
1022 let stored = futures::executor::block_on(async {
1023 store.get(&path).await.unwrap().bytes().await.unwrap()
1024 });
1025 assert_eq!(stored.as_ref(), &data[..]);
1026 }
1027
1028 #[test]
1029 fn staging_names_are_unique_and_recognised() {
1030 let path = Path::from("ns/segments/1-2/data.bin");
1031 let (a, b) = (staging_path(&path), staging_path(&path));
1032 assert_ne!(a, b);
1033 assert!(a.as_ref().starts_with("ns/segments/1-2/staging-"));
1034 assert!(is_staging(a.filename().unwrap()));
1035 assert!(!is_staging("data.bin"));
1036 }
1037
1038 #[test]
1039 fn a_part_under_s3s_minimum_or_zero_concurrency_is_refused() {
1040 assert!(UploadOptions::default().part_size(0).validate().is_err());
1041 let under = UploadOptions::default().part_size(MIN_PART_SIZE - 1);
1042 assert!(under.validate().is_err());
1043 UploadOptions::default()
1044 .part_size(MIN_PART_SIZE)
1045 .validate()
1046 .unwrap();
1047 assert!(UploadOptions::default().concurrency(0).validate().is_err());
1048 UploadOptions::default().validate().unwrap();
1049 }
1050}