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
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Single-object uploads using either a single PUT or multipart upload.
//!
//! Construct an upload through the client's fluent builder or
//! [`UploadInput::builder`](crate::model::UploadInput::builder).
//! Wait for [`UploadHandle::join`](crate::operation::upload::UploadHandle::join) to obtain
//! [`UploadOutput`](crate::model::UploadOutput), which combines service response metadata with
//! transfer metrics. Optional response fields depend on the selected path
//! and the values returned by S3; see [`UploadOutput`](crate::model::UploadOutput)
//! for their provenance.
//!
//! # Integrity inputs
//!
//! An upload fails with [`ErrorKind::InputInvalid`](crate::error::ErrorKind::InputInvalid) when it
//! cannot send an integrity check you supplied:
//!
//! - The upload sets [Content-MD5](crate::operation::upload::UploadInput::content_md5()) and is
//!   sent as a multipart upload: the body's size has no upper bound, the body is a
//!   [`PartStream`](crate::io::PartStream), or its upper bound is at least the multipart
//!   threshold. A Content-MD5 covers the whole object, which only a single-request upload
//!   carries. `initiate` returns this error, and no request is sent.
//! - The upload's [checksum strategy](crate::types::ChecksumStrategy) is
//!   [composite](crate::types::ChecksumStrategy::composite) and has an
//!   [expected value](crate::types::ChecksumStrategy::with_expected_value), and the upload is sent
//!   as a multipart upload, under the same conditions as for Content-MD5. The expected value covers
//!   the whole object, which no composite multipart request carries. `initiate` returns this
//!   error, and no request is sent.
//! - A [`PartStream`](crate::io::PartStream) part carries a
//!   [checksum](crate::io::PartData::with_checksum), but the upload has no
//!   [checksum strategy](crate::types::ChecksumStrategy) to name its algorithm.
//!   [`UploadHandle::join`](crate::operation::upload::UploadHandle::join) returns this error.
//!   The part is not sent; earlier parts may have been, and the multipart upload is then
//!   handled as for any failed part.

/// Operation builders
pub mod builders;
mod request;

mod context;
pub(crate) mod file_body;
mod handle;
mod observability;
mod part_body;
mod transfer;

pub(crate) use transfer::UploadTransfer;

use crate::config::user_agent::OperationFeatures;
use crate::error;
pub use crate::model::builders::UploadInputBuilder;
pub use crate::model::builders::UploadOutputBuilder;
/// Request type for uploads to Amazon S3
pub use crate::model::UploadInput;
/// Response type for uploads to Amazon S3
pub use crate::model::UploadOutput;
use crate::transfer::TransferContext;
use crate::types::{BucketType, ChecksumStrategy};
use aws_runtime::sdk_feature::AwsSdkFeature;
pub use handle::UploadHandle;

use std::sync::Arc;

/// Operation struct for single object upload
#[derive(Clone, Default, Debug)]
pub(crate) struct Upload;

impl Upload {
    /// Execute a single `Upload` transfer operation.
    pub(crate) fn orchestrate(
        handle: Arc<crate::client::Handle>,
        input: crate::operation::upload::UploadInput,
    ) -> Result<UploadHandle, error::Error> {
        Self::orchestrate_inner(handle, input, None)
    }

    /// Execute an `Upload` as a child of another transfer.
    ///
    /// The child's `TransferContext` is linked to `parent_id` so that
    /// `signal_terminal` on the child wakes the parent (letting the parent's
    /// state machine reap it) and cancelling the parent cascades to this child.
    pub(crate) fn orchestrate_child(
        handle: Arc<crate::client::Handle>,
        input: crate::operation::upload::UploadInput,
        parent_id: u64,
    ) -> Result<UploadHandle, error::Error> {
        Self::orchestrate_inner(handle, input, Some(parent_id))
    }

    fn orchestrate_inner(
        handle: Arc<crate::client::Handle>,
        mut input: crate::operation::upload::UploadInput,
        parent_id: Option<u64>,
    ) -> Result<UploadHandle, error::Error> {
        if input.checksum_strategy.is_none() {
            // User didn't explicitly set checksum strategy.
            // If SDK is configured to send checksums: use default checksum strategy.
            // Else: continue with no checksums
            if handle
                .s3_client
                .config()
                .request_checksum_calculation()
                .cloned()
                .unwrap_or_default()
                == aws_sdk_s3::config::RequestChecksumCalculation::WhenSupported
            {
                input.checksum_strategy = Some(ChecksumStrategy::default());
            }
        }

        let stream = input.take_body();

        let bucket_type =
            BucketType::from_bucket_name(input.bucket().expect("bucket is available"));

        // Create transfer context — linked to parent when this is a child
        // transfer, so signal_terminal wakes the parent and cancellation
        // cascades from the parent.
        let (ctx, completion_rx) = match parent_id {
            Some(pid) => TransferContext::new_child(handle.clone(), pid),
            None => TransferContext::new(handle.clone()),
        };

        let features = OperationFeatures::new(
            parent_id
                .map(|_| AwsSdkFeature::S3TransferUploadDirectory)
                .into_iter()
                .chain(stream.is_file_backed().then_some(AwsSdkFeature::S3FilePath)),
        );
        let transfer =
            UploadTransfer::try_new(ctx.with_features(features), bucket_type, input, stream)?;

        handle
            .scheduler
            .enqueue_transfer(Box::new(transfer.clone()));

        Ok(UploadHandle::new(completion_rx, transfer))
    }
}

