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
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
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
use std::cmp;
use std::fs::File;
use std::future::{poll_fn, Future};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

use bytes::{Buf, Bytes};
use tokio::sync::Notify;

use crate::io::error::Error;
use crate::io::fs::read_exact_at;
use crate::io::path_body::PathBody;
use crate::io::stream::RawInputStream;
use crate::io::InputStream;
use crate::io::PartData;
use crate::memory::BufferPool;
use crate::types::ByteSize;

use super::stream::{BoxStream, StreamContext};

/// Builder for creating a `PartReader`
#[derive(Debug)]
pub(crate) struct Builder {
    stream: Option<RawInputStream>,
    part_size: usize,
    direct_io: bool,
    buffer_pool: Option<BufferPool>,
    metrics: Option<std::sync::Arc<crate::transfer::MetricsState>>,
    telemetry: Option<std::sync::Arc<crate::telemetry::Telemetry>>,
}

impl Builder {
    pub(crate) fn new() -> Self {
        Self {
            stream: None,
            part_size: ByteSize::mib(5).as_usize(),
            direct_io: false,
            buffer_pool: None,
            metrics: None,
            telemetry: None,
        }
    }

    /// Set the input stream to read from.
    pub(crate) fn stream(mut self, stream: InputStream) -> Self {
        self.stream = Some(stream.inner);
        self
    }

    /// Set the target part size that should be used when reading data.
    ///
    /// All parts except for possibly the last one should be of this size.
    pub(crate) fn part_size(mut self, part_size: usize) -> Self {
        self.part_size = part_size;
        self
    }

    /// Set direct I/O mode (read on calling thread vs spawn_blocking).
    pub(crate) fn direct_io(mut self, direct: bool) -> Self {
        self.direct_io = direct;
        self
    }

    /// Sets the shared pool available to stream producers.
    pub(crate) fn buffer_pool(mut self, buffer_pool: BufferPool) -> Self {
        self.buffer_pool = Some(buffer_pool);
        self
    }

    /// Set the metrics state for recording I/O metrics.
    pub(crate) fn metrics(
        mut self,
        metrics: std::sync::Arc<crate::transfer::MetricsState>,
    ) -> Self {
        self.metrics = Some(metrics);
        self
    }

    /// Set the per-client telemetry for forwarding I/O samples.
    pub(crate) fn telemetry(
        mut self,
        telemetry: std::sync::Arc<crate::telemetry::Telemetry>,
    ) -> Self {
        self.telemetry = Some(telemetry);
        self
    }

    pub(crate) fn build(self) -> Result<PartReader, crate::error::Error> {
        let stream = self.stream.expect("input stream set");
        let buffer_pool = self.buffer_pool.expect("buffer pool set");
        let metrics = self.metrics.expect("metrics set");
        let telemetry = self.telemetry.expect("telemetry set");
        PartReader::new(
            stream,
            self.part_size,
            self.direct_io,
            buffer_pool,
            metrics,
            telemetry,
        )
    }
}

/// Produces numbered upload parts from memory, files, or a custom [`PartStream`].
///
/// Each started read is independent work owned by [`NextPartFuture`]. Custom streams remain
/// logically single-owner because [`PartStreamGate`] hands their mutable stream value to exactly one
/// future at a time.
///
/// [`PartStream`]: crate::io::PartStream
#[derive(Debug)]
pub(crate) struct PartReader {
    inner: Inner,
    stream_cx: Arc<StreamContext>,
}

impl PartReader {
    fn new(
        raw: RawInputStream,
        part_size: usize,
        direct_io: bool,
        buffer_pool: BufferPool,
        metrics: std::sync::Arc<crate::transfer::MetricsState>,
        telemetry: std::sync::Arc<crate::telemetry::Telemetry>,
    ) -> Result<Self, crate::error::Error> {
        let inner = match raw {
            RawInputStream::Buf(buf) => Inner::Bytes(BytesPartReader::new(buf)),
            RawInputStream::Fs(path_body) => {
                Inner::Fs(Arc::new(PathBodyPartReader::new(path_body)?))
            }
            RawInputStream::Dyn(box_body) => Inner::Dyn(Arc::new(DynPartReader::new(box_body))),
        };

        let stream_cx = Arc::new(StreamContext::new(
            part_size,
            buffer_pool,
            direct_io,
            metrics,
            telemetry,
        ));
        Ok(Self { inner, stream_cx })
    }

