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

use std::fmt;
use std::ops::RangeInclusive;
use std::path::PathBuf;

use aws_sdk_s3::operation::abort_multipart_upload::AbortMultipartUploadError;
use aws_sdk_s3::operation::complete_multipart_upload::CompleteMultipartUploadError;
use aws_sdk_s3::operation::create_multipart_upload::CreateMultipartUploadError;
use aws_sdk_s3::operation::get_object::GetObjectError;
use aws_sdk_s3::operation::head_object::HeadObjectError;
use aws_sdk_s3::operation::list_objects_v2::ListObjectsV2Error;
use aws_sdk_s3::operation::put_object::PutObjectError;
use aws_sdk_s3::operation::upload_part::UploadPartError;
use aws_sdk_s3::operation::RequestIdExt;
use aws_smithy_observability::unit_of_work::checksums::{
    ChecksumOutcome, ResponseChecksumAlgorithm,
};
use aws_smithy_runtime_api::client::orchestrator::HttpResponse;
use aws_smithy_runtime_api::client::result::{ConnectorError, SdkError};
use aws_smithy_types::error::metadata::ProvideErrorMetadata;
use aws_smithy_types::retry::ErrorKind as RetryErrorKind;
use aws_types::request_id::RequestId;

use crate::model::ChecksumAlgorithm;
use crate::types::{FailedDownload, FailedUpload};

pub use crate::model::UnknownVariantError;

/// A boxed error that is `Send` and `Sync`.
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;

/// Errors returned by this library.
///
/// NOTE: Use [`aws_smithy_types::error::display::DisplayErrorContext`] or similar to display
/// the entire error cause/source chain.
#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
    source: BoxError,
    /// Optional metadata. `None` unless a builder attached service, chunk,
    /// local-path, upload, or bulk-failure detail. Boxed to keep [`Error`] small.
    extra: Option<Box<ErrorExtra>>,
}

/// Optional metadata attached to an [`Error`].
#[derive(Debug, Default)]
struct ErrorExtra {
    /// Set when the error originated from an S3 service call.
    service: Option<ServiceMetadata>,
    /// HTTP status of an unsuccessful service response, including bodyless HEAD errors.
    http_status: Option<u16>,
    /// Set when the error is attributable to a specific chunk of an object.
    location: Option<ChunkRef>,
    /// Set when a local filesystem operation on a known path failed.
    local: Option<LocalContext>,
    /// Set when a failed upload left this multipart upload open in S3.
    upload_id: Option<String>,
    /// Per-object upload failures when this error aggregates a bulk upload.
    failed_uploads: Option<Vec<FailedUpload>>,
    /// Per-object download failures when this error aggregates a bulk download.
    failed_downloads: Option<Vec<FailedDownload>>,
    /// `true` when the underlying `SdkError` was a transient transport failure
    /// (a connect/read/write IO error or a client-side timeout) rather than a
    /// service response — a re-issuable failure the SDK's own retry may not have
    /// recovered (e.g. its shared retry token bucket was exhausted under a
    /// concurrent burst). Set at conversion from the typed `SdkError`, where the
    /// distinction is still available before type erasure. Never set for
    /// throttling/service errors — see `retry::classify_upload_part_retry`.
    transient_transport: bool,
}

/// General categories of transfer errors.
///
/// The kind classifies where a failure arose. It does not say whether
/// resubmitting the operation can succeed: failures the transfer manager can
/// repair, such as throttling responses and interrupted body reads, are retried
/// internally before an error of any kind is returned.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ErrorKind {
    /// The operation's input was rejected: a required field is missing, a value
    /// is out of range, settings conflict, or the source cannot be transferred as
    /// requested, such as a stream that produces more parts than a multipart
    /// upload allows or an object key that resolves outside the download
    /// destination or to the destination itself. Conditions visible in the
    /// input are reported before any request is sent; conditions that depend
    /// on the source data are reported when the transfer encounters them.
    InputInvalid,

    /// An I/O operation failed. This covers both local filesystem failures
    /// (opening, reading, writing, or renaming a file) and transport failures
    /// while reading an object body from S3, such as a reset connection or a
    /// truncated response. The source error identifies which.
    ///
    /// Because the kind spans local and remote failures, it does not indicate
    /// whether resubmitting the operation can succeed. When a body read fails
    /// for a specific chunk, [`Error::chunk`] identifies it.
    IOError,

    /// The transfer manager could not continue for an internal reason that is
    /// not an input, I/O or service failure.
    RuntimeError,

    /// Object discovery failed for a reason that is not a service-call error, such
    /// as a response missing required metadata.
    ObjectNotDiscoverable,

    /// A request to S3 failed, or S3 answered with a response the transfer
    /// cannot use, such as an UploadPart response without an ETag or a ranged
    /// GetObject or HeadObject response whose `Content-Range` doesn't match the
    /// requested range. The
    /// originating operation, service error code (when S3 reported one),
    /// message, and request ids are available via the accessors on [`Error`]
    /// ([`Error::operation_name`], [`Error::code`], [`Error::request_id`]).
    ///
    /// Service-specific outcomes are identified by their code rather than by a
    /// kind of their own. A conditional write whose precondition did not hold
    /// (`if_match` / `if_none_match` on an upload) arrives here with
    /// [`Error::code`] of `"PreconditionFailed"`; S3 reports that code in the
    /// response body, so it is available whatever HTTP status carries it.
    ///
    /// A whole-object download with checksum validation enabled, or a download of an
    /// open-ended or suffix range, discovers the object with HeadObject. S3 answers a
    /// failed HeadObject without a body, so the error carries the HTTP status and
    /// request ids but no message, and a code only where the status identifies one:
    /// `"PreconditionFailed"` for 412, `"NotModified"` for 304, `"InvalidRange"` for
    /// 416, and the SDK's `"NotFound"` for 404. A missing key is `"NotFound"`, not
    /// `"NoSuchKey"` as a failed GetObject reports.
    ServiceError,

    /// Object integrity validation failed: the received bytes did not match the
    /// expected checksum. See the wrapped [`IntegrityError`] for detail.
    IntegrityError(IntegrityError),

    /// A child of a bulk transfer (`upload_objects` / `download_objects`) failed.
    /// The individual failures are available via [`Error::failed_uploads`] /
    /// [`Error::failed_downloads`].
    ///
    /// The error's [`source`](std::error::Error::source) is the error of the
    /// first failed object. Under
    /// [`FailedTransferPolicy::Abort`](crate::types::FailedTransferPolicy::Abort)
    /// that is the failure that stopped the transfer.
    ChildOperationFailed,

    /// The operation was cancelled, either because the user called `.abort()` on the
    /// handle, or a child operation failed under the abort policy.
    OperationCancelled,
}

