aws-s3-transfer 1.0.0

Transfer Manager for Amazon S3 - a high-performance data plane client for uploading and downloading objects and directories.
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
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! HTTP body implementations for file-backed `PutObject` uploads.
//!
//! [`FileBodySource`] opens the file once before the retryable SDK body is
//! constructed. Every attempt clones that same file identity and the client's
//! shared memory pool.
//!
//! [`DirectFileBody`] performs positioned reads on a managed polling thread.
//! [`OffloadedFileBody`] submits reads through the transfer runtime's blocking
//! pool and a bounded channel when HTTP polling ownership is unknown. Both emit
//! owner-backed `Bytes` frames from pooled chunks and reacquire storage for each
//! retry attempt.

use std::fs::File;
use std::future::poll_fn;
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use bytes::Bytes;
use http_body_1x::{Body, Frame, SizeHint};
use tokio::sync::mpsc;

use crate::io::fs::read_exact_at;
use crate::io::PartBuffer;
use crate::memory::{BufferPool, SegmentedBytes};

/// Byte count per chunk yielded as an [`http_body_1x::Frame`].
///
/// Bounds peak memory for arbitrarily large PutObject bodies independent of
/// the configured MPU threshold. A user could configure
/// [`Config::multipart_threshold`](crate::Config) above S3's single-PUT
/// limit (5 GB); without chunking, the body would buffer the entire payload.
pub(crate) const FILE_BODY_CHUNK_SIZE: usize = 1024 * 1024;

/// Channel capacity for [`OffloadedFileBody`]. Bounds the number of chunks
/// the reader task may stage ahead of the HTTP layer. Pool accounting remains
/// authoritative when body frames are retained downstream.
const FILE_BODY_READAHEAD: usize = 4;

/// Stable file identity and memory domain shared by all body attempts.
#[derive(Clone, Debug)]
pub(crate) struct FileBodySource {
    file: Arc<File>,
    pool: BufferPool,
}

impl FileBodySource {
    /// Wraps the opened `file` for use by every SDK and transfer-manager retry.
    pub(crate) fn new(file: File, pool: BufferPool) -> Self {
        Self {
            file: Arc::new(file),
            pool,
        }
    }
}

/// Payload bytes not yet emitted by a file body.
#[derive(Debug)]
struct FileBodyProgress {
    pending: SegmentedBytes,
    remaining: u64,
}

impl FileBodyProgress {
    fn new(length: u64) -> Self {
        Self {
            pending: SegmentedBytes::from(Bytes::new()),
            remaining: length,
        }
    }

    /// Makes one completed pooled chunk available to the HTTP layer.
    fn publish(&mut self, data: SegmentedBytes) -> io::Result<()> {
        if !self.pending.is_empty() {
            return Err(io::Error::other(
                "file body replaced bytes that had not been emitted",
            ));
        }

        let count = data.len() as u64;
        if count == 0 && self.remaining != 0 {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "file body produced no bytes before its declared length",
            ));
        }
        if count > self.remaining {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "file body produced more bytes than its declared length",
            ));
        }

        self.pending = data;
        Ok(())
    }

    /// Removes the next presentation segment and records it as emitted.
    fn take_frame(&mut self) -> Option<Frame<Bytes>> {
        let bytes = self.pending.take_front_segment()?;
        self.remaining = self
            .remaining
            .checked_sub(bytes.len() as u64)
            .expect("published file body segment exceeded its remaining length");
        Some(Frame::data(bytes))
    }

    /// Releases retained bytes and makes an error terminal for this body.
    fn terminate(&mut self) {
        self.pending = SegmentedBytes::from(Bytes::new());
        self.remaining = 0;
    }

    fn size_hint(&self) -> SizeHint {
        SizeHint::with_exact(self.remaining)
    }

    fn is_end_stream(&self) -> bool {
        self.remaining == 0
    }
}