    /// Starts one owned source operation.
    ///
    /// In-memory reads are completed synchronously. File reads retain their asynchronous operation.
    /// Custom streams serialize mutable polling through a private gate: callers arriving while a
    /// poll is actively making progress wait for direct handoff, while callers arriving after the
    /// source reports `Poll::Pending` receive [`PartReadStart::Blocked`] without creating another
    /// source future.
    pub(crate) async fn start_part_read(self: &Arc<Self>) -> PartReadStart {
        match &self.inner {
            Inner::Bytes(bytes) => {
                PartReadStart::Ready(NextPartFuture::ready(bytes.next_part(&self.stream_cx)))
            }
            Inner::Fs(path_body) => {
                let path_body = Arc::clone(path_body);
                let stream_cx = Arc::clone(&self.stream_cx);
                PartReadStart::Ready(NextPartFuture::file(async move {
                    path_body.next_part(&stream_cx).await
                }))
            }
            Inner::Dyn(part_stream) => match part_stream.gate.acquire().await {
                SourceAccess::Acquired(stream) => {
                    let future = DynNextPartFuture {
                        part_stream: Arc::clone(part_stream),
                        stream_cx: Arc::clone(&self.stream_cx),
                        stream: Some(stream),
                    };
                    PartReadStart::Ready(NextPartFuture::dynamic(future))
                }
                SourceAccess::Blocked => PartReadStart::Blocked,
                SourceAccess::Finished => PartReadStart::Finished,
            },
        }
    }

    /// Returns whether a custom stream cannot start another source operation.
    pub(crate) fn source_unavailable(&self) -> bool {
        match &self.inner {
            Inner::Dyn(part_stream) => part_stream.gate.is_unavailable(),
            Inner::Bytes(_) | Inner::Fs(_) => false,
        }
    }

    pub(crate) async fn full_object_checksum(&self) -> Option<String> {
        match &self.inner {
            Inner::Dyn(part_stream) => part_stream.full_object_checksum().await,
            _ => None,
        }
    }
}

#[derive(Debug)]
enum Inner {
    Bytes(BytesPartReader),
    Fs(Arc<PathBodyPartReader>),
    Dyn(Arc<DynPartReader>),
}

/// Result of obtaining authority to start one part read.
pub(crate) enum PartReadStart {
    /// The exact source operation to poll and retain if it blocks.
    Ready(NextPartFuture),
    /// A custom stream already has one externally blocked operation.
    Blocked,
    /// The source has already reported end-of-stream.
    Finished,
}

/// Owned source operation that may move between scheduler executions.
pub(crate) struct NextPartFuture {
    inner: NextPartFutureInner,
}

enum NextPartFutureInner {
    /// In-memory reads complete while the operation is created.
    Ready(Option<Result<Option<PartData>, Error>>),
    /// File reads remain boxed until the pooled file-read path supplies a concrete future.
    File(Pin<Box<dyn Future<Output = Result<Option<PartData>, Error>> + Send + 'static>>),
    /// A custom stream poll that owns the stream gate until completion or drop.
    Dynamic(DynNextPartFuture),
}

impl NextPartFuture {
    fn ready(result: Result<Option<PartData>, Error>) -> Self {
        Self {
            inner: NextPartFutureInner::Ready(Some(result)),
        }
    }

    fn file(
        future: impl Future<Output = Result<Option<PartData>, Error>> + Send + 'static,
    ) -> Self {
        Self {
            inner: NextPartFutureInner::File(Box::pin(future)),
        }
    }

    fn dynamic(future: DynNextPartFuture) -> Self {
        Self {
            inner: NextPartFutureInner::Dynamic(future),
        }
    }
}

impl Future for NextPartFuture {
    type Output = Result<Option<PartData>, Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match &mut self.get_mut().inner {
            NextPartFutureInner::Ready(result) => Poll::Ready(
                result
                    .take()
                    .expect("completed part-read future polled again"),
            ),
            NextPartFutureInner::File(future) => future.as_mut().poll(cx),
            NextPartFutureInner::Dynamic(future) => Pin::new(future).poll(cx),
        }
    }
}

impl std::fmt::Debug for NextPartFuture {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let source = match &self.inner {
            NextPartFutureInner::Ready(_) => "memory",
            NextPartFutureInner::File(_) => "file",
            NextPartFutureInner::Dynamic(_) => "custom",
        };
        formatter
            .debug_struct("NextPartFuture")
            .field("source", &source)
            .finish_non_exhaustive()
    }
}

#[derive(Debug)]
struct PartReaderState {
    // current start offset
    offset: u64,
    // current part number
    part_number: u64,
    // total number of bytes remaining to be read
    remaining: u64,
}

impl PartReaderState {
    /// Create a new `PartReaderState`
    fn new(content_length: u64) -> Self {
        Self {
            offset: 0,
            part_number: 1,
            remaining: content_length,
        }
    }

    /// Set the initial offset to start reading from
    fn with_offset(self, offset: u64) -> Self {
        Self { offset, ..self }
    }

    pub(crate) fn is_end(&self) -> bool {
        self.remaining == 0
    }
}

/// Implementation for in-memory input streams.
#[derive(Debug)]
struct BytesPartReader {
    buf: Bytes,
    state: Mutex<PartReaderState>,
}

impl BytesPartReader {
    fn new(buf: Bytes) -> Self {
        let content_length = buf.remaining() as u64;
        Self {
            buf,
            state: Mutex::new(PartReaderState::new(content_length)), // std Mutex
        }
    }
}

