opendal/services/obs/
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::collections::HashMap;
19use std::fmt::Debug;
20use std::fmt::Formatter;
21use std::sync::Arc;
22
23use http::Response;
24use http::StatusCode;
25use http::Uri;
26use log::debug;
27use reqsign::HuaweicloudObsConfig;
28use reqsign::HuaweicloudObsCredentialLoader;
29use reqsign::HuaweicloudObsSigner;
30
31use super::core::{constants, ObsCore};
32use super::delete::ObsDeleter;
33use super::error::parse_error;
34use super::lister::ObsLister;
35use super::writer::ObsWriter;
36use super::writer::ObsWriters;
37use crate::raw::*;
38use crate::services::ObsConfig;
39use crate::*;
40
41impl Configurator for ObsConfig {
42    type Builder = ObsBuilder;
43
44    #[allow(deprecated)]
45    fn into_builder(self) -> Self::Builder {
46        ObsBuilder {
47            config: self,
48
49            http_client: None,
50        }
51    }
52}
53
54/// Huawei-Cloud Object Storage Service (OBS) support
55#[doc = include_str!("docs.md")]
56#[derive(Default, Clone)]
57pub struct ObsBuilder {
58    config: ObsConfig,
59
60    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
61    http_client: Option<HttpClient>,
62}
63
64impl Debug for ObsBuilder {
65    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
66        let mut d = f.debug_struct("ObsBuilder");
67        d.field("config", &self.config);
68        d.finish_non_exhaustive()
69    }
70}
71
72impl ObsBuilder {
73    /// Set root of this backend.
74    ///
75    /// All operations will happen under this root.
76    pub fn root(mut self, root: &str) -> Self {
77        self.config.root = if root.is_empty() {
78            None
79        } else {
80            Some(root.to_string())
81        };
82
83        self
84    }
85
86    /// Set endpoint of this backend.
87    ///
88    /// Both huaweicloud default domain and user domain endpoints are allowed.
89    /// Please DO NOT add the bucket name to the endpoint.
90    ///
91    /// - `https://obs.cn-north-4.myhuaweicloud.com`
92    /// - `obs.cn-north-4.myhuaweicloud.com` (https by default)
93    /// - `https://custom.obs.com` (port should not be set)
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 access_key_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 access_key_id(mut self, access_key_id: &str) -> Self {
106        if !access_key_id.is_empty() {
107            self.config.access_key_id = Some(access_key_id.to_string());
108        }
109
110        self
111    }
112
113    /// Set secret_access_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_access_key(mut self, secret_access_key: &str) -> Self {
117        if !secret_access_key.is_empty() {
118            self.config.secret_access_key = Some(secret_access_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    /// Specify the http client that used by this service.
142    ///
143    /// # Notes
144    ///
145    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
146    /// during minor updates.
147    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
148    #[allow(deprecated)]
149    pub fn http_client(mut self, client: HttpClient) -> Self {
150        self.http_client = Some(client);
151        self
152    }
153}
154
155impl Builder for ObsBuilder {
156    const SCHEME: Scheme = Scheme::Obs;
157    type Config = ObsConfig;
158
159    fn build(self) -> Result<impl Access> {
160        debug!("backend build started: {:?}", &self);
161
162        let root = normalize_root(&self.config.root.unwrap_or_default());
163        debug!("backend use root {}", root);
164
165        let bucket = match &self.config.bucket {
166            Some(bucket) => Ok(bucket.to_string()),
167            None => Err(
168                Error::new(ErrorKind::ConfigInvalid, "The bucket is misconfigured")
169                    .with_context("service", Scheme::Obs),
170            ),
171        }?;
172        debug!("backend use bucket {}", &bucket);
173
174        let uri = match &self.config.endpoint {
175            Some(endpoint) => endpoint.parse::<Uri>().map_err(|err| {
176                Error::new(ErrorKind::ConfigInvalid, "endpoint is invalid")
177                    .with_context("service", Scheme::Obs)
178                    .set_source(err)
179            }),
180            None => Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
181                .with_context("service", Scheme::Obs)),
182        }?;
183
184        let scheme = match uri.scheme_str() {
185            Some(scheme) => scheme.to_string(),
186            None => "https".to_string(),
187        };
188
189        let (endpoint, is_obs_default) = {
190            let host = uri.host().unwrap_or_default().to_string();
191            if host.starts_with("obs.")
192                && (host.ends_with(".myhuaweicloud.com") || host.ends_with(".huawei.com"))
193            {
194                (format!("{bucket}.{host}"), true)
195            } else {
196                (host, false)
197            }
198        };
199        debug!("backend use endpoint {}", &endpoint);
200
201        let mut cfg = HuaweicloudObsConfig::default();
202        // Load cfg from env first.
203        cfg = cfg.from_env();
204
205        if let Some(v) = self.config.access_key_id {
206            cfg.access_key_id = Some(v);
207        }
208
209        if let Some(v) = self.config.secret_access_key {
210            cfg.secret_access_key = Some(v);
211        }
212
213        let loader = HuaweicloudObsCredentialLoader::new(cfg);
214
215        // Set the bucket name in CanonicalizedResource.
216        // 1. If the bucket is bound to a user domain name, use the user domain name as the bucket name,
217        // for example, `/obs.ccc.com/object`. `obs.ccc.com` is the user domain name bound to the bucket.
218        // 2. If you do not access OBS using a user domain name, this field is in the format of `/bucket/object`.
219        //
220        // Please refer to this doc for more details:
221        // https://support.huaweicloud.com/intl/en-us/api-obs/obs_04_0010.html
222        let signer = HuaweicloudObsSigner::new({
223            if is_obs_default {
224                &bucket
225            } else {
226                &endpoint
227            }
228        });
229
230        debug!("backend build finished");
231        Ok(ObsBackend {
232            core: Arc::new(ObsCore {
233                info: {
234                    let am = AccessorInfo::default();
235                    am.set_scheme(Scheme::Obs)
236                        .set_root(&root)
237                        .set_name(&bucket)
238                        .set_native_capability(Capability {
239                            stat: true,
240                            stat_with_if_match: true,
241                            stat_with_if_none_match: true,
242                            stat_has_cache_control: true,
243                            stat_has_content_length: true,
244                            stat_has_content_type: true,
245                            stat_has_content_encoding: true,
246                            stat_has_content_range: true,
247                            stat_has_etag: true,
248                            stat_has_content_md5: true,
249                            stat_has_last_modified: true,
250                            stat_has_content_disposition: true,
251                            stat_has_user_metadata: true,
252
253                            read: true,
254
255                            read_with_if_match: true,
256                            read_with_if_none_match: true,
257
258                            write: true,
259                            write_can_empty: true,
260                            write_can_append: true,
261                            write_can_multi: true,
262                            write_with_content_type: true,
263                            write_with_cache_control: true,
264                            // The min multipart size of OBS is 5 MiB.
265                            //
266                            // ref: <https://support.huaweicloud.com/intl/en-us/ugobs-obs/obs_41_0021.html>
267                            write_multi_min_size: Some(5 * 1024 * 1024),
268                            // The max multipart size of OBS is 5 GiB.
269                            //
270                            // ref: <https://support.huaweicloud.com/intl/en-us/ugobs-obs/obs_41_0021.html>
271                            write_multi_max_size: if cfg!(target_pointer_width = "64") {
272                                Some(5 * 1024 * 1024 * 1024)
273                            } else {
274                                Some(usize::MAX)
275                            },
276                            write_with_user_metadata: true,
277
278                            delete: true,
279                            copy: true,
280
281                            list: true,
282                            list_with_recursive: true,
283                            list_has_content_length: true,
284
285                            presign: true,
286                            presign_stat: true,
287                            presign_read: true,
288                            presign_write: true,
289
290                            shared: true,
291
292                            ..Default::default()
293                        });
294
295                    // allow deprecated api here for compatibility
296                    #[allow(deprecated)]
297                    if let Some(client) = self.http_client {
298                        am.update_http_client(|_| client);
299                    }
300
301                    am.into()
302                },
303                bucket,
304                root,
305                endpoint: format!("{}://{}", &scheme, &endpoint),
306                signer,
307                loader,
308            }),
309        })
310    }
311}
312
313/// Backend for Huaweicloud OBS services.
314#[derive(Debug, Clone)]
315pub struct ObsBackend {
316    core: Arc<ObsCore>,
317}
318
319impl Access for ObsBackend {
320    type Reader = HttpBody;
321    type Writer = ObsWriters;
322    type Lister = oio::PageLister<ObsLister>;
323    type Deleter = oio::OneShotDeleter<ObsDeleter>;
324    type BlockingReader = ();
325    type BlockingWriter = ();
326    type BlockingLister = ();
327    type BlockingDeleter = ();
328
329    fn info(&self) -> Arc<AccessorInfo> {
330        self.core.info.clone()
331    }
332
333    async fn stat(&self, path: &str, args: OpStat) -> Result<RpStat> {
334        let resp = self.core.obs_head_object(path, &args).await?;
335        let headers = resp.headers();
336
337        let status = resp.status();
338
339        // The response is very similar to azblob.
340        match status {
341            StatusCode::OK => {
342                let mut meta = parse_into_metadata(path, headers)?;
343                let user_meta = headers
344                    .iter()
345                    .filter_map(|(name, _)| {
346                        name.as_str()
347                            .strip_prefix(constants::X_OBS_META_PREFIX)
348                            .and_then(|stripped_key| {
349                                parse_header_to_str(headers, name)
350                                    .unwrap_or(None)
351                                    .map(|val| (stripped_key.to_string(), val.to_string()))
352                            })
353                    })
354                    .collect::<HashMap<_, _>>();
355
356                if !user_meta.is_empty() {
357                    meta.with_user_metadata(user_meta);
358                }
359
360                if let Some(v) = parse_header_to_str(headers, constants::X_OBS_VERSION_ID)? {
361                    meta.set_version(v);
362                }
363
364                Ok(RpStat::new(meta))
365            }
366            StatusCode::NOT_FOUND if path.ends_with('/') => {
367                Ok(RpStat::new(Metadata::new(EntryMode::DIR)))
368            }
369            _ => Err(parse_error(resp)),
370        }
371    }
372
373    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
374        let resp = self.core.obs_get_object(path, args.range(), &args).await?;
375
376        let status = resp.status();
377
378        match status {
379            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
380                Ok((RpRead::default(), resp.into_body()))
381            }
382            _ => {
383                let (part, mut body) = resp.into_parts();
384                let buf = body.to_buffer().await?;
385                Err(parse_error(Response::from_parts(part, buf)))
386            }
387        }
388    }
389
390    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
391        let writer = ObsWriter::new(self.core.clone(), path, args.clone());
392
393        let w = if args.append() {
394            ObsWriters::Two(oio::AppendWriter::new(writer))
395        } else {
396            ObsWriters::One(oio::MultipartWriter::new(
397                self.core.info.clone(),
398                writer,
399                args.concurrent(),
400            ))
401        };
402
403        Ok((RpWrite::default(), w))
404    }
405
406    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
407        Ok((
408            RpDelete::default(),
409            oio::OneShotDeleter::new(ObsDeleter::new(self.core.clone())),
410        ))
411    }
412
413    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
414        let l = ObsLister::new(self.core.clone(), path, args.recursive(), args.limit());
415        Ok((RpList::default(), oio::PageLister::new(l)))
416    }
417
418    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
419        let resp = self.core.obs_copy_object(from, to).await?;
420
421        let status = resp.status();
422
423        match status {
424            StatusCode::OK => Ok(RpCopy::default()),
425            _ => Err(parse_error(resp)),
426        }
427    }
428
429    async fn presign(&self, path: &str, args: OpPresign) -> Result<RpPresign> {
430        let req = match args.operation() {
431            PresignOperation::Stat(v) => self.core.obs_head_object_request(path, v),
432            PresignOperation::Read(v) => {
433                self.core
434                    .obs_get_object_request(path, BytesRange::default(), v)
435            }
436            PresignOperation::Write(v) => {
437                self.core
438                    .obs_put_object_request(path, None, v, Buffer::new())
439            }
440            PresignOperation::Delete(_) => Err(Error::new(
441                ErrorKind::Unsupported,
442                "operation is not supported",
443            )),
444        };
445        let mut req = req?;
446        self.core.sign_query(&mut req, args.expire()).await?;
447
448        // We don't need this request anymore, consume it directly.
449        let (parts, _) = req.into_parts();
450
451        Ok(RpPresign::new(PresignedRequest::new(
452            parts.method,
453            parts.uri,
454            parts.headers,
455        )))
456    }
457}