multibucket 0.2.0

A unified async object-storage trait with a from-scratch Qiniu Kodo backend (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
//! Qiniu Kodo backend.

mod auth;
mod config;
mod region;

pub use auth::{Mac, PutPolicy};
pub use config::QiniuConfig;
pub use region::Region;

use std::collections::BTreeMap;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use async_trait::async_trait;
use bytes::Bytes;
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use reqwest::multipart::{Form, Part};
use serde::Deserialize;

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

use auth::{urlsafe_b64, FORM_CONTENT_TYPE};

/// Keep RFC-3986 unreserved characters, plus `/` for path-like keys.
const KEY_SET: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'_')
    .remove(b'.')
    .remove(b'~')
    .remove(b'/');

/// Encode only what must be escaped in a query value.
const QUERY_VALUE_SET: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'_')
    .remove(b'.')
    .remove(b'~');

/// Qiniu error code meaning "no such file or directory".
const QINIU_NO_SUCH_FILE: u16 = 612;

/// Default lifetime (seconds) for upload tokens and signed download URLs.
const DEFAULT_TOKEN_TTL: u64 = 3600;

/// Default part size for resumable uploads: 4 MiB.
const DEFAULT_PART_SIZE: usize = 4 * 1024 * 1024;
/// Qiniu v2 requires every non-final part to be at least 1 MiB.
const MIN_PART_SIZE: usize = 1024 * 1024;
/// Maximum number of parts allowed by Qiniu (`PartNumber` is 1..=10000).
const MAX_PARTS: u32 = 10_000;
/// How many times a single failed part is retried before giving up.
const PART_RETRY: usize = 3;

/// An asynchronous Qiniu Kodo client implementing [`ObjectStorage`].
#[derive(Debug, Clone)]
pub struct QiniuClient {
    config: QiniuConfig,
    mac: Mac,
    http: reqwest::Client,
}

impl QiniuClient {
    /// Create a client from a [`QiniuConfig`] using a default HTTP client.
    pub fn new(config: QiniuConfig) -> Self {
        QiniuClient {
            mac: Mac::new(&config.access_key, &config.secret_key),
            http: reqwest::Client::new(),
            config,
        }
    }