impl BytesPartReader {
    fn next_part(&self, stream_cx: &StreamContext) -> Result<Option<PartData>, Error> {
        let mut state = self.state.lock().expect("lock valid");
        if state.is_end() {
            return Ok(None);
        }

        let expected_offset = (state.part_number - 1) * stream_cx.part_size() as u64;
        if state.offset != expected_offset {
            return Err(Error::offset_not_aligned_with_part_number(
                state.offset,
                state.part_number,
            ));
        }

        let start = state.offset as usize;
        let end = cmp::min(start + stream_cx.part_size(), self.buf.len());
        let data = self.buf.slice(start..end);
        let part_number = state.part_number;
        state.part_number += 1;
        state.offset += data.len() as u64;
        state.remaining -= data.len() as u64;
        Ok(Some(PartData::new(part_number, data)))
    }
}

/// Produces pooled multipart payloads from disjoint ranges of one open file.
///
/// Range claims are serialized, but the resulting positional reads may complete
/// concurrently and out of part-number order.
#[derive(Debug)]
struct PathBodyPartReader {
    body: PathBody,
    state: Mutex<PartReaderState>, // std Mutex
    file: Arc<File>,
}

impl PathBodyPartReader {
    fn new(body: PathBody) -> Result<Self, crate::error::Error> {
        // TODO(vnext): Consider O_DIRECT for large sequential uploads (requires aligned
        // buffers from buffer pool). Also consider fadvise(POSIX_FADV_SEQUENTIAL) — generation
        // order is sequential so kernel readahead would help, but concurrent execution creates
        // some scatter. Benchmark before adding.
        // TODO(vnext): does this need to be async now?
        let file = Arc::new(body.open()?);
        let offset = body.offset;
        let content_length = body.length;
        Ok(Self {
            body,
            state: Mutex::new(PartReaderState::new(content_length).with_offset(offset)),
            file,
        })
    }
}

impl PathBodyPartReader {
    /// Claims and reads the next file range.
    ///
    /// The complete range is admitted before file I/O begins. The returned
    /// payload retains its pooled storage independently of this reader.
    async fn next_part(&self, stream_cx: &StreamContext) -> Result<Option<PartData>, Error> {
        let (offset, part_number, part_size) = match self.advance(stream_cx)? {
            Some(PathBodyReadCursor {
                offset,
                part_number,
                part_size,
            }) => (offset, part_number, part_size),
            None => return Ok(None),
        };
        let part_size = part_size as usize;
        let mut dst = stream_cx.part_buffer();
        poll_fn(|cx| dst.poll_acquire(cx, part_size)).await?;

        let read_error = |e| Error::io_at("reading", &self.body.path, e);
        if stream_cx.direct_io() {
            // Managed threads: read directly, no thread pool hop.
            read_exact_at(&self.file, &mut dst, offset).map_err(read_error)?;
        } else {
            // Shared runtime: offload to blocking thread pool.
            let fd = Arc::clone(&self.file);
            dst = tokio::task::spawn_blocking(move || {
                read_exact_at(&fd, &mut dst, offset)?;
                Ok::<_, std::io::Error>(dst)
            })
            .await?
            .map_err(read_error)?;
        }

        stream_cx.record_io(&crate::metrics::IoSample {
            disk_read: part_size as u64,
            ..Default::default()
        });

        Ok(Some(PartData::from_segmented(part_number, dst.freeze())))
    }

    /// Claims the next disjoint file range without performing I/O.
    ///
    /// A successful claim advances the shared cursor exactly once. Completion
    /// order does not affect later range offsets or part numbers.
    fn advance(&self, stream_cx: &StreamContext) -> Result<Option<PathBodyReadCursor>, Error> {
        let mut state = self.state.lock().expect("lock valid");
        if state.is_end() {
            return Ok(None);
        }
        let offset = state.offset;
        let part_number = state.part_number;

        let expected_offset = self.body.offset + (part_number - 1) * stream_cx.part_size() as u64;
        if offset != expected_offset {
            return Err(Error::offset_not_aligned_with_part_number(
                offset,
                part_number,
            ));
        }
        let part_size = cmp::min(stream_cx.part_size() as u64, state.remaining);
        state.offset += part_size;
        state.part_number += 1;
        state.remaining -= part_size;

        Ok(Some(PathBodyReadCursor {
            offset,
            part_number,
            part_size,
        }))
    }
}

/// One claimed file range and its multipart metadata.
#[derive(Debug, Clone, Copy)]
struct PathBodyReadCursor {
    offset: u64,
    part_number: u64,
    part_size: u64,
}

/// Custom-stream reader state shared by the reader and its currently active future.
#[derive(Debug)]
struct DynPartReader {
    gate: PartStreamGate,
}

impl DynPartReader {
    fn new(inner: BoxStream) -> Self {
        Self {
            gate: PartStreamGate::new(inner),
        }
    }

    async fn full_object_checksum(&self) -> Option<String> {
        let state = self.gate.state.lock().expect("part stream gate poisoned");
        match &*state {
            GateState::Available(stream) | GateState::Finished(stream) => {
                stream.full_object_checksum()
            }
            GateState::Polling | GateState::Blocked => {
                panic!("part stream checksum requested while a source operation remained")
            }
        }
    }
}

