r2kit 0.1.0

A safe, ergonomic Rust toolkit for Cloudflare R2 object storage.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
use std::{
    collections::BTreeMap,
    fmt,
    num::NonZeroU16,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use aws_sdk_s3::{
    presigning::PresigningConfig,
    types::{CompletedMultipartUpload, CompletedPart},
};
use base64::{Engine as _, engine::general_purpose::STANDARD};

use crate::{Bucket, Error, ObjectUploadOptions, ValidationError, validation};

// https://developers.cloudflare.com/r2/platform/limits/
const MAX_MULTIPART_OBJECT_SIZE: u64 = 5 * 1024 * 1024 * 1024 * 1024 - 5 * 1024 * 1024 * 1024;
const MAX_PARTS: u16 = 10_000;

/// A validated multipart part number in the range `1..=10_000`.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PartNumber(NonZeroU16);

impl PartNumber {
    /// Returns the numeric part number.
    #[must_use]
    pub const fn get(self) -> u16 {
        self.0.get()
    }
}

impl TryFrom<u16> for PartNumber {
    type Error = Error;

    fn try_from(value: u16) -> Result<Self, Self::Error> {
        let provided = value;
        let value = NonZeroU16::new(value).ok_or(ValidationError::PartNumberOutOfRange {
            provided,
            min: 1,
            max: MAX_PARTS,
        })?;
        if value.get() > MAX_PARTS {
            return Err(ValidationError::PartNumberOutOfRange {
                provided,
                min: 1,
                max: MAX_PARTS,
            }
            .into());
        }
        Ok(Self(value))
    }
}

/// A successfully uploaded multipart part.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UploadedPart {
    part_number: PartNumber,
    etag: String,
}

/// A validated Base64-encoded 128-bit MD5 digest for one multipart part.
///
/// R2 checks this value against the request body when it is included in a
/// presigned `UploadPart` request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PartMd5(String);

impl PartMd5 {
    /// Returns the canonical Base64 representation expected by `Content-MD5`.
    #[must_use]
    pub fn as_base64(&self) -> &str {
        &self.0
    }
}

impl TryFrom<String> for PartMd5 {
    type Error = Error;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        let decoded = STANDARD.decode(&value).map_err(|_| Error::InvalidInput {
            field: "content_md5",
            reason: "must be canonical Base64 for a 128-bit MD5 digest",
        })?;
        if decoded.len() != 16 || STANDARD.encode(decoded) != value {
            return Err(Error::InvalidInput {
                field: "content_md5",
                reason: "must be canonical Base64 for a 128-bit MD5 digest",
            });
        }
        Ok(Self(value))
    }
}

impl TryFrom<&str> for PartMd5 {
    type Error = Error;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::try_from(value.to_owned())
    }
}

/// Untrusted transport data reported by a direct multipart uploader.
///
/// Convert this value with [`MultipartPartReceipt::try_into_uploaded_part`]
/// before using it in a completion manifest.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct MultipartPartReceipt {
    part_number: u16,
    etag: String,
}

impl MultipartPartReceipt {
    /// Creates a wire receipt from primitive values.
    #[must_use]
    pub fn new(part_number: u16, etag: impl Into<String>) -> Self {
        Self {
            part_number,
            etag: etag.into(),
        }
    }

    /// Returns the unvalidated numeric part number.
    #[must_use]
    pub const fn part_number(&self) -> u16 {
        self.part_number
    }

    /// Returns the exact ETag reported by R2.
    #[must_use]
    pub fn etag(&self) -> &str {
        &self.etag
    }

    /// Validates this untrusted receipt for use in a completion manifest.
    pub fn try_into_uploaded_part(self) -> Result<UploadedPart, Error> {
        UploadedPart::new(PartNumber::try_from(self.part_number)?, self.etag)
    }
}

impl UploadedPart {
    /// Creates a completion entry from the exact ETag returned by R2.
    pub fn new(part_number: PartNumber, etag: impl Into<String>) -> Result<Self, Error> {
        let etag = etag.into();
        if etag.is_empty() {
            return Err(Error::InvalidInput {
                field: "etag",
                reason: "must not be empty",
            });
        }
        Ok(Self { part_number, etag })
    }

    /// Returns the part number.
    #[must_use]
    pub const fn part_number(&self) -> PartNumber {
        self.part_number
    }

    /// Returns the exact R2 ETag, including quotes when R2 supplied them.
    #[must_use]
    pub fn etag(&self) -> &str {
        &self.etag
    }
}

/// A canonical, duplicate-free completion manifest sorted by part number.
#[derive(Clone, Debug)]
pub struct CompletionManifest(Vec<UploadedPart>);