/// Detail about an integrity (checksum) validation failure.
///
/// [`algorithm`](Self::algorithm), [`expected`](Self::expected) and
/// [`computed`](Self::computed) are all `Some` for a mismatch the SDK reported. The
/// body error that ended the read is available via [`std::error::Error::source`].
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct IntegrityError {
    algorithm: Option<ChecksumAlgorithm>,
    expected: Option<String>,
    computed: Option<String>,
}

impl IntegrityError {
    /// The checksum algorithm that failed validation, if known.
    pub fn algorithm(&self) -> Option<&ChecksumAlgorithm> {
        self.algorithm.as_ref()
    }

    /// The checksum S3 reported for the object, base64-encoded, if known.
    pub fn expected(&self) -> Option<&str> {
        self.expected.as_deref()
    }

    /// The checksum computed over the received bytes, base64-encoded, if known.
    pub fn computed(&self) -> Option<&str> {
        self.computed.as_deref()
    }
}

/// Identifies the chunk of an object a failure is attributable to.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct ChunkRef {
    seq: u64,
    range: Option<RangeInclusive<u64>>,
}

impl ChunkRef {
    pub(crate) fn new(seq: u64, range: Option<RangeInclusive<u64>>) -> Self {
        Self { seq, range }
    }

    /// Sequence number of the chunk within the transfer.
    pub fn seq(&self) -> u64 {
        self.seq
    }

    /// Byte range of the chunk within the object, if known.
    pub fn byte_range(&self) -> Option<&RangeInclusive<u64>> {
        self.range.as_ref()
    }
}

/// A failed local filesystem operation and the path it acted on.
///
/// `action` is a lowercase gerund phrase whose object is `path`, such as
/// `"opening"` or `"creating temporary file for"`, so that `Display` reads
/// `I/O error opening "/data/a.bin"`.
#[derive(Debug)]
struct LocalContext {
    action: &'static str,
    path: PathBuf,
    /// The object key the operation was for, when there is one.
    key: Option<String>,
}

/// Service-call detail, read from the concrete `SdkError` of a failed request, or from the output
/// of a successful response the transfer cannot use.
#[derive(Debug)]
struct ServiceMetadata {
    operation: &'static str,
    code: Option<String>,
    message: Option<String>,
    request_id: Option<String>,
    extended_request_id: Option<String>,
}

impl Error {
    /// Creates a new transfer [`Error`] from a known kind and an arbitrary source.
    pub fn new<E>(kind: ErrorKind, err: E) -> Error
    where
        E: Into<BoxError>,
    {
        Error {
            kind,
            source: err.into(),
            extra: None,
        }
    }

    /// Returns the corresponding [`ErrorKind`] for this error.
    pub fn kind(&self) -> &ErrorKind {
        &self.kind
    }

    /// Test-only: a `ServiceError` flagged as transient transport, mirroring what
    /// `service_error` produces for an IO `DispatchFailure` (which cannot be
    /// constructed directly in a unit test).
    #[cfg(test)]
    pub(crate) fn test_transient_transport() -> Error {
        Error {
            kind: ErrorKind::ServiceError,
            source: "injected transient transport".into(),
            extra: Some(Box::new(ErrorExtra {
                transient_transport: true,
                ..Default::default()
            })),
        }
    }

    /// Test-only: a `ServiceError` carrying the given service error code,
    /// mirroring what `service_error` produces from an `SdkError` (which cannot
    /// be constructed directly in a unit test). Lets retry classifiers be tested
    /// against a code (e.g. throttle detection) without a live wire error.
    #[cfg(test)]
    pub(crate) fn test_service_error(code: &str) -> Error {
        Error {
            kind: ErrorKind::ServiceError,
            source: "injected service error".into(),
            extra: Some(Box::new(ErrorExtra {
                service: Some(ServiceMetadata {
                    operation: "TestOperation",
                    code: Some(code.to_owned()),
                    message: None,
                    request_id: None,
                    extended_request_id: None,
                }),
                ..Default::default()
            })),
        }
    }

    fn service(&self) -> Option<&ServiceMetadata> {
        self.extra.as_ref().and_then(|e| e.service.as_ref())
    }

    /// Lazily get a mutable reference to the boxed extra, allocating it on first use.
    fn extra_mut(&mut self) -> &mut ErrorExtra {
        self.extra
            .get_or_insert_with(|| Box::new(ErrorExtra::default()))
    }

    /// The S3 operation that produced this error, if it originated from a service
    /// call (e.g. `"GetObject"`, `"HeadObject"`, `"PutObject"`).
    pub fn operation_name(&self) -> Option<&str> {
        self.service().map(|m| m.operation)
    }

    /// The service error code, if any (e.g. `"NoSuchKey"`, `"AccessDenied"`).
    pub fn code(&self) -> Option<&str> {
        self.service().and_then(|m| m.code.as_deref())
    }

