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                            stat_has_cache_control: true,
244                            stat_has_content_length: true,
245                            stat_has_content_type: true,
246                            stat_has_content_encoding: true,
247                            stat_has_content_range: true,
248                            stat_has_etag: true,
249                            stat_has_content_md5: true,
250                            stat_has_last_modified: true,
251                            stat_has_content_disposition: true,
252                            stat_has_user_metadata: true,
253
254                            read: true,
255
256                            read_with_if_match: true,
257                            read_with_if_none_match: true,
258
259                            write: true,
260                            write_can_empty: true,
261                            write_can_append: true,
262                            write_can_multi: true,
263                            write_with_content_type: true,
264                            write_with_cache_control: true,
265                            // The min multipart size of OBS is 5 MiB.
266                            //
267                            // ref: <https://support.huaweicloud.com/intl/en-us/ugobs-obs/obs_41_0021.html>
268                            write_multi_min_size: Some(5 * 1024 * 1024),
269                            // The max multipart size of OBS is 5 GiB.
270                            //
271                            // ref: <https://support.huaweicloud.com/intl/en-us/ugobs-obs/obs_41_0021.html>
272                            write_multi_max_size: if cfg!(target_pointer_width = "64") {
273                                Some(5 * 1024 * 1024 * 1024)
274                            } else {
275                                Some(usize::MAX)
276                            },
277                            write_with_user_metadata: true,
278
279                            delete: true,
280                            copy: true,
281
282                            list: true,
283                            list_with_recursive: true,
284                            list_has_content_length: true,
285
286                            presign: true,
287                            presign_stat: true,
288                            presign_read: true,
289                            presign_write: true,
290
291                            shared: true,
292
293                            ..Default::default()
294                        });
295
296                    // allow deprecated api here for compatibility
297                    #[allow(deprecated)]
298                    if let Some(client) = self.http_client {
299                        am.update_http_client(|_| client);
300                    }
301
302                    am.into()
303                },
304                bucket,
305                root,
306                endpoint: format!("{}://{}", &scheme, &endpoint),
307                signer,
308                loader,
309            }),
310        })
311    }
312}
313
314/// Backend for Huaweicloud OBS services.
315#[derive(Debug, Clone)]
316pub struct ObsBackend {
317    core: Arc<ObsCore>,
318}
319
320impl Access for ObsBackend {
321    type Reader = HttpBody;
322    type Writer = ObsWriters;
323    type Lister = oio::PageLister<ObsLister>;
324    type Deleter = oio::OneShotDeleter<ObsDeleter>;
325
326    fn info(&self) -> Arc<AccessorInfo> {
327        self.core.info.clone()
328    }
329
330    async fn stat(&self, path: &str, args: OpStat) -> Result<RpStat> {
331        let resp = self.core.obs_head_object(path, &args).await?;
332        let headers = resp.headers();
333
334        let status = resp.status();
335
336        // The response is very similar to azblob.
337        match status {
338            StatusCode::OK => {
339                let mut meta = parse_into_metadata(path, headers)?;
340                let user_meta = headers
341                    .iter()
342                    .filter_map(|(name, _)| {
343                        name.as_str()
344                            .strip_prefix(constants::X_OBS_META_PREFIX)
345                            .and_then(|stripped_key| {
346                                parse_header_to_str(headers, name)
347                                    .unwrap_or(None)
348                                    .map(|val| (stripped_key.to_string(), val.to_string()))
349                            })
350                    })
351                    .collect::<HashMap<_, _>>();
352
353                if !user_meta.is_empty() {
354                    meta = meta.with_user_metadata(user_meta);
355                }
356
357                if let Some(v) = parse_header_to_str(headers, constants::X_OBS_VERSION_ID)? {
358                    meta.set_version(v);
359                }
360
361                Ok(RpStat::new(meta))
362            }
363            StatusCode::NOT_FOUND if path.ends_with('/') => {
364                Ok(RpStat::new(Metadata::new(EntryMode::DIR)))
365            }
366            _ => Err(parse_error(resp)),
367        }
368    }
369
370    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
371        let resp = self.core.obs_get_object(path, args.range(), &args).await?;
372
373        let status = resp.status();
374
375        match status {
376            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
377                Ok((RpRead::default(), resp.into_body()))
378            }
379            _ => {
380                let (part, mut body) = resp.into_parts();
381                let buf = body.to_buffer().await?;
382                Err(parse_error(Response::from_parts(part, buf)))
383            }
384        }
385    }
386
387    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
388        let writer = ObsWriter::new(self.core.clone(), path, args.clone());
389
390        let w = if args.append() {
391            ObsWriters::Two(oio::AppendWriter::new(writer))
392        } else {
393            ObsWriters::One(oio::MultipartWriter::new(
394                self.core.info.clone(),
395                writer,
396                args.concurrent(),
397            ))
398        };
399
400        Ok((RpWrite::default(), w))
401    }
402
403    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
404        Ok((
405            RpDelete::default(),
406            oio::OneShotDeleter::new(ObsDeleter::new(self.core.clone())),
407        ))
408    }
409
410    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
411        let l = ObsLister::new(self.core.clone(), path, args.recursive(), args.limit());
412        Ok((RpList::default(), oio::PageLister::new(l)))
413    }
414
415    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
416        let resp = self.core.obs_copy_object(from, to).await?;
417
418        let status = resp.status();
419
420        match status {
421            StatusCode::OK => Ok(RpCopy::default()),
422            _ => Err(parse_error(resp)),
423        }
424    }
425
426    async fn presign(&self, path: &str, args: OpPresign) -> Result<RpPresign> {
427        let req = match args.operation() {
428            PresignOperation::Stat(v) => self.core.obs_head_object_request(path, v),
429            PresignOperation::Read(v) => {
430                self.core
431                    .obs_get_object_request(path, BytesRange::default(), v)
432            }
433            PresignOperation::Write(v) => {
434                self.core
435                    .obs_put_object_request(path, None, v, Buffer::new())
436            }
437            PresignOperation::Delete(_) => Err(Error::new(
438                ErrorKind::Unsupported,
439                "operation is not supported",
440            )),
441        };
442        let mut req = req?;
443        self.core.sign_query(&mut req, args.expire()).await?;
444
445        // We don't need this request anymore, consume it directly.
446        let (parts, _) = req.into_parts();
447
448        Ok(RpPresign::new(PresignedRequest::new(
449            parts.method,
450            parts.uri,
451            parts.headers,
452        )))
453    }
454}