impl CompletionManifest {
    /// Validates and canonicalizes uploaded parts.
    pub fn try_from_parts(parts: impl IntoIterator<Item = UploadedPart>) -> Result<Self, Error> {
        let mut canonical = BTreeMap::new();
        for part in parts {
            let number = part.part_number();
            if canonical.insert(number, part).is_some() {
                return Err(Error::InvalidInput {
                    field: "parts",
                    reason: "contains a duplicate part number",
                });
            }
        }
        if canonical.is_empty() {
            return Err(Error::InvalidInput {
                field: "parts",
                reason: "must contain at least one uploaded part",
            });
        }
        Ok(Self(canonical.into_values().collect()))
    }

    /// Validates untrusted uploader receipts and builds a canonical manifest.
    pub fn try_from_receipts(
        receipts: impl IntoIterator<Item = MultipartPartReceipt>,
    ) -> Result<Self, Error> {
        receipts
            .into_iter()
            .map(MultipartPartReceipt::try_into_uploaded_part)
            .collect::<Result<Vec<_>, _>>()
            .and_then(Self::try_from_parts)
    }

    /// Iterates over canonical parts in ascending part-number order.
    pub fn parts(&self) -> impl ExactSizeIterator<Item = &UploadedPart> {
        self.0.iter()
    }
}

/// A presigned URL treated as a bearer credential.
#[derive(Clone)]
pub struct SecretUrl(String);

impl SecretUrl {
    /// Deliberately exposes the bearer URL for transmission to an uploader.
    #[must_use]
    pub fn expose(&self) -> &str {
        &self.0
    }

    /// Deliberately consumes and exposes the bearer URL.
    #[must_use]
    pub fn into_exposed_string(self) -> String {
        self.0
    }
}

impl fmt::Debug for SecretUrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("SecretUrl([REDACTED PRESIGNED URL])")
    }
}

/// An HTTP request signed for temporary direct access to R2.
#[derive(Clone)]
pub struct PresignedRequest {
    method: String,
    url: SecretUrl,
    required_headers: Vec<(String, String)>,
    expires_at: SystemTime,
}

impl PresignedRequest {
    pub(crate) fn from_sdk(
        signed: aws_sdk_s3::presigning::PresignedRequest,
        expires_in: Duration,
    ) -> Result<Self, Error> {
        let required_headers = signed
            .headers()
            .map(|(name, value)| (name.to_owned(), value.to_owned()))
            .collect();
        Ok(Self {
            method: signed.method().to_owned(),
            url: SecretUrl(signed.uri().to_string()),
            required_headers,
            expires_at: SystemTime::now() + expires_in,
        })
    }

    /// Returns the HTTP method the uploader must use.
    #[must_use]
    pub fn method(&self) -> &str {
        &self.method
    }

    /// Returns the redacted-by-default bearer URL wrapper.
    #[must_use]
    pub fn url(&self) -> &SecretUrl {
        &self.url
    }

    /// Returns headers that must be replayed exactly by the uploader.
    pub fn required_headers(&self) -> impl ExactSizeIterator<Item = (&str, &str)> {
        self.required_headers
            .iter()
            .map(|(name, value)| (name.as_str(), value.as_str()))
    }

    /// Returns the approximate expiration instant.
    #[must_use]
    pub const fn expires_at(&self) -> SystemTime {
        self.expires_at
    }

    /// Deliberately exposes all request components for an HTTP client.
    #[must_use]
    pub fn into_exposed_parts(self) -> (String, String, Vec<(String, String)>) {
        (
            self.method,
            self.url.into_exposed_string(),
            self.required_headers,
        )
    }
}

impl fmt::Debug for PresignedRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let header_names: Vec<&str> = self
            .required_headers
            .iter()
            .map(|(name, _)| name.as_str())
            .collect();
        f.debug_struct("PresignedRequest")
            .field("method", &self.method)
            .field("url", &"[REDACTED PRESIGNED URL]")
            .field("required_header_names", &header_names)
            .field("expires_at", &self.expires_at)
            .finish()
    }
}

/// A presigned upload request for one known multipart part.
#[derive(Clone, Debug)]
pub struct PresignedUploadPart {
    part_number: PartNumber,
    content_length: u64,
    content_md5: Option<PartMd5>,
    request: PresignedRequest,
}

impl PresignedUploadPart {
    /// Returns the part number.
    #[must_use]
    pub const fn part_number(&self) -> PartNumber {
        self.part_number
    }

    /// Returns the exact number of bytes expected for this part.
    #[must_use]
    pub const fn content_length(&self) -> u64 {
        self.content_length
    }

    /// Returns the body checksum enforced by R2, when one was signed.
    #[must_use]
    pub fn content_md5(&self) -> Option<&PartMd5> {
        self.content_md5.as_ref()
    }