/// Transfers exclusive ownership of a custom stream between part-read futures.
///
/// `Polling` is a short handoff state while the active future has not reported whether it can make
/// progress. Once that future observes `Poll::Pending`, `Blocked` lets later executions return
/// immediately instead of waiting behind the same external dependency.
#[derive(Debug)]
struct PartStreamGate {
    state: Mutex<GateState>,
    changed: Notify,
}

/// Ownership state for one custom [`PartStream`].
///
/// [`PartStream`]: crate::io::PartStream
#[derive(Debug)]
enum GateState {
    /// No source operation is active; the next caller may take the stream.
    Available(BoxStream),
    /// One future owns the stream and has not yet reported source blockage.
    Polling,
    /// The owning future returned `Poll::Pending` and is retained by transfer state.
    Blocked,
    /// End-of-stream was observed; the stream is retained only for final metadata.
    Finished(BoxStream),
}

/// Result of trying to take custom-stream polling authority.
enum SourceAccess {
    /// The caller owns the stream until it releases, finishes, or drops the operation.
    Acquired(BoxStream),
    /// A retained future is waiting on the external source.
    Blocked,
    /// End-of-stream was already observed.
    Finished,
}

impl PartStreamGate {
    fn new(stream: BoxStream) -> Self {
        Self {
            state: Mutex::new(GateState::Available(stream)),
            changed: Notify::new(),
        }
    }

    async fn acquire(&self) -> SourceAccess {
        loop {
            let changed = self.changed.notified();
            {
                let mut state = self.state.lock().expect("part stream gate poisoned");
                match &*state {
                    GateState::Blocked => return SourceAccess::Blocked,
                    GateState::Polling => {}
                    GateState::Finished(_) => return SourceAccess::Finished,
                    GateState::Available(_) => {
                        let GateState::Available(stream) =
                            std::mem::replace(&mut *state, GateState::Polling)
                        else {
                            unreachable!("available state changed under lock");
                        };
                        return SourceAccess::Acquired(stream);
                    }
                }
            }
            changed.await;
        }
    }

    fn is_unavailable(&self) -> bool {
        matches!(
            &*self.state.lock().expect("part stream gate poisoned"),
            GateState::Blocked | GateState::Finished(_)
        )
    }

    fn mark_blocked(&self) {
        let notify = {
            let mut state = self.state.lock().expect("part stream gate poisoned");
            match &*state {
                GateState::Polling => {
                    *state = GateState::Blocked;
                    true
                }
                GateState::Blocked => false,
                GateState::Available(_) | GateState::Finished(_) => {
                    panic!("part stream became blocked without polling authority")
                }
            }
        };
        if notify {
            self.changed.notify_waiters();
        }
    }

    fn release(&self, stream: BoxStream) {
        {
            let mut state = self.state.lock().expect("part stream gate poisoned");
            assert!(
                matches!(&*state, GateState::Polling | GateState::Blocked),
                "part stream released without polling authority"
            );
            *state = GateState::Available(stream);
        }
        self.changed.notify_one();
    }

    fn finish(&self, stream: BoxStream) {
        {
            let mut state = self.state.lock().expect("part stream gate poisoned");
            assert!(
                matches!(&*state, GateState::Polling | GateState::Blocked),
                "part stream finished without polling authority"
            );
            *state = GateState::Finished(stream);
        }
        self.changed.notify_waiters();
    }
}

/// Exact custom-stream operation retained across scheduler executions.
struct DynNextPartFuture {
    part_stream: Arc<DynPartReader>,
    stream_cx: Arc<StreamContext>,
    stream: Option<BoxStream>,
}

impl Future for DynNextPartFuture {
    type Output = Result<Option<PartData>, Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        let stream = this
            .stream
            .as_mut()
            .expect("custom stream future polled after completion");

        match stream.poll_next(cx, &this.stream_cx) {
            Poll::Pending => {
                this.part_stream.gate.mark_blocked();
                Poll::Pending
            }
            Poll::Ready(result) => {
                let stream = this
                    .stream
                    .take()
                    .expect("custom stream disappeared at completion");
                match result {
                    Some(Ok(part)) => {
                        this.part_stream.gate.release(stream);
                        Poll::Ready(Ok(Some(part)))
                    }
                    Some(Err(error)) => {
                        this.part_stream.gate.finish(stream);
                        Poll::Ready(Err(error.into()))
                    }
                    None => {
                        this.part_stream.gate.finish(stream);
                        Poll::Ready(Ok(None))
                    }
                }
            }
        }
    }
}

impl Drop for DynNextPartFuture {
    fn drop(&mut self) {
        let Some(stream) = self.stream.take() else {
            return;
        };
        self.part_stream.gate.release(stream);
    }
}

