multibucket 0.2.1

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
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
//! 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::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Arc, OnceLock};
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.
const DEFAULT_TOKEN_TTL: u64 = 3600;

/// Default lifetime (seconds) for signed *download* URLs.
///
/// Qiniu's download servers reject a private download token whose deadline `e`
/// is more than ~5 minutes ahead of their clock (HTTP 403
/// `RequestExpiresTooSkewed`); empirically `e = now + 300` is accepted while
/// `e = now + 600` is not. Download URLs are therefore capped at 300 s, well
/// inside that window. Upload tokens use the longer [`DEFAULT_TOKEN_TTL`].
const DEFAULT_DOWNLOAD_TTL: u64 = 300;

/// 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,
    /// Origin (源站) download hosts resolved from the UC service, filled on
    /// first use and reused afterwards.
    io_src_hosts: OnceLock<Vec<String>>,
    /// Cached clock offset `server_time - local_time` (seconds), used to mint
    /// token deadlines that survive client/server skew. Seeded from
    /// [`QiniuConfig::deadline_offset_secs`] and refined by
    /// [`sync_clock`](Self::sync_clock).
    clock_offset: Arc<AtomicI64>,
}

/// One `hosts` entry of the UC v4 query response
/// (`GET https://uc.qiniuapi.com/v4/query?ak=<AK>&bucket=<bucket>`).
#[derive(Debug, Deserialize)]
struct UcHostEntry {
    region: String,
    #[serde(default)]
    io_src: Option<UcDomains>,
}

#[derive(Debug, Deserialize)]
struct UcDomains {
    #[serde(default)]
    domains: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct UcQueryResponse {
    #[serde(default)]
    hosts: Vec<UcHostEntry>,
}

impl QiniuClient {
    /// Create a client from a [`QiniuConfig`] using a default HTTP client.
    pub fn new(config: QiniuConfig) -> Self {
        // Seed the clock offset from the explicit config value; `sync_clock`
        // later refines it against Qiniu's real server time.
        let clock_offset = Arc::new(AtomicI64::new(config.deadline_offset_secs));
        QiniuClient {
            mac: Mac::new(&config.access_key, &config.secret_key),
            http: reqwest::Client::new(),
            config,
            io_src_hosts: OnceLock::new(),
            clock_offset,
        }
    }

    /// 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 = self.deadline_now() + ttl.as_secs() as i64;
        let policy = PutPolicy::for_key(&self.config.bucket, key, deadline);
        self.mac.upload_token(&policy)
    }

    // ---- origin (源站) download ------------------------------------------

    /// Resolve the bucket's origin download hosts via the UC service,
    /// caching the result on the client.
    ///
    /// `GET https://uc.qiniuapi.com/v4/query?ak=<AK>&bucket=<bucket>` is
    /// unsigned; it reports the region the bucket really lives in and its
    /// per-bucket origin domain(s) such as `<bucket>.kodo-<region>.qiniucs.com`.
    async fn resolve_io_src_hosts(&self) -> Result<&[String]> {
        if let Some(hosts) = self.io_src_hosts.get() {
            return Ok(hosts.as_slice());
        }
        let url = format!(
            "https://uc.qiniuapi.com/v4/query?ak={}&bucket={}",
            self.config.access_key,
            utf8_percent_encode(&self.config.bucket, QUERY_VALUE_SET)
        );
        let resp = self.check(self.http.get(&url).send().await?).await?;
        let query: UcQueryResponse = resp.json().await?;
        let entry = query
            .hosts
            .iter()
            .find(|h| h.region == self.config.region.id())
            .or_else(|| query.hosts.first())
            .ok_or_else(|| {
                Error::InvalidInput(format!(
                    "uc query returned no hosts for bucket {}",
                    self.config.bucket
                ))
            })?;
        let hosts = entry
            .io_src
            .as_ref()
            .map(|d| d.domains.clone())
            .filter(|d| !d.is_empty())
            .ok_or_else(|| {
                Error::InvalidInput(format!(
                    "uc query returned no io_src hosts for region {}",
                    entry.region
                ))
            })?;
        // A racing concurrent resolution may have set the cache first; keep it.
        let stored = self.io_src_hosts.get_or_init(|| hosts);
        Ok(stored.as_slice())
    }