    /// Returns the signed request.
    #[must_use]
    pub fn request(&self) -> &PresignedRequest {
        &self.request
    }

    /// Consumes the part wrapper and returns the signed request.
    #[must_use]
    pub fn into_request(self) -> PresignedRequest {
        self.request
    }

    /// Deliberately exposes the bearer request as a serializable protocol DTO.
    ///
    /// The resulting value still redacts its URL and header values from
    /// `Debug`, but serialization exposes them for transport to an uploader.
    pub fn into_protocol_request(self) -> Result<MultipartUploadPartRequest, Error> {
        let expires_at_unix_seconds = self
            .request
            .expires_at()
            .duration_since(UNIX_EPOCH)
            .map_err(|_| Error::Presign)?
            .as_secs();
        let (method, url, required_headers) = self.request.into_exposed_parts();
        Ok(MultipartUploadPartRequest {
            part_number: self.part_number.get(),
            content_length: self.content_length,
            content_md5: self.content_md5.map(|value| value.0),
            method,
            url,
            required_headers,
            expires_at_unix_seconds,
        })
    }
}

/// Serializable protocol DTO sent from a trusted signer to an uploader.
///
/// This value contains a bearer URL. Serialization is therefore an explicit
/// secret-exposure boundary even though `Debug` remains redacted. Its primitive
/// fields are a transport representation of an already validated and signed
/// request; deserializing this DTO does not establish a new trusted validation
/// boundary.
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct MultipartUploadPartRequest {
    part_number: u16,
    content_length: u64,
    content_md5: Option<String>,
    method: String,
    url: String,
    required_headers: Vec<(String, String)>,
    expires_at_unix_seconds: u64,
}

impl MultipartUploadPartRequest {
    /// Returns the part number this request may upload.
    #[must_use]
    pub const fn part_number(&self) -> u16 {
        self.part_number
    }

    /// Returns the exact required request-body length.
    #[must_use]
    pub const fn content_length(&self) -> u64 {
        self.content_length
    }

    /// Returns the signed Base64 `Content-MD5`, when enabled.
    #[must_use]
    pub fn content_md5(&self) -> Option<&str> {
        self.content_md5.as_deref()
    }

    /// Returns the signed HTTP method.
    #[must_use]
    pub fn method(&self) -> &str {
        &self.method
    }

    /// Deliberately exposes the bearer URL to the uploader.
    #[must_use]
    pub fn expose_url(&self) -> &str {
        &self.url
    }

    /// Returns headers that the uploader must replay exactly.
    pub fn required_headers(&self) -> impl ExactSizeIterator<Item = (&str, &str)> {
        self.required_headers
            .iter()
            .map(|(name, value)| (name.as_str(), value.as_str()))
    }

    /// Returns the approximate Unix expiration timestamp in seconds.
    #[must_use]
    pub const fn expires_at_unix_seconds(&self) -> u64 {
        self.expires_at_unix_seconds
    }
}

impl fmt::Debug for MultipartUploadPartRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let header_names: Vec<&str> = self
            .required_headers
            .iter()
            .map(|(name, _)| name.as_str())
            .collect();
        f.debug_struct("MultipartUploadPartRequest")
            .field("part_number", &self.part_number)
            .field("content_length", &self.content_length)
            .field("content_md5", &self.content_md5)
            .field("method", &self.method)
            .field("url", &"[REDACTED PRESIGNED URL]")
            .field("required_header_names", &header_names)
            .field("expires_at_unix_seconds", &self.expires_at_unix_seconds)
            .finish()
    }
}

/// Persistable state needed to resume a presigned multipart upload.
#[derive(Clone)]
pub struct MultipartSessionSnapshot {
    bucket: String,
    key: String,
    upload_id: String,
    file_size: u64,
    part_size: u64,
}

/// Versioned persistence DTO for resuming a multipart session.
///
/// This value contains an upload ID. Serialization deliberately exposes that
/// credential to the selected persistence layer, while `Debug` redacts it.
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct MultipartSessionRecord {
    version: u8,
    bucket: String,
    key: String,
    upload_id: String,
    file_size: u64,
    part_size: u64,
}

impl MultipartSessionRecord {
    /// Returns the persistence schema version.
    #[must_use]
    pub const fn version(&self) -> u8 {
        self.version
    }

    /// Returns the bucket stored in this untrusted record.
    #[must_use]
    pub fn bucket(&self) -> &str {
        &self.bucket
    }

    /// Returns the key stored in this untrusted record.
    #[must_use]
    pub fn key(&self) -> &str {
        &self.key
    }