#[cfg(test)]
mod test {
    use crate::types::ByteSize;
    use std::future::Future;
    use std::io::Write;
    use std::pin::Pin;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};
    use std::task::{Context, Poll, Waker};

    use bytes::{Buf, Bytes};
    use tempfile::NamedTempFile;

    use crate::config::MemoryBudgetConfig;
    use crate::io::part_reader::{
        Builder, BytesPartReader, PartData, PartReadStart, PartReader, PathBodyPartReader,
    };
    use crate::io::path_body::PathBody;
    use crate::io::stream::{PartStream, StreamContext};
    use crate::io::InputStream;
    use crate::memory::BufferPool;

    fn test_stream_cx(part_size: usize) -> StreamContext {
        StreamContext::new(
            part_size,
            test_pool(),
            false,
            test_metrics(),
            test_telemetry(),
        )
    }

    fn test_pool() -> BufferPool {
        BufferPool::builder()
            .memory_budget(MemoryBudgetConfig::Limit(ByteSize::new(1024 * 1024)))
            .build()
            .unwrap()
    }

    fn test_metrics() -> std::sync::Arc<crate::transfer::MetricsState> {
        std::sync::Arc::new(crate::transfer::MetricsState::new())
    }

    fn test_telemetry() -> std::sync::Arc<crate::telemetry::Telemetry> {
        std::sync::Arc::new(crate::telemetry::Telemetry::new(
            std::time::Duration::from_secs(1),
        ))
    }

    async fn collect_parts(reader: PartReader) -> Vec<PartData> {
        let reader = Arc::new(reader);
        let mut parts = Vec::new();
        let mut expected_part_number = 1;
        loop {
            let PartReadStart::Ready(future) = reader.start_part_read().await else {
                panic!("test source unexpectedly blocked");
            };
            let Some(part) = future.await.unwrap() else {
                break;
            };
            assert_eq!(expected_part_number, part.part_number);
            expected_part_number += 1;
            parts.push(part);
        }
        parts
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_bytes_part_reader() {
        let data = Bytes::from("a lep is a ball, a tay is a hammer, a flix is a comb");
        let stream = InputStream::from(data.clone());
        let expected = data.chunks(5).collect::<Vec<_>>();
        let reader = Builder::new()
            .part_size(5)
            .stream(stream)
            .buffer_pool(test_pool())
            .metrics(test_metrics())
            .telemetry(test_telemetry())
            .build()
            .unwrap();
        let parts = collect_parts(reader).await;
        let actual = parts.iter().map(|p| p.data.chunk()).collect::<Vec<_>>();

        assert_eq!(expected, actual);
    }

    async fn path_reader_test(limit: Option<usize>, offset: Option<usize>) {
        let part_size = 5;
        let mut tmp = NamedTempFile::new().unwrap();
        let mut data = Bytes::from("a lep is a ball, a tay is a hammer, a flix is a comb");
        tmp.write_all(data.chunk()).unwrap();
        let pool = test_pool();

        let mut builder = InputStream::read_from().path(tmp.path());
        if let Some(limit) = limit {
            data.truncate(limit);
            builder = builder.length((limit - offset.unwrap_or_default()) as u64);
        }

        if let Some(offset) = offset {
            data.advance(offset);
            builder = builder.offset(offset as u64);
        }

        let expected = data.chunks(part_size).collect::<Vec<_>>();

        let stream = builder.build().unwrap();
        let reader = Builder::new()
            .part_size(part_size)
            .stream(stream)
            .buffer_pool(pool.clone())
            .metrics(test_metrics())
            .telemetry(test_telemetry())
            .build()
            .unwrap();

        let parts = collect_parts(reader).await;
        {
            let actual = parts.iter().map(|p| p.data.chunk()).collect::<Vec<_>>();
            assert_eq!(expected, actual);
        }
        assert_eq!(
            pool.metrics().in_use_bytes(),
            (parts.len() * pool.carrier_size()) as u64
        );
        drop(parts);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_path_part_reader() {
        path_reader_test(None, None).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_path_part_reader_with_offset() {
        path_reader_test(None, Some(8)).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_path_part_reader_with_explicit_length() {
        path_reader_test(Some(12), None).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_path_part_reader_with_length_and_offset() {
        path_reader_test(Some(23), Some(4)).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn path_reader_fills_multiple_pooled_runs_without_gathering() {
        let pool = test_pool();
        let carrier_size = pool.carrier_size();
        let part_size = carrier_size * 2 + 37;
        let data = (0..part_size)
            .map(|index| (index % 251) as u8)
            .collect::<Vec<_>>();
        let mut tmp = NamedTempFile::new().unwrap();
        tmp.write_all(&data).unwrap();

        let reader = Arc::new(
            Builder::new()
                .part_size(part_size)
                .direct_io(true)
                .stream(InputStream::read_from().path(tmp.path()).build().unwrap())
                .buffer_pool(pool.clone())
                .metrics(test_metrics())
                .telemetry(test_telemetry())
                .build()
                .unwrap(),
        );
        let PartReadStart::Ready(future) = reader.start_part_read().await else {
            panic!("file source unexpectedly blocked");
        };
        let part = future.await.unwrap().unwrap();
        assert_eq!(part.data.len(), part_size);
        assert_eq!(pool.metrics().in_use_bytes(), (carrier_size * 3) as u64);

        let segments = part.data.into_segments();
        assert_eq!(segments.len(), 1);
        assert_eq!(segments[0].as_ref(), data);
        drop(segments);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn dropping_file_read_waiting_for_admission_cancels_its_request() {
        let pool = test_pool();
        let carrier_size = pool.carrier_size();
        let capacity = pool.metrics().capacity_bytes() as usize;
        let reservation = pool.try_reserve(capacity).unwrap().unwrap();
        let holder = pool.acquire(&reservation, capacity).unwrap();
        let mut tmp = NamedTempFile::new().unwrap();
        tmp.write_all(&vec![0x5a; carrier_size]).unwrap();

        let reader = Arc::new(
            Builder::new()
                .part_size(carrier_size)
                .stream(InputStream::read_from().path(tmp.path()).build().unwrap())
                .buffer_pool(pool.clone())
                .metrics(test_metrics())
                .telemetry(test_telemetry())
                .build()
                .unwrap(),
        );
        let PartReadStart::Ready(mut future) = reader.start_part_read().await else {
            panic!("file source unexpectedly blocked");
        };
        let waker = Waker::noop();
        let mut cx = Context::from_waker(waker);
        assert!(Pin::new(&mut future).poll(&mut cx).is_pending());
        assert_eq!(pool.metrics().waiting_requests(), 1);

        drop(future);
        assert_eq!(pool.metrics().waiting_requests(), 0);
        drop(holder);
        drop(reservation);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn short_file_read_releases_pooled_storage() {
        let pool = test_pool();
        let mut tmp = NamedTempFile::new().unwrap();
        tmp.write_all(b"short").unwrap();
        let stream = InputStream::read_from()
            .path(tmp.path())
            .length(10)
            .build()
            .unwrap();
        let reader = Arc::new(
            Builder::new()
                .part_size(10)
                .stream(stream)
                .buffer_pool(pool.clone())
                .metrics(test_metrics())
                .telemetry(test_telemetry())
                .build()
                .unwrap(),
        );
        let PartReadStart::Ready(future) = reader.start_part_read().await else {
            panic!("file source unexpectedly blocked");
        };

        assert!(future.await.is_err());
        assert_eq!(pool.metrics().active_planned_demand_bytes(), 0);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[derive(Debug)]
    struct TestStream {
        data: Vec<Bytes>,
        idx: usize,
    }

    impl TestStream {
        fn new(data: Vec<Bytes>) -> Self {
            Self { data, idx: 0 }
        }
    }

    impl PartStream for TestStream {
        fn poll_part(
            mut self: std::pin::Pin<&mut Self>,
            _cx: &mut std::task::Context<'_>,
            _stream_cx: &StreamContext,
        ) -> Poll<Option<std::io::Result<PartData>>> {
            if self.idx < self.data.len() {
                let part = PartData::new(self.idx as u64 + 1, self.data[self.idx].clone());
                self.as_mut().idx += 1;
                Poll::Ready(Some(Ok(part)))
            } else {
                Poll::Ready(None)
            }
        }

        fn size_hint(&self) -> crate::io::SizeHint {
            unimplemented!()
        }
    }

    // sanity test custom PollPart is wired up and can be supplied to input stream
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_dyn_reader() {
        let data = Bytes::from("a lep is a ball, a tay is a hammer, a flix is a comb");
        let expected = data.chunks(5).collect::<Vec<_>>();
        let stream = TestStream::new(
            data.chunks(5)
                .map(|x| Bytes::from(x.to_owned()))
                .collect::<Vec<_>>(),
        );
        let stream = InputStream::from_part_stream(stream);
        let reader = Builder::new()
            .part_size(5)
            .stream(stream)
            .buffer_pool(test_pool())
            .metrics(test_metrics())
            .telemetry(test_telemetry())
            .build()
            .unwrap();
        let parts = collect_parts(reader).await;
        let actual = parts.iter().map(|p| p.data.chunk()).collect::<Vec<_>>();
        assert_eq!(expected, actual);
    }

    #[derive(Debug)]
    struct BlockingStream {
        ready: Arc<AtomicBool>,
        source_waker: Arc<Mutex<Option<Waker>>>,
        yielded: bool,
    }

    impl PartStream for BlockingStream {
        fn poll_part(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            _stream_cx: &StreamContext,
        ) -> Poll<Option<std::io::Result<PartData>>> {
            if self.yielded {
                return Poll::Ready(None);
            }
            if self.ready.load(Ordering::Acquire) {
                self.yielded = true;
                return Poll::Ready(Some(Ok(PartData::new(1, Bytes::from_static(b"ready")))));
            }
            *self.source_waker.lock().expect("source waker poisoned") = Some(cx.waker().clone());
            Poll::Pending
        }

        fn size_hint(&self) -> crate::io::SizeHint {
            crate::io::SizeHint::exact(5)
        }
    }

    fn blocking_reader() -> (Arc<PartReader>, Arc<AtomicBool>, Arc<Mutex<Option<Waker>>>) {
        let ready = Arc::new(AtomicBool::new(false));
        let source_waker = Arc::new(Mutex::new(None));
        let stream = BlockingStream {
            ready: Arc::clone(&ready),
            source_waker: Arc::clone(&source_waker),
            yielded: false,
        };
        let reader = Builder::new()
            .part_size(5)
            .stream(InputStream::from_part_stream(stream))
            .buffer_pool(test_pool())
            .metrics(test_metrics())
            .telemetry(test_telemetry())
            .build()
            .unwrap();
        (Arc::new(reader), ready, source_waker)
    }

    // Tokio's test runtime initializes kqueue, which Miri cannot execute.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn custom_stream_pending_blocks_waiters_until_exact_future_resumes() {
        let (reader, ready, source_waker) = blocking_reader();
        let PartReadStart::Ready(mut first) = reader.start_part_read().await else {
            panic!("fresh custom stream was blocked");
        };

        let waiter_reader = Arc::clone(&reader);
        let waiter = tokio::spawn(async move { waiter_reader.start_part_read().await });
        tokio::task::yield_now().await;
        assert!(!waiter.is_finished(), "waiter bypassed active stream poll");

        let waker = Waker::noop();
        let mut cx = Context::from_waker(waker);
        assert!(Pin::new(&mut first).poll(&mut cx).is_pending());
        assert!(reader.source_unavailable());

        assert!(matches!(waiter.await.unwrap(), PartReadStart::Blocked));

        ready.store(true, Ordering::Release);
        source_waker
            .lock()
            .expect("source waker poisoned")
            .take()
            .expect("source did not register a waker")
            .wake();

        let part = first.await.unwrap().expect("source should yield a part");
        assert_eq!(part.data, Bytes::from_static(b"ready"));
        assert!(!reader.source_unavailable());
    }

    // Tokio's test runtime initializes kqueue, which Miri cannot execute.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn custom_stream_ready_completion_hands_gate_to_one_waiter() {
        let data = vec![Bytes::from_static(b"first"), Bytes::from_static(b"second")];
        let reader = Arc::new(
            Builder::new()
                .part_size(6)
                .stream(InputStream::from_part_stream(TestStream::new(data)))
                .buffer_pool(test_pool())
                .metrics(test_metrics())
                .telemetry(test_telemetry())
                .build()
                .unwrap(),
        );

        let PartReadStart::Ready(first) = reader.start_part_read().await else {
            panic!("fresh custom stream was blocked");
        };
        let waiter_reader = Arc::clone(&reader);
        let waiter = tokio::spawn(async move { waiter_reader.start_part_read().await });
        tokio::task::yield_now().await;
        assert!(!waiter.is_finished(), "waiter bypassed active stream poll");

        assert_eq!(
            first.await.unwrap().unwrap().data,
            Bytes::from_static(b"first")
        );
        let PartReadStart::Ready(second) = waiter.await.unwrap() else {
            panic!("ready handoff reported source blockage");
        };
        assert_eq!(
            second.await.unwrap().unwrap().data,
            Bytes::from_static(b"second")
        );
        assert!(!reader.source_unavailable());
    }

    #[derive(Debug)]
    struct EofOnceStream {
        polls: Arc<AtomicUsize>,
    }

    impl PartStream for EofOnceStream {
        fn poll_part(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            _stream_cx: &StreamContext,
        ) -> Poll<Option<std::io::Result<PartData>>> {
            assert_eq!(
                self.polls.fetch_add(1, Ordering::Relaxed),
                0,
                "custom stream was polled after end-of-stream"
            );
            Poll::Ready(None)
        }

        fn size_hint(&self) -> crate::io::SizeHint {
            crate::io::SizeHint::default()
        }
    }

    // Tokio's test runtime initializes kqueue, which Miri cannot execute.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn custom_stream_eof_retires_waiters_without_another_poll() {
        let polls = Arc::new(AtomicUsize::new(0));
        let reader = Arc::new(
            Builder::new()
                .part_size(5)
                .stream(InputStream::from_part_stream(EofOnceStream {
                    polls: Arc::clone(&polls),
                }))
                .buffer_pool(test_pool())
                .metrics(test_metrics())
                .telemetry(test_telemetry())
                .build()
                .unwrap(),
        );
        let PartReadStart::Ready(eof) = reader.start_part_read().await else {
            panic!("fresh custom stream was unavailable");
        };
        let waiter_reader = Arc::clone(&reader);
        let waiter = tokio::spawn(async move { waiter_reader.start_part_read().await });
        tokio::task::yield_now().await;

        assert!(eof.await.unwrap().is_none());
        assert!(matches!(waiter.await.unwrap(), PartReadStart::Finished));
        assert!(reader.source_unavailable());
        assert_eq!(polls.load(Ordering::Relaxed), 1);
    }

    #[derive(Debug)]
    struct ErrorOnceStream {
        polls: Arc<AtomicUsize>,
    }

    impl PartStream for ErrorOnceStream {
        fn poll_part(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            _stream_cx: &StreamContext,
        ) -> Poll<Option<std::io::Result<PartData>>> {
            assert_eq!(
                self.polls.fetch_add(1, Ordering::Relaxed),
                0,
                "custom stream was polled after its terminal error"
            );
            Poll::Ready(Some(Err(std::io::Error::other(
                "simulated terminal source error",
            ))))
        }

        fn size_hint(&self) -> crate::io::SizeHint {
            crate::io::SizeHint::default()
        }
    }

    #[tokio::test]
    async fn custom_stream_error_retires_waiters_without_another_poll() {
        let polls = Arc::new(AtomicUsize::new(0));
        let reader = Arc::new(
            Builder::new()
                .part_size(5)
                .stream(InputStream::from_part_stream(ErrorOnceStream {
                    polls: Arc::clone(&polls),
                }))
                .buffer_pool(test_pool())
                .metrics(test_metrics())
                .telemetry(test_telemetry())
                .build()
                .unwrap(),
        );
        let PartReadStart::Ready(failing) = reader.start_part_read().await else {
            panic!("fresh custom stream was unavailable");
        };
        let waiter_reader = Arc::clone(&reader);
        let waiter = tokio::spawn(async move { waiter_reader.start_part_read().await });
        tokio::task::yield_now().await;

        assert!(failing.await.is_err());
        assert!(matches!(waiter.await.unwrap(), PartReadStart::Finished));
        assert!(reader.source_unavailable());
        assert_eq!(polls.load(Ordering::Relaxed), 1);
    }

    // Tokio's test runtime initializes kqueue, which Miri cannot execute.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn dropping_blocked_custom_future_restores_stream_authority() {
        let (reader, _ready, _source_waker) = blocking_reader();
        let PartReadStart::Ready(mut first) = reader.start_part_read().await else {
            panic!("fresh custom stream was blocked");
        };
        let waker = Waker::noop();
        let mut cx = Context::from_waker(waker);
        assert!(Pin::new(&mut first).poll(&mut cx).is_pending());
        assert!(reader.source_unavailable());

        drop(first);
        assert!(!reader.source_unavailable());
        assert!(matches!(
            reader.start_part_read().await,
            PartReadStart::Ready(_)
        ));
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_bytes_part_reader_offset_not_aligned_error() {
        let data = Bytes::from("test data for alignment error");
        let reader = BytesPartReader::new(data);
        let stream_cx = test_stream_cx(5);

        // First call should succeed
        let result = reader.next_part(&stream_cx);
        assert!(result.is_ok());

        // Manually corrupt the offset to create misalignment
        {
            let mut state = reader.state.lock().unwrap();
            state.offset = 99; // Invalid offset that doesn't align with part_number
        }

        // Second call should fail with offset_not_aligned_with_part_number error
        let result = reader.next_part(&stream_cx);
        assert!(result.is_err());
    }

    // A payload shorter than one part is a single final part: the read after it
    // must report the end of the stream rather than an empty part.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_bytes_part_reader_ends_after_final_part() {
        let data = Bytes::from("test");
        let reader = BytesPartReader::new(data);
        let stream_cx = test_stream_cx(10);

        let result = reader.next_part(&stream_cx).unwrap().unwrap();
        assert_eq!(result.part_number, 1);
        assert_eq!(result.data.len(), 4);
        assert!(reader.next_part(&stream_cx).unwrap().is_none());
    }

    #[test]
    fn test_path_body_part_reader_advance() {
        let mut tmp = NamedTempFile::new().unwrap();
        tmp.write_all(&[0u8; 30]).unwrap();

        let path_body = PathBody {
            path: tmp.path().to_path_buf(),
            offset: 10,
            length: 20,
        };
        let reader = PathBodyPartReader::new(path_body).unwrap();
        let stream_cx = test_stream_cx(5);

        // First advance should succeed
        let result = reader.advance(&stream_cx).unwrap().unwrap();
        assert_eq!(result.offset, 10);
        assert_eq!(result.part_number, 1);
        assert_eq!(result.part_size, 5);
        assert!(!reader.state.lock().unwrap().is_end());

        // Second advance should succeed
        let result = reader.advance(&stream_cx).unwrap().unwrap();
        assert_eq!(result.offset, 15);
        assert_eq!(result.part_number, 2);
        assert_eq!(result.part_size, 5);
        assert!(!reader.state.lock().unwrap().is_end());

        // Manually corrupt the offset to test validation
        {
            let mut state = reader.state.lock().unwrap();
            state.offset = 99; // Invalid offset
        }

        // Third advance should fail due to misaligned offset
        let result = reader.advance(&stream_cx);
        assert!(result.is_err());
    }

    // A range shorter than one part is claimed whole, and the claim after it
    // reports the end of the range.
    #[test]
    fn test_path_body_part_reader_advance_ends_after_final_part() {
        let mut tmp = NamedTempFile::new().unwrap();
        tmp.write_all(&[0u8; 3]).unwrap();

        let path_body = PathBody {
            path: tmp.path().to_path_buf(),
            offset: 0,
            length: 3,
        };
        let reader = PathBodyPartReader::new(path_body).unwrap();
        let stream_cx = test_stream_cx(10);

        let result = reader.advance(&stream_cx).unwrap().unwrap();
        assert_eq!(result.offset, 0);
        assert_eq!(result.part_size, 3);
        assert!(reader.advance(&stream_cx).unwrap().is_none());
    }
}