    /// Download an object through the bucket's origin (源站) domain.
    ///
    /// Qiniu's shared `iovip-*` hosts cannot serve private-bucket downloads
    /// without a download token; the origin (`kodo-*`/`io_src`) domain is used
    /// as a fallback and is signed with a **download token** (the standard
    /// `?e=<deadline>&token=<hmac>` scheme), which works for both private and
    /// public buckets. This is what [`get`](ObjectStorage::get) falls back to
    /// when the primary download host refuses.
    pub async fn get_via_io_src(&self, key: &str) -> Result<Bytes> {
        let hosts = self.resolve_io_src_hosts().await?;
        let deadline = self.deadline_now() + DEFAULT_DOWNLOAD_TTL as i64;
        let mut last_err = None;
        for host in hosts {
            let base = format!(
                "{}://{}/{}",
                self.config.scheme(),
                host,
                self.encode_key(key),
            );
            // Sign with a download token; Qiniu's io_src host checks for this
            // token (it returns "download token not specified" otherwise), and a
            // signed URL is also accepted by public buckets, so this is safe.
            let url = self.mac.private_download_url(&base, deadline);
            let resp = self.http.get(&url).send().await?;
            match self.check(resp).await {
                Ok(resp) => return Ok(resp.bytes().await?),
                Err(e) => last_err = Some(e),
            }
        }
        Err(last_err.expect("io_src hosts list is non-empty"))
    }

    /// Build a short-lived upload token for `key`, honouring `insert_only`.
    fn make_upload_token(&self, key: &str, opts: &PutOptions) -> Result<String> {
        let deadline = self.deadline_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;
        }
        // Qiniu rejects private download tokens whose deadline `e` is more than
        // ~5 minutes ahead of its server clock (`RequestExpiresTooSkewed`), so
        // cap the TTL regardless of what the caller asked for.
        let ttl = ttl.min(Duration::from_secs(DEFAULT_DOWNLOAD_TTL));
        let deadline = self.deadline_now() + ttl.as_secs() as i64;
        self.mac.private_download_url(&base, 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)
}

/// `unix_now()` plus the cached clock offset (`server_time - local_time`),
/// so token deadlines survive client/server skew. The offset is seeded from
/// [`QiniuConfig::deadline_offset_secs`] and refined by
/// [`sync_clock`](Self::sync_clock).
impl QiniuClient {
fn deadline_now(&self) -> i64 {
    unix_now().saturating_add(self.clock_offset.load(Ordering::Relaxed))
}

/// Best-effort clock sync: probe Qiniu's server time via the `Date` response
/// header and cache `server_time - local_time` so token deadlines (`e`) are
/// computed against Qiniu's clock instead of the (possibly skewed) local one.
///
/// This is the robust fix for Qiniu's `403 RequestExpiresTooSkewed`: when the
/// client machine's wall clock disagrees with Qiniu's servers, every signed
/// download/upload token is rejected. Call this once after construction (the
/// [`download_test`](crate) example does). On any failure it leaves the
/// configured [`QiniuConfig::deadline_offset_secs`] in place and returns `Ok`.
pub async fn sync_clock(&self) -> Result<()> {
    let host = self.config.rs_host_resolved();
    let url = format!("{}://{}/", self.config.scheme(), host);
    let resp = match self.http.get(&url).send().await {
        Ok(r) => r,
        // Transport failure: keep the configured offset, don't hard-fail.
        Err(_) => return Ok(()),
    };
    if let Some(date_hdr) = resp.headers().get(reqwest::header::DATE) {
        if let Ok(date_str) = date_hdr.to_str() {
            if let Some(server_epoch) = parse_http_date(date_str) {
                let local_epoch = unix_now();
                let offset = server_epoch - local_epoch;
                self.clock_offset.store(offset, Ordering::Relaxed);
            }
        }
    }
    Ok(())
}

}

