Skip to main content

opendal_service_cos/
backend.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::fmt::Debug;
19use std::sync::Arc;
20
21use bytes::Buf;
22use http::StatusCode;
23use http::Uri;
24use log::debug;
25use reqsign_core::Context;
26use reqsign_core::OsEnv;
27use reqsign_file_read_tokio::TokioFileRead;
28use reqsign_tencent_cos::DefaultCredentialProvider;
29use reqsign_tencent_cos::RequestSigner;
30use reqsign_tencent_cos::StaticCredentialProvider;
31
32use super::COS_SCHEME;
33use super::config::CosConfig;
34use super::copier::{COS_COPY_MAX_PART_SIZE, COS_COPY_MIN_PART_SIZE, CosCopier, CosCopiers};
35use super::core::parse_error;
36use super::core::*;
37use super::deleter::CosDeleter;
38use super::lister::CosLister;
39use super::lister::CosListers;
40use super::lister::CosObjectVersionsLister;
41use super::reader::*;
42use super::writer::CosWriter;
43use super::writer::CosWriters;
44use opendal_core::raw::*;
45use opendal_core::*;
46
47/// Tencent-Cloud COS services support.
48#[doc = include_str!("docs.md")]
49#[derive(Default)]
50pub struct CosBuilder {
51    pub(super) config: CosConfig,
52}
53
54impl Debug for CosBuilder {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        f.debug_struct("CosBuilder")
57            .field("config", &self.config)
58            .finish_non_exhaustive()
59    }
60}
61
62impl CosBuilder {
63    /// Set root of this backend.
64    ///
65    /// All operations will happen under this root.
66    pub fn root(mut self, root: &str) -> Self {
67        self.config.root = if root.is_empty() {
68            None
69        } else {
70            Some(root.to_string())
71        };
72
73        self
74    }
75
76    /// Set endpoint of this backend.
77    ///
78    /// NOTE: no bucket or account id in endpoint, we will trim them if exists.
79    ///
80    /// # Examples
81    ///
82    /// - `https://cos.ap-singapore.myqcloud.com`
83    pub fn endpoint(mut self, endpoint: &str) -> Self {
84        if !endpoint.is_empty() {
85            self.config.endpoint = Some(endpoint.trim_end_matches('/').to_string());
86        }
87
88        self
89    }
90
91    /// Set secret_id of this backend.
92    /// - If it is set, we will take user's input first.
93    /// - If not, we will try to load it from environment.
94    pub fn secret_id(mut self, secret_id: &str) -> Self {
95        if !secret_id.is_empty() {
96            self.config.secret_id = Some(secret_id.to_string());
97        }
98
99        self
100    }
101
102    /// Set secret_key of this backend.
103    /// - If it is set, we will take user's input first.
104    /// - If not, we will try to load it from environment.
105    pub fn secret_key(mut self, secret_key: &str) -> Self {
106        if !secret_key.is_empty() {
107            self.config.secret_key = Some(secret_key.to_string());
108        }
109
110        self
111    }
112
113    /// Set security_token (a.k.a. session token) of this backend.
114    ///
115    /// This is used when authenticating via Tencent Cloud STS temporary
116    /// credentials (e.g. obtained from `GetFederationToken` or
117    /// `AssumeRole`). When provided, it will be combined with `secret_id`
118    /// and `secret_key` to sign requests, and the `x-cos-security-token`
119    /// header will be attached automatically.
120    ///
121    /// - If this is set along with `secret_id` and `secret_key`, a static
122    ///   credential provider with the token will be used.
123    /// - If this is not set, the default credential chain in reqsign will
124    ///   try to load credentials (including the token) from environment
125    ///   variables such as `TENCENTCLOUD_TOKEN`,
126    ///   `TENCENTCLOUD_SECURITY_TOKEN`, and `QCLOUD_SECRET_TOKEN`
127    ///   (unless `disable_config_load` is enabled).
128    pub fn security_token(mut self, security_token: &str) -> Self {
129        if !security_token.is_empty() {
130            self.config.security_token = Some(security_token.to_string());
131        }
132
133        self
134    }
135
136    /// Set bucket of this backend.
137    /// The param is required.
138    pub fn bucket(mut self, bucket: &str) -> Self {
139        if !bucket.is_empty() {
140            self.config.bucket = Some(bucket.to_string());
141        }
142
143        self
144    }
145
146    /// Deprecated: COS versioning capability is enabled by default.
147    #[deprecated(
148        since = "0.57.0",
149        note = "COS versioning capability is enabled by default and this option is no longer needed."
150    )]
151    pub fn enable_versioning(self, _enabled: bool) -> Self {
152        self
153    }
154
155    /// Disable config load so that opendal will not load config from
156    /// environment.
157    ///
158    /// For examples:
159    ///
160    /// - envs like `TENCENTCLOUD_SECRET_ID`
161    pub fn disable_config_load(mut self) -> Self {
162        self.config.disable_config_load = true;
163        self
164    }
165}
166
167impl Builder for CosBuilder {
168    type Config = CosConfig;
169
170    fn build(self) -> Result<impl Service> {
171        debug!("backend build started: {:?}", self);
172
173        let root = normalize_root(&self.config.root.unwrap_or_default());
174        debug!("backend use root {root}");
175
176        let bucket = match &self.config.bucket {
177            Some(bucket) => Ok(bucket.to_string()),
178            None => Err(
179                Error::new(ErrorKind::ConfigInvalid, "The bucket is misconfigured")
180                    .with_context("service", COS_SCHEME),
181            ),
182        }?;
183        debug!("backend use bucket {}", bucket);
184
185        let uri = match &self.config.endpoint {
186            Some(endpoint) => endpoint.parse::<Uri>().map_err(|err| {
187                Error::new(ErrorKind::ConfigInvalid, "endpoint is invalid")
188                    .with_context("service", COS_SCHEME)
189                    .with_context("endpoint", endpoint)
190                    .set_source(err)
191            }),
192            None => Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
193                .with_context("service", COS_SCHEME)),
194        }?;
195
196        let endpoint = build_endpoint(&uri, &bucket)?;
197        debug!("backend use endpoint {}", endpoint);
198
199        let os_env = OsEnv;
200        let ctx = Context::new()
201            .with_file_read(TokioFileRead)
202            .with_env(os_env);
203
204        let mut credential = if self.config.disable_config_load {
205            DefaultCredentialProvider::builder()
206                .no_env()
207                .no_web_identity()
208                .build()
209        } else {
210            DefaultCredentialProvider::new()
211        };
212
213        if let (Some(secret_id), Some(secret_key)) = (
214            self.config.secret_id.as_deref(),
215            self.config.secret_key.as_deref(),
216        ) {
217            let static_provider = if let Some(token) = self.config.security_token.as_deref() {
218                StaticCredentialProvider::with_security_token(secret_id, secret_key, token)
219            } else {
220                StaticCredentialProvider::new(secret_id, secret_key)
221            };
222
223            credential = credential.push_front(static_provider);
224        }
225
226        let credential_provider = Arc::new(credential);
227        let request_signer = Arc::new(RequestSigner::new());
228
229        let info = ServiceInfo::new(COS_SCHEME, &root, &bucket);
230        let capability = Capability {
231            stat: true,
232            stat_with_if_match: true,
233            stat_with_if_none_match: true,
234            stat_with_if_modified_since: true,
235            stat_with_if_unmodified_since: true,
236            stat_with_version: true,
237
238            read: true,
239            read_with_suffix: true,
240
241            read_with_if_match: true,
242            read_with_if_none_match: true,
243            read_with_if_modified_since: true,
244            read_with_if_unmodified_since: true,
245            read_with_override_cache_control: true,
246            read_with_override_content_disposition: true,
247            read_with_override_content_type: true,
248            read_with_version: true,
249
250            write: true,
251            write_can_empty: true,
252            write_can_append: true,
253            write_can_multi: true,
254            write_with_checksum: true,
255            write_with_content_type: true,
256            write_with_cache_control: true,
257            write_with_content_disposition: true,
258            write_with_if_not_exists: true,
259            copy_with_if_not_exists: true,
260            copy_with_source_version: true,
261            restore: true,
262            restore_with_version: true,
263            // The min multipart size of COS is 1 MiB.
264            //
265            // ref: <https://www.tencentcloud.com/document/product/436/14112>
266            write_multi_min_size: Some(1024 * 1024),
267            // The max multipart size of COS is 5 GiB.
268            //
269            // ref: <https://www.tencentcloud.com/document/product/436/14112>
270            write_multi_max_size: if cfg!(target_pointer_width = "64") {
271                Some(5 * 1024 * 1024 * 1024)
272            } else {
273                Some(usize::MAX)
274            },
275            write_with_user_metadata: true,
276
277            delete: true,
278            delete_with_version: true,
279            copy: true,
280            copy_can_multi: true,
281            copy_multi_min_size: Some(COS_COPY_MIN_PART_SIZE),
282            copy_multi_max_size: Some(COS_COPY_MAX_PART_SIZE),
283
284            list: true,
285            list_with_recursive: true,
286            list_with_versions: true,
287            list_with_deleted: true,
288
289            presign: true,
290            presign_stat: true,
291            presign_read: true,
292            presign_write: true,
293
294            shared: true,
295
296            ..Default::default()
297        };
298
299        Ok(CosBackend {
300            core: Arc::new(CosCore {
301                info,
302                capability,
303                bucket: bucket.clone(),
304                root,
305                endpoint,
306                sign_ctx: ctx,
307                credential_provider,
308                request_signer,
309                signers: HttpTransportCache::new(),
310            }),
311        })
312    }
313}
314
315/// Backend for Tencent-Cloud COS services.
316#[derive(Debug, Clone)]
317pub struct CosBackend {
318    pub(crate) core: Arc<CosCore>,
319}
320
321impl Service for CosBackend {
322    type Reader = oio::StreamReader<CosReader>;
323    type Writer = CosWriters;
324    type Lister = CosListers;
325    type Deleter = oio::OneShotDeleter<CosDeleter>;
326    type Copier = CosCopiers;
327    type Composer = ();
328
329    fn info(&self) -> ServiceInfo {
330        self.core.info.clone()
331    }
332
333    fn capability(&self) -> Capability {
334        self.core.capability
335    }
336
337    async fn create_dir(
338        &self,
339        _ctx: &OperationContext,
340        _path: &str,
341        _args: OpCreateDir,
342    ) -> Result<RpCreateDir> {
343        Err(Error::new(
344            ErrorKind::Unsupported,
345            "operation is not supported",
346        ))
347    }
348
349    async fn stat(&self, ctx: &OperationContext, path: &str, args: OpStat) -> Result<RpStat> {
350        let resp = self.core.cos_head_object(ctx, path, &args).await?;
351
352        let status = resp.status();
353
354        match status {
355            StatusCode::OK => {
356                let headers = resp.headers();
357                let mut meta = parse_into_metadata(path, headers)?.into_builder();
358
359                let user_meta = parse_prefixed_headers(headers, "x-cos-meta-");
360                if !user_meta.is_empty() {
361                    meta.user_metadata(user_meta);
362                }
363
364                if let Some(v) = parse_header_to_str(headers, constants::X_COS_VERSION_ID)?
365                    && v != "null"
366                {
367                    meta.version(v);
368                }
369
370                Ok(RpStat::new(meta.build()))
371            }
372            _ => Err(parse_error(
373                ErrorContext::new(ServiceOperation("HeadObject"))
374                    .with_caller_condition(args.is_conditional()),
375                resp,
376            )),
377        }
378    }
379    fn read(&self, ctx: &OperationContext, path: &str, args: OpRead) -> Result<Self::Reader> {
380        let output: oio::StreamReader<CosReader> = {
381            Ok(oio::StreamReader::new(CosReader::new(
382                self.clone(),
383                ctx.clone(),
384                path,
385                args,
386            )))
387        }?;
388
389        Ok(output)
390    }
391
392    fn write(&self, ctx: &OperationContext, path: &str, args: OpWrite) -> Result<Self::Writer> {
393        let append = args.append();
394        let concurrent = args.concurrent();
395        let writer = CosWriter::new(self.core.clone(), ctx.clone(), path, args)?;
396        Ok(if append {
397            CosWriters::Two(oio::AppendWriter::new(writer))
398        } else {
399            CosWriters::One(oio::MultipartWriter::new(
400                ctx.executor().clone(),
401                writer,
402                concurrent,
403            ))
404        })
405    }
406
407    fn delete(&self, ctx: &OperationContext) -> Result<Self::Deleter> {
408        let output: oio::OneShotDeleter<CosDeleter> = {
409            Ok(oio::OneShotDeleter::new(CosDeleter::new(
410                self.core.clone(),
411                ctx.clone(),
412            )))
413        }?;
414
415        Ok(output)
416    }
417
418    fn list(&self, ctx: &OperationContext, path: &str, args: OpList) -> Result<Self::Lister> {
419        let output: CosListers = {
420            let l = if args.versions() || args.deleted() {
421                TwoWays::Two(oio::PageLister::new(CosObjectVersionsLister::new(
422                    self.core.clone(),
423                    ctx.clone(),
424                    path,
425                    args,
426                )))
427            } else {
428                TwoWays::One(oio::PageLister::new(CosLister::new(
429                    self.core.clone(),
430                    ctx.clone(),
431                    path,
432                    args.recursive(),
433                    args.limit(),
434                )))
435            };
436
437            Ok(l)
438        }?;
439
440        Ok(output)
441    }
442
443    fn copy(
444        &self,
445        ctx: &OperationContext,
446        from: &str,
447        to: &str,
448        args: OpCopy,
449    ) -> Result<Self::Copier> {
450        Ok(CosCopier::multipart(self.core.clone(), ctx, from, to, args))
451    }
452
453    async fn rename(
454        &self,
455        _ctx: &OperationContext,
456        _from: &str,
457        _to: &str,
458        _args: OpRename,
459    ) -> Result<RpRename> {
460        Err(Error::new(
461            ErrorKind::Unsupported,
462            "operation is not supported",
463        ))
464    }
465
466    async fn restore(
467        &self,
468        ctx: &OperationContext,
469        path: &str,
470        args: OpRestore,
471    ) -> Result<RpRestore> {
472        if let Some(version) = args.version() {
473            let copy_args = OpCopy::from_options(
474                &self.capability(),
475                options::CopyOptions {
476                    source_version: Some(version.to_owned()),
477                    ..Default::default()
478                },
479            )?;
480            self.core
481                .cos_copy_object(ctx, path, path, &copy_args)
482                .await?;
483            return Ok(RpRestore::new());
484        }
485
486        let resp = self
487            .core
488            .cos_list_object_versions(ctx, path, "", Some(1), "", "")
489            .await?;
490        if resp.status() != StatusCode::OK {
491            return Err(parse_error(
492                ErrorContext::new(ServiceOperation("ListObjectVersions")),
493                resp,
494            ));
495        }
496
497        let output: ListObjectVersionsOutput =
498            quick_xml::de::from_reader(resp.into_body().reader())
499                .map_err(new_xml_deserialize_error)
500                .map_err(Error::set_temporary)?;
501        let abs_path = build_absolute_path(&self.core.root, path);
502
503        if output
504            .version
505            .iter()
506            .any(|version| version.key == abs_path && version.is_latest)
507        {
508            return Ok(RpRestore::new());
509        }
510
511        let Some(marker) = output
512            .delete_marker
513            .into_iter()
514            .find(|marker| marker.key == abs_path && marker.is_latest)
515        else {
516            return Err(Error::new(
517                ErrorKind::NotFound,
518                "no live object or current delete marker exists",
519            ));
520        };
521
522        let delete_args = OpDelete::from_options(
523            &self.capability(),
524            options::DeleteOptions {
525                version: Some(marker.version_id),
526                ..Default::default()
527            },
528        )?;
529        let resp = self.core.cos_delete_object(ctx, path, &delete_args).await?;
530        match resp.status() {
531            StatusCode::NO_CONTENT => {
532                // COS can still list a marker after it was deleted. Only a
533                // deletion of an existing marker returns this response header.
534                if resp
535                    .headers()
536                    .get("x-cos-delete-marker")
537                    .is_some_and(|v| v == "true")
538                {
539                    Ok(RpRestore::new())
540                } else {
541                    Err(Error::new(
542                        ErrorKind::Unexpected,
543                        "the listed delete marker no longer exists; retry after the version listing updates",
544                    )
545                    .set_temporary())
546                }
547            }
548            _ => Err(parse_error(
549                ErrorContext::new(ServiceOperation("DeleteObject")),
550                resp,
551            )),
552        }
553    }
554
555    async fn presign(
556        &self,
557        ctx: &OperationContext,
558        path: &str,
559        args: OpPresign,
560    ) -> Result<RpPresign> {
561        let req = match args.operation() {
562            PresignOperation::Stat(v) => self.core.cos_head_object_request(path, v),
563            PresignOperation::Read(range, v) => self.core.cos_get_object_request(path, *range, v),
564            PresignOperation::Write(v) => {
565                if v.checksum().is_some() {
566                    return Err(Error::new(
567                        ErrorKind::Unsupported,
568                        "COS cannot verify a checksum for a presigned write",
569                    ));
570                }
571                self.core
572                    .cos_put_object_request(path, None, v, Buffer::new())
573            }
574            PresignOperation::Delete(_) => Err(Error::new(
575                ErrorKind::Unsupported,
576                "operation is not supported",
577            )),
578            _ => Err(Error::new(
579                ErrorKind::Unsupported,
580                "operation is not supported",
581            )),
582        };
583        let req = req?;
584        let req = self.core.sign_query(ctx, req, args.expire()).await?;
585
586        // We don't need this request anymore, consume it directly.
587        let (parts, _) = req.into_parts();
588
589        Ok(RpPresign::new(PresignedRequest::new(
590            parts.method,
591            parts.uri,
592            parts.headers,
593        )))
594    }
595}
596
597/// Compose the request endpoint for a bucket, as `scheme://bucket.host[:port]`.
598///
599/// Extracted so it can be unit tested, mirroring `S3Builder::build_endpoint`.
600fn build_endpoint(uri: &Uri, bucket: &str) -> Result<String> {
601    let scheme = uri.scheme_str().unwrap_or("https");
602
603    let host = uri.host().ok_or_else(|| {
604        Error::new(ErrorKind::ConfigInvalid, "endpoint host is empty")
605            .with_context("service", COS_SCHEME)
606            .with_context("endpoint", uri.to_string())
607    })?;
608
609    // If the endpoint already carries the bucket as its leftmost label, don't add it twice.
610    let host = host.strip_prefix(&format!("{bucket}.")).unwrap_or(host);
611
612    // Keep the port. `Uri::host` omits it, so composing from the host alone silently sent every
613    // request to the scheme default.
614    Ok(match uri.port_u16() {
615        Some(port) => format!("{scheme}://{bucket}.{host}:{port}"),
616        None => format!("{scheme}://{bucket}.{host}"),
617    })
618}
619
620#[cfg(test)]
621mod tests {
622    use http::header::CONTENT_ENCODING;
623
624    use super::*;
625
626    #[tokio::test]
627    async fn presign_read_signs_optional_response_overrides() {
628        let op = Operator::new(
629            CosBuilder::default()
630                .bucket("test")
631                .endpoint("https://cos.example.com")
632                .secret_id("test")
633                .secret_key("test")
634                .disable_config_load(),
635        )
636        .unwrap();
637
638        let cache_control = Some("private, max-age=42, no-transform");
639        let disposition = Some("attachment; filename=\"preview & report.txt\"");
640        let content_type = Some("application/json; profile=\"a&b\"");
641        for (cache_control, disposition, content_type) in [
642            (None, None, None),
643            (cache_control, None, None),
644            (None, disposition, None),
645            (None, None, content_type),
646            (cache_control, disposition, content_type),
647        ] {
648            let request = op
649                .presign_read_options(
650                    "object.txt",
651                    Duration::from_secs(60),
652                    options::ReadOptions {
653                        override_cache_control: cache_control.map(str::to_owned),
654                        override_content_disposition: disposition.map(str::to_owned),
655                        override_content_type: content_type.map(str::to_owned),
656                        ..Default::default()
657                    },
658                )
659                .await
660                .unwrap();
661            let query = request.uri().query().unwrap();
662            let signed_params = query
663                .split('&')
664                .find_map(|param| param.strip_prefix("q-url-param-list="))
665                .map(percent_decode_path)
666                .expect("missing COS signed query parameters");
667            for (key, expected) in [
668                ("response-cache-control", cache_control),
669                ("response-content-disposition", disposition),
670                ("response-content-type", content_type),
671            ] {
672                let values: Vec<_> = query
673                    .split('&')
674                    .filter_map(|param| param.split_once('='))
675                    .filter(|(name, _)| *name == key)
676                    .map(|(_, value)| percent_decode_path(value))
677                    .collect();
678                assert_eq!(values.as_slice(), expected.as_slice(), "{key} query values");
679                assert_eq!(
680                    signed_params.split(';').filter(|name| *name == key).count(),
681                    usize::from(expected.is_some()),
682                    "{key} signed query count"
683                );
684            }
685        }
686    }
687
688    #[tokio::test]
689    async fn presign_write_signs_optional_content_encoding() {
690        let op = Operator::new(
691            CosBuilder::default()
692                .bucket("test")
693                .endpoint("https://cos.example.com")
694                .secret_id("test")
695                .secret_key("test")
696                .disable_config_load(),
697        )
698        .unwrap();
699
700        for encoding in [Some("gzip"), None] {
701            let request = op
702                .presign_write_options(
703                    "object.txt",
704                    Duration::from_secs(60),
705                    options::WriteOptions {
706                        content_type: Some("text/plain".to_owned()),
707                        content_encoding: encoding.map(str::to_owned),
708                        ..Default::default()
709                    },
710                )
711                .await
712                .unwrap();
713            let values: Vec<_> = request.header().get_all(CONTENT_ENCODING).iter().collect();
714            assert_eq!(values.as_slice(), encoding.as_slice());
715
716            let signed_headers = request
717                .uri()
718                .query()
719                .unwrap()
720                .split('&')
721                .find_map(|param| param.strip_prefix("q-header-list="))
722                .map(percent_decode_path)
723                .expect("missing COS signed headers");
724            let signed_count = signed_headers
725                .split(';')
726                .filter(|name| *name == CONTENT_ENCODING.as_str())
727                .count();
728            assert_eq!(signed_count, usize::from(encoding.is_some()));
729        }
730    }
731
732    fn endpoint_of(raw: &str, bucket: &str) -> String {
733        build_endpoint(&raw.parse::<Uri>().unwrap(), bucket).unwrap()
734    }
735
736    #[test]
737    fn build_endpoint_keeps_a_custom_port() {
738        assert_eq!(
739            endpoint_of(
740                "https://cos.internal.example.com:8443",
741                "examplebucket-1250000000"
742            ),
743            "https://examplebucket-1250000000.cos.internal.example.com:8443"
744        );
745    }
746
747    #[test]
748    fn build_endpoint_prefixes_the_bucket() {
749        assert_eq!(
750            endpoint_of(
751                "https://cos.ap-guangzhou.myqcloud.com",
752                "examplebucket-1250000000"
753            ),
754            "https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com"
755        );
756    }
757
758    #[test]
759    fn build_endpoint_does_not_repeat_a_bucket_already_in_the_host() {
760        // The previous `replace("//{bucket}.", "//")` could never match, because Uri::host never
761        // contains "//", so this doubled the bucket label.
762        assert_eq!(
763            endpoint_of(
764                "https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com",
765                "examplebucket-1250000000"
766            ),
767            "https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com"
768        );
769    }
770
771    #[test]
772    fn build_endpoint_defaults_the_scheme_to_https() {
773        // A bare host parses with no scheme; "//host" parses with no host at all, which is why
774        // the missing-host case below is a real input rather than a contrived one.
775        assert_eq!(
776            endpoint_of("cos.ap-guangzhou.myqcloud.com", "b"),
777            "https://b.cos.ap-guangzhou.myqcloud.com"
778        );
779    }
780
781    #[test]
782    fn build_endpoint_reports_a_missing_host_instead_of_panicking() {
783        // Both of these parse to host = None. The previous code called .unwrap() on that.
784        for raw in ["/just/a/path", "//cos.ap-guangzhou.myqcloud.com"] {
785            let uri = raw.parse::<Uri>().unwrap();
786            assert!(
787                build_endpoint(&uri, "b").is_err(),
788                "expected an error for {raw}"
789            );
790        }
791    }
792}