    /// Deliberately exposes the persisted upload ID.
    #[must_use]
    pub fn expose_upload_id(&self) -> &str {
        &self.upload_id
    }

    /// Returns the planned object size.
    #[must_use]
    pub const fn file_size(&self) -> u64 {
        self.file_size
    }

    /// Returns the planned part size.
    #[must_use]
    pub const fn part_size(&self) -> u64 {
        self.part_size
    }
}

impl fmt::Debug for MultipartSessionRecord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MultipartSessionRecord")
            .field("version", &self.version)
            .field("bucket", &self.bucket)
            .field("key", &self.key)
            .field("upload_id", &"[REDACTED]")
            .field("file_size", &self.file_size)
            .field("part_size", &self.part_size)
            .finish()
    }
}

impl MultipartSessionSnapshot {
    /// Restores validated multipart session state previously returned by [`PresignedMultipart::snapshot`].
    pub fn restore(
        bucket: impl Into<String>,
        key: impl Into<String>,
        upload_id: impl Into<String>,
        file_size: u64,
        part_size: u64,
    ) -> Result<Self, Error> {
        let key = key.into();
        validation::validate_key(&key)?;
        MultipartPlan::new(file_size, part_size)?;
        let upload_id = upload_id.into();
        if upload_id.is_empty() {
            return Err(Error::InvalidInput {
                field: "upload_id",
                reason: "must not be empty",
            });
        }
        Ok(Self {
            bucket: bucket.into(),
            key,
            upload_id,
            file_size,
            part_size,
        })
    }

    /// Validates a deserialized persistence record before it becomes session state.
    pub fn from_persistence_record(record: MultipartSessionRecord) -> Result<Self, Error> {
        if record.version != 1 {
            return Err(Error::InvalidInput {
                field: "version",
                reason: "unsupported multipart session record version",
            });
        }
        Self::restore(
            record.bucket,
            record.key,
            record.upload_id,
            record.file_size,
            record.part_size,
        )
    }

    /// Deliberately exposes resumable state as a versioned persistence DTO.
    #[must_use]
    pub fn into_persistence_record(self) -> MultipartSessionRecord {
        MultipartSessionRecord {
            version: 1,
            bucket: self.bucket,
            key: self.key,
            upload_id: self.upload_id,
            file_size: self.file_size,
            part_size: self.part_size,
        }
    }

    /// Deliberately exposes the upload ID for persistence.
    #[must_use]
    pub fn expose_upload_id(&self) -> &str {
        &self.upload_id
    }

    /// Returns the bucket owning this upload.
    #[must_use]
    pub fn bucket(&self) -> &str {
        &self.bucket
    }

    /// Returns the destination object key.
    #[must_use]
    pub fn key(&self) -> &str {
        &self.key
    }

    /// Returns the complete object size in bytes.
    #[must_use]
    pub const fn file_size(&self) -> u64 {
        self.file_size
    }

    /// Returns the uniform non-final part size in bytes.
    #[must_use]
    pub const fn part_size(&self) -> u64 {
        self.part_size
    }
}

impl fmt::Debug for MultipartSessionSnapshot {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MultipartSessionSnapshot")
            .field("bucket", &self.bucket)
            .field("key", &self.key)
            .field("upload_id", &"[REDACTED]")
            .field("file_size", &self.file_size)
            .field("part_size", &self.part_size)
            .finish()
    }
}

#[derive(Clone, Debug)]
struct MultipartPlan {
    file_size: u64,
    part_size: u64,
    part_count: u16,
}

impl MultipartPlan {
    fn new(file_size: u64, part_size: u64) -> Result<Self, Error> {
        if file_size == 0 {
            return Err(ValidationError::MultipartFileSizeZero.into());
        }
        if file_size > MAX_MULTIPART_OBJECT_SIZE {
            return Err(ValidationError::MultipartObjectTooLarge {
                provided: file_size,
                max: MAX_MULTIPART_OBJECT_SIZE,
            }
            .into());
        }
        validation::validate_part_size(part_size)?;
        let part_count = file_size.div_ceil(part_size);
        if part_count > u64::from(MAX_PARTS) {
            return Err(ValidationError::TooManyParts {
                required: part_count,
                max: MAX_PARTS,
            }
            .into());
        }
        Ok(Self {
            file_size,
            part_size,
            part_count: part_count as u16,
        })
    }

    fn part_length(&self, number: PartNumber) -> Result<u64, Error> {
        if number.get() > self.part_count {
            return Err(Error::InvalidInput {
                field: "part_number",
                reason: "exceeds this upload's planned part count",
            });
        }
        let start = u64::from(number.get() - 1) * self.part_size;
        Ok((self.file_size - start).min(self.part_size))
    }
}