/// File-backed HTTP body for callers on a managed thread with direct I/O.
///
/// Pool admission may return `Poll::Pending`. Once storage is available,
/// `poll_frame` reads the next chunk synchronously. This body is valid only
/// when the transfer manager owns the polling thread.
///
/// Each retry starts at `offset` but retains the same [`FileBodySource`].
#[derive(Debug)]
pub(crate) struct DirectFileBody {
    source: FileBodySource,
    /// Absolute byte offset of the next read.
    offset: u64,
    /// Bytes not yet read from the file.
    unread: u64,
    /// Read bytes not yet emitted by the body.
    progress: FileBodyProgress,
    /// Admission or mutable storage for the next chunk.
    buffer: Option<PartBuffer>,
}

impl DirectFileBody {
    pub(crate) fn new(source: FileBodySource, offset: u64, length: u64) -> Self {
        Self {
            source,
            offset,
            unread: length,
            progress: FileBodyProgress::new(length),
            buffer: None,
        }
    }
}

impl Body for DirectFileBody {
    type Data = Bytes;
    type Error = io::Error;

    fn poll_frame(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, io::Error>>> {
        let this = self.get_mut();
        loop {
            if let Some(frame) = this.progress.take_frame() {
                return Poll::Ready(Some(Ok(frame)));
            }
            if this.unread == 0 {
                if this.progress.is_end_stream() {
                    return Poll::Ready(None);
                }
                this.progress.terminate();
                return Poll::Ready(Some(Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "file body ended before its declared length",
                ))));
            }

            let to_read = (this.unread as usize).min(FILE_BODY_CHUNK_SIZE);
            let buffer = this
                .buffer
                .get_or_insert_with(|| PartBuffer::new(&this.source.pool, to_read));
            match buffer.poll_acquire(cx, to_read) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(Ok(())) => {}
                Poll::Ready(Err(error)) => {
                    this.unread = 0;
                    this.progress.terminate();
                    this.buffer = None;
                    return Poll::Ready(Some(Err(error)));
                }
            }

            if let Err(error) = read_exact_at(&this.source.file, buffer, this.offset) {
                this.unread = 0;
                this.progress.terminate();
                this.buffer = None;
                return Poll::Ready(Some(Err(error)));
            }

            let data = this
                .buffer
                .take()
                .expect("completed direct file read lost its buffer")
                .freeze();
            this.offset += to_read as u64;
            this.unread -= to_read as u64;
            if let Err(error) = this.progress.publish(data) {
                this.unread = 0;
                this.progress.terminate();
                return Poll::Ready(Some(Err(error)));
            }
        }
    }

    fn size_hint(&self) -> SizeHint {
        self.progress.size_hint()
    }

    fn is_end_stream(&self) -> bool {
        self.progress.is_end_stream()
    }
}

/// File-backed HTTP body with reads offloaded through the transfer runtime.
///
/// A reader task on `reader_runtime` acquires pooled chunks and reads them via
/// that runtime's `spawn_blocking` pool, then publishes them through a bounded
/// channel. Body polling requires no Tokio context.
/// `poll_frame` drains the channel with ordinary waker registration.
///
/// The reader task is spawned lazily on the first `poll_frame` call. Dropping
/// the body aborts admission or channel waits. An in-flight `spawn_blocking`
/// read cannot be cancelled, so it retains its buffer until the operating
/// system call completes.
pub(crate) struct OffloadedFileBody {
    reader_runtime: tokio::runtime::Handle,
    state: OffloadedState,
    /// Received bytes not yet emitted by the body.
    progress: FileBodyProgress,
}

enum OffloadedState {
    /// Reader task not yet spawned.
    Pending { source: FileBodySource, offset: u64 },
    /// Reader task streaming chunks through `rx`.
    Active {
        rx: mpsc::Receiver<io::Result<SegmentedBytes>>,
        task: tokio::task::JoinHandle<()>,
    },
}

impl std::fmt::Debug for OffloadedFileBody {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let state = match &self.state {
            OffloadedState::Pending { .. } => "pending",
            OffloadedState::Active { .. } => "active",
        };
        f.debug_struct("OffloadedFileBody")
            .field("state", &state)
            .field("progress", &self.progress)
            .finish_non_exhaustive()
    }
}

