multibucket 0.3.0

A unified async object-storage trait with from-scratch Qiniu Kodo and Amazon S3 (S3-compatible) backends (upload / download / delete / stat / list / signed URLs).
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
//! Amazon S3 (and S3-compatible) backend.
//!
//! Speaks AWS Signature Version 4, so it works against AWS S3 as well as
//! S3-compatible services (MinIO, Cloudflare R2, Aliyun OSS, Tencent COS,
//! Qiniu Kodo's S3 interface, …). The signing is implemented from scratch in
//! [`sigv4`] — no `aws-sdk` / `rust-s3` dependency.

mod config;
mod sigv4;

pub use config::S3Config;

use std::time::{Duration, SystemTime};

use async_trait::async_trait;
use bytes::Bytes;
use reqwest::header::{CONTENT_LENGTH, CONTENT_TYPE, ETAG};

use crate::error::{Error, Result};
use crate::storage::{ListOptions, ObjectStorage};
use crate::types::{ListOutcome, ObjectMetadata, PutBody, PutOptions};

use sigv4::{
    amz_date_now, canonical_query, sha256_hex, uri_encode, Credentials, RequestToSign,
    EMPTY_PAYLOAD_SHA256,
};

/// S3 multipart minimum part size (everything but the last part).
const S3_MIN_PART_SIZE: usize = 5 * 1024 * 1024;
/// Default part size used by [`put_resumable`](ObjectStorage::put_resumable).
const S3_DEFAULT_PART_SIZE: usize = 8 * 1024 * 1024;
/// S3 allows at most 10 000 parts per upload.
const S3_MAX_PARTS: u32 = 10_000;
/// Max lifetime of a pre-signed URL (AWS S3 cap).
const S3_MAX_EXPIRES: u64 = 604_800;

/// An asynchronous S3 client implementing [`ObjectStorage`].
#[derive(Debug, Clone)]
pub struct S3Client {
    config: S3Config,
    http: reqwest::Client,
}

impl S3Client {
    /// Create a client from an [`S3Config`] using a default HTTP client.
    pub fn new(config: S3Config) -> Self {
        S3Client {
            config,
            http: reqwest::Client::new(),
        }
    }

    /// Use a custom `reqwest::Client` (timeouts, proxies, connection pools…).
    pub fn with_http(mut self, http: reqwest::Client) -> Self {
        self.http = http;
        self
    }

    /// Access the underlying configuration.
    pub fn config(&self) -> &S3Config {
        &self.config
    }