/// Server-observed state of a live multipart upload.
#[derive(Clone, Debug)]
pub struct MultipartReconciliation {
    uploaded_parts: Vec<UploadedPart>,
    missing_parts: Vec<PartNumber>,
}

impl MultipartReconciliation {
    /// Returns uploaded parts in ascending part-number order.
    pub fn uploaded_parts(&self) -> impl ExactSizeIterator<Item = &UploadedPart> {
        self.uploaded_parts.iter()
    }

    /// Consumes the reconciliation and returns uploaded parts in ascending
    /// part-number order.
    #[must_use]
    pub fn into_uploaded_parts(self) -> Vec<UploadedPart> {
        self.uploaded_parts
    }

    /// Returns planned parts that R2 has not received yet.
    pub fn missing_parts(&self) -> impl ExactSizeIterator<Item = PartNumber> + '_ {
        self.missing_parts.iter().copied()
    }

    /// Returns whether R2 has every planned part with the expected size.
    #[must_use]
    pub fn is_complete(&self) -> bool {
        self.missing_parts.is_empty()
    }

    /// Builds a canonical completion manifest when every part is present.
    pub fn into_completion_manifest(self) -> Result<CompletionManifest, Error> {
        if !self.missing_parts.is_empty() {
            return Err(Error::InvalidInput {
                field: "remote_parts",
                reason: "multipart upload is missing planned parts",
            });
        }
        CompletionManifest::try_from_parts(self.uploaded_parts)
    }
}

/// Builder for a new presigned multipart upload session.
#[derive(Clone, Debug)]
pub struct PresignedMultipartBuilder {
    bucket: Bucket,
    key: String,
    file_size: Option<u64>,
    part_size: Option<u64>,
    options: ObjectUploadOptions,
}

impl PresignedMultipartBuilder {
    /// Sets typed metadata stored on the completed object.
    #[must_use]
    pub fn upload_options(mut self, options: ObjectUploadOptions) -> Self {
        self.options = options;
        self
    }

    /// Sets the completed object's MIME media type.
    #[must_use]
    pub fn content_type(mut self, value: mime::Mime) -> Self {
        self.options = self.options.with_content_type(value);
        self
    }

    /// Sets the completed object's typed HTTP cache policy.
    #[must_use]
    pub fn cache_control(mut self, value: headers::CacheControl) -> Self {
        self.options = self.options.with_cache_control(value);
        self
    }

    /// Sets the completed object's content disposition.
    #[must_use]
    pub fn content_disposition(mut self, value: impl Into<String>) -> Self {
        self.options = self.options.with_content_disposition(value);
        self
    }

    /// Sets the completed object's content encoding.
    #[must_use]
    pub fn content_encoding(mut self, value: impl Into<String>) -> Self {
        self.options = self.options.with_content_encoding(value);
        self
    }

    /// Sets the completed object's content language.
    #[must_use]
    pub fn content_language(mut self, value: impl Into<String>) -> Self {
        self.options = self.options.with_content_language(value);
        self
    }

    /// Sets the completed object's HTTP expiration time.
    #[must_use]
    pub fn expires(mut self, value: SystemTime) -> Self {
        self.options = self.options.with_expires(value);
        self
    }

    /// Adds user-defined metadata to the completed object.
    #[must_use]
    pub fn custom_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.options = self.options.with_custom_metadata(key, value);
        self
    }

    /// Sets the complete object size in bytes.
    ///
    /// This is required because r2kit plans every part before creating the
    /// remote upload: it determines the final part length, enforces R2's object
    /// and 10,000-part limits, signs exact content lengths, and later verifies
    /// the remote parts. For browser uploads, send the browser's `File.size`
    /// to the trusted server and treat it as untrusted input; r2kit validates
    /// the value before network I/O.
    ///
    /// Managed local-file uploads do not require this setting because
    /// [`crate::ManagedMultipartBuilder::upload_file`] reads file metadata.
    #[must_use]
    pub const fn file_size(mut self, bytes: u64) -> Self {
        self.file_size = Some(bytes);
        self
    }

    /// Sets the uniform multipart part size in bytes.
    #[must_use]
    pub const fn part_size(mut self, bytes: u64) -> Self {
        self.part_size = Some(bytes);
        self
    }

    /// Sets the uniform multipart part size in mebibytes (MiB).
    ///
    /// This is equivalent to [`Self::part_size`] with a binary-unit conversion
    /// and avoids repeating `1024 * 1024` at call sites. Values that cannot be
    /// represented as bytes are rejected by [`Self::create`].
    #[must_use]
    pub const fn part_size_mib(mut self, mebibytes: u64) -> Self {
        self.part_size = Some(validation::mebibytes(mebibytes));
        self
    }

    /// Creates the remote multipart upload after local validation succeeds.
    pub async fn create(self) -> Result<PresignedMultipart, Error> {
        self.options.validate()?;
        let plan = MultipartPlan::new(
            self.file_size.ok_or(Error::InvalidInput {
                field: "file_size",
                reason: "is required",
            })?,
            self.part_size.ok_or(Error::InvalidInput {
                field: "part_size",
                reason: "is required",
            })?,
        )?;
        let output = self
            .bucket
            .client
            .as_sdk()
            .create_multipart_upload()
            .bucket(&self.bucket.name)
            .key(&self.key)
            .set_content_type(self.options.content_type_value())
            .set_cache_control(self.options.cache_control_value())
            .set_content_disposition(self.options.content_disposition_value())
            .set_content_encoding(self.options.content_encoding_value())
            .set_content_language(self.options.content_language_value())
            .set_expires(self.options.expires_value())
            .set_metadata(self.options.custom_metadata_values())
            .send()
            .await
            .map_err(|error| Error::remote("CreateMultipartUpload", &error))?;
        let upload_id = output.upload_id().ok_or(Error::Service {
            operation: "CreateMultipartUpload",
        })?;

        Ok(PresignedMultipart {
            bucket: self.bucket,
            key: self.key,
            upload_id: upload_id.to_owned(),
            plan,
        })
    }
}