#[cfg(test)]
mod test {
    use crate::types::ByteSize;

    use aws_sdk_s3::operation::abort_multipart_upload::AbortMultipartUploadOutput;
    use aws_sdk_s3::operation::complete_multipart_upload::CompleteMultipartUploadOutput;
    use aws_sdk_s3::operation::create_multipart_upload::CreateMultipartUploadOutput;
    use aws_sdk_s3::operation::upload_part::UploadPartOutput;
    use aws_smithy_mocks::{mock, mock_client, RuleMode};
    use aws_smithy_runtime_api::client::http::{
        http_client_fn, HttpConnector, HttpConnectorFuture, SharedHttpConnector,
    };
    use aws_smithy_runtime_api::client::orchestrator::{HttpRequest, HttpResponse};
    use aws_smithy_types::body::SdkBody;
    use bytes::Bytes;
    use std::future::Future;
    use std::pin::Pin;
    use std::sync::{Arc, Mutex};
    use std::task::Poll;
    use std::time::Duration;
    use tokio::sync::Semaphore;

    use crate::config::RuntimeConfig;
    use crate::config::{ConcurrencyMode, PartSize};
    use crate::io::InputStream;
    use crate::operation::upload::UploadInput;

    use crate::types::{AbortOutcome, FailedMultipartUploadPolicy, TransferStatus};

    /// Polls `future` once and returns the result of that poll.
    ///
    /// `UploadHandle::abort()` calls `request_abort()` before its first
    /// `.await`, so one poll is enough to know the abort has been requested.
    async fn poll_once<F: Future + Unpin>(future: &mut F) -> Poll<F::Output> {
        std::future::poll_fn(|cx| Poll::Ready(Pin::new(&mut *future).poll(cx))).await
    }

    /// Connector that holds CreateMultipartUpload until `create_release` gets
    /// a permit, then accepts it, and records the URI of every
    /// AbortMultipartUpload.
    #[derive(Debug)]
    struct HeldCreateMpuConnector {
        create_started: Arc<Semaphore>,
        create_release: Arc<Semaphore>,
        abort_uris: Arc<Mutex<Vec<String>>>,
    }

    impl HttpConnector for HeldCreateMpuConnector {
        fn call(&self, request: HttpRequest) -> HttpConnectorFuture {
            let uri = request.uri().to_string();
            match request.method() {
                "POST" if uri.contains("uploads") && !uri.contains("uploadId=") => {
                    let create_started = self.create_started.clone();
                    let create_release = self.create_release.clone();
                    HttpConnectorFuture::new(async move {
                        create_started.add_permits(1);
                        create_release
                            .acquire()
                            .await
                            .expect("release semaphore closed")
                            .forget();
                        Ok(HttpResponse::new(
                            200.try_into().unwrap(),
                            SdkBody::from(
                                r#"<?xml version="1.0" encoding="UTF-8"?>
                                    <InitiateMultipartUploadResult>
                                        <Bucket>test-bucket</Bucket>
                                        <Key>test-key</Key>
                                        <UploadId>test-upload-id</UploadId>
                                    </InitiateMultipartUploadResult>"#,
                            ),
                        ))
                    })
                }
                "DELETE" if uri.contains("uploadId=") => {
                    self.abort_uris.lock().unwrap().push(uri);
                    HttpConnectorFuture::ready(Ok(HttpResponse::new(
                        204.try_into().unwrap(),
                        SdkBody::empty(),
                    )))
                }
                method => panic!("unexpected request: {method} {uri}"),
            }
        }
    }