    /// Build the SigV4 credentials view.
    fn creds(&self) -> Credentials<'_> {
        Credentials {
            access_key: &self.config.access_key,
            secret_key: &self.config.secret_key,
            session_token: self.config.session_token.as_deref(),
            region: &self.config.region,
            service: "s3",
        }
    }

    /// `(host, path)` for an object-level operation (path is the canonical,
    /// percent-encoded request path including the leading `/`).
    fn object_parts(&self, key: &str) -> (String, String) {
        let endpoint_host = self.config.endpoint_host();
        let ek = encode_key(key);
        if self.config.force_path_style {
            (
                endpoint_host.clone(),
                format!("/{}/{}", self.config.bucket, ek),
            )
        } else {
            (
                format!("{}.{}", self.config.bucket, endpoint_host),
                format!("/{ek}"),
            )
        }
    }

    /// `(host, path)` for a bucket-level operation (list, multipart init…).
    fn bucket_parts(&self) -> (String, String) {
        let endpoint_host = self.config.endpoint_host();
        if self.config.force_path_style {
            (endpoint_host.clone(), format!("/{}", self.config.bucket))
        } else {
            (
                format!("{}.{}", self.config.bucket, endpoint_host),
                "/".to_string(),
            )
        }
    }

    /// Sign a request and assemble the wire URL (query already encoded).
    ///
    /// Returns `(url, amz_date, authorization)`. `extra_signed` lists any
    /// additional headers the caller both sends *and* wants signed (typically
    /// `content-type`); `host`, `x-amz-content-sha256` and `x-amz-date` are
    /// always signed.
    fn signed(
        &self,
        method: &str,
        host: &str,
        path: &str,
        query: &[(String, String)],
        extra_signed: &[(&str, &str)],
        payload_sha256: &str,
    ) -> (String, String, String) {
        let amz_date = amz_date_now(SystemTime::now());
        let mut headers: Vec<(String, String)> = vec![
            ("host".to_string(), host.to_string()),
            (
                "x-amz-content-sha256".to_string(),
                payload_sha256.to_string(),
            ),
            ("x-amz-date".to_string(), amz_date.clone()),
        ];
        if let Some(token) = &self.config.session_token {
            headers.push(("x-amz-security-token".to_string(), token.clone()));
        }
        for (n, v) in extra_signed {
            headers.push((n.to_string(), v.to_string()));
        }
        let req = RequestToSign {
            method,
            canonical_uri: path,
            query,
            headers,
            payload_sha256,
            amz_date: &amz_date,
        };
        let auth = req.authorization(&self.creds());
        let cq = canonical_query(query);
        let url = if cq.is_empty() {
            format!("{}://{}{}", self.config.scheme(), host, path)
        } else {
            format!("{}://{}{}?{}", self.config.scheme(), host, path, cq)
        };
        (url, amz_date, auth)
    }

    /// Turn a non-success response into an [`Error`], surfacing the S3
    /// `<Code>` / `<Message>` when present.
    async fn check(&self, resp: reqwest::Response) -> Result<reqwest::Response> {
        let status = resp.status();
        if status.is_success() {
            return Ok(resp);
        }
        let body = resp.text().await.unwrap_or_default();
        let short: String = body.chars().take(512).collect();
        let friendly = s3_error_message(&short).unwrap_or_else(|| short.clone());
        Err(Error::api(status.as_u16(), None, friendly))
    }

    // ---- multipart (分片上传) -------------------------------------------

    /// Start a multipart upload and return a handle.
    pub async fn create_multipart_upload(
        &self,
        key: &str,
        opts: &PutOptions,
    ) -> Result<MultipartUpload> {
        let (host, path) = self.bucket_parts();
        let query = vec![("uploads".to_string(), String::new())];
        let extra = match &opts.content_type {
            Some(ct) => vec![("content-type", ct.as_str())],
            None => vec![],
        };
        let (url, amz_date, auth) =
            self.signed("POST", &host, &path, &query, &extra, EMPTY_PAYLOAD_SHA256);
        let mut reqb = self
            .http
            .post(&url)
            .header(reqwest::header::AUTHORIZATION, &auth)
            .header("x-amz-content-sha256", EMPTY_PAYLOAD_SHA256)
            .header("x-amz-date", &amz_date);
        if let Some(ct) = &opts.content_type {
            reqb = reqb.header(CONTENT_TYPE, ct);
        }
        let resp = reqb.send().await?;
        let resp = self.check(resp).await?;
        let xml = resp.text().await?;
        let upload_id = between_tags(&xml, "UploadId")
            .into_iter()
            .next()
            .ok_or_else(|| Error::InvalidInput("multipart init returned no UploadId".into()))?;
        Ok(MultipartUpload {
            client: self.clone(),
            upload_id: upload_id.trim().to_string(),
            key: key.to_string(),
        })
    }

    /// Re-attach to an existing upload id (resume after a restart).
    pub fn multipart_upload(&self, key: &str, upload_id: impl Into<String>) -> MultipartUpload {
        MultipartUpload {
            client: self.clone(),
            upload_id: upload_id.into(),
            key: key.to_string(),
        }
    }

    /// High-level resumable upload: a single simple `PUT` for small payloads,
    /// multipart upload for anything larger than [`S3_MIN_PART_SIZE`].
    async fn upload_resumable(
        &self,
        key: &str,
        data: Bytes,
        part_size: usize,
        opts: &PutOptions,
    ) -> Result<ObjectMetadata> {
        // Files up to 5 MiB fit a single simple PUT; larger ones need multipart.
        if data.is_empty() || data.len() <= S3_MIN_PART_SIZE {
            return self.put(key, PutBody::Bytes(data), opts).await;
        }
        let mp = self.create_multipart_upload(key, opts).await?;
        let part_size = if part_size == 0 {
            S3_DEFAULT_PART_SIZE
        } else {
            part_size.max(S3_MIN_PART_SIZE)
        };
        let total = data.len();
        let total_parts = (total + part_size - 1) / part_size;
        if total_parts > S3_MAX_PARTS as usize {
            let _ = mp.abort().await;
            return Err(Error::InvalidInput(format!(
                "need {total_parts} parts (> {S3_MAX_PARTS}); use a larger part_size"
            )));
        }
        let mut parts: Vec<CompletedPart> = Vec::with_capacity(total_parts);
        for idx in 0..total_parts {
            let number = (idx + 1) as u32;
            let start = idx * part_size;
            let end = (start + part_size).min(total);
            let chunk = data.slice(start..end);
            let etag = mp.upload_part(number, chunk).await?;
            parts.push(CompletedPart { number, etag });
        }
        mp.complete(&parts).await
    }
}