    /// HTTP status of the service response, if the error has one.
    pub(crate) fn http_status(&self) -> Option<u16> {
        self.extra.as_ref().and_then(|e| e.http_status)
    }

    /// The service error message, if any.
    pub fn message(&self) -> Option<&str> {
        self.service().and_then(|m| m.message.as_deref())
    }

    /// The AWS request id of the failed call, if any.
    pub fn request_id(&self) -> Option<&str> {
        self.service().and_then(|m| m.request_id.as_deref())
    }

    /// The AWS extended request id of the failed call, if any.
    pub fn extended_request_id(&self) -> Option<&str> {
        self.service()
            .and_then(|m| m.extended_request_id.as_deref())
    }

    /// Whether the service error code denotes a missing bucket, key, or
    /// multipart upload.
    pub fn is_not_found(&self) -> bool {
        matches!(
            self.code(),
            Some("NotFound" | "NoSuchKey" | "NoSuchUpload" | "NoSuchBucket")
        )
    }

    /// Whether this error was a transient transport failure (connection IO error
    /// or client-side timeout) as opposed to a service response. Such failures
    /// are safe to re-issue and may not have been recovered by the SDK's own
    /// retry (e.g. its shared retry token bucket was exhausted under a concurrent
    /// burst). Always `false` for throttling and modeled service errors.
    pub(crate) fn is_transient_transport(&self) -> bool {
        self.extra.as_ref().is_some_and(|e| e.transient_transport)
    }

    /// The chunk this failure is attributable to, if known.
    pub fn chunk(&self) -> Option<&ChunkRef> {
        self.extra.as_ref().and_then(|e| e.location.as_ref())
    }

    /// The ID of a multipart upload that the failed upload left open in S3.
    ///
    /// Set on the error an upload's [`join`](crate::operation::upload::UploadHandle::join) or
    /// [`abort`](crate::operation::upload::UploadHandle::abort) returns when the upload created a
    /// multipart upload that was neither completed nor aborted: the
    /// [`FailedMultipartUploadPolicy::Retain`](crate::types::FailedMultipartUploadPolicy::Retain)
    /// policy kept it, the AbortMultipartUpload request failed, or a worker panicked while
    /// executing the upload, as when the caller's [`PartStream`](crate::io::PartStream) panics,
    /// which ends it with [`ErrorKind::RuntimeError`] without sending AbortMultipartUpload. S3
    /// keeps, and bills for, the uploaded parts until the multipart upload is completed or
    /// aborted with this ID.
    ///
    /// A panic that ends the upload while CompleteMultipartUpload or AbortMultipartUpload is in
    /// flight also sets the ID, although that request may still close the multipart upload.
    ///
    /// `None` when no multipart upload was created, when AbortMultipartUpload removed it, and on
    /// errors from other operations.
    pub fn upload_id(&self) -> Option<&str> {
        self.extra.as_ref().and_then(|e| e.upload_id.as_deref())
    }

    /// Per-object upload failures, when this error aggregates a bulk upload.
    pub fn failed_uploads(&self) -> Option<&[FailedUpload]> {
        self.extra
            .as_ref()
            .and_then(|e| e.failed_uploads.as_deref())
    }

    /// Per-object download failures, when this error aggregates a bulk download.
    pub fn failed_downloads(&self) -> Option<&[FailedDownload]> {
        self.extra
            .as_ref()
            .and_then(|e| e.failed_downloads.as_deref())
    }

    /// Attaches chunk location, preserving kind and source.
    pub(crate) fn with_chunk(mut self, location: ChunkRef) -> Self {
        self.extra_mut().location = Some(location);
        self
    }

    /// Attaches the local operation that failed and the path it acted on,
    /// preserving kind and source. See [`io_at`] for `action`.
    pub(crate) fn with_local(mut self, action: &'static str, path: impl Into<PathBuf>) -> Self {
        self.extra_mut().local = Some(LocalContext {
            action,
            path: path.into(),
            key: None,
        });
        self
    }

    /// Names the object key a local operation attached with
    /// [`with_local`](Self::with_local) was for. No effect without one.
    pub(crate) fn with_local_key(mut self, key: impl Into<String>) -> Self {
        if let Some(local) = self.extra.as_mut().and_then(|e| e.local.as_mut()) {
            local.key = Some(key.into());
        }
        self
    }

    /// Attaches the ID of a multipart upload the failed upload left open,
    /// preserving kind and source.
    pub(crate) fn with_upload_id(mut self, upload_id: String) -> Self {
        self.extra_mut().upload_id = Some(upload_id);
        self
    }

    /// Attaches per-object upload failures, preserving kind and source.
    pub(crate) fn with_failed_uploads(mut self, failed: Vec<FailedUpload>) -> Self {
        self.extra_mut().failed_uploads = Some(failed);
        self
    }

    /// Attaches per-object download failures, preserving kind and source.
    pub(crate) fn with_failed_downloads(mut self, failed: Vec<FailedDownload>) -> Self {
        self.extra_mut().failed_downloads = Some(failed);
        self
    }
}

