Skip to main content

itzma_core/
put.rs

1//! Put-if-absent writes of objects too large for one PUT.
2//!
3//! `object_store`'s multipart upload takes no put-if-absent, so a large
4//! object goes up in parts to a staging key in its own directory,
5//! `staging-<nonce>.bin`, with no condition, and is then copied to its key
6//! with `CopyMode::Create`, which fails when an object is already there. On
7//! S3 the copy runs inside the service. An object already at the key must
8//! hold the same bytes, compared a piece at a time; the staging
9//! object is deleted either way, and one left by a stopped run is `gc`'s.
10//! Below [`UploadOptions::stream_above`] an object is one PUT, as before.
11//!
12//! An object's bytes are a [`Body`]: pieces in memory, or in a spill file a
13//! [`Spill`] made, read back a part at a time, so a large segment is never
14//! held whole.
15
16use 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
34/// The default [`UploadOptions::stream_above`]: 64 MiB.
35pub const DEFAULT_STREAM_ABOVE: u64 = 64 * 1024 * 1024;
36/// The default [`UploadOptions::part_size`]: 8 MiB. S3 needs at least 5 MiB
37/// in every part but the last.
38pub const DEFAULT_PART_SIZE: usize = 8 * 1024 * 1024;
39/// The smallest [`UploadOptions::part_size`]: 5 MiB, S3's smallest part.
40pub const MIN_PART_SIZE: usize = 5 * 1024 * 1024;
41/// The default [`UploadOptions::concurrency`].
42pub const DEFAULT_UPLOAD_CONCURRENCY: usize = 4;
43/// The default [`UploadOptions::fallback_max`]: 256 MiB.
44pub const DEFAULT_FALLBACK_MAX: u64 = 256 * 1024 * 1024;
45
46/// The bytes compared per read when an object is already at the key.
47const COMPARE_PIECE: u64 = 8 * 1024 * 1024;
48
49/// How a handle writes segments and their sidecars, set with
50/// [`Namespace::with_upload_options`](crate::Namespace::with_upload_options).
51///
52/// An object over `stream_above` goes up in parts of `part_size`,
53/// `concurrency` at a time, to a staging key, then is copied to its key with
54/// put-if-absent. That copy needs a store that supports
55/// `CopyMode::Create`: `InMemory`, `LocalFileSystem`, itzma's GCS, Azure
56/// and AWS adapters, and `object_store`'s S3 client only when built with
57/// `S3CopyIfNotExists::Multipart`. On a store that answers `NotSupported`
58/// an object up to `fallback_max` is written with one PUT instead, and a
59/// larger one fails with the store's error. The handle remembers a
60/// `NotSupported` and stages nothing after it. itzma's Azure adapter copies
61/// by reading the staging object back and writing it in one request, so on
62/// Azure a streamed segment is held whole while it is copied.
63///
64/// A merge whose output is expected over `stream_above` writes its sections
65/// to files under `spill_dir` (default: `itzma-<pid>` in the system temp
66/// directory) as they fill, so it holds about a part per section in memory;
67/// the files are deleted when the merge is done or fails.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(default)]
70#[non_exhaustive]
71pub struct UploadOptions {
72    /// Objects larger than this many bytes are streamed. Default 64 MiB.
73    pub stream_above: u64,
74    /// Bytes per uploaded part. Default 8 MiB; S3 needs at least 5 MiB.
75    pub part_size: usize,
76    /// Parts in flight at once. Default 4.
77    pub concurrency: usize,
78    /// The largest object written with one PUT when the store cannot copy
79    /// with put-if-absent. Default 256 MiB.
80    pub fallback_max: u64,
81    /// Where a merge's spill files go. Default `None`: a `itzma-<pid>`
82    /// directory under the system temp directory.
83    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    /// Set [`stream_above`](Self::stream_above).
100    pub fn stream_above(mut self, bytes: u64) -> Self {
101        self.stream_above = bytes;
102        self
103    }
104
105    /// Set [`part_size`](Self::part_size).
106    pub fn part_size(mut self, bytes: usize) -> Self {
107        self.part_size = bytes;
108        self
109    }
110
111    /// Set [`concurrency`](Self::concurrency).
112    pub fn concurrency(mut self, parts: usize) -> Self {
113        self.concurrency = parts;
114        self
115    }
116
117    /// Set [`fallback_max`](Self::fallback_max).
118    pub fn fallback_max(mut self, bytes: u64) -> Self {
119        self.fallback_max = bytes;
120        self
121    }
122
123    /// Set [`spill_dir`](Self::spill_dir).
124    pub fn spill_dir(mut self, dir: Option<PathBuf>) -> Self {
125        self.spill_dir = dir;
126        self
127    }
128
129    /// Check the settings.
130    ///
131    /// # Errors
132    ///
133    /// [`ItzmaError::InvalidConfig`] for a `part_size` under
134    /// [`MIN_PART_SIZE`] (S3 refuses a multipart upload with a smaller part
135    /// but the last, and only at completion, after every part was sent) or
136    /// a `concurrency` of zero.
137    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    /// The spill directory for this process, made by [`Spill::new`].
152    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/// An object's bytes, in file order: pieces in memory or in spill files.
162#[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    /// Bytes in all.
197    pub(crate) fn len(&self) -> u64 {
198        self.len
199    }
200
201    /// The body cut into spans of at most `size` bytes, in order: what
202    /// reading it a part at a time visits. Each span owns what it reads, so
203    /// it can be read on the pool.
204    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    /// The body as a payload, when every piece is in memory (a writer that
229    /// was never given a spill).
230    ///
231    /// # Errors
232    ///
233    /// [`ItzmaError::CorruptSegment`] for a body with a spilled piece.
234    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    /// Whether any piece is in a spill file.
249    #[cfg(test)]
250    pub(crate) fn spilled(&self) -> bool {
251        self.pieces
252            .iter()
253            .any(|p| matches!(p, Piece::Spilled { .. }))
254    }
255
256    /// The whole body in memory, for one PUT.
257    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
291/// Part of a [`Body`], owning what it reads.
292enum 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    /// The span's bytes, read from its spill file if it is in one.
310    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/// Where spill files go: one directory per process.
328#[derive(Debug, Clone)]
329pub(crate) struct Spill {
330    dir: PathBuf,
331}
332
333impl Spill {
334    /// A new, empty spill file, deleted when the last handle to it drops.
335    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        // On Unix the name goes at once and the open handle keeps the file,
350        // so a process killed mid-merge leaves nothing on disk. Elsewhere
351        // the file is removed when dropped, and one a killed process left
352        // stays in its `itzma-<pid>` directory.
353        #[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
368/// One spill file, appended to while a section is written and read back
369/// while it is uploaded. Removed when dropped.
370pub(crate) struct SpillFile {
371    /// The file's name while it has one: on Unix it is removed at once.
372    path: Option<PathBuf>,
373    file: Mutex<std::fs::File>,
374    len: AtomicU64,
375}
376
377impl SpillFile {
378    /// Append `bytes` and return the offset they start at.
379    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
406/// The compute pool's cost for `len` bytes.
407fn 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
418/// What [`write`] says about an object at its key.
419pub(crate) struct Refusal {
420    /// The error for a key whose object vanished while it was compared.
421    pub(crate) missing: fn(&Path) -> ItzmaError,
422    /// The `CorruptSegment` reason for an object that differs.
423    pub(crate) differs: &'static str,
424}
425
426/// A handle's upload settings and what it has learnt about its store: once
427/// the store has answered `NotSupported` to a conditional copy, later writes
428/// skip the staged upload they would only throw away.
429#[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
444/// Write `body` at `path` with put-if-absent, or find it already there
445/// byte for byte. Streams through a staging
446/// key when `body` is over `stream_above` (see the module docs).
447///
448/// # Errors
449///
450/// [`ItzmaError::CorruptSegment`] with `refusal.differs` when another object
451/// is at the key, `refusal.missing` when the object at the key vanished while
452/// it was compared, the store's `NotSupported` for a body over
453/// `fallback_max` on a store without a conditional copy, and the store's
454/// other errors.
455pub(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
513/// One PUT with put-if-absent, or the same bytes already at the key.
514async 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
533/// An object is already at `path`: the same bytes or nothing.
534async 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
551/// Upload `body` to `staging` in parts of exactly `part_size` bytes but
552/// the last, at most `concurrency` in flight. The
553/// parts are sent here, not through `object_store`'s `WriteMultipart`,
554/// which spawns them on a Tokio runtime the caller may not have. A failed
555/// upload is aborted.
556async 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
615/// `staging-<nonce>.bin` beside `path`: the process id, a nanosecond time
616/// and a per-process counter, unique per attempt without randomness.
617fn 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
631/// Whether a file name in a segment directory is a staging object.
632pub(crate) fn is_staging(name: &str) -> bool {
633    name.starts_with("staging-") && name.ends_with(".bin")
634}
635
636/// Whether the object at `path` holds exactly `body`'s bytes, compared a
637/// piece at a time.
638async 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    /// Tiny parts, which only stores without S3's minimum take: built
689    /// directly, since `validate` refuses them.
690    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    /// `InMemory` that records each part it is sent and how many uploads
809    /// were started, and with `copy: false` cannot copy with put-if-absent,
810    /// as `object_store`'s S3 client without `S3CopyIfNotExists`.
811    #[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    /// Parts are exactly `part_size` but the last, whatever the pieces'
916    /// boundaries: S3 refuses a smaller one in the middle.
917    #[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    /// Without a conditional copy, a body up to `fallback_max` is one PUT
945    /// and a larger one fails; neither leaves a staging object behind, and
946    /// once the store has said so no later write stages an upload.
947    #[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    /// A streamed write needs no Tokio runtime: the parts are sent from the
1014    /// caller's own future.
1015    #[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}