/// Percent-encode an object key for use in a URL path, per S3's rules
/// (each `/`-delimited segment is encoded; `/` separators stay literal).
fn encode_key(key: &str) -> String {
    let key = key.strip_prefix('/').unwrap_or(key);
    key.split('/')
        .map(|seg| uri_encode(seg, false))
        .collect::<Vec<_>>()
        .join("/")
}

// --------------------------------------------------------------------------
// ObjectStorage implementation
// --------------------------------------------------------------------------

#[async_trait]
impl ObjectStorage for S3Client {
    fn backend(&self) -> &'static str {
        "s3"
    }

    fn bucket(&self) -> &str {
        &self.config.bucket
    }

    async fn put(&self, key: &str, body: PutBody, opts: &PutOptions) -> Result<ObjectMetadata> {
        let data = body.into_bytes();
        let size = data.len() as u64;
        let payload_sha = sha256_hex(&data);

        let (host, path) = self.object_parts(key);
        let extra = match &opts.content_type {
            Some(ct) => vec![("content-type", ct.as_str())],
            None => vec![],
        };
        let (url, amz_date, auth) = self.signed("PUT", &host, &path, &[], &extra, &payload_sha);

        let mut reqb = self
            .http
            .put(&url)
            .header(reqwest::header::AUTHORIZATION, &auth)
            .header("x-amz-content-sha256", &payload_sha)
            .header("x-amz-date", &amz_date);
        if let Some(ct) = &opts.content_type {
            reqb = reqb.header(CONTENT_TYPE, ct);
        }
        // `insert_only` → refuse to overwrite (S3 conditional write).
        if opts.insert_only {
            reqb = reqb.header("if-none-match", "*");
        }
        let resp = reqb.body(data).send().await?;
        let resp = self.check(resp).await?;
        let etag = read_etag(&resp);
        Ok(ObjectMetadata {
            key: key.to_string(),
            size,
            content_type: opts.content_type.clone(),
            etag,
            last_modified: None,
        })
    }

    async fn put_resumable(
        &self,
        key: &str,
        body: PutBody,
        part_size: usize,
        opts: &PutOptions,
    ) -> Result<ObjectMetadata> {
        self.upload_resumable(key, body.into_bytes(), part_size, opts)
            .await
    }

    async fn get(&self, key: &str) -> Result<Bytes> {
        let (host, path) = self.object_parts(key);
        let (url, amz_date, auth) =
            self.signed("GET", &host, &path, &[], &[], EMPTY_PAYLOAD_SHA256);
        let resp = self
            .http
            .get(&url)
            .header(reqwest::header::AUTHORIZATION, &auth)
            .header("x-amz-content-sha256", EMPTY_PAYLOAD_SHA256)
            .header("x-amz-date", &amz_date)
            .send()
            .await?;
        let resp = self.check(resp).await?;
        Ok(resp.bytes().await?)
    }

    async fn delete(&self, key: &str) -> Result<()> {
        let (host, path) = self.object_parts(key);
        let (url, amz_date, auth) =
            self.signed("DELETE", &host, &path, &[], &[], EMPTY_PAYLOAD_SHA256);
        let resp = self
            .http
            .delete(&url)
            .header(reqwest::header::AUTHORIZATION, &auth)
            .header("x-amz-content-sha256", EMPTY_PAYLOAD_SHA256)
            .header("x-amz-date", &amz_date)
            .send()
            .await?;
        // S3 DELETE is idempotent: 204 even when the key was already gone, so
        // this never reports "missing". (Differs from Qiniu, which 404s.)
        self.check(resp).await?;
        Ok(())
    }

    async fn exists(&self, key: &str) -> Result<bool> {
        match self.stat(key).await {
            Ok(_) => Ok(true),
            Err(Error::Api { status: 404, .. }) => Ok(false),
            Err(other) => Err(other),
        }
    }

    async fn stat(&self, key: &str) -> Result<ObjectMetadata> {
        let (host, path) = self.object_parts(key);
        let (url, amz_date, auth) =
            self.signed("HEAD", &host, &path, &[], &[], EMPTY_PAYLOAD_SHA256);
        let resp = self
            .http
            .head(&url)
            .header(reqwest::header::AUTHORIZATION, &auth)
            .header("x-amz-content-sha256", EMPTY_PAYLOAD_SHA256)
            .header("x-amz-date", &amz_date)
            .send()
            .await?;
        let status = resp.status();
        if status.as_u16() == 404 {
            return Err(Error::api(404, None, "NoSuchKey"));
        }
        let resp = self.check(resp).await?;
        let headers = resp.headers();
        let size = headers
            .get(CONTENT_LENGTH)
            .and_then(|v| v.to_str().ok())
            .and_then(|s| s.parse::<u64>().ok())
            .unwrap_or(0);
        let content_type = headers
            .get(CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .map(str::to_string);
        let etag = headers
            .get(ETAG)
            .and_then(|v| v.to_str().ok())
            .map(strip_quotes);
        let last_modified = headers
            .get("last-modified")
            .and_then(|v| v.to_str().ok())
            .and_then(parse_iso8601);
        Ok(ObjectMetadata {
            key: key.to_string(),
            size,
            content_type,
            etag,
            last_modified,
        })
    }

    async fn list(&self, prefix: &str, opts: &ListOptions) -> Result<ListOutcome> {
        let (host, path) = self.bucket_parts();
        let mut q: Vec<(String, String)> = vec![("list-type".to_string(), "2".to_string())];
        if !prefix.is_empty() {
            q.push(("prefix".to_string(), prefix.to_string()));
        }
        if let Some(d) = &opts.delimiter {
            q.push(("delimiter".to_string(), d.clone()));
        }
        if let Some(m) = &opts.marker {
            q.push(("continuation-token".to_string(), m.clone()));
        }
        q.push((
            "max-keys".to_string(),
            opts.limit.unwrap_or(1000).to_string(),
        ));

        let (url, amz_date, auth) = self.signed("GET", &host, &path, &q, &[], EMPTY_PAYLOAD_SHA256);
        let resp = self
            .http
            .get(&url)
            .header(reqwest::header::AUTHORIZATION, &auth)
            .header("x-amz-content-sha256", EMPTY_PAYLOAD_SHA256)
            .header("x-amz-date", &amz_date)
            .send()
            .await?;
        let resp = self.check(resp).await?;
        let xml = resp.text().await?;
        parse_list(&xml)
    }

    fn presign_get(&self, key: &str, expires: Duration) -> Result<String> {
        let (host, path) = self.object_parts(key);
        let amz_date = amz_date_now(SystemTime::now());
        let headers = vec![("host".to_string(), host.clone())];
        let req = RequestToSign {
            method: "GET",
            canonical_uri: &path,
            query: &[],
            headers,
            payload_sha256: "UNSIGNED-PAYLOAD",
            amz_date: &amz_date,
        };
        let expires = expires.as_secs().min(S3_MAX_EXPIRES);
        let (appended, _sig) = req.presign(&self.creds(), expires);
        Ok(format!(
            "{}://{}{}?{}",
            self.config.scheme(),
            host,
            path,
            appended
        ))
    }
}

