opendal/services/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 http::Response;
22use http::StatusCode;
23use http::Uri;
24use log::debug;
25use reqsign::TencentCosConfig;
26use reqsign::TencentCosCredentialLoader;
27use reqsign::TencentCosSigner;
28
29use super::core::*;
30use super::delete::CosDeleter;
31use super::error::parse_error;
32use super::lister::CosLister;
33use super::lister::CosListers;
34use super::lister::CosObjectVersionsLister;
35use super::writer::CosWriter;
36use super::writer::CosWriters;
37use super::DEFAULT_SCHEME;
38use crate::raw::oio::PageLister;
39use crate::raw::*;
40use crate::services::CosConfig;
41use crate::*;
42impl Configurator for CosConfig {
43    type Builder = CosBuilder;
44
45    #[allow(deprecated)]
46    fn into_builder(self) -> Self::Builder {
47        CosBuilder {
48            config: self,
49
50            http_client: None,
51        }
52    }
53}
54
55/// Tencent-Cloud COS services support.
56#[doc = include_str!("docs.md")]
57#[derive(Default, Clone)]
58pub struct CosBuilder {
59    config: CosConfig,
60
61    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
62    http_client: Option<HttpClient>,
63}
64
65impl Debug for CosBuilder {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        f.debug_struct("CosBuilder")
68            .field("config", &self.config)
69            .finish()
70    }
71}
72
73impl CosBuilder {
74    /// Set root of this backend.
75    ///
76    /// All operations will happen under this root.
77    pub fn root(mut self, root: &str) -> Self {
78        self.config.root = if root.is_empty() {
79            None
80        } else {
81            Some(root.to_string())
82        };
83
84        self
85    }
86
87    /// Set endpoint of this backend.
88    ///
89    /// NOTE: no bucket or account id in endpoint, we will trim them if exists.
90    ///
91    /// # Examples
92    ///
93    /// - `https://cos.ap-singapore.myqcloud.com`
94    pub fn endpoint(mut self, endpoint: &str) -> Self {
95        if !endpoint.is_empty() {
96            self.config.endpoint = Some(endpoint.trim_end_matches('/').to_string());
97        }
98
99        self
100    }
101
102    /// Set secret_id 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_id(mut self, secret_id: &str) -> Self {
106        if !secret_id.is_empty() {
107            self.config.secret_id = Some(secret_id.to_string());
108        }
109
110        self
111    }
112
113    /// Set secret_key of this backend.
114    /// - If it is set, we will take user's input first.
115    /// - If not, we will try to load it from environment.
116    pub fn secret_key(mut self, secret_key: &str) -> Self {
117        if !secret_key.is_empty() {
118            self.config.secret_key = Some(secret_key.to_string());
119        }
120
121        self
122    }
123
124    /// Set bucket of this backend.
125    /// The param is required.
126    pub fn bucket(mut self, bucket: &str) -> Self {
127        if !bucket.is_empty() {
128            self.config.bucket = Some(bucket.to_string());
129        }
130
131        self
132    }
133
134    /// Set bucket versioning status for this backend
135    pub fn enable_versioning(mut self, enabled: bool) -> Self {
136        self.config.enable_versioning = enabled;
137
138        self
139    }
140
141    /// Disable config load so that opendal will not load config from
142    /// environment.
143    ///
144    /// For examples:
145    ///
146    /// - envs like `TENCENTCLOUD_SECRET_ID`
147    pub fn disable_config_load(mut self) -> Self {
148        self.config.disable_config_load = true;
149        self
150    }
151
152    /// Specify the http client that used by this service.
153    ///
154    /// # Notes
155    ///
156    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
157    /// during minor updates.
158    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
159    #[allow(deprecated)]
160    pub fn http_client(mut self, client: HttpClient) -> Self {
161        self.http_client = Some(client);
162        self
163    }
164}
165
166impl Builder for CosBuilder {
167    type Config = CosConfig;
168
169    fn build(self) -> Result<impl Access> {
170        debug!("backend build started: {:?}", &self);
171
172        let root = normalize_root(&self.config.root.unwrap_or_default());
173        debug!("backend use root {root}");
174
175        let bucket = match &self.config.bucket {
176            Some(bucket) => Ok(bucket.to_string()),
177            None => Err(
178                Error::new(ErrorKind::ConfigInvalid, "The bucket is misconfigured")
179                    .with_context("service", Scheme::Cos),
180            ),
181        }?;
182        debug!("backend use bucket {}", &bucket);
183
184        let uri = match &self.config.endpoint {
185            Some(endpoint) => endpoint.parse::<Uri>().map_err(|err| {
186                Error::new(ErrorKind::ConfigInvalid, "endpoint is invalid")
187                    .with_context("service", Scheme::Cos)
188                    .with_context("endpoint", endpoint)
189                    .set_source(err)
190            }),
191            None => Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
192                .with_context("service", Scheme::Cos)),
193        }?;
194
195        let scheme = match uri.scheme_str() {
196            Some(scheme) => scheme.to_string(),
197            None => "https".to_string(),
198        };
199
200        // If endpoint contains bucket name, we should trim them.
201        let endpoint = uri.host().unwrap().replace(&format!("//{bucket}."), "//");
202        debug!("backend use endpoint {}", &endpoint);
203
204        let mut cfg = TencentCosConfig::default();
205        if !self.config.disable_config_load {
206            cfg = cfg.from_env();
207        }
208
209        if let Some(v) = self.config.secret_id {
210            cfg.secret_id = Some(v);
211        }
212        if let Some(v) = self.config.secret_key {
213            cfg.secret_key = Some(v);
214        }
215
216        let cred_loader = TencentCosCredentialLoader::new(GLOBAL_REQWEST_CLIENT.clone(), cfg);
217
218        let signer = TencentCosSigner::new();
219
220        Ok(CosBackend {
221            core: Arc::new(CosCore {
222                info: {
223                    let am = AccessorInfo::default();
224                    am.set_scheme(DEFAULT_SCHEME)
225                        .set_root(&root)
226                        .set_name(&bucket)
227                        .set_native_capability(Capability {
228                            stat: true,
229                            stat_with_if_match: true,
230                            stat_with_if_none_match: true,
231                            stat_with_version: self.config.enable_versioning,
232
233                            read: true,
234
235                            read_with_if_match: true,
236                            read_with_if_none_match: true,
237                            read_with_if_modified_since: true,
238                            read_with_if_unmodified_since: true,
239                            read_with_version: self.config.enable_versioning,
240
241                            write: true,
242                            write_can_empty: true,
243                            write_can_append: true,
244                            write_can_multi: true,
245                            write_with_content_type: true,
246                            write_with_cache_control: true,
247                            write_with_content_disposition: true,
248                            // Cos doesn't support forbid overwrite while version has been enabled.
249                            write_with_if_not_exists: !self.config.enable_versioning,
250                            // The min multipart size of COS is 1 MiB.
251                            //
252                            // ref: <https://www.tencentcloud.com/document/product/436/14112>
253                            write_multi_min_size: Some(1024 * 1024),
254                            // The max multipart size of COS is 5 GiB.
255                            //
256                            // ref: <https://www.tencentcloud.com/document/product/436/14112>
257                            write_multi_max_size: if cfg!(target_pointer_width = "64") {
258                                Some(5 * 1024 * 1024 * 1024)
259                            } else {
260                                Some(usize::MAX)
261                            },
262                            write_with_user_metadata: true,
263
264                            delete: true,
265                            delete_with_version: self.config.enable_versioning,
266                            copy: true,
267
268                            list: true,
269                            list_with_recursive: true,
270                            list_with_versions: self.config.enable_versioning,
271                            list_with_deleted: self.config.enable_versioning,
272
273                            presign: true,
274                            presign_stat: true,
275                            presign_read: true,
276                            presign_write: true,
277
278                            shared: true,
279
280                            ..Default::default()
281                        });
282
283                    // allow deprecated api here for compatibility
284                    #[allow(deprecated)]
285                    if let Some(client) = self.http_client {
286                        am.update_http_client(|_| client);
287                    }
288
289                    am.into()
290                },
291                bucket: bucket.clone(),
292                root,
293                endpoint: format!("{}://{}.{}", &scheme, &bucket, &endpoint),
294                signer,
295                loader: cred_loader,
296            }),
297        })
298    }
299}
300
301/// Backend for Tencent-Cloud COS services.
302#[derive(Debug, Clone)]
303pub struct CosBackend {
304    core: Arc<CosCore>,
305}
306
307impl Access for CosBackend {
308    type Reader = HttpBody;
309    type Writer = CosWriters;
310    type Lister = CosListers;
311    type Deleter = oio::OneShotDeleter<CosDeleter>;
312
313    fn info(&self) -> Arc<AccessorInfo> {
314        self.core.info.clone()
315    }
316
317    async fn stat(&self, path: &str, args: OpStat) -> Result<RpStat> {
318        let resp = self.core.cos_head_object(path, &args).await?;
319
320        let status = resp.status();
321
322        match status {
323            StatusCode::OK => {
324                let headers = resp.headers();
325                let mut meta = parse_into_metadata(path, headers)?;
326
327                let user_meta = parse_prefixed_headers(headers, "x-cos-meta-");
328                if !user_meta.is_empty() {
329                    meta = meta.with_user_metadata(user_meta);
330                }
331
332                if let Some(v) = parse_header_to_str(headers, constants::X_COS_VERSION_ID)? {
333                    if v != "null" {
334                        meta.set_version(v);
335                    }
336                }
337
338                Ok(RpStat::new(meta))
339            }
340            _ => Err(parse_error(resp)),
341        }
342    }
343
344    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
345        let resp = self.core.cos_get_object(path, args.range(), &args).await?;
346
347        let status = resp.status();
348
349        match status {
350            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
351                Ok((RpRead::default(), resp.into_body()))
352            }
353            _ => {
354                let (part, mut body) = resp.into_parts();
355                let buf = body.to_buffer().await?;
356                Err(parse_error(Response::from_parts(part, buf)))
357            }
358        }
359    }
360
361    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
362        let writer = CosWriter::new(self.core.clone(), path, args.clone());
363
364        let w = if args.append() {
365            CosWriters::Two(oio::AppendWriter::new(writer))
366        } else {
367            CosWriters::One(oio::MultipartWriter::new(
368                self.core.info.clone(),
369                writer,
370                args.concurrent(),
371            ))
372        };
373
374        Ok((RpWrite::default(), w))
375    }
376
377    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
378        Ok((
379            RpDelete::default(),
380            oio::OneShotDeleter::new(CosDeleter::new(self.core.clone())),
381        ))
382    }
383
384    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
385        let l = if args.versions() || args.deleted() {
386            TwoWays::Two(PageLister::new(CosObjectVersionsLister::new(
387                self.core.clone(),
388                path,
389                args,
390            )))
391        } else {
392            TwoWays::One(PageLister::new(CosLister::new(
393                self.core.clone(),
394                path,
395                args.recursive(),
396                args.limit(),
397            )))
398        };
399
400        Ok((RpList::default(), l))
401    }
402
403    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
404        let resp = self.core.cos_copy_object(from, to).await?;
405
406        let status = resp.status();
407
408        match status {
409            StatusCode::OK => Ok(RpCopy::default()),
410            _ => Err(parse_error(resp)),
411        }
412    }
413
414    async fn presign(&self, path: &str, args: OpPresign) -> Result<RpPresign> {
415        let req = match args.operation() {
416            PresignOperation::Stat(v) => self.core.cos_head_object_request(path, v),
417            PresignOperation::Read(v) => {
418                self.core
419                    .cos_get_object_request(path, BytesRange::default(), v)
420            }
421            PresignOperation::Write(v) => {
422                self.core
423                    .cos_put_object_request(path, None, v, Buffer::new())
424            }
425            PresignOperation::Delete(_) => Err(Error::new(
426                ErrorKind::Unsupported,
427                "operation is not supported",
428            )),
429        };
430        let mut req = req?;
431        self.core.sign_query(&mut req, args.expire()).await?;
432
433        // We don't need this request anymore, consume it directly.
434        let (parts, _) = req.into_parts();
435
436        Ok(RpPresign::new(PresignedRequest::new(
437            parts.method,
438            parts.uri,
439            parts.headers,
440        )))
441    }
442}