    /// An abort requested while CreateMultipartUpload is in flight waits for
    /// Create's response, and no part is uploaded. Under `AbortUpload` it
    /// aborts the upload Create returned and reports `Cancelled`; under
    /// `Retain` it leaves the upload open and reports `Retained`. Both carry
    /// the upload ID.
    async fn abort_during_create_mpu(
        runtime_config: RuntimeConfig,
        policy: FailedMultipartUploadPolicy,
    ) {
        let retain = matches!(policy, FailedMultipartUploadPolicy::Retain);
        let create_started = Arc::new(Semaphore::new(0));
        let create_release = Arc::new(Semaphore::new(0));
        let abort_uris = Arc::new(Mutex::new(Vec::new()));
        let connector = SharedHttpConnector::new(HeldCreateMpuConnector {
            create_started: create_started.clone(),
            create_release: create_release.clone(),
            abort_uris: abort_uris.clone(),
        });
        let http_client = http_client_fn(move |_, _| connector.clone());
        let client = aws_sdk_s3::Client::from_conf(
            aws_sdk_s3::config::Config::builder()
                .http_client(http_client)
                .region(aws_sdk_s3::config::Region::new("us-west-2"))
                .with_test_defaults()
                .build(),
        );

        let tm_config = crate::Config::builder()
            .concurrency(ConcurrencyMode::Explicit(1))
            .runtime_config(runtime_config)
            .set_multipart_threshold(PartSize::Target(ByteSize::new(10)))
            .set_target_part_size(PartSize::Target(ByteSize::mib(5)))
            .sdk_client(client)
            .build()
            .expect("valid config");
        let tm = crate::Client::new(tm_config);
        let handle = UploadInput::builder()
            .bucket("test-bucket")
            .key("test-key")
            .body(InputStream::from(Bytes::from_static(
                b"force multipart upload",
            )))
            .failed_multipart_upload_policy(policy)
            .initiate_with(&tm)
            .unwrap();

        let permit = tokio::time::timeout(Duration::from_secs(5), create_started.acquire())
            .await
            .expect("CreateMultipartUpload did not start")
            .expect("start semaphore closed");
        permit.forget();

        let mut abort = Box::pin(handle.abort());
        assert!(
            poll_once(&mut abort).await.is_pending(),
            "abort returned while CreateMultipartUpload was held"
        );
        create_release.add_permits(1);

        let aborted = tokio::time::timeout(Duration::from_secs(5), abort)
            .await
            .expect("abort hung after CreateMultipartUpload returned")
            .expect("abort failed");

        assert_eq!(aborted.upload_id(), Some("test-upload-id"));
        let abort_uris = abort_uris.lock().unwrap();
        if retain {
            assert_eq!(aborted.outcome(), AbortOutcome::Retained);
            assert!(
                abort_uris.is_empty(),
                "unexpected AbortMultipartUpload under Retain: {abort_uris:?}"
            );
        } else {
            assert_eq!(aborted.outcome(), AbortOutcome::Cancelled);
            assert_eq!(
                abort_uris.len(),
                1,
                "expected one AbortMultipartUpload: {abort_uris:?}"
            );
            assert!(
                abort_uris[0].contains("uploadId=test-upload-id"),
                "AbortMultipartUpload for the wrong upload: {}",
                abort_uris[0]
            );
        }
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn abort_during_create_mpu_on_tokio_runtime() {
        abort_during_create_mpu(
            RuntimeConfig::multi_thread_tokio(),
            FailedMultipartUploadPolicy::AbortUpload,
        )
        .await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn abort_during_create_mpu_on_managed_runtime() {
        abort_during_create_mpu(
            RuntimeConfig::default(),
            FailedMultipartUploadPolicy::AbortUpload,
        )
        .await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn abort_during_create_mpu_retains_upload_on_tokio_runtime() {
        abort_during_create_mpu(
            RuntimeConfig::multi_thread_tokio(),
            FailedMultipartUploadPolicy::Retain,
        )
        .await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn abort_during_create_mpu_retains_upload_on_managed_runtime() {
        abort_during_create_mpu(
            RuntimeConfig::default(),
            FailedMultipartUploadPolicy::Retain,
        )
        .await;
    }

    /// How [`CompleteMpuConnector`] answers CompleteMultipartUpload.
    #[derive(Debug, Clone, Copy)]
    enum CompleteMpuBehavior {
        /// Wait until `complete_release` gets a permit, then answer
        /// `NoSuchUpload`, as S3 does when the upload was aborted before
        /// Complete committed.
        HoldThenNoSuchUpload,
        /// Wait like `HoldThenNoSuchUpload`, then answer with the same error
        /// as `Fail`.
        HoldThenFail,
        /// Respond with a non-retryable error.
        Fail,
        /// Wait like `HoldThenNoSuchUpload`, then answer 200: Complete
        /// committed before the abort took effect. AbortMultipartUpload is
        /// also held, until `abort_release` gets a permit.
        HoldThenOk,
    }

    /// Connector that serves a single-part multipart upload, applies
    /// [`CompleteMpuBehavior`] to CompleteMultipartUpload, and records the
    /// upload ID of every AbortMultipartUpload. Each AbortMultipartUpload adds
    /// a permit to `abort_started`.
    #[derive(Debug)]
    struct CompleteMpuConnector {
        behavior: CompleteMpuBehavior,
        complete_started: Arc<Semaphore>,
        complete_release: Arc<Semaphore>,
        abort_started: Arc<Semaphore>,
        abort_release: Arc<Semaphore>,
        abort_uris: Arc<Mutex<Vec<String>>>,
    }

    impl HttpConnector for CompleteMpuConnector {
        fn call(&self, request: HttpRequest) -> HttpConnectorFuture {
            let uri = request.uri().to_string();
            let has_upload_id = uri.contains("uploadId=");
            let response = match (request.method(), has_upload_id) {
                ("POST", false) if uri.contains("uploads") => HttpResponse::new(
                    200.try_into().unwrap(),
                    SdkBody::from(
                        r#"<?xml version="1.0" encoding="UTF-8"?>
                            <InitiateMultipartUploadResult>
                                <Bucket>test-bucket</Bucket>
                                <Key>test-key</Key>
                                <UploadId>test-upload-id</UploadId>
                            </InitiateMultipartUploadResult>"#,
                    ),
                ),
                ("PUT", true) if uri.contains("partNumber=") => {
                    let mut response = HttpResponse::new(200.try_into().unwrap(), SdkBody::empty());
                    response.headers_mut().insert("ETag", "\"test-etag\"");
                    response
                }
                ("POST", true) => {
                    let complete_started = self.complete_started.clone();
                    let complete_release = self.complete_release.clone();
                    let behavior = self.behavior;
                    return HttpConnectorFuture::new(async move {
                        complete_started.add_permits(1);
                        let behavior = match behavior {
                            CompleteMpuBehavior::HoldThenFail => {
                                complete_release
                                    .acquire()
                                    .await
                                    .expect("release semaphore closed")
                                    .forget();
                                CompleteMpuBehavior::Fail
                            }
                            other => other,
                        };
                        match behavior {
                            CompleteMpuBehavior::HoldThenNoSuchUpload => {
                                complete_release
                                    .acquire()
                                    .await
                                    .expect("release semaphore closed")
                                    .forget();
                                Ok(HttpResponse::new(
                                    404.try_into().unwrap(),
                                    SdkBody::from(
                                        r#"<?xml version="1.0" encoding="UTF-8"?>
                                    <Error>
                                        <Code>NoSuchUpload</Code>
                                        <Message>The specified upload does not exist.</Message>
                                    </Error>"#,
                                    ),
                                ))
                            }
                            CompleteMpuBehavior::Fail => Ok(HttpResponse::new(
                                400.try_into().unwrap(),
                                SdkBody::from(
                                    r#"<?xml version="1.0" encoding="UTF-8"?>
                                    <Error>
                                        <Code>InvalidPart</Code>
                                        <Message>One or more of the specified parts could not be found.</Message>
                                    </Error>"#,
                                ),
                            )),
                            CompleteMpuBehavior::HoldThenOk => {
                                complete_release
                                    .acquire()
                                    .await
                                    .expect("release semaphore closed")
                                    .forget();
                                Ok(HttpResponse::new(
                                    200.try_into().unwrap(),
                                    SdkBody::from(
                                        r#"<?xml version="1.0" encoding="UTF-8"?>
                                    <CompleteMultipartUploadResult>
                                        <Bucket>test-bucket</Bucket>
                                        <Key>test-key</Key>
                                        <ETag>"test-object-etag"</ETag>
                                    </CompleteMultipartUploadResult>"#,
                                    ),
                                ))
                            }
                            CompleteMpuBehavior::HoldThenFail => unreachable!("resolved above"),
                        }
                    });
                }
                ("DELETE", true) => {
                    self.abort_uris.lock().unwrap().push(uri);
                    self.abort_started.add_permits(1);
                    if let CompleteMpuBehavior::HoldThenOk = self.behavior {
                        let abort_release = self.abort_release.clone();
                        return HttpConnectorFuture::new(async move {
                            abort_release
                                .acquire()
                                .await
                                .expect("release semaphore closed")
                                .forget();
                            Ok(HttpResponse::new(204.try_into().unwrap(), SdkBody::empty()))
                        });
                    }
                    HttpResponse::new(204.try_into().unwrap(), SdkBody::empty())
                }
                _ => panic!("unexpected request: {} {uri}", request.method()),
            };
            HttpConnectorFuture::ready(Ok(response))
        }
    }

    /// Semaphores and recorded requests shared with a [`CompleteMpuConnector`].
    struct CompleteMpuProbe {
        complete_started: Arc<Semaphore>,
        complete_release: Arc<Semaphore>,
        abort_started: Arc<Semaphore>,
        abort_release: Arc<Semaphore>,
        abort_uris: Arc<Mutex<Vec<String>>>,
    }

    /// Starts a single-part multipart upload against a
    /// [`CompleteMpuConnector`] and waits until CompleteMultipartUpload has
    /// been sent.
    async fn start_upload_until_complete_mpu(
        runtime_config: RuntimeConfig,
        behavior: CompleteMpuBehavior,
        concurrency: usize,
    ) -> (crate::operation::upload::UploadHandle, CompleteMpuProbe) {
        let probe = CompleteMpuProbe {
            complete_started: Arc::new(Semaphore::new(0)),
            complete_release: Arc::new(Semaphore::new(0)),
            abort_started: Arc::new(Semaphore::new(0)),
            abort_release: Arc::new(Semaphore::new(0)),
            abort_uris: Arc::new(Mutex::new(Vec::new())),
        };
        let connector = SharedHttpConnector::new(CompleteMpuConnector {
            behavior,
            complete_started: probe.complete_started.clone(),
            complete_release: probe.complete_release.clone(),
            abort_started: probe.abort_started.clone(),
            abort_release: probe.abort_release.clone(),
            abort_uris: probe.abort_uris.clone(),
        });
        let http_client = http_client_fn(move |_, _| connector.clone());
        let client = aws_sdk_s3::Client::from_conf(
            aws_sdk_s3::config::Config::builder()
                .http_client(http_client)
                .region(aws_sdk_s3::config::Region::new("us-west-2"))
                .with_test_defaults()
                .build(),
        );

        let tm_config = crate::Config::builder()
            .concurrency(ConcurrencyMode::Explicit(concurrency))
            .runtime_config(runtime_config)
            .set_multipart_threshold(PartSize::Target(ByteSize::new(10)))
            .set_target_part_size(PartSize::Target(ByteSize::mib(5)))
            .sdk_client(client)
            .build()
            .expect("valid config");
        let tm = crate::Client::new(tm_config);
        let handle = UploadInput::builder()
            .bucket("test-bucket")
            .key("test-key")
            .body(InputStream::from(Bytes::from_static(
                b"force multipart upload",
            )))
            .initiate_with(&tm)
            .unwrap();

        tokio::time::timeout(Duration::from_secs(5), probe.complete_started.acquire())
            .await
            .expect("CompleteMultipartUpload did not start")
            .expect("start semaphore closed")
            .forget();
        (handle, probe)
    }

    /// An abort requested while CompleteMultipartUpload is in flight sends
    /// AbortMultipartUpload without interrupting Complete. When Complete then
    /// returns `NoSuchUpload` (the abort won), the upload is cancelled.
    ///
    /// Concurrency 2 so AbortMultipartUpload can go out while Complete holds a
    /// slot; Complete is released only after S3 has seen the abort, as in the
    /// real race.
    async fn abort_during_complete_mpu(runtime_config: RuntimeConfig) {
        let (handle, probe) = start_upload_until_complete_mpu(
            runtime_config,
            CompleteMpuBehavior::HoldThenNoSuchUpload,
            2,
        )
        .await;

        let mut abort = Box::pin(handle.abort());
        assert!(
            poll_once(&mut abort).await.is_pending(),
            "abort returned while CompleteMultipartUpload was held"
        );
        tokio::time::timeout(Duration::from_secs(5), probe.abort_started.acquire())
            .await
            .expect("AbortMultipartUpload was not sent while Complete was in flight")
            .expect("abort semaphore closed")
            .forget();
        probe.complete_release.add_permits(1);

        let aborted = tokio::time::timeout(Duration::from_secs(5), abort)
            .await
            .expect("abort hung after CompleteMultipartUpload returned")
            .expect("abort failed");

        assert_eq!(aborted.outcome(), AbortOutcome::Cancelled);
        assert_eq!(aborted.upload_id(), Some("test-upload-id"));
        let abort_uris = probe.abort_uris.lock().unwrap();
        assert_eq!(
            abort_uris.len(),
            1,
            "expected one AbortMultipartUpload: {abort_uris:?}"
        );
        assert!(
            abort_uris[0].contains("uploadId=test-upload-id"),
            "AbortMultipartUpload for the wrong upload: {}",
            abort_uris[0]
        );
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn abort_during_complete_mpu_aborts_upload_on_tokio_runtime() {
        abort_during_complete_mpu(RuntimeConfig::multi_thread_tokio()).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn abort_during_complete_mpu_aborts_upload_on_managed_runtime() {
        abort_during_complete_mpu(RuntimeConfig::default()).await;
    }

    /// An abort requested while CompleteMultipartUpload is in flight sends
    /// AbortMultipartUpload. When Complete then fails with an error other
    /// than `NoSuchUpload`, `abort()` returns that error instead of
    /// `Cancelled`.
    async fn complete_mpu_failure_during_abort(runtime_config: RuntimeConfig) {
        let (handle, probe) =
            start_upload_until_complete_mpu(runtime_config, CompleteMpuBehavior::HoldThenFail, 2)
                .await;

        let mut abort = Box::pin(handle.abort());
        assert!(
            poll_once(&mut abort).await.is_pending(),
            "abort returned while CompleteMultipartUpload was held"
        );
        tokio::time::timeout(Duration::from_secs(5), probe.abort_started.acquire())
            .await
            .expect("AbortMultipartUpload was not sent while Complete was in flight")
            .expect("abort semaphore closed")
            .forget();
        probe.complete_release.add_permits(1);

        let error = tokio::time::timeout(Duration::from_secs(5), abort)
            .await
            .expect("abort hung after CompleteMultipartUpload returned")
            .expect_err("a Complete failure during abort must be returned");
        assert_eq!(error.code(), Some("InvalidPart"));
        let abort_uris = probe.abort_uris.lock().unwrap();
        assert_eq!(
            abort_uris.len(),
            1,
            "expected one AbortMultipartUpload: {abort_uris:?}"
        );
        assert!(
            abort_uris[0].contains("uploadId=test-upload-id"),
            "AbortMultipartUpload for the wrong upload: {}",
            abort_uris[0]
        );
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn complete_mpu_failure_during_abort_returns_error_on_tokio_runtime() {
        complete_mpu_failure_during_abort(RuntimeConfig::multi_thread_tokio()).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn complete_mpu_failure_during_abort_returns_error_on_managed_runtime() {
        complete_mpu_failure_during_abort(RuntimeConfig::default()).await;
    }

    /// A failed CompleteMultipartUpload aborts the multipart upload, and
    /// `abort()` on the failed upload returns the failure without sending a
    /// second AbortMultipartUpload.
    async fn abort_after_failed_complete_mpu(runtime_config: RuntimeConfig) {
        let (handle, probe) =
            start_upload_until_complete_mpu(runtime_config, CompleteMpuBehavior::Fail, 1).await;

        tokio::time::timeout(Duration::from_secs(5), async {
            while handle.status() != TransferStatus::Failed {
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        })
        .await
        .expect("upload did not fail after CompleteMultipartUpload error");

        let error = tokio::time::timeout(Duration::from_secs(5), handle.abort())
            .await
            .expect("abort hung on a failed upload")
            .expect_err("abort on a failed upload must return its error");
        assert_eq!(error.code(), Some("InvalidPart"));
        let abort_uris = probe.abort_uris.lock().unwrap();
        assert_eq!(
            abort_uris.len(),
            1,
            "expected one AbortMultipartUpload: {abort_uris:?}"
        );
        assert!(
            abort_uris[0].contains("uploadId=test-upload-id"),
            "AbortMultipartUpload for the wrong upload: {}",
            abort_uris[0]
        );
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn abort_after_failed_complete_mpu_returns_error_on_tokio_runtime() {
        abort_after_failed_complete_mpu(RuntimeConfig::multi_thread_tokio()).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn abort_after_failed_complete_mpu_returns_error_on_managed_runtime() {
        abort_after_failed_complete_mpu(RuntimeConfig::default()).await;
    }

    /// An abort requested while CompleteMultipartUpload is in flight sends
    /// AbortMultipartUpload. When Complete then returns 200 (S3 committed
    /// first), `abort()` reports `AlreadyCompleted` with the upload output,
    /// and returns only after AbortMultipartUpload has finished.
    async fn complete_mpu_wins_race_with_abort(runtime_config: RuntimeConfig) {
        let (handle, probe) =
            start_upload_until_complete_mpu(runtime_config, CompleteMpuBehavior::HoldThenOk, 2)
                .await;

        let mut abort = Box::pin(handle.abort());
        assert!(
            poll_once(&mut abort).await.is_pending(),
            "abort returned while CompleteMultipartUpload was held"
        );
        tokio::time::timeout(Duration::from_secs(5), probe.abort_started.acquire())
            .await
            .expect("AbortMultipartUpload was not sent while Complete was in flight")
            .expect("abort semaphore closed")
            .forget();
        probe.complete_release.add_permits(1);

        // Complete has committed, but AbortMultipartUpload is still held.
        // There is no signal for when the transfer has handled Complete's
        // response, so give it time; a regression returns early here.
        tokio::time::sleep(Duration::from_millis(100)).await;
        assert!(
            poll_once(&mut abort).await.is_pending(),
            "abort returned while AbortMultipartUpload was still in flight"
        );
        probe.abort_release.add_permits(1);

        let aborted = tokio::time::timeout(Duration::from_secs(5), abort)
            .await
            .expect("abort hung after AbortMultipartUpload returned")
            .expect("abort failed");

        assert_eq!(aborted.outcome(), AbortOutcome::AlreadyCompleted);
        assert!(
            aborted.output().is_some(),
            "AlreadyCompleted must carry the upload output"
        );
        let abort_uris = probe.abort_uris.lock().unwrap();
        assert_eq!(
            abort_uris.len(),
            1,
            "expected one AbortMultipartUpload: {abort_uris:?}"
        );
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn complete_mpu_wins_race_with_abort_on_tokio_runtime() {
        complete_mpu_wins_race_with_abort(RuntimeConfig::multi_thread_tokio()).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn complete_mpu_wins_race_with_abort_on_managed_runtime() {
        complete_mpu_wins_race_with_abort(RuntimeConfig::default()).await;
    }

    /// Connector that holds PutObject forever, adding a permit to
    /// `put_started` when it arrives, and records the URI of any other
    /// request.
    #[derive(Debug)]
    struct HeldPutObjectConnector {
        put_started: Arc<Semaphore>,
        other_uris: Arc<Mutex<Vec<String>>>,
    }

    impl HttpConnector for HeldPutObjectConnector {
        fn call(&self, request: HttpRequest) -> HttpConnectorFuture {
            let uri = request.uri().to_string();
            if request.method() == "PUT" && !uri.contains("uploadId=") {
                self.put_started.add_permits(1);
                return HttpConnectorFuture::new(std::future::pending());
            }
            self.other_uris
                .lock()
                .unwrap()
                .push(format!("{} {uri}", request.method()));
            HttpConnectorFuture::ready(Ok(HttpResponse::new(
                500.try_into().unwrap(),
                SdkBody::empty(),
            )))
        }
    }

    /// An abort interrupts an in-flight PutObject instead of waiting for it.
    /// The upload ends as cancelled with no upload ID, and nothing else is
    /// sent.
    async fn abort_interrupts_put_object(runtime_config: RuntimeConfig) {
        let put_started = Arc::new(Semaphore::new(0));
        let other_uris = Arc::new(Mutex::new(Vec::new()));
        let connector = SharedHttpConnector::new(HeldPutObjectConnector {
            put_started: put_started.clone(),
            other_uris: other_uris.clone(),
        });
        let http_client = http_client_fn(move |_, _| connector.clone());
        let client = aws_sdk_s3::Client::from_conf(
            aws_sdk_s3::config::Config::builder()
                .http_client(http_client)
                .region(aws_sdk_s3::config::Region::new("us-west-2"))
                .with_test_defaults()
                .build(),
        );

        let tm_config = crate::Config::builder()
            .concurrency(ConcurrencyMode::Explicit(1))
            .runtime_config(runtime_config)
            .set_multipart_threshold(PartSize::Target(ByteSize::mib(1)))
            .sdk_client(client)
            .build()
            .expect("valid config");
        let tm = crate::Client::new(tm_config);
        let handle = UploadInput::builder()
            .bucket("test-bucket")
            .key("test-key")
            .body(InputStream::from(Bytes::from_static(b"single put object")))
            .initiate_with(&tm)
            .unwrap();

        tokio::time::timeout(Duration::from_secs(5), put_started.acquire())
            .await
            .expect("PutObject did not start")
            .expect("start semaphore closed")
            .forget();

        let aborted = tokio::time::timeout(Duration::from_secs(5), handle.abort())
            .await
            .expect("abort waited for the held PutObject")
            .expect("abort failed");

        assert_eq!(aborted.outcome(), AbortOutcome::Cancelled);
        assert_eq!(aborted.upload_id(), None);
        let other_uris = other_uris.lock().unwrap();
        assert!(other_uris.is_empty(), "unexpected requests: {other_uris:?}");
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn abort_interrupts_put_object_on_tokio_runtime() {
        abort_interrupts_put_object(RuntimeConfig::multi_thread_tokio()).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn abort_interrupts_put_object_on_managed_runtime() {
        abort_interrupts_put_object(RuntimeConfig::default()).await;
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_abort_upload() {
        let body = Bytes::from_static(b"every adolescent dog goes bonkers early");
        let stream = InputStream::from(body);

        let create_mpu =
            mock!(aws_sdk_s3::Client::create_multipart_upload).then_output(move || {
                CreateMultipartUploadOutput::builder()
                    .upload_id("test-upload-id")
                    .build()
            });

        let upload_part = mock!(aws_sdk_s3::Client::upload_part)
            .then_output(|| UploadPartOutput::builder().e_tag("test-etag").build());

        let abort_mpu = mock!(aws_sdk_s3::Client::abort_multipart_upload)
            .then_output(|| AbortMultipartUploadOutput::builder().build());

        // The test races abort against the upload completion. Under slow execution
        // (e.g. ASAN-instrumented), the single-part upload can reach
        // CompleteMultipartUpload before abort dispatches. Provide a rule for that
        // case so the mock doesn't panic on no-rule-matched, which would crash a
        // managed thread and leave Arc cycles for LeakSanitizer to flag.
        let complete_mpu = mock!(aws_sdk_s3::Client::complete_multipart_upload)
            .then_output(|| CompleteMultipartUploadOutput::builder().build());

        let client = mock_client!(
            aws_sdk_s3,
            RuleMode::MatchAny,
            &[create_mpu, upload_part, abort_mpu, complete_mpu]
        );

        let tm_config = crate::Config::builder()
            .concurrency(ConcurrencyMode::Explicit(1))
            .set_multipart_threshold(PartSize::Target(ByteSize::new(10)))
            .set_target_part_size(PartSize::Target(ByteSize::mib(5)))
            .sdk_client(client)
            .build()
            .expect("valid config");

        let tm = crate::Client::new(tm_config);

        let request = UploadInput::builder()
            .bucket("test-bucket")
            .key("test-key")
            .body(stream);
        let handle = request.initiate_with(&tm).unwrap();

        // Small delay to let scheduler start processing
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Abort should complete without error
        let result = tokio::time::timeout(std::time::Duration::from_secs(5), handle.abort())
            .await
            .expect("abort timed out");
        assert!(result.is_ok());
    }
}

/// Integration-style tests using StaticReplayClient for retry behavior
#[cfg(test)]
mod retry_tests {
    use crate::types::ByteSize;
    use aws_sdk_s3::config::Region;
    use aws_smithy_http_client::test_util::{ReplayEvent, StaticReplayClient};
    use aws_smithy_types::body::SdkBody;
    use bytes::Bytes;

    use crate::config::{ConcurrencyMode, PartSize};
    use crate::io::InputStream;

    fn dummy_request() -> http::Request<SdkBody> {
        http::Request::builder().body(SdkBody::empty()).unwrap()
    }

    /// Test that SDK retries transient errors for upload_part.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_upload_part_retry() {
        // Responses in order: CreateMPU, UploadPart (500), UploadPart (200 retry), CompleteMPU
        let http_client = StaticReplayClient::new(vec![
            // CreateMultipartUpload - success
            ReplayEvent::new(
                dummy_request(),
                http::Response::builder()
                    .status(200)
                    .body(SdkBody::from(
                        r#"<?xml version="1.0" encoding="UTF-8"?>
                        <InitiateMultipartUploadResult>
                            <Bucket>test-bucket</Bucket>
                            <Key>test-key</Key>
                            <UploadId>test-upload-id</UploadId>
                        </InitiateMultipartUploadResult>"#,
                    ))
                    .unwrap(),
            ),
            // UploadPart - first attempt fails with 500
            ReplayEvent::new(
                dummy_request(),
                http::Response::builder()
                    .status(500)
                    .body(SdkBody::from(
                        r#"<?xml version="1.0" encoding="UTF-8"?>
                        <Error>
                            <Code>InternalError</Code>
                            <Message>Internal Server Error</Message>
                        </Error>"#,
                    ))
                    .unwrap(),
            ),
            // UploadPart - retry succeeds
            ReplayEvent::new(
                dummy_request(),
                http::Response::builder()
                    .status(200)
                    .header("ETag", "\"test-etag\"")
                    .body(SdkBody::empty())
                    .unwrap(),
            ),
            // CompleteMultipartUpload - success
            ReplayEvent::new(
                dummy_request(),
                http::Response::builder()
                    .status(200)
                    .body(SdkBody::from(
                        r#"<?xml version="1.0" encoding="UTF-8"?>
                        <CompleteMultipartUploadResult>
                            <Location>https://test-bucket.s3.amazonaws.com/test-key</Location>
                            <Bucket>test-bucket</Bucket>
                            <Key>test-key</Key>
                            <ETag>"final-etag"</ETag>
                        </CompleteMultipartUploadResult>"#,
                    ))
                    .unwrap(),
            ),
        ]);

        let s3_client = aws_sdk_s3::Client::from_conf(
            aws_sdk_s3::config::Config::builder()
                .http_client(http_client.clone())
                .region(Region::from_static("us-west-2"))
                .retry_config(aws_config::retry::RetryConfig::standard().with_max_attempts(3))
                .with_test_defaults()
                .build(),
        );

        let tm_config = crate::Config::builder()
            .concurrency(ConcurrencyMode::Explicit(1))
            .set_multipart_threshold(PartSize::Target(ByteSize::new(10)))
            .set_target_part_size(PartSize::Target(ByteSize::mib(5)))
            .sdk_client(s3_client)
            .build()
            .expect("valid config");

        let tm = crate::Client::new(tm_config);

        let body = Bytes::from_static(b"every adolescent dog goes bonkers early");
        let stream = InputStream::from(body);

        let handle = tm
            .upload()
            .bucket("test-bucket")
            .key("test-key")
            .body(stream)
            .initiate()
            .unwrap();

        let result = tokio::time::timeout(std::time::Duration::from_secs(5), handle.join())
            .await
            .expect("join timed out");
        assert!(
            result.is_ok(),
            "upload should succeed after retry: {:?}",
            result.err()
        );

        // Verify all 4 requests were made (including the retry)
        let requests: Vec<_> = http_client.actual_requests().collect();
        assert_eq!(
            4,
            requests.len(),
            "should have made 4 requests (including retry)"
        );
    }

    /// Test that SDK retries an `InternalError` embedded in a CompleteMultipartUpload HTTP 200.
    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_complete_mpu_http_200_internal_error_retry() {
        // Responses in order: CreateMPU, UploadPart, CompleteMPU (200 + error), CompleteMPU (retry)
        let http_client = StaticReplayClient::new(vec![
            // CreateMultipartUpload - success
            ReplayEvent::new(
                dummy_request(),
                http::Response::builder()
                    .status(200)
                    .body(SdkBody::from(
                        r#"<?xml version="1.0" encoding="UTF-8"?>
                        <InitiateMultipartUploadResult>
                            <Bucket>test-bucket</Bucket>
                            <Key>test-key</Key>
                            <UploadId>test-upload-id</UploadId>
                        </InitiateMultipartUploadResult>"#,
                    ))
                    .unwrap(),
            ),
            // UploadPart - success
            ReplayEvent::new(
                dummy_request(),
                http::Response::builder()
                    .status(200)
                    .header("ETag", "\"test-etag\"")
                    .body(SdkBody::empty())
                    .unwrap(),
            ),
            // CompleteMultipartUpload - HTTP 200 carrying an InternalError body
            ReplayEvent::new(
                dummy_request(),
                http::Response::builder()
                    .status(200)
                    .body(SdkBody::from(
                        r#"<?xml version="1.0" encoding="UTF-8"?>
                        <Error>
                            <Code>InternalError</Code>
                            <Message>We encountered an internal error. Please try again.</Message>
                            <RequestId>656c76696e6727732072657175657374</RequestId>
                            <HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPf==</HostId>
                        </Error>"#,
                    ))
                    .unwrap(),
            ),
            // CompleteMultipartUpload - retry succeeds
            ReplayEvent::new(
                dummy_request(),
                http::Response::builder()
                    .status(200)
                    .body(SdkBody::from(
                        r#"<?xml version="1.0" encoding="UTF-8"?>
                        <CompleteMultipartUploadResult>
                            <Location>https://test-bucket.s3.amazonaws.com/test-key</Location>
                            <Bucket>test-bucket</Bucket>
                            <Key>test-key</Key>
                            <ETag>"final-etag"</ETag>
                        </CompleteMultipartUploadResult>"#,
                    ))
                    .unwrap(),
            ),
        ]);

        let s3_client = aws_sdk_s3::Client::from_conf(
            aws_sdk_s3::config::Config::builder()
                .http_client(http_client.clone())
                .region(Region::from_static("us-west-2"))
                .retry_config(aws_config::retry::RetryConfig::standard().with_max_attempts(3))
                .with_test_defaults()
                .build(),
        );

        let tm_config = crate::Config::builder()
            .concurrency(ConcurrencyMode::Explicit(1))
            .set_multipart_threshold(PartSize::Target(ByteSize::new(10)))
            .set_target_part_size(PartSize::Target(ByteSize::mib(5)))
            .sdk_client(s3_client)
            .build()
            .expect("valid config");

        let tm = crate::Client::new(tm_config);

        let body = Bytes::from_static(b"every adolescent dog goes bonkers early");
        let stream = InputStream::from(body);

        let handle = tm
            .upload()
            .bucket("test-bucket")
            .key("test-key")
            .body(stream)
            .initiate()
            .unwrap();

        let result = tokio::time::timeout(std::time::Duration::from_secs(5), handle.join())
            .await
            .expect("join timed out");
        assert!(
            result.is_ok(),
            "upload should succeed after CompleteMultipartUpload retry: {:?}",
            result.err()
        );

        // Verify all 4 requests were made (including the retry)
        let requests: Vec<_> = http_client.actual_requests().collect();
        assert_eq!(
            4,
            requests.len(),
            "should have made 4 requests (including retry)"
        );
    }
}