// --------------------------------------------------------------------------
// Multipart upload handle
// --------------------------------------------------------------------------

/// Handle for one in-flight S3 multipart upload.
///
/// Obtained from [`S3Client::create_multipart_upload`]. Persist
/// [`upload_id`](Self::upload_id) to resume after a crash via
/// [`S3Client::multipart_upload`].
#[derive(Debug, Clone)]
pub struct MultipartUpload {
    client: S3Client,
    upload_id: String,
    key: String,
}

impl MultipartUpload {
    /// The server-assigned upload id (persist it to resume later).
    pub fn upload_id(&self) -> &str {
        &self.upload_id
    }

    /// The object key this upload writes to.
    pub fn key(&self) -> &str {
        &self.key
    }

    /// Upload one part. `part_number` is 1-based (`1..=10000`); every part but
    /// the last must be >= 5 MiB. Returns the part ETag used in
    /// [`complete`](Self::complete).
    pub async fn upload_part(&self, part_number: u32, data: Bytes) -> Result<String> {
        if part_number == 0 || part_number > S3_MAX_PARTS {
            return Err(Error::InvalidInput(
                "part_number must be within 1..=10000".into(),
            ));
        }
        let (host, path) = self.client.object_parts(&self.key);
        let query = vec![
            ("partNumber".to_string(), part_number.to_string()),
            ("uploadId".to_string(), self.upload_id.clone()),
        ];
        let payload_sha = sha256_hex(&data);
        let (url, amz_date, auth) =
            self.client
                .signed("PUT", &host, &path, &query, &[], &payload_sha);
        let resp = self
            .client
            .http
            .put(&url)
            .header(reqwest::header::AUTHORIZATION, &auth)
            .header("x-amz-content-sha256", &payload_sha)
            .header("x-amz-date", &amz_date)
            .body(data)
            .send()
            .await?;
        let resp = self.client.check(resp).await?;
        let etag = read_etag(&resp)
            .ok_or_else(|| Error::InvalidInput("upload-part response missing ETag".into()))?;
        Ok(etag)
    }