    /// 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) -> &QiniuConfig {
        &self.config
    }

    /// Generate a raw upload token for `key` valid for `ttl`.
    ///
    /// Useful when a browser / mobile client uploads directly to Qiniu and you
    /// only need to hand it a token.
    pub fn upload_token(&self, key: &str, ttl: Duration) -> Result<String> {
        let deadline = unix_now() + ttl.as_secs() as i64;
        let policy = PutPolicy::for_key(&self.config.bucket, key, deadline);
        self.mac.upload_token(&policy)
    }

    /// Build a short-lived upload token for `key`, honouring `insert_only`.
    fn make_upload_token(&self, key: &str, opts: &PutOptions) -> Result<String> {
        let deadline = unix_now() + DEFAULT_TOKEN_TTL as i64;
        let policy =
            PutPolicy::for_key(&self.config.bucket, key, deadline).insert_only(opts.insert_only);
        self.mac.upload_token(&policy)
    }

    // ---- bucket management (控制面) --------------------------------------

    /// Create the bucket this client is configured for (`mkbucketv3`).
    ///
    /// With `private = true` the new bucket is switched to private read access
    /// right away (see [`set_bucket_private`](Self::set_bucket_private)). Note
    /// the two steps are separate requests: if the second one fails the bucket
    /// exists but is still public.
    ///
    /// Client-side signing is a separate setting: to get signed download URLs
    /// out of [`presign_get`](ObjectStorage::presign_get) you still have to
    /// declare the bucket private in the config
    /// ([`QiniuConfig::private_bucket`]).
    ///
    /// This is an account-level control-plane call, so it uses Qiniu's `Qiniu`
    /// management signature instead of the per-object `UpToken`/`QBox` schemes;
    /// the credentials behind `access_key` must be allowed to manage buckets.
    /// Qiniu requires the name to be globally unique and to consist of 3-63
    /// characters of `a-z`, `0-9` and `-`, starting and ending with a letter or
    /// a digit; the region comes from [`QiniuConfig::region`].
    pub async fn create_bucket(&self, private: bool) -> Result<()> {
        validate_bucket_name(&self.config.bucket)?;
        // `create_bucket`'s validation guarantees the name needs no escaping,
        // and Qiniu expects the plain (not base64-encoded) name here.
        let path = format!(
            "/mkbucketv3/{}/region/{}",
            self.config.bucket,
            self.config.region.id()
        );
        let _resp = self.management_post(&path, "", "").await?;
        if private {
            self.set_bucket_private(true).await?;
        }
        Ok(())
    }

    /// Switch the configured bucket between private and public read access.
    ///
    /// `true` = private (downloads must be signed), `false` = public. Applies to
    /// an existing bucket; call it when you don't want to recreate the bucket
    /// through [`create_bucket`](Self::create_bucket).
    pub async fn set_bucket_private(&self, private: bool) -> Result<()> {
        let body = format!(
            "bucket={}&private={}",
            utf8_percent_encode(&self.config.bucket, QUERY_VALUE_SET),
            if private { 1 } else { 0 }
        );
        let _resp = self.management_post("/private", "", &body).await?;
        Ok(())
    }

    // ---- internal helpers ------------------------------------------------

    /// Send a form-encoded control-plane `POST` to the management host, signed
    /// with the `Qiniu` scheme. `query` and `body` must already be encoded
    /// exactly as they go on the wire, since both feed the signature.
    async fn management_post(
        &self,
        path: &str,
        query: &str,
        body: &str,
    ) -> Result<reqwest::Response> {
        let host = self.config.rs_host_resolved();
        let path_and_query = if query.is_empty() {
            path.to_string()
        } else {
            format!("{path}?{query}")
        };
        let url = format!("{}://{}{}", self.config.scheme(), host, path_and_query);
        let auth =
            self.mac
                .qiniu_authorization("POST", &path_and_query, host, FORM_CONTENT_TYPE, body);
        let resp = self
            .http
            .post(&url)
            .header(reqwest::header::AUTHORIZATION, auth)
            // Must equal the content type used for signing above.
            .header(CONTENT_TYPE, FORM_CONTENT_TYPE)
            .body(body.to_string())
            .send()
            .await?;
        self.check(resp).await
    }

    /// Percent-encode an object key for use in a URL path.
    fn encode_key(&self, key: &str) -> String {
        utf8_percent_encode(key, KEY_SET).to_string()
    }

    /// `urlsafe_base64("bucket:key")`, used by the RS management API.
    fn encoded_entry(&self, key: &str) -> String {
        let entry = format!("{}:{}", self.config.bucket, key);
        urlsafe_b64(entry.as_bytes())
    }

    /// Build a download URL, signing it when the bucket is private.
    fn download_url(&self, key: &str, ttl: Duration) -> String {
        let encoded_path = format!("/{}", self.encode_key(key));
        let base = format!(
            "{}://{}{}",
            self.config.scheme(),
            self.config.download_host(),
            encoded_path
        );
        if !self.config.private_bucket {
            return base;
        }
        let deadline = unix_now() + ttl.as_secs() as i64;
        self.mac
            .private_download_url(&base, &encoded_path, deadline)
    }

    /// Turn a non-success response into an [`Error`], reading the body.
    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();
        Err(Error::api(
            status.as_u16(),
            Some(status.as_u16() as i64),
            short,
        ))
    }

    // ---- resumable (分片上传 v2) ----------------------------------------

    /// Start a resumable (multipart) upload task and return a handle.
    ///
    /// `POST /buckets/<enc(bucket)>/objects/<enc(key)>/uploads` with `UpToken` auth.
    pub async fn initiate_multipart_upload(
        &self,
        key: &str,
        opts: &PutOptions,
    ) -> Result<MultipartUpload> {
        let token = self.make_upload_token(key, opts)?;
        let enc_bucket = urlsafe_b64(self.config.bucket.as_bytes());
        let enc_key = urlsafe_b64(key.as_bytes());
        let path = format!("/buckets/{enc_bucket}/objects/{enc_key}/uploads");
        let url = format!(
            "{}://{}{path}",
            self.config.scheme(),
            self.config.up_host_resolved()
        );

        let resp = self
            .http
            .post(&url)
            .header(
                reqwest::header::AUTHORIZATION,
                Mac::up_authorization(&token),
            )
            .header(CONTENT_TYPE, "text/plain;charset=utf8")
            .send()
            .await?;
        let resp = self.check(resp).await?;

        #[derive(Deserialize)]
        struct InitResp {
            #[serde(rename = "uploadId")]
            upload_id: String,
        }
        let init: InitResp = resp.json().await?;
        Ok(MultipartUpload {
            client: self.clone(),
            upload_id: init.upload_id,
            key: key.to_string(),
            token,
        })
    }

    /// Re-attach to an existing upload id (used when resuming after a restart).
    pub fn multipart_upload(
        &self,
        key: &str,
        upload_id: impl Into<String>,
    ) -> Result<MultipartUpload> {
        let token = self.make_upload_token(key, &PutOptions::default())?;
        Ok(MultipartUpload {
            client: self.clone(),
            upload_id: upload_id.into(),
            key: key.to_string(),
            token,
        })
    }

    /// High-level resumable upload; `resume` lets callers skip finished parts.
    async fn upload_resumable(
        &self,
        key: &str,
        data: Bytes,
        part_size: usize,
        opts: &PutOptions,
        resume: Option<&ResumeState>,
    ) -> Result<ObjectMetadata> {
        // Empty payloads go through the simple form upload.
        if data.is_empty() {
            return self.put(key, PutBody::Bytes(data), opts).await;
        }

        let part_size = if part_size == 0 {
            DEFAULT_PART_SIZE
        } else {
            part_size.max(MIN_PART_SIZE)
        };
        let total = data.len();
        let total_parts = (total + part_size - 1) / part_size;
        if total_parts > MAX_PARTS as usize {
            return Err(Error::InvalidInput(format!(
                "need {total_parts} parts (> {MAX_PARTS}); use a larger part_size"
            )));
        }

        let (mp, mut done) = match resume {
            Some(state) => (
                self.multipart_upload(key, state.upload_id.clone())?,
                state.parts.clone(),
            ),
            None => (
                self.initiate_multipart_upload(key, opts).await?,
                BTreeMap::new(),
            ),
        };

        let mut parts: Vec<CompletedPart> = Vec::with_capacity(total_parts);
        for idx in 0..total_parts {
            let number = (idx + 1) as u32;
            if let Some(name) = done.get(&number) {
                parts.push(CompletedPart {
                    number,
                    name: name.clone(),
                });
                continue;
            }
            let start = idx * part_size;
            let end = (start + part_size).min(total);
            let chunk = data.slice(start..end);
            let name = mp.upload_part_with_retry(number, chunk).await?;
            done.insert(number, name.clone());
            parts.push(CompletedPart { number, name });
        }

        mp.complete(&parts).await
    }

    /// Resume an interrupted upload, skipping the parts already in `state`.
    pub async fn put_resumable_resume(
        &self,
        key: &str,
        body: PutBody,
        part_size: usize,
        opts: &PutOptions,
        state: &ResumeState,
    ) -> Result<ObjectMetadata> {
        self.upload_resumable(key, body.into_bytes(), part_size, opts, Some(state))
            .await
    }
}