impl fmt::Display for Error {
    // Renders this error's own context only. Source detail (the underlying
    // SdkError message, checksum values) is reached through
    // [`std::error::Error::source`], e.g. via `DisplayErrorContext`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            ErrorKind::InputInvalid => write!(f, "invalid input")?,
            ErrorKind::IOError => write!(f, "I/O error")?,
            ErrorKind::RuntimeError => write!(f, "runtime error")?,
            ErrorKind::ObjectNotDiscoverable => write!(f, "object discovery failed")?,
            ErrorKind::ChildOperationFailed => {
                write!(f, "child operation failed")?;
                // A bulk transfer failed on one or more objects. Name the first
                // failure and the total so the top-level message is actionable;
                // the full per-object detail (including each object's own error)
                // is reached via `failed_uploads` / `failed_downloads`.
                let first_and_count = self
                    .failed_uploads()
                    .map(|f| {
                        let id = f
                            .first()
                            .and_then(|u| u.source_path())
                            .map(|p| p.display().to_string());
                        (id, f.len())
                    })
                    .or_else(|| {
                        self.failed_downloads().map(|f| {
                            let id = f.first().and_then(|d| d.input().key()).map(str::to_owned);
                            (id, f.len())
                        })
                    });
                if let Some((id, n)) = first_and_count {
                    match id {
                        Some(id) => write!(f, ": {id}")?,
                        None => write!(f, ": 1 object")?,
                    }
                    if n > 1 {
                        write!(f, " (and {} more)", n - 1)?;
                    }
                }
            }
            ErrorKind::OperationCancelled => write!(f, "operation cancelled")?,
            ErrorKind::ServiceError => {
                write!(f, "service error")?;
                if let Some(m) = self.service() {
                    write!(f, " calling {}", m.operation)?;
                    if let Some(c) = &m.code {
                        write!(f, " ({c})")?;
                    }
                }
            }
            ErrorKind::IntegrityError(ie) => {
                write!(f, "integrity error")?;
                if let Some(a) = &ie.algorithm {
                    write!(f, " ({a})")?;
                }
            }
        }

        if let Some(local) = self.extra.as_ref().and_then(|e| e.local.as_ref()) {
            write!(f, " {} \"{}\"", local.action, local.path.display())?;
            if let Some(key) = &local.key {
                write!(f, " (key \"{key}\")")?;
            }
        }

        if let Some(loc) = self.chunk() {
            match &loc.range {
                Some(r) => write!(f, " [chunk {}, bytes {}-{}]", loc.seq, r.start(), r.end())?,
                None => write!(f, " [chunk {}]", loc.seq)?,
            }
        }

        // Request ids are not part of the underlying SdkError's own Display, so
        // include them here to keep a logged error traceable.
        if let Some(m) = self.service() {
            match (&m.request_id, &m.extended_request_id) {
                (Some(rid), Some(ext)) => {
                    write!(f, " (request id: {rid}, extended request id: {ext})")?
                }
                (Some(rid), None) => write!(f, " (request id: {rid})")?,
                _ => {}
            }
        }
        Ok(())
    }
}

impl std::error::Error for Error {
    /// The underlying cause.
    ///
    /// For [`ErrorKind::ChildOperationFailed`] carrying per-object failures,
    /// this is the first failed object's error, so the source chain reaches
    /// the child's own cause. Otherwise it is the error this one was created
    /// from.
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        if matches!(self.kind, ErrorKind::ChildOperationFailed) {
            let first_child = self
                .failed_uploads()
                .and_then(<[FailedUpload]>::first)
                .map(FailedUpload::error)
                .or_else(|| {
                    self.failed_downloads()
                        .and_then(<[FailedDownload]>::first)
                        .map(FailedDownload::error)
                });
            if let Some(child) = first_child {
                return Some(child);
            }
        }
        Some(self.source.as_ref())
    }
}

impl From<std::io::Error> for Error {
    fn from(value: std::io::Error) -> Self {
        Self::new(ErrorKind::IOError, value)
    }
}

impl From<aws_smithy_types::error::operation::BuildError> for Error {
    fn from(value: aws_smithy_types::error::operation::BuildError) -> Self {
        Self::new(ErrorKind::InputInvalid, value)
    }
}

pub(crate) fn invalid_input<E>(err: E) -> Error
where
    E: Into<BoxError>,
{
    Error::new(ErrorKind::InputInvalid, err)
}

/// An [`ErrorKind::IOError`] for a local filesystem operation on `path` that
/// failed with `err`.
///
/// `action` is a lowercase gerund phrase whose object is `path`, such as
/// `"opening"`, `"reading"`, or `"renaming temporary file to"`. `Display`
/// renders `I/O error {action} "{path}"`; `err` is the source.
pub(crate) fn io_at(action: &'static str, path: impl Into<PathBuf>, err: std::io::Error) -> Error {
    Error::new(ErrorKind::IOError, err).with_local(action, path)
}

/// Object discovery failed for a non-service reason (e.g. a response missing
/// required metadata). Service-call failures during discovery convert from their
/// `SdkError` and become [`ErrorKind::ServiceError`].
pub(crate) fn discovery_failed<E>(err: E) -> Error
where
    E: Into<BoxError>,
{
    Error::new(ErrorKind::ObjectNotDiscoverable, err)
}

pub(crate) fn from_kind<E>(kind: ErrorKind) -> impl FnOnce(E) -> Error
where
    E: Into<BoxError>,
{
    |err| Error::new(kind, err)
}

/// Maps a body-stream error to an [`Error`].
///
/// `checksum` is the response's checksum outcome when `err` was read. A
/// [`ChecksumOutcome::Mismatch`] makes it an [`ErrorKind::IntegrityError`] carrying the
/// algorithm and the expected and computed checksums. Any other outcome, or none,
/// makes it an [`ErrorKind::IOError`].
pub(crate) fn body_read_error<E>(err: E, checksum: Option<ChecksumOutcome>) -> Error
where
    E: Into<BoxError>,
{
    match checksum {
        Some(ChecksumOutcome::Mismatch {
            algorithm,
            expected,
            computed,
        }) => Error {
            kind: ErrorKind::IntegrityError(IntegrityError {
                algorithm: Some(checksum_algorithm(algorithm)),
                expected: Some(expected),
                computed: Some(computed),
            }),
            source: err.into(),
            extra: None,
        },
        _ => Error::new(ErrorKind::IOError, err),
    }
}