    /// Complete the multipart upload, merging all parts in ascending order.
    pub async fn complete(&self, parts: &[CompletedPart]) -> Result<ObjectMetadata> {
        if parts.is_empty() {
            return Err(Error::InvalidInput("no parts to complete".into()));
        }
        let mut ordered: Vec<&CompletedPart> = parts.iter().collect();
        ordered.sort_by_key(|p| p.number);
        let body = build_complete_xml(&ordered);

        let (host, path) = self.client.object_parts(&self.key);
        let query = vec![("uploadId".to_string(), self.upload_id.clone())];
        let payload_sha = sha256_hex(body.as_bytes());
        let (url, amz_date, auth) =
            self.client
                .signed("POST", &host, &path, &query, &[], &payload_sha);
        let resp = self
            .client
            .http
            .post(&url)
            .header(reqwest::header::AUTHORIZATION, &auth)
            .header("x-amz-content-sha256", &payload_sha)
            .header("x-amz-date", &amz_date)
            .header(CONTENT_TYPE, "application/xml")
            .body(body)
            .send()
            .await?;
        let resp = self.client.check(resp).await?;
        let xml = resp.text().await?;
        let etag = between_tags(&xml, "ETag")
            .into_iter()
            .next()
            .map(|s| strip_quotes(&s));
        let key = between_tags(&xml, "Key")
            .into_iter()
            .next()
            .map(|s| unescape(&s))
            .unwrap_or_else(|| self.key.clone());
        Ok(ObjectMetadata {
            key,
            size: 0,
            content_type: None,
            etag,
            last_modified: None,
        })
    }

    /// Abort an in-flight upload, freeing its parts.
    pub async fn abort(&self) -> Result<()> {
        let (host, path) = self.client.object_parts(&self.key);
        let query = vec![("uploadId".to_string(), self.upload_id.clone())];
        let (url, amz_date, auth) =
            self.client
                .signed("DELETE", &host, &path, &query, &[], EMPTY_PAYLOAD_SHA256);
        let resp = self
            .client
            .http
            .delete(&url)
            .header(reqwest::header::AUTHORIZATION, &auth)
            .header("x-amz-content-sha256", EMPTY_PAYLOAD_SHA256)
            .header("x-amz-date", &amz_date)
            .send()
            .await?;
        self.client.check(resp).await?;
        Ok(())
    }
}