fn unix_now() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

/// Reject bucket names Qiniu would refuse anyway: 3-63 characters of `a-z`,
/// `0-9` and `-`, starting and ending with a letter or a digit.
fn validate_bucket_name(name: &str) -> Result<()> {
    let alnum = |b: u8| b.is_ascii_lowercase() || b.is_ascii_digit();
    let chars: Vec<u8> = name.bytes().collect();
    let ok = (3..=63).contains(&chars.len())
        && chars.iter().all(|b| alnum(*b) || *b == b'-')
        && chars
            .first()
            .zip(chars.last())
            .map(|(first, last)| alnum(*first) && alnum(*last))
            .unwrap_or(false);
    if ok {
        Ok(())
    } else {
        Err(Error::InvalidInput(format!(
            "invalid bucket name {name:?}: Qiniu wants 3-63 characters of lowercase letters, \
             digits and '-', starting and ending with a letter or a digit"
        )))
    }
}

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

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

    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 token = self.make_upload_token(key, opts)?;

        // `Part::stream` accepts `Bytes` directly (`Part::bytes` only takes
        // `Into<Cow<'static, [u8]>>`), and reqwest still reports the part's
        // known length, so the request keeps a precise Content-Length.
        let mut part =
            Part::stream(data).file_name(key.rsplit('/').next().unwrap_or(key).to_string());
        if let Some(ct) = &opts.content_type {
            if let Ok(value) = HeaderValue::from_str(ct) {
                let mut headers = HeaderMap::new();
                headers.insert(CONTENT_TYPE, value);
                part = part.headers(headers);
            }
        }

        let form = Form::new()
            .text("token", token)
            .text("key", key.to_string())
            .part("file", part);

        let url = format!(
            "{}://{}/",
            self.config.scheme(),
            self.config.up_host_resolved()
        );
        let resp = self.http.post(&url).multipart(form).send().await?;
        let resp = self.check(resp).await?;

        #[derive(Deserialize)]
        struct UpResp {
            #[serde(default)]
            hash: Option<String>,
        }
        let up: UpResp = resp.json().await?;

        Ok(ObjectMetadata {
            key: key.to_string(),
            size,
            content_type: opts.content_type.clone(),
            etag: up.hash,
            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, None)
            .await
    }

    async fn get(&self, key: &str) -> Result<Bytes> {
        let url = self.download_url(key, Duration::from_secs(DEFAULT_TOKEN_TTL));
        let resp = self.check(self.http.get(&url).send().await?).await?;
        Ok(resp.bytes().await?)
    }

    async fn delete(&self, key: &str) -> Result<()> {
        let path = format!("/delete/{}", self.encoded_entry(key));
        let url = format!(
            "{}://{}{}",
            self.config.scheme(),
            self.config.rs_host_resolved(),
            path
        );
        // QBox signing string: "<path>\n" (empty body).
        let auth = self.mac.qbox_authorization(&format!("{path}\n"));
        let resp = self
            .http
            .post(&url)
            .header(reqwest::header::AUTHORIZATION, auth)
            .send()
            .await?;
        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, .. }) if status == QINIU_NO_SUCH_FILE => Ok(false),
            Err(other) => Err(other),
        }
    }

    async fn stat(&self, key: &str) -> Result<ObjectMetadata> {
        let path = format!("/stat/{}", self.encoded_entry(key));
        let url = format!(
            "{}://{}{}",
            self.config.scheme(),
            self.config.rs_host_resolved(),
            path
        );
        let auth = self.mac.qbox_authorization(&format!("{path}\n"));
        let resp = self
            .http
            .post(&url)
            .header(reqwest::header::AUTHORIZATION, auth)
            .send()
            .await?;
        let resp = self.check(resp).await?;

        let stat: StatResp = resp.json().await?;
        Ok(ObjectMetadata {
            key: key.to_string(),
            size: stat.fsize.unwrap_or(0),
            content_type: stat.mime_type,
            etag: stat.hash,
            last_modified: stat.put_time.map(qiniu_puttime_to_system),
        })
    }

    async fn list(&self, prefix: &str, opts: &ListOptions) -> Result<ListOutcome> {
        // Build the query string ourselves so the exact bytes we sign are the
        // exact bytes we send (reqwest must not re-encode them).
        let mut pairs: Vec<String> = Vec::new();
        pairs.push(format!(
            "bucket={}",
            utf8_percent_encode(&self.config.bucket, QUERY_VALUE_SET)
        ));
        if !prefix.is_empty() {
            pairs.push(format!(
                "prefix={}",
                utf8_percent_encode(prefix, QUERY_VALUE_SET)
            ));
        }
        if let Some(delim) = &opts.delimiter {
            pairs.push(format!(
                "delimiter={}",
                utf8_percent_encode(delim, QUERY_VALUE_SET)
            ));
        }
        if let Some(marker) = &opts.marker {
            pairs.push(format!(
                "marker={}",
                utf8_percent_encode(marker, QUERY_VALUE_SET)
            ));
        }
        pairs.push(format!("limit={}", opts.limit.unwrap_or(100)));

        let query = pairs.join("&");
        let path = "/list";
        let url = format!(
            "{}://{}{}?{}",
            self.config.scheme(),
            self.config.rsf_host_resolved(),
            path,
            query
        );
        let auth = self.mac.qbox_authorization(&format!("{path}?{query}\n"));

        let resp = self
            .http
            .get(&url)
            .header(reqwest::header::AUTHORIZATION, auth)
            .send()
            .await?;
        let resp = self.check(resp).await?;

        let page: ListResp = resp.json().await?;
        let items = page
            .items
            .into_iter()
            .map(|i| ObjectMetadata {
                key: i.key,
                size: i.fsize.unwrap_or(0),
                content_type: i.mime_type,
                etag: i.hash,
                last_modified: i.put_time.map(qiniu_puttime_to_system),
            })
            .collect();
        Ok(ListOutcome {
            items,
            next_marker: page.marker.filter(|m| !m.is_empty()),
        })
    }

    fn presign_get(&self, key: &str, expires: Duration) -> Result<String> {
        Ok(self.download_url(key, expires))
    }
}

