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 crate::raw::*;
39use crate::services::ObsConfig;
40use crate::*;
41
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    const SCHEME: Scheme = Scheme::Obs;
158    type Config = ObsConfig;
159
160    fn build(self) -> Result<impl Access> {
161        debug!("backend build started: {:?}", &self);
162
163        let root = normalize_root(&self.config.root.unwrap_or_default());
164        debug!("backend use root {root}");
165
166        let bucket = match &self.config.bucket {
167            Some(bucket) => Ok(bucket.to_string()),
168            None => Err(
169                Error::new(ErrorKind::ConfigInvalid, "The bucket is misconfigured")
170                    .with_context("service", Scheme::Obs),
171            ),
172        }?;
173        debug!("backend use bucket {}", &bucket);
174
175        let uri = match &self.config.endpoint {
176            Some(endpoint) => endpoint.parse::<Uri>().map_err(|err| {
177                Error::new(ErrorKind::ConfigInvalid, "endpoint is invalid")
178                    .with_context("service", Scheme::Obs)
179                    .set_source(err)
180            }),
181            None => Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
182                .with_context("service", Scheme::Obs)),
183        }?;
184
185        let scheme = match uri.scheme_str() {
186            Some(scheme) => scheme.to_string(),
187            None => "https".to_string(),
188        };
189
190        let (endpoint, is_obs_default) = {
191            let host = uri.host().unwrap_or_default().to_string();
192            if host.starts_with("obs.")
193                && (host.ends_with(".myhuaweicloud.com") || host.ends_with(".huawei.com"))
194            {
195                (format!("{bucket}.{host}"), true)
196            } else {
197                (host, false)
198            }
199        };
200        debug!("backend use endpoint {}", &endpoint);
201
202        let mut cfg = HuaweicloudObsConfig::default();
203        // Load cfg from env first.
204        cfg = cfg.from_env();
205
206        if let Some(v) = self.config.access_key_id {
207            cfg.access_key_id = Some(v);
208        }
209
210        if let Some(v) = self.config.secret_access_key {
211            cfg.secret_access_key = Some(v);
212        }
213
214        let loader = HuaweicloudObsCredentialLoader::new(cfg);
215
216        // Set the bucket name in CanonicalizedResource.
217        // 1. If the bucket is bound to a user domain name, use the user domain name as the bucket name,
218        // for example, `/obs.ccc.com/object`. `obs.ccc.com` is the user domain name bound to the bucket.
219        // 2. If you do not access OBS using a user domain name, this field is in the format of `/bucket/object`.
220        //
221        // Please refer to this doc for more details:
222        // https://support.huaweicloud.com/intl/en-us/api-obs/obs_04_0010.html
223        let signer = HuaweicloudObsSigner::new({
224            if is_obs_default {
225                &bucket
226            } else {
227                &endpoint
228            }
229        });
230
231        debug!("backend build finished");
232        Ok(ObsBackend {
233            core: Arc::new(ObsCore {
234                info: {
235                    let am = AccessorInfo::default();
236                    am.set_scheme(Scheme::Obs)
237                        .set_root(&root)
238                        .set_name(&bucket)
239                        .set_native_capability(Capability {
240                            stat: true,
241                            stat_with_if_match: true,
242                            stat_with_if_none_match: true,
243
244                            read: true,
245
246                            read_with_if_match: true,
247                            read_with_if_none_match: true,
248
249                            write: true,
250                            write_can_empty: true,
251                            write_can_append: true,
252                            write_can_multi: true,
253                            write_with_content_type: true,
254                            write_with_cache_control: true,
255                            // The min multipart size of OBS is 5 MiB.
256                            //
257                            // ref: <https://support.huaweicloud.com/intl/en-us/ugobs-obs/obs_41_0021.html>
258                            write_multi_min_size: Some(5 * 1024 * 1024),
259                            // The max multipart size of OBS is 5 GiB.
260                            //
261                            // ref: <https://support.huaweicloud.com/intl/en-us/ugobs-obs/obs_41_0021.html>
262                            write_multi_max_size: if cfg!(target_pointer_width = "64") {
263                                Some(5 * 1024 * 1024 * 1024)
264                            } else {
265                                Some(usize::MAX)
266                            },
267                            write_with_user_metadata: true,
268
269                            delete: true,
270                            copy: true,
271
272                            list: true,
273                            list_with_recursive: true,
274
275                            presign: true,
276                            presign_stat: true,
277                            presign_read: true,
278                            presign_write: true,
279
280                            shared: true,
281
282                            ..Default::default()
283                        });
284
285                    // allow deprecated api here for compatibility
286                    #[allow(deprecated)]
287                    if let Some(client) = self.http_client {
288                        am.update_http_client(|_| client);
289                    }
290
291                    am.into()
292                },
293                bucket,
294                root,
295                endpoint: format!("{}://{}", &scheme, &endpoint),
296                signer,
297                loader,
298            }),
299        })
300    }
301}
302
303/// Backend for Huaweicloud OBS services.
304#[derive(Debug, Clone)]
305pub struct ObsBackend {
306    core: Arc<ObsCore>,
307}
308
309impl Access for ObsBackend {
310    type Reader = HttpBody;
311    type Writer = ObsWriters;
312    type Lister = oio::PageLister<ObsLister>;
313    type Deleter = oio::OneShotDeleter<ObsDeleter>;
314
315    fn info(&self) -> Arc<AccessorInfo> {
316        self.core.info.clone()
317    }
318
319    async fn stat(&self, path: &str, args: OpStat) -> Result<RpStat> {
320        let resp = self.core.obs_head_object(path, &args).await?;
321        let headers = resp.headers();
322
323        let status = resp.status();
324
325        // The response is very similar to azblob.
326        match status {
327            StatusCode::OK => {
328                let mut meta = parse_into_metadata(path, headers)?;
329                let user_meta = headers
330                    .iter()
331                    .filter_map(|(name, _)| {
332                        name.as_str()
333                            .strip_prefix(constants::X_OBS_META_PREFIX)
334                            .and_then(|stripped_key| {
335                                parse_header_to_str(headers, name)
336                                    .unwrap_or(None)
337                                    .map(|val| (stripped_key.to_string(), val.to_string()))
338                            })
339                    })
340                    .collect::<HashMap<_, _>>();
341
342                if !user_meta.is_empty() {
343                    meta = meta.with_user_metadata(user_meta);
344                }
345
346                if let Some(v) = parse_header_to_str(headers, constants::X_OBS_VERSION_ID)? {
347                    meta.set_version(v);
348                }
349
350                Ok(RpStat::new(meta))
351            }
352            StatusCode::NOT_FOUND if path.ends_with('/') => {
353                Ok(RpStat::new(Metadata::new(EntryMode::DIR)))
354            }
355            _ => Err(parse_error(resp)),
356        }
357    }
358
359    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
360        let resp = self.core.obs_get_object(path, args.range(), &args).await?;
361
362        let status = resp.status();
363
364        match status {
365            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
366                Ok((RpRead::default(), resp.into_body()))
367            }
368            _ => {
369                let (part, mut body) = resp.into_parts();
370                let buf = body.to_buffer().await?;
371                Err(parse_error(Response::from_parts(part, buf)))
372            }
373        }
374    }
375
376    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
377        let writer = ObsWriter::new(self.core.clone(), path, args.clone());
378
379        let w = if args.append() {
380            ObsWriters::Two(oio::AppendWriter::new(writer))
381        } else {
382            ObsWriters::One(oio::MultipartWriter::new(
383                self.core.info.clone(),
384                writer,
385                args.concurrent(),
386            ))
387        };
388
389        Ok((RpWrite::default(), w))
390    }
391
392    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
393        Ok((
394            RpDelete::default(),
395            oio::OneShotDeleter::new(ObsDeleter::new(self.core.clone())),
396        ))
397    }
398
399    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
400        let l = ObsLister::new(self.core.clone(), path, args.recursive(), args.limit());
401        Ok((RpList::default(), oio::PageLister::new(l)))
402    }
403
404    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
405        let resp = self.core.obs_copy_object(from, to).await?;
406
407        let status = resp.status();
408
409        match status {
410            StatusCode::OK => Ok(RpCopy::default()),
411            _ => Err(parse_error(resp)),
412        }
413    }
414
415    async fn presign(&self, path: &str, args: OpPresign) -> Result<RpPresign> {
416        let req = match args.operation() {
417            PresignOperation::Stat(v) => self.core.obs_head_object_request(path, v),
418            PresignOperation::Read(v) => {
419                self.core
420                    .obs_get_object_request(path, BytesRange::default(), v)
421            }
422            PresignOperation::Write(v) => {
423                self.core
424                    .obs_put_object_request(path, None, v, Buffer::new())
425            }
426            PresignOperation::Delete(_) => Err(Error::new(
427                ErrorKind::Unsupported,
428                "operation is not supported",
429            )),
430        };
431        let mut req = req?;
432        self.core.sign_query(&mut req, args.expire()).await?;
433
434        // We don't need this request anymore, consume it directly.
435        let (parts, _) = req.into_parts();
436
437        Ok(RpPresign::new(PresignedRequest::new(
438            parts.method,
439            parts.uri,
440            parts.headers,
441        )))
442    }
443}