/// Returns an integrity error carrying the algorithm and stored/calculated S3 header values.
///
/// `expected` and `computed` are base64 checksum encodings for the same algorithm.
pub(crate) fn integrity_mismatch(
    algorithm: ChecksumAlgorithm,
    expected: String,
    computed: String,
) -> Error {
    Error::new(
        ErrorKind::IntegrityError(IntegrityError {
            algorithm: Some(algorithm),
            expected: Some(expected),
            computed: Some(computed),
        }),
        "calculated object checksum does not match its stored value",
    )
}

/// The [`ChecksumAlgorithm`] named like a response checksum algorithm: its variant
/// for that name, or `Unknown` for a name it has no variant for. It maps by name so
/// an algorithm a newer SDK validates, which observability has no variant for yet,
/// still reads `Validated`.
pub(crate) fn checksum_algorithm(algorithm: ResponseChecksumAlgorithm) -> ChecksumAlgorithm {
    ChecksumAlgorithm::from(algorithm.as_str().to_ascii_uppercase().as_str())
}

/// Reads the operation name and service code/message/request ids into a
/// [`ServiceMetadata`].
fn service_metadata<E, R>(operation: &'static str, e: &SdkError<E, R>) -> ServiceMetadata
where
    E: ProvideErrorMetadata,
    SdkError<E, R>: RequestId + RequestIdExt,
{
    ServiceMetadata {
        operation,
        code: e.code().map(str::to_owned),
        message: e.message().map(str::to_owned),
        request_id: e.request_id().map(str::to_owned),
        extended_request_id: e.extended_request_id().map(str::to_owned),
    }
}

/// Whether a single [`ConnectorError`] frame denotes a transient transport
/// failure: an IO error, a client-side timeout, or one the http client tagged
/// [`RetryErrorKind::TransientError`] (an incomplete/truncated response, TLS
/// negotiation timeout, and similar). A bare `Other(None)` connector error
/// carries no marker and is not transient on its own.
fn connector_error_is_transient(conn: &ConnectorError) -> bool {
    conn.is_io() || conn.is_timeout() || conn.as_other() == Some(RetryErrorKind::TransientError)
}

/// Whether an `SdkError` is a transient transport failure — a connection-level
/// IO error, a client-side timeout, or a connector error the http client tagged
/// [`RetryErrorKind::TransientError`] (e.g. an incomplete/truncated HTTP
/// response) — rather than a service response. Captured here because the
/// flattening into [`ErrorKind::ServiceError`] erases the `SdkError` variant.
///
/// Walks the error source chain rather than inspecting only the outermost
/// [`ConnectorError`]. A nested dispatch can re-wrap a fully-classified inner
/// connector error inside an outer `ConnectorError::Other(None)`, which carries
/// no transient marker; the SDK's own `TransientErrorClassifier` inspects only
/// that outer frame and misclassifies the error as non-retryable. Scanning every
/// `ConnectorError` in the chain recovers the inner classification.
///
/// Deliberately excludes service responses: a 503 `SlowDown` arrives as a
/// `ServiceError`, not a `DispatchFailure`, so throttling is never classified
/// transient here (see `retry::classify_upload_part_retry` for why that matters).
fn is_sdk_transient_transport<E, R>(e: &SdkError<E, R>) -> bool {
    if let SdkError::TimeoutError(_) = e {
        return true;
    }
    // A DispatchFailure carries a ConnectorError; scan it and every nested
    // ConnectorError in the source chain for a transient classification.
    let conn = match e {
        SdkError::DispatchFailure(df) => df.as_connector_error(),
        _ => return false,
    };
    let Some(conn) = conn else { return false };
    if connector_error_is_transient(conn) {
        return true;
    }
    let mut source = std::error::Error::source(conn);
    while let Some(err) = source {
        if let Some(conn) = err.downcast_ref::<ConnectorError>() {
            if connector_error_is_transient(conn) {
                return true;
            }
        }
        source = err.source();
    }
    false
}

/// Associates an SDK service error type with its originating S3 operation.
pub(crate) trait SdkOperationError:
    ProvideErrorMetadata + std::error::Error + Send + Sync + 'static
{
    const OPERATION_NAME: &'static str;
}

/// Converts an `SdkError` into an [`ErrorKind::ServiceError`], capturing the
/// operation name, service metadata, and whether it was a transient transport
/// failure.
pub(crate) fn service_error<E: SdkOperationError>(e: SdkError<E, HttpResponse>) -> Error {
    let service = service_metadata(E::OPERATION_NAME, &e);
    let http_status = e.raw_response().map(|response| response.status().as_u16());
    let transient_transport = is_sdk_transient_transport(&e);
    Error {
        kind: ErrorKind::ServiceError,
        source: Box::new(e),
        extra: Some(Box::new(ErrorExtra {
            service: Some(service),
            http_status,
            transient_transport,
            ..Default::default()
        })),
    }
}

/// Converts a failed HeadObject into an [`ErrorKind::ServiceError`].
///
/// S3 answers a failed HEAD with the status and request ids only. A HEAD response has
/// no body, so it carries no error code or message. Where the status identifies a
/// single S3 code, the code is filled in: 412 is `PreconditionFailed`, 304 is
/// `NotModified`, and 416 is `InvalidRange`. Any other status keeps the code the SDK
/// reported: `NotFound` for 404, and none otherwise.
pub(crate) fn head_object_error(e: SdkError<HeadObjectError, HttpResponse>) -> Error {
    let mut error = service_error(e);
    let code = error
        .extra
        .as_ref()
        .and_then(|extra| extra.http_status)
        .and_then(head_status_code);
    if let (Some(code), Some(service)) = (
        code,
        error
            .extra
            .as_mut()
            .and_then(|extra| extra.service.as_mut()),
    ) {
        service.code.get_or_insert_with(|| code.to_owned());
    }
    error
}

/// The S3 error code a failed HEAD's `status` alone identifies, if there is exactly one.
fn head_status_code(status: u16) -> Option<&'static str> {
    match status {
        304 => Some("NotModified"),
        412 => Some("PreconditionFailed"),
        416 => Some("InvalidRange"),
        _ => None,
    }
}