/// One finished part: its 1-based number and the ETag returned by
/// [`MultipartUpload::upload_part`].
#[derive(Debug, Clone)]
pub struct CompletedPart {
    /// 1-based part number.
    pub number: u32,
    /// ETag returned when the part was uploaded.
    pub etag: String,
}

// --------------------------------------------------------------------------
// Response parsing (XML, no extra dependency)
// --------------------------------------------------------------------------

/// Read the ETag response header, stripped of surrounding quotes.
fn read_etag(resp: &reqwest::Response) -> Option<String> {
    resp.headers()
        .get(ETAG)
        .and_then(|v| v.to_str().ok())
        .map(strip_quotes)
}

/// Strip one pair of surrounding double quotes.
fn strip_quotes(s: &str) -> String {
    let s = s.trim();
    if s.len() >= 2 && s.starts_with('"') && s.ends_with('"') {
        s[1..s.len() - 1].to_string()
    } else {
        s.to_string()
    }
}

/// Return every inner text found between `<tag>` and `</tag>` (tag has no
/// attributes, as in S3's XML). Used for `<Contents>`, `<Key>`, `<ETag>`…
fn between_tags(xml: &str, tag: &str) -> Vec<String> {
    let open = format!("<{tag}>");
    let close = format!("</{tag}>");
    let mut out = Vec::new();
    let mut i = 0;
    while let Some(o) = xml[i..].find(&open) {
        let start = i + o + open.len();
        if let Some(c) = xml[start..].find(&close) {
            out.push(xml[start..start + c].to_string());
            i = start + c + close.len();
        } else {
            break;
        }
    }
    out
}

/// Build the `<CompleteMultipartUpload>` XML body.
fn build_complete_xml(parts: &[&CompletedPart]) -> String {
    let mut body = String::from("<CompleteMultipartUpload>");
    for p in parts {
        body.push_str(&format!(
            "<Part><PartNumber>{}</PartNumber><ETag>{}</ETag></Part>",
            p.number,
            escape_xml(&p.etag)
        ));
    }
    body.push_str("</CompleteMultipartUpload>");
    body
}

/// Minimal XML escaping for values we write into the request body.
fn escape_xml(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            _ => out.push(c),
        }
    }
    out
}

/// Minimal XML unescaping for text we read back.
fn unescape(s: &str) -> String {
    s.replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&apos;", "'")
        .replace("&amp;", "&")
}

/// Parse the S3 `<Error>` body into a `Code: Message` string when possible.
fn s3_error_message(body: &str) -> Option<String> {
    let code = between_tags(body, "Code").into_iter().next()?;
    let msg = between_tags(body, "Message")
        .into_iter()
        .next()
        .unwrap_or_default();
    Some(format!("{code}: {msg}"))
}

/// Parse `ListObjectsV2` XML into a [`ListOutcome`].
///
/// `CommonPrefixes` (directory grouping from a `delimiter`) are intentionally
/// not returned as items; only the object keys under `<Contents>` are.
fn parse_list(xml: &str) -> Result<ListOutcome> {
    let items = between_tags(xml, "Contents")
        .into_iter()
        .map(|c| {
            let key = between_tags(&c, "Key")
                .into_iter()
                .next()
                .unwrap_or_default();
            let key = unescape(&key);
            let size = between_tags(&c, "Size")
                .into_iter()
                .next()
                .and_then(|s| s.trim().parse::<u64>().ok())
                .unwrap_or(0);
            let etag = between_tags(&c, "ETag")
                .into_iter()
                .next()
                .map(|s| strip_quotes(&s));
            let last_modified = between_tags(&c, "LastModified")
                .into_iter()
                .next()
                .and_then(|s| parse_iso8601(&s));
            ObjectMetadata {
                key,
                size,
                content_type: None,
                etag,
                last_modified,
            }
        })
        .collect();
    let next_marker = between_tags(xml, "NextContinuationToken")
        .into_iter()
        .next()
        .filter(|s| !s.is_empty());
    Ok(ListOutcome { items, next_marker })
}

