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;
32use super::core::ObsCore;
33use super::delete::ObsDeleter;
34use super::error::parse_error;
35use super::lister::ObsLister;
36use super::writer::ObsWriter;
37use super::writer::ObsWriters;
38use super::DEFAULT_SCHEME;
39use crate::raw::*;
40use crate::services::ObsConfig;
41use crate::*;
42impl Configurator for ObsConfig {
43    type Builder = ObsBuilder;
44
45    #[allow(deprecated)]
46    fn into_builder(self) -> Self::Builder {
47        ObsBuilder {
48            config: self,
49
50            http_client: None,
51        }
52    }
53}
54
55/// Huawei-Cloud Object Storage Service (OBS) support
56#[doc = include_str!("docs.md")]
57#[derive(Default, Clone)]
58pub struct ObsBuilder {
59    config: ObsConfig,
60
61    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
62    http_client: Option<HttpClient>,
63}
64
65impl Debug for ObsBuilder {
66    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
67        let mut d = f.debug_struct("ObsBuilder");
68        d.field("config", &self.config);
69        d.finish_non_exhaustive()
70    }
71}
72
73impl ObsBuilder {
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    /// Both huaweicloud default domain and user domain endpoints are allowed.
90    /// Please DO NOT add the bucket name to the endpoint.
91    ///
92    /// - `https://obs.cn-north-4.myhuaweicloud.com`
93    /// - `obs.cn-north-4.myhuaweicloud.com` (https by default)
94    /// - `https://custom.obs.com` (port should not be set)
95    pub fn endpoint(mut self, endpoint: &str) -> Self {
96        if !endpoint.is_empty() {
97            self.config.endpoint = Some(endpoint.trim_end_matches('/').to_string());
98        }
99
100        self
101    }
102
103    /// Set access_key_id of this backend.
104    /// - If it is set, we will take user's input first.
105    /// - If not, we will try to load it from environment.
106    pub fn access_key_id(mut self, access_key_id: &str) -> Self {
107        if !access_key_id.is_empty() {
108            self.config.access_key_id = Some(access_key_id.to_string());
109        }
110
111        self
112    }
113
114    /// Set secret_access_key of this backend.
115    /// - If it is set, we will take user's input first.
116    /// - If not, we will try to load it from environment.
117    pub fn secret_access_key(mut self, secret_access_key: &str) -> Self {
118        if !secret_access_key.is_empty() {
119            self.config.secret_access_key = Some(secret_access_key.to_string());
120        }
121
122        self
123    }
124
125    /// Set bucket of this backend.
126    /// The param is required.
127    pub fn bucket(mut self, bucket: &str) -> Self {
128        if !bucket.is_empty() {
129            self.config.bucket = Some(bucket.to_string());
130        }
131
132        self
133    }
134
135    /// Set bucket versioning status for this backend
136    pub fn enable_versioning(mut self, enabled: bool) -> Self {
137        self.config.enable_versioning = enabled;
138
139        self
140    }
141
142    /// Specify the http client that used by this service.
143    ///
144    /// # Notes
145    ///
146    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
147    /// during minor updates.
148    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
149    #[allow(deprecated)]
150    pub fn http_client(mut self, client: HttpClient) -> Self {
151        self.http_client = Some(client);
152        self
153    }
154}
155
156impl Builder for ObsBuilder {
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(DEFAULT_SCHEME)
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
243                            read: true,
244
245                            read_with_if_match: true,
246                            read_with_if_none_match: true,
247
248                            write: true,
249                            write_can_empty: true,
250                            write_can_append: true,
251                            write_can_multi: true,
252                            write_with_content_type: true,
253                            write_with_cache_control: true,
254                            // The min multipart size of OBS is 5 MiB.
255                            //
256                            // ref: <https://support.huaweicloud.com/intl/en-us/ugobs-obs/obs_41_0021.html>
257                            write_multi_min_size: Some(5 * 1024 * 1024),
258                            // The max multipart size of OBS is 5 GiB.
259                            //
260                            // ref: <https://support.huaweicloud.com/intl/en-us/ugobs-obs/obs_41_0021.html>
261                            write_multi_max_size: if cfg!(target_pointer_width = "64") {
262                                Some(5 * 1024 * 1024 * 1024)
263                            } else {
264                                Some(usize::MAX)
265                            },
266                            write_with_user_metadata: true,
267
268                            delete: true,
269                            copy: true,
270
271                            list: true,
272                            list_with_recursive: true,
273
274                            presign: true,
275                            presign_stat: true,
276                            presign_read: true,
277                            presign_write: true,
278
279                            shared: true,
280
281                            ..Default::default()
282                        });
283
284                    // allow deprecated api here for compatibility
285                    #[allow(deprecated)]
286                    if let Some(client) = self.http_client {
287                        am.update_http_client(|_| client);
288                    }
289
290                    am.into()
291                },
292                bucket,
293                root,
294                endpoint: format!("{}://{}", &scheme, &endpoint),
295                signer,
296                loader,
297            }),
298        })
299    }
300}
301
302/// Backend for Huaweicloud OBS services.
303#[derive(Debug, Clone)]
304pub struct ObsBackend {
305    core: Arc<ObsCore>,
306}
307
308impl Access for ObsBackend {
309    type Reader = HttpBody;
310    type Writer = ObsWriters;
311    type Lister = oio::PageLister<ObsLister>;
312    type Deleter = oio::OneShotDeleter<ObsDeleter>;
313
314    fn info(&self) -> Arc<AccessorInfo> {
315        self.core.info.clone()
316    }
317
318    async fn stat(&self, path: &str, args: OpStat) -> Result<RpStat> {
319        let resp = self.core.obs_head_object(path, &args).await?;
320        let headers = resp.headers();
321
322        let status = resp.status();
323
324        // The response is very similar to azblob.
325        match status {
326            StatusCode::OK => {
327                let mut meta = parse_into_metadata(path, headers)?;
328                let user_meta = headers
329                    .iter()
330                    .filter_map(|(name, _)| {
331                        name.as_str()
332                            .strip_prefix(constants::X_OBS_META_PREFIX)
333                            .and_then(|stripped_key| {
334                                parse_header_to_str(headers, name)
335                                    .unwrap_or(None)
336                                    .map(|val| (stripped_key.to_string(), val.to_string()))
337                            })
338                    })
339                    .collect::<HashMap<_, _>>();
340
341                if !user_meta.is_empty() {
342                    meta = meta.with_user_metadata(user_meta);
343                }
344
345                if let Some(v) = parse_header_to_str(headers, constants::X_OBS_VERSION_ID)? {
346                    meta.set_version(v);
347                }
348
349                Ok(RpStat::new(meta))
350            }
351            StatusCode::NOT_FOUND if path.ends_with('/') => {
352                Ok(RpStat::new(Metadata::new(EntryMode::DIR)))
353            }
354            _ => Err(parse_error(resp)),
355        }
356    }
357
358    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
359        let resp = self.core.obs_get_object(path, args.range(), &args).await?;
360
361        let status = resp.status();
362
363        match status {
364            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
365                Ok((RpRead::default(), resp.into_body()))
366            }
367            _ => {
368                let (part, mut body) = resp.into_parts();
369                let buf = body.to_buffer().await?;
370                Err(parse_error(Response::from_parts(part, buf)))
371            }
372        }
373    }
374
375    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
376        let writer = ObsWriter::new(self.core.clone(), path, args.clone());
377
378        let w = if args.append() {
379            ObsWriters::Two(oio::AppendWriter::new(writer))
380        } else {
381            ObsWriters::One(oio::MultipartWriter::new(
382                self.core.info.clone(),
383                writer,
384                args.concurrent(),
385            ))
386        };
387
388        Ok((RpWrite::default(), w))
389    }
390
391    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
392        Ok((
393            RpDelete::default(),
394            oio::OneShotDeleter::new(ObsDeleter::new(self.core.clone())),
395        ))
396    }
397
398    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
399        let l = ObsLister::new(self.core.clone(), path, args.recursive(), args.limit());
400        Ok((RpList::default(), oio::PageLister::new(l)))
401    }
402
403    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
404        let resp = self.core.obs_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.obs_head_object_request(path, v),
417            PresignOperation::Read(v) => {
418                self.core
419                    .obs_get_object_request(path, BytesRange::default(), v)
420            }
421            PresignOperation::Write(v) => {
422                self.core
423                    .obs_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}