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