// --------------------------------------------------------------------------
// Response models
// --------------------------------------------------------------------------

#[derive(Deserialize)]
struct StatResp {
    #[serde(default)]
    fsize: Option<u64>,
    #[serde(default)]
    hash: Option<String>,
    #[serde(default, rename = "mimeType")]
    mime_type: Option<String>,
    /// 100-nanosecond units since the Unix epoch.
    #[serde(default, rename = "putTime")]
    put_time: Option<i64>,
}

#[derive(Deserialize)]
struct ListResp {
    #[serde(default)]
    items: Vec<ListItem>,
    #[serde(default)]
    marker: Option<String>,
}

#[derive(Deserialize)]
struct ListItem {
    key: String,
    #[serde(default)]
    fsize: Option<u64>,
    #[serde(default)]
    hash: Option<String>,
    #[serde(default, rename = "mimeType")]
    mime_type: Option<String>,
    #[serde(default, rename = "putTime")]
    put_time: Option<i64>,
}

/// Qiniu `putTime` is in 100-nanosecond intervals since the epoch.
fn qiniu_puttime_to_system(put_time: i64) -> SystemTime {
    let secs = (put_time / 10_000_000).max(0) as u64;
    UNIX_EPOCH + Duration::from_secs(secs)
}

// --------------------------------------------------------------------------
// Resumable (分片上传 v2) handle & state
// --------------------------------------------------------------------------

