itzma-core 0.4.0

Vector search on object storage: an embedded library, no server, just your bucket
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
//! Put-if-absent writes of objects too large for one PUT.
//!
//! `object_store`'s multipart upload takes no put-if-absent, so a large
//! object goes up in parts to a staging key in its own directory,
//! `staging-<nonce>.bin`, with no condition, and is then copied to its key
//! with `CopyMode::Create`, which fails when an object is already there. On
//! S3 the copy runs inside the service. An object already at the key must
//! hold the same bytes, compared a piece at a time; the staging
//! object is deleted either way, and one left by a stopped run is `gc`'s.
//! Below [`UploadOptions::stream_above`] an object is one PUT, as before.
//!
//! An object's bytes are a [`Body`]: pieces in memory, or in a spill file a
//! [`Spill`] made, read back a part at a time, so a large segment is never
//! held whole.

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};

/// The default [`UploadOptions::stream_above`]: 64 MiB.
pub const DEFAULT_STREAM_ABOVE: u64 = 64 * 1024 * 1024;
/// The default [`UploadOptions::part_size`]: 8 MiB. S3 needs at least 5 MiB
/// in every part but the last.
pub const DEFAULT_PART_SIZE: usize = 8 * 1024 * 1024;
/// The smallest [`UploadOptions::part_size`]: 5 MiB, S3's smallest part.
pub const MIN_PART_SIZE: usize = 5 * 1024 * 1024;
/// The default [`UploadOptions::concurrency`].
pub const DEFAULT_UPLOAD_CONCURRENCY: usize = 4;
/// The default [`UploadOptions::fallback_max`]: 256 MiB.
pub const DEFAULT_FALLBACK_MAX: u64 = 256 * 1024 * 1024;

/// The bytes compared per read when an object is already at the key.
const COMPARE_PIECE: u64 = 8 * 1024 * 1024;

/// How a handle writes segments and their sidecars, set with
/// [`Namespace::with_upload_options`](crate::Namespace::with_upload_options).
///
/// An object over `stream_above` goes up in parts of `part_size`,
/// `concurrency` at a time, to a staging key, then is copied to its key with
/// put-if-absent. That copy needs a store that supports
/// `CopyMode::Create`: `InMemory`, `LocalFileSystem`, itzma's GCS, Azure
/// and AWS adapters, and `object_store`'s S3 client only when built with
/// `S3CopyIfNotExists::Multipart`. On a store that answers `NotSupported`
/// an object up to `fallback_max` is written with one PUT instead, and a
/// larger one fails with the store's error. The handle remembers a
/// `NotSupported` and stages nothing after it. itzma's Azure adapter copies
/// by reading the staging object back and writing it in one request, so on
/// Azure a streamed segment is held whole while it is copied.
///
/// A merge whose output is expected over `stream_above` writes its sections
/// to files under `spill_dir` (default: `itzma-<pid>` in the system temp
/// directory) as they fill, so it holds about a part per section in memory;
/// the files are deleted when the merge is done or fails.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct UploadOptions {
    /// Objects larger than this many bytes are streamed. Default 64 MiB.
    pub stream_above: u64,
    /// Bytes per uploaded part. Default 8 MiB; S3 needs at least 5 MiB.
    pub part_size: usize,
    /// Parts in flight at once. Default 4.
    pub concurrency: usize,
    /// The largest object written with one PUT when the store cannot copy
    /// with put-if-absent. Default 256 MiB.
    pub fallback_max: u64,
    /// Where a merge's spill files go. Default `None`: a `itzma-<pid>`
    /// directory under the system temp directory.
    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 {
    /// Set [`stream_above`](Self::stream_above).
    pub fn stream_above(mut self, bytes: u64) -> Self {
        self.stream_above = bytes;
        self
    }

    /// Set [`part_size`](Self::part_size).
    pub fn part_size(mut self, bytes: usize) -> Self {
        self.part_size = bytes;
        self
    }

    /// Set [`concurrency`](Self::concurrency).
    pub fn concurrency(mut self, parts: usize) -> Self {
        self.concurrency = parts;
        self
    }

    /// Set [`fallback_max`](Self::fallback_max).
    pub fn fallback_max(mut self, bytes: u64) -> Self {
        self.fallback_max = bytes;
        self
    }

    /// Set [`spill_dir`](Self::spill_dir).
    pub fn spill_dir(mut self, dir: Option<PathBuf>) -> Self {
        self.spill_dir = dir;
        self
    }

    /// Check the settings.
    ///
    /// # Errors
    ///
    /// [`ItzmaError::InvalidConfig`] for a `part_size` under
    /// [`MIN_PART_SIZE`] (S3 refuses a multipart upload with a smaller part
    /// but the last, and only at completion, after every part was sent) or
    /// a `concurrency` of zero.
    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(())
    }

    /// The spill directory for this process, made by [`Spill::new`].
    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 }
    }
}