/// Converts a successful S3 response that the transfer cannot use, such as one missing a field
/// the transfer requires, into an [`ErrorKind::ServiceError`].
///
/// The error carries the same service metadata as one converted from a failed request:
/// `operation`, `message`, and the request ids read from `output`. `code` is `None` because S3
/// reported no error. `message` is also the error's source, so it appears in the error chain.
pub(crate) fn invalid_service_response<O>(
    operation: &'static str,
    output: &O,
    message: impl Into<String>,
) -> Error
where
    O: RequestId + RequestIdExt,
{
    invalid_service_response_ids(
        operation,
        output.request_id(),
        output.extended_request_id(),
        message,
    )
}

/// [`invalid_service_response`] for a response already converted to transfer manager
/// metadata, which carries the request ids but not the SDK's request id traits.
pub(crate) fn invalid_service_response_ids(
    operation: &'static str,
    request_id: Option<&str>,
    extended_request_id: Option<&str>,
    message: impl Into<String>,
) -> Error {
    let message = message.into();
    Error {
        kind: ErrorKind::ServiceError,
        source: message.clone().into(),
        extra: Some(Box::new(ErrorExtra {
            service: Some(ServiceMetadata {
                operation,
                code: None,
                message: Some(message),
                request_id: request_id.map(str::to_owned),
                extended_request_id: extended_request_id.map(str::to_owned),
            }),
            ..Default::default()
        })),
    }
}

macro_rules! sdk_operation_error {
    ($err:ty, $op:literal) => {
        impl SdkOperationError for $err {
            const OPERATION_NAME: &'static str = $op;
        }
    };
}

sdk_operation_error!(GetObjectError, "GetObject");
sdk_operation_error!(HeadObjectError, "HeadObject");
sdk_operation_error!(PutObjectError, "PutObject");
sdk_operation_error!(UploadPartError, "UploadPart");
sdk_operation_error!(CreateMultipartUploadError, "CreateMultipartUpload");
sdk_operation_error!(CompleteMultipartUploadError, "CompleteMultipartUpload");
sdk_operation_error!(AbortMultipartUploadError, "AbortMultipartUpload");
sdk_operation_error!(ListObjectsV2Error, "ListObjectsV2");