/// An active R2 multipart upload that can presign parts, complete, or abort.
#[derive(Clone)]
pub struct PresignedMultipart {
    bucket: Bucket,
    key: String,
    upload_id: String,
    plan: MultipartPlan,
}

impl PresignedMultipart {
    /// Returns the number of planned parts.
    #[must_use]
    pub const fn part_count(&self) -> u16 {
        self.plan.part_count
    }

    /// Returns the expected byte length for a part.
    pub fn part_length(&self, number: PartNumber) -> Result<u64, Error> {
        self.plan.part_length(number)
    }

    /// Creates a temporary signed PUT request for one part.
    pub async fn presign_part(
        &self,
        number: PartNumber,
        expires_in: Duration,
    ) -> Result<PresignedUploadPart, Error> {
        self.presign_part_inner(number, None, expires_in).await
    }

    /// Creates a signed PUT request that makes R2 verify `Content-MD5`.
    ///
    /// The uploader must replay the returned `content-md5` header exactly.
    pub async fn presign_part_with_md5(
        &self,
        number: PartNumber,
        content_md5: PartMd5,
        expires_in: Duration,
    ) -> Result<PresignedUploadPart, Error> {
        self.presign_part_inner(number, Some(content_md5), expires_in)
            .await
    }

    async fn presign_part_inner(
        &self,
        number: PartNumber,
        content_md5: Option<PartMd5>,
        expires_in: Duration,
    ) -> Result<PresignedUploadPart, Error> {
        let content_length = self.plan.part_length(number)?;
        validation::validate_expiry(expires_in)?;
        let config = PresigningConfig::expires_in(expires_in).map_err(|_| Error::Presign)?;
        let request = self
            .bucket
            .client
            .as_sdk()
            .upload_part()
            .bucket(&self.bucket.name)
            .key(&self.key)
            .upload_id(&self.upload_id)
            .part_number(i32::from(number.get()));
        let request = match &content_md5 {
            Some(value) => request.content_md5(value.as_base64()),
            None => request,
        };
        let signed = request
            .presigned(config)
            .await
            .map_err(|_| Error::Presign)?;

        Ok(PresignedUploadPart {
            part_number: number,
            content_length,
            content_md5,
            request: PresignedRequest::from_sdk(signed, expires_in)?,
        })
    }