/// An object's bytes, in file order: pieces in memory or in spill files.
#[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,
            });
        }
    }

    /// Bytes in all.
    pub(crate) fn len(&self) -> u64 {
        self.len
    }

    /// The body cut into spans of at most `size` bytes, in order: what
    /// reading it a part at a time visits. Each span owns what it reads, so
    /// it can be read on the pool.
    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
    }

    /// The body as a payload, when every piece is in memory (a writer that
    /// was never given a spill).
    ///
    /// # Errors
    ///
    /// [`ItzmaError::CorruptSegment`] for a body with a spilled piece.
    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())
    }

    /// Whether any piece is in a spill file.
    #[cfg(test)]
    pub(crate) fn spilled(&self) -> bool {
        self.pieces
            .iter()
            .any(|p| matches!(p, Piece::Spilled { .. }))
    }

    /// The whole body in memory, for one PUT.
    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
    }
}

/// Part of a [`Body`], owning what it reads.
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,
        }
    }

    /// The span's bytes, read from its spill file if it is in one.
    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,
        }
    }
}

/// Where spill files go: one directory per process.
#[derive(Debug, Clone)]
pub(crate) struct Spill {
    dir: PathBuf,
}

impl Spill {
    /// A new, empty spill file, deleted when the last handle to it drops.
    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)?;
        // On Unix the name goes at once and the open handle keeps the file,
        // so a process killed mid-merge leaves nothing on disk. Elsewhere
        // the file is removed when dropped, and one a killed process left
        // stays in its `itzma-<pid>` directory.
        #[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),
        }))
    }
}

/// One spill file, appended to while a section is written and read back
/// while it is uploaded. Removed when dropped.
pub(crate) struct SpillFile {
    /// The file's name while it has one: on Unix it is removed at once.
    path: Option<PathBuf>,
    file: Mutex<std::fs::File>,
    len: AtomicU64,
}

impl SpillFile {
    /// Append `bytes` and return the offset they start at.
    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);
        }
    }
}

/// The compute pool's cost for `len` bytes.
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(),
    })
}

/// What [`write`] says about an object at its key.
pub(crate) struct Refusal {
    /// The error for a key whose object vanished while it was compared.
    pub(crate) missing: fn(&Path) -> ItzmaError,
    /// The `CorruptSegment` reason for an object that differs.
    pub(crate) differs: &'static str,
}

/// A handle's upload settings and what it has learnt about its store: once
/// the store has answered `NotSupported` to a conditional copy, later writes
/// skip the staged upload they would only throw away.
#[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),
        }
    }
}

/// Write `body` at `path` with put-if-absent, or find it already there
/// byte for byte. Streams through a staging
/// key when `body` is over `stream_above` (see the module docs).
///
/// # Errors
///
/// [`ItzmaError::CorruptSegment`] with `refusal.differs` when another object
/// is at the key, `refusal.missing` when the object at the key vanished while
/// it was compared, the store's `NotSupported` for a body over
/// `fallback_max` on a store without a conditional copy, and the store's
/// other errors.
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(),
    })
}

/// One PUT with put-if-absent, or the same bytes already at the key.
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()),
    }
}

/// An object is already at `path`: the same bytes or nothing.
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()),
    }
}

/// Upload `body` to `staging` in parts of exactly `part_size` bytes but
/// the last, at most `concurrency` in flight. The
/// parts are sent here, not through `object_store`'s `WriteMultipart`,
/// which spawns them on a Tokio runtime the caller may not have. A failed
/// upload is aborted.
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(())
}

/// `staging-<nonce>.bin` beside `path`: the process id, a nanosecond time
/// and a per-process counter, unique per attempt without randomness.
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}"))
}

/// Whether a file name in a segment directory is a staging object.
pub(crate) fn is_staging(name: &str) -> bool {
    name.starts_with("staging-") && name.ends_with(".bin")
}

/// Whether the object at `path` holds exactly `body`'s bytes, compared a
/// piece at a time.
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
    }

    /// Tiny parts, which only stores without S3's minimum take: built
    /// directly, since `validate` refuses them.
    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"
        );
    }

    /// `InMemory` that records each part it is sent and how many uploads
    /// were started, and with `copy: false` cannot copy with put-if-absent,
    /// as `object_store`'s S3 client without `S3CopyIfNotExists`.
    #[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,
            }
        }
    }

    /// Parts are exactly `part_size` but the last, whatever the pieces'
    /// boundaries: S3 refuses a smaller one in the middle.
    #[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[..]
        );
    }

    /// Without a conditional copy, a body up to `fallback_max` is one PUT
    /// and a larger one fails; neither leaves a staging object behind, and
    /// once the store has said so no later write stages an upload.
    #[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"]
        );
    }

    /// A streamed write needs no Tokio runtime: the parts are sent from the
    /// caller's own future.
    #[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();
    }
}