/// Handle for one in-flight resumable (multipart) upload task.
///
/// Obtained from [`QiniuClient::initiate_multipart_upload`] or
/// [`QiniuClient::multipart_upload`]. Persist [`upload_id`](Self::upload_id) to
/// resume across process restarts.
#[derive(Debug, Clone)]
pub struct MultipartUpload {
    client: QiniuClient,
    upload_id: String,
    key: String,
    token: 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 a single part. `part_number` is 1-based (`1..=10000`).
    ///
    /// Returns the `partName` you must pass back in [`complete`](Self::complete).
    pub async fn upload_part(&self, part_number: u32, data: Bytes) -> Result<String> {
        if part_number == 0 || part_number > MAX_PARTS {
            return Err(Error::InvalidInput(
                "part_number must be within 1..=10000".into(),
            ));
        }
        let url = format!(
            "{}://{}/uploadIds/{}/{}",
            self.client.config.scheme(),
            self.client.config.up_host_resolved(),
            self.upload_id,
            part_number
        );
        let resp = self
            .client
            .http
            .put(&url)
            .header(
                reqwest::header::AUTHORIZATION,
                Mac::up_authorization(&self.token),
            )
            .header(CONTENT_TYPE, "application/octet-stream")
            .body(data)
            .send()
            .await?;
        let resp = self.client.check(resp).await?;

        #[derive(Deserialize)]
        struct PartResp {
            #[serde(rename = "partName")]
            part_name: String,
        }
        let pr: PartResp = resp.json().await?;
        Ok(pr.part_name)
    }