/// Parse an RFC 1123 HTTP `Date` header, e.g. `Wed, 30 Sep 2026 07:45:00 GMT`.
fn parse_http_date(s: &str) -> Option<i64> {
    let parts: Vec<&str> = s.trim().split_whitespace().collect();
    // [weekday,] day month year time GMT  -> at least 5 meaningful tokens.
    if parts.len() < 5 {
        return None;
    }
    // Skip an optional leading weekday token (may carry a trailing comma).
    let (day_s, month_s, year_s, time_s) = if parts.len() == 6 {
        (parts[1], parts[2], parts[3], parts[4])
    } else {
        (parts[0], parts[1], parts[2], parts[3])
    };
    let day: i64 = day_s.trim_end_matches(',').parse().ok()?;
    let month = match month_s {
        "Jan" => 1,
        "Feb" => 2,
        "Mar" => 3,
        "Apr" => 4,
        "May" => 5,
        "Jun" => 6,
        "Jul" => 7,
        "Aug" => 8,
        "Sep" => 9,
        "Oct" => 10,
        "Nov" => 11,
        "Dec" => 12,
        _ => return None,
    };
    let year: i64 = year_s.parse().ok()?;
    let time: Vec<&str> = time_s.split(':').collect();
    if time.len() != 3 {
        return None;
    }
    let h: i64 = time[0].parse().ok()?;
    let m: i64 = time[1].parse().ok()?;
    let sec: i64 = time[2].parse().ok()?;
    let days = days_from_civil(year, month, day);
    Some(days * 86_400 + h * 3_600 + m * 60 + sec)
}

/// Days since 1970-01-01 for a proleptic Gregorian date (Howard Hinnant's
/// algorithm). Used by [`parse_http_date`].
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
}

/// 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_DOWNLOAD_TTL));
        // Capture the transport result so a DNS / connection failure can also
        // trigger the io_src fallback (`.send().await?` would otherwise escape
        // before `check` and before our match below).
        let resp = match self.http.get(&url).send().await {
            Ok(r) => self.check(r).await,
            Err(e) => Err(Error::Http(e)),
        };
        match resp {
            Ok(resp) => Ok(resp.bytes().await?),
            // With no custom download domain, the default host may either refuse
            // (private bucket -> 401/403/404) or be unreachable altogether
            // (DNS / connection error). In both cases fall back to the origin
            // (源站) domain, which is signed with a download token.
            Err(e) if self.config.download_domain.is_none() => match e {
                Error::Api { status, .. } if matches!(status, 401 | 403 | 404) => {
                    self.get_via_io_src(key).await
                }
                Error::Http(_) => self.get_via_io_src(key).await,
                other => Err(other),
            },
            Err(other) => Err(other),
        }
    }

    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::{parse_http_date, validate_bucket_name, UcQueryResponse};

    /// The UC v4 query shape, captured from the live service.
    #[test]
    fn uc_query_response_parses_the_live_shape() {
        let json = r#"{"hosts":[{"region":"z2","ttl":86400,"io":{"domains":["iovip-z2.qbox.me"]},
            "io_src":{"domains":["demo.kodo-cn-south-1.qiniucs.com"]},
            "up":{"domains":["upload-z2.qiniup.com","up-z2.qiniup.com"]}}],"ttl":86400}"#;
        let q: UcQueryResponse = serde_json::from_str(json).unwrap();
        assert_eq!(q.hosts.len(), 1);
        assert_eq!(q.hosts[0].region, "z2");
        assert_eq!(
            q.hosts[0].io_src.as_ref().unwrap().domains,
            vec!["demo.kodo-cn-south-1.qiniucs.com"]
        );
    }

    #[test]
    fn uc_query_response_tolerates_missing_io_src() {
        let json = r#"{"hosts":[{"region":"z0"}]}"#;
        let q: UcQueryResponse = serde_json::from_str(json).unwrap();
        assert!(q.hosts[0].io_src.is_none());
    }

    #[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());
    }

    #[test]
    fn parses_rfc1123_http_date() {
        // Known epochs (UTC).
        assert_eq!(parse_http_date("Thu, 01 Jan 1970 00:00:00 GMT").unwrap(), 0);
        assert_eq!(parse_http_date("Thu, 01 Jan 1970 00:00:01 GMT").unwrap(), 1);
        // 2000-01-01 00:00:00 UTC.
        assert_eq!(
            parse_http_date("Sat, 01 Jan 2000 00:00:00 GMT").unwrap(),
            946_684_800
        );
        // The weekday prefix is optional.
        assert_eq!(
            parse_http_date("30 Sep 2026 07:45:00 GMT").unwrap(),
            parse_http_date("Wed, 30 Sep 2026 07:45:00 GMT").unwrap()
        );
    }
}