    /// Reconciles persisted client state with the parts currently stored by R2.
    ///
    /// Every remote part is checked for a valid number, a unique entry, and
    /// the exact size required by the original upload plan.
    pub async fn reconcile(&self) -> Result<MultipartReconciliation, Error> {
        let mut marker = None;
        let mut uploaded: Vec<Option<UploadedPart>> = std::iter::repeat_with(|| None)
            .take(usize::from(self.plan.part_count))
            .collect();
        loop {
            let output = self
                .bucket
                .client
                .as_sdk()
                .list_parts()
                .bucket(&self.bucket.name)
                .key(&self.key)
                .upload_id(&self.upload_id)
                .max_parts(1_000)
                .set_part_number_marker(marker)
                .send()
                .await
                .map_err(|error| Error::remote("ListParts", &error))?;
            for remote in output.parts() {
                let raw_number = remote.part_number().ok_or(Error::Service {
                    operation: "ListParts",
                })?;
                let number = u16::try_from(raw_number)
                    .ok()
                    .and_then(|value| PartNumber::try_from(value).ok())
                    .ok_or(Error::InvalidInput {
                        field: "remote_parts",
                        reason: "contains an invalid part number",
                    })?;
                let expected_size =
                    self.plan
                        .part_length(number)
                        .map_err(|_| Error::InvalidInput {
                            field: "remote_parts",
                            reason: "contains a part outside the upload plan",
                        })?;
                if remote.size().and_then(|size| u64::try_from(size).ok()) != Some(expected_size) {
                    return Err(Error::InvalidInput {
                        field: "remote_parts",
                        reason: "contains a part with an unexpected size",
                    });
                }
                let etag = remote.e_tag().ok_or(Error::Service {
                    operation: "ListParts",
                })?;
                let part = UploadedPart::new(number, etag)?;
                let slot = &mut uploaded[usize::from(number.get() - 1)];
                if slot.replace(part).is_some() {
                    return Err(Error::InvalidInput {
                        field: "remote_parts",
                        reason: "contains a duplicate part number",
                    });
                }
            }
            if output.is_truncated() != Some(true) {
                break;
            }
            marker = output.next_part_number_marker;
            if marker.is_none() {
                return Err(Error::Service {
                    operation: "ListParts",
                });
            }
        }

        let mut uploaded_parts = Vec::with_capacity(uploaded.len());
        let mut missing_parts = Vec::new();
        for (index, part) in uploaded.into_iter().enumerate() {
            match part {
                Some(part) => uploaded_parts.push(part),
                None => missing_parts.push(
                    PartNumber::try_from(index as u16 + 1).expect("planned part numbers are valid"),
                ),
            }
        }
        Ok(MultipartReconciliation {
            uploaded_parts,
            missing_parts,
        })
    }

    /// Verifies client receipts against R2 before completing the upload.
    ///
    /// This extra `ListParts` round trip rejects stale, missing, incorrectly
    /// sized, or mismatched part receipts before `CompleteMultipartUpload`.
    pub async fn complete_verified(
        &self,
        manifest: CompletionManifest,
    ) -> Result<CompletedObject, Error> {
        let reconciliation = self.reconcile().await?;
        if !reconciliation.is_complete()
            || reconciliation.uploaded_parts.as_slice() != manifest.0.as_slice()
        {
            return Err(Error::InvalidInput {
                field: "parts",
                reason: "does not match the parts currently stored by R2",
            });
        }
        self.complete(manifest).await
    }

    /// Completes the upload with the exact ETags returned by every uploaded part.
    pub async fn complete(&self, manifest: CompletionManifest) -> Result<CompletedObject, Error> {
        if manifest.0.len() != usize::from(self.plan.part_count)
            || manifest
                .0
                .iter()
                .enumerate()
                .any(|(index, part)| usize::from(part.part_number().get()) != index + 1)
        {
            return Err(Error::InvalidInput {
                field: "parts",
                reason: "must include every planned part exactly once",
            });
        }

        let parts = manifest
            .0
            .into_iter()
            .map(|part| {
                CompletedPart::builder()
                    .part_number(i32::from(part.part_number.get()))
                    .e_tag(part.etag)
                    .build()
            })
            .collect();
        let upload = CompletedMultipartUpload::builder()
            .set_parts(Some(parts))
            .build();
        let output = self
            .bucket
            .client
            .as_sdk()
            .complete_multipart_upload()
            .bucket(&self.bucket.name)
            .key(&self.key)
            .upload_id(&self.upload_id)
            .multipart_upload(upload)
            .send()
            .await
            .map_err(|error| Error::remote("CompleteMultipartUpload", &error))?;

        Ok(CompletedObject {
            etag: output.e_tag().map(ToOwned::to_owned),
        })
    }

    /// Aborts the remote multipart upload.
    pub async fn abort(&self) -> Result<(), Error> {
        self.bucket
            .client
            .as_sdk()
            .abort_multipart_upload()
            .bucket(&self.bucket.name)
            .key(&self.key)
            .upload_id(&self.upload_id)
            .send()
            .await
            .map_err(|error| Error::remote("AbortMultipartUpload", &error))?;
        Ok(())
    }

    /// Captures resumable session state. Its debug output redacts the upload ID.
    #[must_use]
    pub fn snapshot(&self) -> MultipartSessionSnapshot {
        MultipartSessionSnapshot {
            bucket: self.bucket.name.clone(),
            key: self.key.clone(),
            upload_id: self.upload_id.clone(),
            file_size: self.plan.file_size,
            part_size: self.plan.part_size,
        }
    }
}