/// Parse an ISO-8601 timestamp with a `Z` / `+hh:mm` offset into [`SystemTime`].
///
/// S3 uses e.g. `2021-03-12T09:00:00.000Z`. Hand-rolled to avoid a date crate.
fn parse_iso8601(s: &str) -> Option<SystemTime> {
    let s = s.trim();
    // Split off a trailing `Z` or a `+hh:mm` / `-hh:mm` offset, but only treat
    // `+` / `-` as an offset when it comes *after* the `T` (the date part
    // itself is full of `-`).
    let (body, offset): (&str, i64) = if let Some(stripped) = s.strip_suffix('Z') {
        (stripped, 0)
    } else if let Some(idx) = s.rfind(['+', '-']) {
        let (head, tail) = s.split_at(idx);
        if head.contains('T') {
            let sign = if tail.starts_with('-') { -1 } else { 1 };
            let off = parse_offset(&tail[1..])? as i64;
            (head, sign * off)
        } else {
            (s, 0)
        }
    } else {
        (s, 0)
    };

    let (d, t) = body.split_once('T')?;
    let mut ymd = d.splitn(3, '-');
    let y: i64 = ymd.next()?.parse().ok()?;
    let m: i64 = ymd.next()?.parse().ok()?;
    let day: i64 = ymd.next()?.parse().ok()?;
    let t = t.trim_end_matches('Z');
    let mut hms = t.splitn(3, ':');
    let h: i64 = hms.next()?.parse().ok()?;
    let min: i64 = hms.next()?.parse().ok()?;
    let sec_str = hms.next()?.trim_end_matches('Z');
    let sec: f64 = sec_str.parse().ok()?; // allow fractional seconds
    let days = days_from_civil(y, m, day);
    let total = days * 86_400 + h * 3_600 + min * 60 + sec as i64 - offset;
    let secs = total.max(0) as u64;
    Some(std::time::UNIX_EPOCH + Duration::from_secs(secs))
}

/// Parse a `+hh:mm` / `+hhmm` offset into seconds.
fn parse_offset(s: &str) -> Option<i64> {
    let s = s.trim_end_matches('Z').trim_end_matches('z');
    let s = s.trim();
    if s.is_empty() {
        return Some(0);
    }
    let (h, m) = s.split_once(':').unwrap_or((s, "0"));
    let h: i64 = h.parse().ok()?;
    let m: i64 = m.parse().ok()?;
    Some(h * 3_600 + m * 60)
}

/// Days since 1970-01-01 for a proleptic Gregorian date (Howard Hinnant).
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

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

    /// Exercises the XML list parser against a captured ListObjectsV2 shape.
    #[test]
    fn parses_list_objects_v2() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <Name>example-bucket</Name>
  <Prefix>docs/</Prefix>
  <KeyCount>2</KeyCount>
  <MaxKeys>1000</MaxKeys>
  <IsTruncated>false</IsTruncated>
  <Contents>
    <Key>docs/a.txt</Key>
    <LastModified>2021-03-12T09:00:00.000Z</LastModified>
    <ETag>"abc123"</ETag>
    <Size>1024</Size>
    <StorageClass>STANDARD</StorageClass>
  </Contents>
  <Contents>
    <Key>docs/b &amp; c.txt</Key>
    <LastModified>2022-01-02T03:04:05.000Z</LastModified>
    <ETag>"def456"</ETag>
    <Size>2048</Size>
  </Contents>
  <NextContinuationToken>token123</NextContinuationToken>
</ListBucketResult>"#;
        let out = parse_list(xml).unwrap();
        assert_eq!(out.items.len(), 2);
        assert_eq!(out.items[0].key, "docs/a.txt");
        assert_eq!(out.items[0].size, 1024);
        assert_eq!(out.items[0].etag.as_deref(), Some("abc123"));
        assert_eq!(out.items[1].key, "docs/b & c.txt"); // entity unescaped
        assert_eq!(out.items[1].size, 2048);
        assert_eq!(out.next_marker.as_deref(), Some("token123"));
    }

    #[test]
    fn encodes_object_keys_per_rfc3986() {
        assert_eq!(encode_key("a/b c.txt"), "a/b%20c.txt");
        assert_eq!(encode_key("photos/me+you.png"), "photos/me%2Byou.png");
        assert_eq!(encode_key("/leading/slash"), "leading/slash");
    }
}