impl OffloadedFileBody {
    pub(crate) fn new(
        source: FileBodySource,
        offset: u64,
        length: u64,
        reader_runtime: tokio::runtime::Handle,
    ) -> Self {
        Self {
            reader_runtime,
            state: OffloadedState::Pending { source, offset },
            progress: FileBodyProgress::new(length),
        }
    }
}

impl Drop for OffloadedFileBody {
    fn drop(&mut self) {
        if let OffloadedState::Active { task, .. } = &self.state {
            task.abort();
        }
    }
}

impl Body for OffloadedFileBody {
    type Data = Bytes;
    type Error = io::Error;

    fn poll_frame(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, io::Error>>> {
        let this = self.get_mut();
        loop {
            if let Some(frame) = this.progress.take_frame() {
                return Poll::Ready(Some(Ok(frame)));
            }
            if this.progress.is_end_stream() {
                return Poll::Ready(None);
            }
            if let OffloadedState::Pending { source, offset } = &this.state {
                let (tx, rx) = mpsc::channel(FILE_BODY_READAHEAD);
                let task = this.reader_runtime.spawn(read_task(
                    source.clone(),
                    *offset,
                    this.progress.remaining,
                    tx,
                ));
                this.state = OffloadedState::Active { rx, task };
            }

            let rx = match &mut this.state {
                OffloadedState::Active { rx, .. } => rx,
                OffloadedState::Pending { .. } => unreachable!("transitioned above"),
            };
            match rx.poll_recv(cx) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(None) => {
                    this.progress.terminate();
                    return Poll::Ready(Some(Err(io::Error::new(
                        io::ErrorKind::UnexpectedEof,
                        "file reader stopped before the declared body length",
                    ))));
                }
                Poll::Ready(Some(Ok(data))) => {
                    if let Err(error) = this.progress.publish(data) {
                        this.progress.terminate();
                        return Poll::Ready(Some(Err(error)));
                    }
                }
                Poll::Ready(Some(Err(error))) => {
                    this.progress.terminate();
                    return Poll::Ready(Some(Err(error)));
                }
            }
        }
    }

    fn size_hint(&self) -> SizeHint {
        self.progress.size_hint()
    }

    fn is_end_stream(&self) -> bool {
        self.progress.is_end_stream()
    }
}