impl fmt::Debug for PresignedMultipart {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PresignedMultipart")
            .field("bucket", &self.bucket.name)
            .field("key", &self.key)
            .field("upload_id", &"[REDACTED]")
            .field("plan", &self.plan)
            .finish()
    }
}

/// Result metadata for a completed multipart object.
#[derive(Clone, Debug)]
pub struct CompletedObject {
    etag: Option<String>,
}

impl CompletedObject {
    /// Returns R2's multipart ETag. It is not the MD5 of the complete object.
    #[must_use]
    pub fn etag(&self) -> Option<&str> {
        self.etag.as_deref()
    }
}

impl Bucket {
    /// Starts configuring a presigned multipart upload for an object key.
    pub fn presigned_multipart(
        &self,
        key: impl Into<String>,
    ) -> Result<PresignedMultipartBuilder, Error> {
        let key = key.into();
        validation::validate_key(&key)?;
        Ok(PresignedMultipartBuilder {
            bucket: self.clone(),
            key,
            file_size: None,
            part_size: None,
            options: ObjectUploadOptions::default(),
        })
    }

    /// Restores a previously captured multipart upload session.
    pub fn resume_presigned_multipart(
        &self,
        snapshot: MultipartSessionSnapshot,
    ) -> Result<PresignedMultipart, Error> {
        if snapshot.bucket != self.name {
            return Err(Error::InvalidInput {
                field: "bucket",
                reason: "snapshot belongs to another bucket",
            });
        }
        let plan = MultipartPlan::new(snapshot.file_size, snapshot.part_size)?;
        Ok(PresignedMultipart {
            bucket: self.clone(),
            key: snapshot.key,
            upload_id: snapshot.upload_id,
            plan,
        })
    }
}

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

    #[test]
    fn plans_exact_and_short_final_parts() {
        let plan = MultipartPlan::new(11 * 1024 * 1024, 5 * 1024 * 1024).unwrap();
        assert_eq!(plan.part_count, 3);
        assert_eq!(
            plan.part_length(PartNumber::try_from(1).unwrap()).unwrap(),
            5 * 1024 * 1024
        );
        assert_eq!(
            plan.part_length(PartNumber::try_from(3).unwrap()).unwrap(),
            1024 * 1024
        );
    }

    #[test]
    fn rejects_too_many_parts() {
        let min_part_size = 5 * 1024 * 1024;
        let result = MultipartPlan::new(10_001 * min_part_size, min_part_size);
        assert!(matches!(
            result,
            Err(Error::Validation(ValidationError::TooManyParts {
                required: 10_001,
                max: 10_000
            }))
        ));
    }

    #[test]
    fn rejects_an_object_over_r2s_effective_limit() {
        let max_part_size = validation::MAX_MULTIPART_PART_SIZE;
        let result = MultipartPlan::new(MAX_MULTIPART_OBJECT_SIZE + 1, max_part_size);
        assert!(matches!(
            result,
            Err(Error::Validation(
                ValidationError::MultipartObjectTooLarge {
                    provided,
                    max: MAX_MULTIPART_OBJECT_SIZE
                }
            )) if provided == MAX_MULTIPART_OBJECT_SIZE + 1
        ));
    }

    #[test]
    fn rejects_subsecond_presign_expiry() {
        assert!(matches!(
            validation::validate_expiry(Duration::from_millis(999)),
            Err(Error::Validation(
                ValidationError::PresignExpiryOutOfRange { provided, .. }
            )) if provided == Duration::from_millis(999)
        ));
    }

    #[test]
    fn canonicalizes_manifest_and_rejects_duplicates() {
        let one = PartNumber::try_from(1).unwrap();
        let two = PartNumber::try_from(2).unwrap();
        let manifest = CompletionManifest::try_from_parts([
            UploadedPart::new(two, "two").unwrap(),
            UploadedPart::new(one, "one").unwrap(),
        ])
        .unwrap();
        assert_eq!(manifest.0[0].part_number(), one);

        let duplicate = CompletionManifest::try_from_parts([
            UploadedPart::new(one, "one").unwrap(),
            UploadedPart::new(one, "again").unwrap(),
        ]);
        assert!(duplicate.is_err());
    }

    #[test]
    fn redacts_secret_wrappers() {
        let min_part_size = 5 * 1024 * 1024;
        let url = SecretUrl("https://example.invalid/?X-Amz-Signature=secret".into());
        assert!(!format!("{url:?}").contains("X-Amz-Signature"));
        let snapshot = MultipartSessionSnapshot::restore(
            "r2kit",
            "key",
            "secret-upload-id",
            min_part_size,
            min_part_size,
        )
        .unwrap();
        assert!(!format!("{snapshot:?}").contains("secret-upload-id"));
    }
}