    /// Upload a part, retrying transient failures up to [`PART_RETRY`] times.
    async fn upload_part_with_retry(&self, part_number: u32, data: Bytes) -> Result<String> {
        let mut last: Option<Error> = None;
        for _ in 0..PART_RETRY {
            match self.upload_part(part_number, data.clone()).await {
                Ok(name) => return Ok(name),
                Err(e) => last = Some(e),
            }
        }
        Err(last.unwrap_or_else(|| Error::InvalidInput("upload_part exhausted retries".into())))
    }

    /// Complete the upload, merging all parts (ascending part order).
    pub async fn complete(&self, parts: &[CompletedPart]) -> Result<ObjectMetadata> {
        if parts.is_empty() {
            return Err(Error::InvalidInput("no parts to complete".into()));
        }
        let joined = parts
            .iter()
            .map(|p| p.name.as_str())
            .collect::<Vec<_>>()
            .join(",");
        let etaets = urlsafe_b64(joined.as_bytes());
        let query = format!("op=mkfile&etaets={etaets}&etaets_cnt={}", parts.len());
        let url = format!(
            "{}://{}/uploadIds/{}?{}",
            self.client.config.scheme(),
            self.client.config.up_host_resolved(),
            self.upload_id,
            query
        );
        let resp = self
            .client
            .http
            .post(&url)
            .header(
                reqwest::header::AUTHORIZATION,
                Mac::up_authorization(&self.token),
            )
            .header(CONTENT_TYPE, "text/plain;charset=utf8")
            .send()
            .await?;
        let resp = self.client.check(resp).await?;

        #[derive(Deserialize)]
        struct CompleteResp {
            #[serde(default)]
            key: Option<String>,
            #[serde(default)]
            hash: Option<String>,
            #[serde(default, rename = "mimeType")]
            mime_type: Option<String>,
            #[serde(default)]
            fsize: Option<u64>,
        }
        let c: CompleteResp = resp.json().await?;
        Ok(ObjectMetadata {
            key: c.key.unwrap_or_else(|| self.key.clone()),
            size: c.fsize.unwrap_or(0),
            content_type: c.mime_type,
            etag: c.hash,
            last_modified: None,
        })
    }
}

/// One finished part: its 1-based number and the server-assigned `partName`.
#[derive(Debug, Clone)]
pub struct CompletedPart {
    /// 1-based part number.
    pub number: u32,
    /// `partName` returned when the part was uploaded.
    pub name: String,
}

/// Snapshot of a resumable upload, persistable to resume after a crash.
#[derive(Debug, Clone)]
pub struct ResumeState {
    /// Upload id from [`QiniuClient::initiate_multipart_upload`].
    pub upload_id: String,
    /// Already-uploaded parts, keyed by 1-based part number.
    pub parts: BTreeMap<u32, String>,
}

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

    #[test]
    fn bucket_names_follow_qinius_rules() {
        assert!(validate_bucket_name("abc").is_ok());
        assert!(validate_bucket_name("my-bucket-01").is_ok());
        assert!(validate_bucket_name(&"a".repeat(63)).is_ok());

        // Too short, too long, dashed ends, or characters Qiniu forbids.
        assert!(validate_bucket_name("ab").is_err());
        assert!(validate_bucket_name(&"a".repeat(64)).is_err());
        assert!(validate_bucket_name("-abc").is_err());
        assert!(validate_bucket_name("abc-").is_err());
        assert!(validate_bucket_name("My-Bucket").is_err());
        assert!(validate_bucket_name("my_bucket").is_err());
        assert!(validate_bucket_name("").is_err());
    }
}