/// Acquires, fills, and publishes bounded chunks for [`OffloadedFileBody`].
async fn read_task(
    source: FileBodySource,
    start_offset: u64,
    length: u64,
    tx: mpsc::Sender<io::Result<SegmentedBytes>>,
) {
    let mut offset = start_offset;
    let mut remaining = length;

    while remaining > 0 {
        let to_read = (remaining as usize).min(FILE_BODY_CHUNK_SIZE);
        let read_offset = offset;
        let mut buffer = PartBuffer::new(&source.pool, to_read);
        if let Err(error) = poll_fn(|cx| buffer.poll_acquire(cx, to_read)).await {
            let _ = tx.send(Err(error)).await;
            return;
        }
        let file = Arc::clone(&source.file);

        let read_result = tokio::task::spawn_blocking(move || -> io::Result<SegmentedBytes> {
            read_exact_at(&file, &mut buffer, read_offset)?;
            Ok(buffer.freeze())
        })
        .await;

        match read_result {
            Ok(Ok(data)) => {
                let count = data.len() as u64;
                if tx.send(Ok(data)).await.is_err() {
                    return;
                }
                offset += count;
                remaining -= count;
            }
            Ok(Err(e)) => {
                let _ = tx.send(Err(e)).await;
                return;
            }
            Err(_join_err) => {
                let _ = tx
                    .send(Err(io::Error::other("file read task panicked")))
                    .await;
                return;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::ByteSize;
    use std::fmt::Debug;
    use std::future::poll_fn;
    use std::io::Write;
    use std::path::Path;
    use std::task::Waker;

    use crate::config::MemoryBudgetConfig;
    use crate::io::InputStream;

    const TEST_POOL_CAPACITY: usize = 4 * 1024 * 1024;

    async fn collect_body<B>(mut body: B) -> Result<Vec<u8>, B::Error>
    where
        B: Body<Data = Bytes> + Unpin,
        B::Error: Debug,
    {
        let mut out = Vec::new();
        loop {
            let frame = poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await;
            match frame {
                Some(Ok(frame)) => {
                    if let Ok(data) = frame.into_data() {
                        out.extend_from_slice(&data);
                    }
                }
                Some(Err(e)) => return Err(e),
                None => return Ok(out),
            }
        }
    }

    fn write_tempfile(contents: &[u8]) -> tempfile::NamedTempFile {
        let mut tmp = tempfile::NamedTempFile::new().unwrap();
        tmp.write_all(contents).unwrap();
        tmp.flush().unwrap();
        tmp
    }

    fn test_pool() -> BufferPool {
        BufferPool::builder()
            .memory_budget(MemoryBudgetConfig::Limit(ByteSize::new(
                TEST_POOL_CAPACITY as u64,
            )))
            .build()
            .unwrap()
    }

    fn source(path: &Path, pool: &BufferPool) -> FileBodySource {
        FileBodySource::new(File::open(path).unwrap(), pool.clone())
    }

    fn poll_body_once<B>(body: &mut B) -> Poll<Option<Result<Frame<Bytes>, B::Error>>>
    where
        B: Body<Data = Bytes> + Unpin,
    {
        let waker = Waker::noop();
        let mut cx = Context::from_waker(waker);
        Pin::new(body).poll_frame(&mut cx)
    }

    #[test]
    fn file_body_progress_tracks_unemitted_segments() {
        let mut data = SegmentedBytes::from(Bytes::from_static(b"left"));
        data.append(SegmentedBytes::from(Bytes::from_static(b"right")));
        let mut progress = FileBodyProgress::new(data.len() as u64);

        progress.publish(data).unwrap();
        assert_eq!(progress.size_hint().exact(), Some(9));
        assert_eq!(
            progress.take_frame().unwrap().into_data().unwrap(),
            Bytes::from_static(b"left")
        );
        assert_eq!(progress.size_hint().exact(), Some(5));
        assert!(!progress.is_end_stream());
        assert_eq!(
            progress.take_frame().unwrap().into_data().unwrap(),
            Bytes::from_static(b"right")
        );
        assert_eq!(progress.size_hint().exact(), Some(0));
        assert!(progress.is_end_stream());
    }

    #[test]
    fn file_body_progress_rejects_invalid_publication_lengths() {
        let mut empty = FileBodyProgress::new(1);
        let error = empty
            .publish(SegmentedBytes::from(Bytes::new()))
            .unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);

        let mut oversized = FileBodyProgress::new(1);
        let error = oversized
            .publish(SegmentedBytes::from(Bytes::from_static(b"too long")))
            .unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
    }

    // ---- DirectFileBody ----

    #[test]
    fn direct_body_size_hint_tracks_unemitted_bytes() {
        let size = FILE_BODY_CHUNK_SIZE + 37;
        let payload = vec![0x5a; size];
        let tmp = write_tempfile(&payload);
        let pool = test_pool();
        let mut body = DirectFileBody::new(source(tmp.path(), &pool), 0, size as u64);

        assert_eq!(body.size_hint().exact(), Some(size as u64));
        let frame = match poll_body_once(&mut body) {
            Poll::Ready(Some(Ok(frame))) => frame.into_data().unwrap(),
            result => panic!("expected one body frame, got {result:?}"),
        };
        assert_eq!(
            body.size_hint().exact(),
            Some(size as u64 - frame.len() as u64)
        );
        assert!(!body.is_end_stream());

        drop(frame);
        drop(body);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[cfg_attr(miri, ignore)] // Tokio's I/O driver uses unsupported platform FFI under Miri.
    #[tokio::test]
    async fn direct_body_reads_small_file_single_frame() {
        let payload: Vec<u8> = (0..1024).map(|i| (i % 251) as u8).collect();
        let tmp = write_tempfile(&payload);
        let pool = test_pool();
        let body = DirectFileBody::new(source(tmp.path(), &pool), 0, payload.len() as u64);

        let out = collect_body(body).await.unwrap();
        assert_eq!(out, payload);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[cfg_attr(miri, ignore)] // Tokio's I/O driver uses unsupported platform FFI under Miri.
    #[tokio::test]
    async fn direct_body_chunks_payload_larger_than_chunk_size() {
        // Must span at least 2 chunks.
        let size = FILE_BODY_CHUNK_SIZE + FILE_BODY_CHUNK_SIZE / 4;
        let payload: Vec<u8> = (0..size).map(|i| (i % 251) as u8).collect();
        let tmp = write_tempfile(&payload);
        let pool = test_pool();
        let body = DirectFileBody::new(source(tmp.path(), &pool), 0, size as u64);

        let out = collect_body(body).await.unwrap();
        assert_eq!(out.len(), size);
        assert_eq!(out, payload);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[cfg_attr(miri, ignore)] // Tokio's I/O driver uses unsupported platform FFI under Miri.
    #[tokio::test]
    async fn direct_body_reads_from_offset() {
        let payload: Vec<u8> = (0..4096).map(|i| (i % 251) as u8).collect();
        let tmp = write_tempfile(&payload);
        let offset = 1024;
        let length = 2048;
        let pool = test_pool();
        let body = DirectFileBody::new(source(tmp.path(), &pool), offset, length);

        let out = collect_body(body).await.unwrap();
        assert_eq!(out, &payload[offset as usize..(offset + length) as usize]);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[cfg_attr(miri, ignore)] // The 1 MiB cross-chunk path is prohibitively slow under Miri.
    #[test]
    fn direct_body_does_not_publish_a_partially_read_chunk_after_truncation() {
        let size = FILE_BODY_CHUNK_SIZE + 37;
        let payload: Vec<u8> = (0..size).map(|i| (i % 251) as u8).collect();
        let tmp = write_tempfile(&payload);
        let pool = test_pool();
        let mut body = DirectFileBody::new(source(tmp.path(), &pool), 0, size as u64);

        let first = match poll_body_once(&mut body) {
            Poll::Ready(Some(Ok(frame))) => frame.into_data().unwrap(),
            result => panic!("expected the complete first chunk, got {result:?}"),
        };
        assert_eq!(first.as_ref(), &payload[..FILE_BODY_CHUNK_SIZE]);
        drop(first);
        assert_eq!(pool.metrics().in_use_bytes(), 0);

        tmp.as_file()
            .set_len((FILE_BODY_CHUNK_SIZE + 5) as u64)
            .unwrap();
        let error = match poll_body_once(&mut body) {
            Poll::Ready(Some(Err(error))) => error,
            result => panic!("expected truncation to fail the next chunk, got {result:?}"),
        };

        assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
        assert!(body.is_end_stream());
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[test]
    fn direct_body_frames_retain_pool_ownership() {
        let payload = b"owner-backed body frame";
        let tmp = write_tempfile(payload);
        let pool = test_pool();
        let mut body = DirectFileBody::new(source(tmp.path(), &pool), 0, payload.len() as u64);

        let frame = match poll_body_once(&mut body) {
            Poll::Ready(Some(Ok(frame))) => frame.into_data().unwrap(),
            result => panic!("expected one body frame, got {result:?}"),
        };
        assert_eq!(frame, payload[..]);
        assert_eq!(pool.metrics().in_use_bytes(), pool.carrier_size() as u64);

        drop(frame);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
        assert!(matches!(poll_body_once(&mut body), Poll::Ready(None)));
    }

    #[test]
    fn dropping_direct_body_cancels_queued_admission() {
        let payload = b"blocked direct body";
        let tmp = write_tempfile(payload);
        let pool = test_pool();
        let reservation = pool.try_reserve(TEST_POOL_CAPACITY).unwrap().unwrap();
        let acquisition = pool
            .acquire(&reservation, TEST_POOL_CAPACITY)
            .expect("test pool should be fully available");
        let mut body = DirectFileBody::new(source(tmp.path(), &pool), 0, payload.len() as u64);

        assert!(poll_body_once(&mut body).is_pending());
        assert_eq!(pool.metrics().waiting_requests(), 1);
        drop(body);
        assert_eq!(pool.metrics().waiting_requests(), 0);

        drop(acquisition);
        reservation.close_acquisition();
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    // ---- OffloadedFileBody ----

    #[test]
    fn empty_offloaded_body_finishes_without_spawning_reader() {
        let tmp = write_tempfile(&[]);
        let pool = test_pool();
        let runtime = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        let mut body =
            OffloadedFileBody::new(source(tmp.path(), &pool), 0, 0, runtime.handle().clone());

        assert!(matches!(poll_body_once(&mut body), Poll::Ready(None)));
        assert!(matches!(body.state, OffloadedState::Pending { .. }));
        assert_eq!(pool.metrics().waits_total(), 0);
    }

    #[cfg_attr(miri, ignore)] // Tokio's runtime uses unsupported platform FFI under Miri.
    #[tokio::test]
    async fn offloaded_body_rejects_early_reader_completion() {
        let (tx, rx) = mpsc::channel(1);
        drop(tx);
        let task = tokio::spawn(async {});
        let mut body = OffloadedFileBody {
            reader_runtime: tokio::runtime::Handle::current(),
            state: OffloadedState::Active { rx, task },
            progress: FileBodyProgress::new(1),
        };

        let error = poll_fn(|cx| Pin::new(&mut body).poll_frame(cx))
            .await
            .expect("reader completion should produce a terminal frame")
            .unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
        assert!(body.is_end_stream());
    }

    #[cfg_attr(miri, ignore)] // Tokio's runtime uses unsupported platform FFI under Miri.
    #[tokio::test]
    async fn offloaded_body_propagates_reader_error() {
        let (tx, rx) = mpsc::channel(1);
        tx.send(Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "injected reader error",
        )))
        .await
        .unwrap();
        drop(tx);
        let task = tokio::spawn(async {});
        let mut body = OffloadedFileBody {
            reader_runtime: tokio::runtime::Handle::current(),
            state: OffloadedState::Active { rx, task },
            progress: FileBodyProgress::new(1),
        };

        let error = poll_fn(|cx| Pin::new(&mut body).poll_frame(cx))
            .await
            .expect("reader error should produce a terminal frame")
            .unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
        assert!(body.is_end_stream());
    }

    #[cfg_attr(miri, ignore)] // Tokio's I/O driver uses unsupported platform FFI under Miri.
    #[tokio::test]
    async fn offloaded_body_reads_small_file() {
        let payload: Vec<u8> = (0..1024).map(|i| (i % 251) as u8).collect();
        let tmp = write_tempfile(&payload);
        let pool = test_pool();
        let body = OffloadedFileBody::new(
            source(tmp.path(), &pool),
            0,
            payload.len() as u64,
            tokio::runtime::Handle::current(),
        );

        let out = collect_body(body).await.unwrap();
        assert_eq!(out, payload);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[cfg_attr(miri, ignore)] // Tokio's I/O driver uses unsupported platform FFI under Miri.
    #[tokio::test]
    async fn offloaded_body_chunks_payload_larger_than_chunk_size() {
        let size = FILE_BODY_CHUNK_SIZE * 3 + 512;
        let payload: Vec<u8> = (0..size).map(|i| (i % 251) as u8).collect();
        let tmp = write_tempfile(&payload);
        let pool = test_pool();
        let body = OffloadedFileBody::new(
            source(tmp.path(), &pool),
            0,
            size as u64,
            tokio::runtime::Handle::current(),
        );

        let out = collect_body(body).await.unwrap();
        assert_eq!(out.len(), size);
        assert_eq!(out, payload);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[cfg_attr(miri, ignore)] // Tokio's I/O driver uses unsupported platform FFI under Miri.
    #[tokio::test]
    async fn offloaded_body_reads_from_offset() {
        let payload: Vec<u8> = (0..4096).map(|i| (i % 251) as u8).collect();
        let tmp = write_tempfile(&payload);
        let offset = 1024;
        let length = 2048;
        let pool = test_pool();
        let body = OffloadedFileBody::new(
            source(tmp.path(), &pool),
            offset,
            length,
            tokio::runtime::Handle::current(),
        );

        let out = collect_body(body).await.unwrap();
        assert_eq!(out, &payload[offset as usize..(offset + length) as usize]);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[cfg_attr(miri, ignore)] // Tokio's I/O driver uses unsupported platform FFI under Miri.
    #[tokio::test]
    async fn dropping_offloaded_body_cancels_queued_admission() {
        let payload = b"blocked offloaded body";
        let tmp = write_tempfile(payload);
        let pool = test_pool();
        let reservation = pool.try_reserve(TEST_POOL_CAPACITY).unwrap().unwrap();
        let acquisition = pool
            .acquire(&reservation, TEST_POOL_CAPACITY)
            .expect("test pool should be fully available");
        let mut body = OffloadedFileBody::new(
            source(tmp.path(), &pool),
            0,
            payload.len() as u64,
            tokio::runtime::Handle::current(),
        );

        assert!(poll_body_once(&mut body).is_pending());
        for _ in 0..100 {
            if pool.metrics().waiting_requests() == 1 {
                break;
            }
            tokio::task::yield_now().await;
        }
        assert_eq!(pool.metrics().waiting_requests(), 1);

        drop(body);
        for _ in 0..100 {
            if pool.metrics().waiting_requests() == 0 {
                break;
            }
            tokio::task::yield_now().await;
        }
        assert_eq!(pool.metrics().waiting_requests(), 0);

        drop(acquisition);
        reservation.close_acquisition();
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[cfg_attr(miri, ignore)] // Tokio's I/O driver uses unsupported platform FFI under Miri.
    #[tokio::test]
    #[cfg(unix)]
    async fn retries_keep_the_open_file_identity_after_path_replacement() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("body");
        let replacement = directory.path().join("replacement");
        let original = b"original opened file";
        let changed = b"replacement contents";
        assert_eq!(original.len(), changed.len());
        for direct_io in [true, false] {
            std::fs::write(&path, original).unwrap();

            let pool = test_pool();
            let stream = InputStream::read_from().path(&path).build().unwrap();
            let body = stream.into_sdk_body(direct_io, pool.clone()).unwrap();
            let retry = body.try_clone().expect("file body should be retryable");
            std::fs::write(&replacement, changed).unwrap();
            std::fs::rename(&replacement, &path).unwrap();

            assert_eq!(collect_body(body).await.unwrap(), original);
            assert_eq!(collect_body(retry).await.unwrap(), original);
            assert_eq!(pool.metrics().in_use_bytes(), 0);
        }
    }

    #[cfg_attr(miri, ignore)]
    #[test]
    fn offloaded_retry_is_rebuilt_and_drained_without_tokio_context() {
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(1)
            .enable_all()
            .build()
            .unwrap();
        let payload = vec![0x5a; FILE_BODY_CHUNK_SIZE + 17];
        let file = write_tempfile(&payload);
        let pool = test_pool();
        let body = runtime.block_on(async {
            InputStream::from_path(file.path())
                .unwrap()
                .into_sdk_body(false, pool.clone())
                .unwrap()
        });
        let expected = payload.clone();
        std::thread::spawn(move || {
            assert!(tokio::runtime::Handle::try_current().is_err());
            let retry = body.try_clone().expect("file body is retryable");
            let first = crate::runtime::test_util::block_on(collect_body(body)).unwrap();
            let second = crate::runtime::test_util::block_on(collect_body(retry)).unwrap();
            assert_eq!(first, expected);
            assert_eq!(second, expected);
        })
        .join()
        .unwrap();
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[cfg_attr(miri, ignore)]
    #[test]
    fn offloaded_reads_use_the_captured_runtime_in_a_foreign_tokio_context() {
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::time::Duration;

        let reader_started = Arc::new(AtomicBool::new(false));
        let observed = reader_started.clone();
        let reader = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .on_thread_start(move || observed.store(true, Ordering::SeqCst))
            .build()
            .unwrap();
        let payload = b"read on the captured runtime";
        let file = write_tempfile(payload);
        let pool = test_pool();
        let body = OffloadedFileBody::new(
            source(file.path(), &pool),
            0,
            payload.len() as u64,
            reader.handle().clone(),
        );
        let (stop, stopped) = tokio::sync::oneshot::channel();
        let reader_thread = std::thread::spawn(move || {
            reader.block_on(async { stopped.await.unwrap() });
        });
        let foreign_started = Arc::new(AtomicBool::new(false));
        let observed = foreign_started.clone();
        let foreign = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .on_thread_start(move || observed.store(true, Ordering::SeqCst))
            .build()
            .unwrap();
        let result = foreign.block_on(async {
            tokio::time::timeout(Duration::from_secs(5), collect_body(body)).await
        });
        stop.send(()).unwrap();
        reader_thread.join().unwrap();
        assert_eq!(result.unwrap().unwrap(), payload);
        assert!(reader_started.load(Ordering::SeqCst));
        assert!(!foreign_started.load(Ordering::SeqCst));
    }

    #[test]
    fn file_body_source_surfaces_open_error_before_request_dispatch() {
        let stream = InputStream::read_from()
            .path("/nonexistent/path/that/should/not/exist/xyz")
            .length(1024)
            .build()
            .unwrap();

        let error = stream.into_sdk_body(true, test_pool()).unwrap_err();
        assert_eq!(error.kind(), &crate::error::ErrorKind::IOError);
        let source = std::error::Error::source(&error)
            .and_then(|source| source.downcast_ref::<io::Error>())
            .expect("the open error is the source");
        assert_eq!(source.kind(), io::ErrorKind::NotFound);
    }

    /// An explicit length skips the builder's metadata check, so the open
    /// itself must reject a FIFO, without waiting for a writer. Android's app
    /// sandbox denies creating the FIFO.
    /// ref: RUST-1674
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    #[cfg(all(unix, not(target_os = "android")))]
    async fn file_body_source_rejects_a_fifo_at_open() {
        let directory = tempfile::tempdir().unwrap();
        let fifo = directory.path().join("fifo");
        nix::unistd::mkfifo(&fifo, nix::sys::stat::Mode::S_IRWXU).unwrap();
        for direct_io in [true, false] {
            let stream = InputStream::read_from()
                .path(&fifo)
                .length(16)
                .build()
                .unwrap();
            let error = stream.into_sdk_body(direct_io, test_pool()).unwrap_err();
            assert_eq!(error.kind(), &crate::error::ErrorKind::InputInvalid);
            let message = aws_smithy_types::error::display::DisplayErrorContext(&error).to_string();
            assert!(message.contains("is not a regular file"), "{message}");
        }
    }

    /// The open rejects the `NUL` device
    /// ref: RUST-1674
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    #[cfg(windows)]
    async fn file_body_source_rejects_the_nul_device_at_open() {
        for direct_io in [true, false] {
            let stream = InputStream::read_from()
                .path("NUL")
                .length(16)
                .build()
                .unwrap();
            let error = stream.into_sdk_body(direct_io, test_pool()).unwrap_err();
            assert_eq!(error.kind(), &crate::error::ErrorKind::InputInvalid);
            let message = aws_smithy_types::error::display::DisplayErrorContext(&error).to_string();
            assert!(message.contains("is not a regular file"), "{message}");
        }
    }

    /// A symbolic link to a regular file passes both the builder and the
    /// open-time check, and the body reads the target's bytes.
    /// ref: RUST-1674
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    #[cfg(unix)]
    async fn file_body_reads_a_regular_file_through_a_symlink() {
        let directory = tempfile::tempdir().unwrap();
        let target = directory.path().join("target");
        let link = directory.path().join("link");
        std::fs::write(&target, b"through a link").unwrap();
        std::os::unix::fs::symlink(&target, &link).unwrap();

        for direct_io in [true, false] {
            let body = InputStream::from_path(&link)
                .unwrap()
                .into_sdk_body(direct_io, test_pool())
                .unwrap();
            assert_eq!(collect_body(body).await.unwrap(), b"through a link");
        }
    }
}