impl From<crate::io::walk::WalkError> for Error {
    /// Maps a directory-walk failure to a transfer error, preserving the
    /// `WalkError` as the source so its classification and path remain reachable
    /// via [`std::error::Error::source`].
    ///
    /// A `ListObjectsV2` service failure is recovered to a full
    /// [`ErrorKind::ServiceError`] (with operation, code, and request ids); an
    /// unreadable or non-directory source root is [`ErrorKind::InputInvalid`];
    /// per-entry filesystem failures are [`ErrorKind::IOError`].
    fn from(e: crate::io::walk::WalkError) -> Self {
        use crate::io::walk::WalkErrorKind;
        let path = e.path().map(std::path::Path::to_path_buf);
        let local = |err: Error| match path {
            Some(path) => err.with_local("walking", path),
            None => err,
        };
        match e.kind() {
            WalkErrorKind::Service => {
                // The S3 walker's only service call is ListObjectsV2, so the
                // boxed source downcasts to that SdkError.
                match e
                    .into_source()
                    .downcast::<SdkError<ListObjectsV2Error, HttpResponse>>()
                {
                    Ok(sdk) => service_error(*sdk),
                    Err(src) => Error::new(ErrorKind::ObjectNotDiscoverable, src),
                }
            }
            WalkErrorKind::SourceUnreadable | WalkErrorKind::NotADirectory => {
                local(Error::new(ErrorKind::InputInvalid, e))
            }
            WalkErrorKind::Io
            | WalkErrorKind::PermissionDenied
            | WalkErrorKind::BrokenSymlink
            | WalkErrorKind::SymlinkCycle => local(Error::new(ErrorKind::IOError, e)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a ServiceError with the given metadata for Display tests.
    fn service(
        operation: &'static str,
        code: Option<&str>,
        request_id: Option<&str>,
        extended_request_id: Option<&str>,
    ) -> Error {
        Error {
            kind: ErrorKind::ServiceError,
            source: "boom".into(),
            extra: Some(Box::new(ErrorExtra {
                service: Some(ServiceMetadata {
                    operation,
                    code: code.map(str::to_owned),
                    message: Some("the message".to_owned()),
                    request_id: request_id.map(str::to_owned),
                    extended_request_id: extended_request_id.map(str::to_owned),
                }),
                ..Default::default()
            })),
        }
    }

    #[test]
    fn display_plain_kind() {
        let e = Error::new(ErrorKind::OperationCancelled, "x");
        assert_eq!(e.to_string(), "operation cancelled");
    }

    /// A mismatch is classified from the response's checksum outcome, not from the
    /// body error's type, so it holds when the body error carries no checksum error
    /// type, as when two copies of `aws-smithy-checksums` are linked.
    #[test]
    fn body_read_error_classifies_mismatch_from_checksum_outcome() {
        let outcome = ChecksumOutcome::Mismatch {
            algorithm: ResponseChecksumAlgorithm::Crc32,
            expected: "AAAAAA==".to_owned(),
            computed: "BBBBBB==".to_owned(),
        };
        let e = body_read_error("opaque body error", Some(outcome));
        let ErrorKind::IntegrityError(ie) = e.kind() else {
            panic!("expected IntegrityError, got {:?}", e.kind());
        };
        assert_eq!(ie.algorithm(), Some(&ChecksumAlgorithm::Crc32));
        assert_eq!(ie.expected(), Some("AAAAAA=="));
        assert_eq!(ie.computed(), Some("BBBBBB=="));
    }

    /// Every algorithm the response outcome names maps to the variant of the same
    /// name.
    #[test]
    fn checksum_algorithm_maps_each_known_name() {
        for (algorithm, expected) in [
            (ResponseChecksumAlgorithm::Crc32, ChecksumAlgorithm::Crc32),
            (ResponseChecksumAlgorithm::Crc32c, ChecksumAlgorithm::Crc32C),
            (
                ResponseChecksumAlgorithm::Crc64Nvme,
                ChecksumAlgorithm::Crc64Nvme,
            ),
            (ResponseChecksumAlgorithm::Sha1, ChecksumAlgorithm::Sha1),
            (ResponseChecksumAlgorithm::Sha256, ChecksumAlgorithm::Sha256),
        ] {
            assert_eq!(checksum_algorithm(algorithm), expected);
        }
    }

    #[test]
    fn display_service_error_full() {
        let e = service(
            "GetObject",
            Some("NoSuchKey"),
            Some("REQ123"),
            Some("EXT456"),
        );
        assert_eq!(
            e.to_string(),
            "service error calling GetObject (NoSuchKey) (request id: REQ123, extended request id: EXT456)"
        );
    }

    #[test]
    fn display_service_error_request_id_only() {
        let e = service("PutObject", Some("AccessDenied"), Some("REQ123"), None);
        assert_eq!(
            e.to_string(),
            "service error calling PutObject (AccessDenied) (request id: REQ123)"
        );
    }

    #[test]
    fn display_service_error_no_metadata() {
        let e = service("HeadObject", None, None, None);
        assert_eq!(e.to_string(), "service error calling HeadObject");
    }

    #[test]
    fn display_omits_source_message() {
        // The underlying message is reached via source(), not Display.
        let e = service("GetObject", Some("NoSuchKey"), None, None);
        assert!(!e.to_string().contains("the message"));
    }

    #[test]
    fn display_integrity_error() {
        let e = Error {
            kind: ErrorKind::IntegrityError(IntegrityError {
                algorithm: Some(ChecksumAlgorithm::Crc32),
                expected: Some("AAAA".to_owned()),
                computed: Some("BBBB".to_owned()),
            }),
            source: "mismatch".into(),
            extra: None,
        };
        // Algorithm is shown; expected/computed are reached via accessors/source.
        assert_eq!(e.to_string(), "integrity error (CRC32)");
    }

    #[test]
    fn display_with_chunk() {
        let e = Error::new(ErrorKind::IOError, "x").with_chunk(ChunkRef::new(3, Some(0..=1023)));
        assert_eq!(e.to_string(), "I/O error [chunk 3, bytes 0-1023]");
    }

    #[test]
    fn display_chunk_no_range() {
        let e = Error::new(ErrorKind::IOError, "x").with_chunk(ChunkRef::new(7, None));
        assert_eq!(e.to_string(), "I/O error [chunk 7]");
    }

    #[test]
    fn is_not_found_matches_codes() {
        assert!(service("GetObject", Some("NoSuchKey"), None, None).is_not_found());
        assert!(!service("GetObject", Some("AccessDenied"), None, None).is_not_found());
    }

    #[test]
    fn display_child_operation_failed_bare() {
        // No attached failure list: the bare kind message, no trailing detail.
        let e = Error::new(ErrorKind::ChildOperationFailed, "x");
        assert_eq!(e.to_string(), "child operation failed");
    }

    #[test]
    fn display_child_operation_failed_names_first_and_count() {
        let failed = vec![
            FailedUpload {
                input: None,
                error: Error::new(ErrorKind::ServiceError, "boom"),
                source_path: Some(std::path::PathBuf::from("/data/a.bin")),
            },
            FailedUpload {
                input: None,
                error: Error::new(ErrorKind::ServiceError, "boom"),
                source_path: Some(std::path::PathBuf::from("/data/b.bin")),
            },
        ];
        let e = Error::new(ErrorKind::ChildOperationFailed, "aborted").with_failed_uploads(failed);
        assert_eq!(
            e.to_string(),
            "child operation failed: /data/a.bin (and 1 more)"
        );
    }

    #[test]
    fn display_child_operation_failed_single_no_path() {
        // A failure list carrying no source path still reports a count.
        let failed = vec![FailedUpload {
            input: None,
            error: Error::new(ErrorKind::ServiceError, "boom"),
            source_path: None,
        }];
        let e = Error::new(ErrorKind::ChildOperationFailed, "aborted").with_failed_uploads(failed);
        assert_eq!(e.to_string(), "child operation failed: 1 object");
    }

    #[test]
    fn display_local_context_names_action_and_path() {
        let e = io_at(
            "creating temporary file for",
            "out/logs/a.log",
            std::io::Error::from(std::io::ErrorKind::NotFound),
        );
        assert_eq!(
            e.to_string(),
            "I/O error creating temporary file for \"out/logs/a.log\""
        );
        // The OS error is the source, not part of the message.
        let source = std::error::Error::source(&e)
            .and_then(|s| s.downcast_ref::<std::io::Error>())
            .expect("the io::Error is the direct source");
        assert_eq!(source.kind(), std::io::ErrorKind::NotFound);

        let e = io_at(
            "creating directory",
            "out/logs",
            std::io::Error::from(std::io::ErrorKind::PermissionDenied),
        )
        .with_local_key("logs/a.log");
        assert_eq!(
            e.to_string(),
            "I/O error creating directory \"out/logs\" (key \"logs/a.log\")"
        );
        // A key without a local operation adds nothing.
        let e = Error::new(ErrorKind::IOError, "x").with_local_key("logs/a.log");
        assert_eq!(e.to_string(), "I/O error");
    }

    #[test]
    fn display_walker_error_names_path() {
        use crate::io::walk::{WalkError, WalkErrorKind};
        let e = Error::from(WalkError::new(
            Some(std::path::PathBuf::from("/data/sub")),
            WalkErrorKind::PermissionDenied,
            Box::new(std::io::Error::from(std::io::ErrorKind::PermissionDenied)),
        ));
        assert_eq!(e.kind(), &ErrorKind::IOError);
        assert_eq!(e.to_string(), "I/O error walking \"/data/sub\"");

        let root = Error::from(WalkError::new(
            Some(std::path::PathBuf::from("/data/missing")),
            WalkErrorKind::SourceUnreadable,
            Box::new(std::io::Error::from(std::io::ErrorKind::NotFound)),
        ));
        assert_eq!(root.kind(), &ErrorKind::InputInvalid);
        assert_eq!(root.to_string(), "invalid input walking \"/data/missing\"");
    }

    #[test]
    fn child_operation_failed_source_is_first_failed_child() {
        let failed = vec![
            FailedUpload {
                input: None,
                error: Error::new(ErrorKind::ServiceError, "first"),
                source_path: None,
            },
            FailedUpload {
                input: None,
                error: Error::new(ErrorKind::ServiceError, "second"),
                source_path: None,
            },
        ];
        let e = Error::new(ErrorKind::ChildOperationFailed, "aborted").with_failed_uploads(failed);
        let source = std::error::Error::source(&e)
            .and_then(|s| s.downcast_ref::<Error>())
            .expect("the source is a child's error");
        assert!(std::ptr::eq(source, e.failed_uploads().unwrap()[0].error()));

        // Without per-object failures, the stored source is reported.
        let bare = Error::new(ErrorKind::ChildOperationFailed, "aborted");
        assert_eq!(
            std::error::Error::source(&bare).map(|s| s.to_string()),
            Some("aborted".to_owned())
        );
    }

    #[test]
    fn upload_id_is_none_unless_attached() {
        let e = Error::new(ErrorKind::ServiceError, "x");
        assert_eq!(e.upload_id(), None);
        let e = e.with_upload_id("abc".to_owned());
        assert_eq!(e.upload_id(), Some("abc"));
        // The upload ID is not part of the message.
        assert_eq!(e.to_string(), "service error");
    }

    // --- transient-transport classification -----------------------------------

    use aws_sdk_s3::operation::get_object::GetObjectError;

    fn dispatch(conn: ConnectorError) -> SdkError<GetObjectError, HttpResponse> {
        SdkError::dispatch_failure(conn)
    }

    #[test]
    fn transient_nested_transient_marker_under_other_none_is_transient() {
        // The Windows failure shape: the http client classified an incomplete
        // response as ConnectorError::Other(TransientError), but a nested dispatch
        // re-wrapped it inside an outer ConnectorError::Other(None). The outer
        // frame carries no marker; the classifier must walk the chain to the inner
        // marker. Inspecting only the outer frame (the previous behavior) would
        // classify this non-transient and abort a retryable error.
        let inner = ConnectorError::other(
            "incomplete message".into(),
            Some(RetryErrorKind::TransientError),
        );
        let inner_sdk: SdkError<GetObjectError, HttpResponse> = SdkError::dispatch_failure(inner);
        let outer = ConnectorError::other(Box::new(inner_sdk), None);
        assert!(
            is_sdk_transient_transport(&dispatch(outer)),
            "a TransientError marker nested under an outer Other(None) must classify transient"
        );
    }

    #[test]
    fn transient_outer_io_is_transient() {
        assert!(is_sdk_transient_transport(&dispatch(ConnectorError::io(
            "reset".into()
        ))));
    }

    #[test]
    fn transient_outer_timeout_is_transient() {
        assert!(is_sdk_transient_transport(&dispatch(
            ConnectorError::timeout("connect".into())
        )));
    }

    #[test]
    fn transient_bare_other_none_is_not_transient() {
        // A connector Other(None) with no transient marker anywhere in the chain
        // is not transient — the fix must not blanket-retry every Other error.
        assert!(!is_sdk_transient_transport(&dispatch(
            ConnectorError::other("unclassified".into(), None)
        )));
    }

    #[test]
    fn transient_user_error_is_not_transient() {
        // A user error (e.g. malformed request) must never be treated transient.
        assert!(!is_sdk_transient_transport(&dispatch(
            ConnectorError::user("bad request".into())
        )));
    }

    // --- conditional-write precondition failures ------------------------------

    use aws_smithy_runtime_api::http::StatusCode;
    use aws_smithy_types::body::SdkBody;

    #[test]
    fn precondition_failure_surfaces_as_service_error_with_code() {
        // A failed `If-Match` / `If-None-Match` gets no kind of its own: callers
        // identify it by the service code. S3 supplies that in the response body,
        // so it is reachable whatever status the failure arrives with.
        let sdk: SdkError<PutObjectError, HttpResponse> = SdkError::service_error(
            PutObjectError::generic(
                aws_smithy_types::error::ErrorMetadata::builder()
                    .code("PreconditionFailed")
                    .build(),
            ),
            HttpResponse::new(StatusCode::try_from(412).unwrap(), SdkBody::empty()),
        );
        let err = service_error(sdk);
        assert!(matches!(err.kind(), ErrorKind::ServiceError));
        assert_eq!(err.code(), Some("PreconditionFailed"));
        assert_eq!(err.operation_name(), Some("PutObject"));
        // The underlying SdkError is preserved as the source.
        assert!(std::error::Error::source(&err)
            .and_then(|s| s.downcast_ref::<SdkError<PutObjectError, HttpResponse>>())
            .is_some());
    }
}