opendal/services/upyun/
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::fmt::Debug;
19use std::fmt::Formatter;
20use std::sync::Arc;
21
22use http::Response;
23use http::StatusCode;
24use log::debug;
25
26use super::core::*;
27use super::delete::UpyunDeleter;
28use super::error::parse_error;
29use super::lister::UpyunLister;
30use super::writer::UpyunWriter;
31use super::writer::UpyunWriters;
32use crate::raw::*;
33use crate::services::UpyunConfig;
34use crate::*;
35
36impl Configurator for UpyunConfig {
37    type Builder = UpyunBuilder;
38
39    #[allow(deprecated)]
40    fn into_builder(self) -> Self::Builder {
41        UpyunBuilder {
42            config: self,
43            http_client: None,
44        }
45    }
46}
47
48/// [upyun](https://www.upyun.com/products/file-storage) services support.
49#[doc = include_str!("docs.md")]
50#[derive(Default)]
51pub struct UpyunBuilder {
52    config: UpyunConfig,
53
54    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
55    http_client: Option<HttpClient>,
56}
57
58impl Debug for UpyunBuilder {
59    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
60        let mut d = f.debug_struct("UpyunBuilder");
61
62        d.field("config", &self.config);
63        d.finish_non_exhaustive()
64    }
65}
66
67impl UpyunBuilder {
68    /// Set root of this backend.
69    ///
70    /// All operations will happen under this root.
71    pub fn root(mut self, root: &str) -> Self {
72        self.config.root = if root.is_empty() {
73            None
74        } else {
75            Some(root.to_string())
76        };
77
78        self
79    }
80
81    /// bucket of this backend.
82    ///
83    /// It is required. e.g. `test`
84    pub fn bucket(mut self, bucket: &str) -> Self {
85        self.config.bucket = bucket.to_string();
86
87        self
88    }
89
90    /// operator of this backend.
91    ///
92    /// It is required. e.g. `test`
93    pub fn operator(mut self, operator: &str) -> Self {
94        self.config.operator = if operator.is_empty() {
95            None
96        } else {
97            Some(operator.to_string())
98        };
99
100        self
101    }
102
103    /// password of this backend.
104    ///
105    /// It is required. e.g. `asecret`
106    pub fn password(mut self, password: &str) -> Self {
107        self.config.password = if password.is_empty() {
108            None
109        } else {
110            Some(password.to_string())
111        };
112
113        self
114    }
115
116    /// Specify the http client that used by this service.
117    ///
118    /// # Notes
119    ///
120    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
121    /// during minor updates.
122    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
123    #[allow(deprecated)]
124    pub fn http_client(mut self, client: HttpClient) -> Self {
125        self.http_client = Some(client);
126        self
127    }
128}
129
130impl Builder for UpyunBuilder {
131    const SCHEME: Scheme = Scheme::Upyun;
132    type Config = UpyunConfig;
133
134    /// Builds the backend and returns the result of UpyunBackend.
135    fn build(self) -> Result<impl Access> {
136        debug!("backend build started: {:?}", &self);
137
138        let root = normalize_root(&self.config.root.clone().unwrap_or_default());
139        debug!("backend use root {}", &root);
140
141        // Handle bucket.
142        if self.config.bucket.is_empty() {
143            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket is empty")
144                .with_operation("Builder::build")
145                .with_context("service", Scheme::Upyun));
146        }
147
148        debug!("backend use bucket {}", &self.config.bucket);
149
150        let operator = match &self.config.operator {
151            Some(operator) => Ok(operator.clone()),
152            None => Err(Error::new(ErrorKind::ConfigInvalid, "operator is empty")
153                .with_operation("Builder::build")
154                .with_context("service", Scheme::Upyun)),
155        }?;
156
157        let password = match &self.config.password {
158            Some(password) => Ok(password.clone()),
159            None => Err(Error::new(ErrorKind::ConfigInvalid, "password is empty")
160                .with_operation("Builder::build")
161                .with_context("service", Scheme::Upyun)),
162        }?;
163
164        let signer = UpyunSigner {
165            operator: operator.clone(),
166            password: password.clone(),
167        };
168
169        Ok(UpyunBackend {
170            core: Arc::new(UpyunCore {
171                info: {
172                    let am = AccessorInfo::default();
173                    am.set_scheme(Scheme::Upyun)
174                        .set_root(&root)
175                        .set_native_capability(Capability {
176                            stat: true,
177                            stat_has_content_length: true,
178                            stat_has_content_type: true,
179                            stat_has_content_md5: true,
180                            stat_has_cache_control: true,
181                            stat_has_content_disposition: true,
182
183                            create_dir: true,
184
185                            read: true,
186
187                            write: true,
188                            write_can_empty: true,
189                            write_can_multi: true,
190                            write_with_cache_control: true,
191                            write_with_content_type: true,
192
193                            // https://help.upyun.com/knowledge-base/rest_api/#e5b9b6e8a18ce5bc8fe696ade782b9e7bbade4bca0
194                            write_multi_min_size: Some(1024 * 1024),
195                            write_multi_max_size: Some(50 * 1024 * 1024),
196
197                            delete: true,
198                            rename: true,
199                            copy: true,
200
201                            list: true,
202                            list_with_limit: true,
203                            list_has_content_length: true,
204                            list_has_content_type: true,
205                            list_has_last_modified: true,
206
207                            shared: true,
208
209                            ..Default::default()
210                        });
211
212                    // allow deprecated api here for compatibility
213                    #[allow(deprecated)]
214                    if let Some(client) = self.http_client {
215                        am.update_http_client(|_| client);
216                    }
217
218                    am.into()
219                },
220                root,
221                operator,
222                bucket: self.config.bucket.clone(),
223                signer,
224            }),
225        })
226    }
227}
228
229/// Backend for upyun services.
230#[derive(Debug, Clone)]
231pub struct UpyunBackend {
232    core: Arc<UpyunCore>,
233}
234
235impl Access for UpyunBackend {
236    type Reader = HttpBody;
237    type Writer = UpyunWriters;
238    type Lister = oio::PageLister<UpyunLister>;
239    type Deleter = oio::OneShotDeleter<UpyunDeleter>;
240    type BlockingReader = ();
241    type BlockingWriter = ();
242    type BlockingLister = ();
243    type BlockingDeleter = ();
244
245    fn info(&self) -> Arc<AccessorInfo> {
246        self.core.info.clone()
247    }
248
249    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
250        let resp = self.core.create_dir(path).await?;
251
252        let status = resp.status();
253
254        match status {
255            StatusCode::OK => Ok(RpCreateDir::default()),
256            _ => Err(parse_error(resp)),
257        }
258    }
259
260    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
261        let resp = self.core.info(path).await?;
262
263        let status = resp.status();
264
265        match status {
266            StatusCode::OK => parse_info(resp.headers()).map(RpStat::new),
267            _ => Err(parse_error(resp)),
268        }
269    }
270
271    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
272        let resp = self.core.download_file(path, args.range()).await?;
273
274        let status = resp.status();
275
276        match status {
277            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
278                Ok((RpRead::default(), resp.into_body()))
279            }
280            _ => {
281                let (part, mut body) = resp.into_parts();
282                let buf = body.to_buffer().await?;
283                Err(parse_error(Response::from_parts(part, buf)))
284            }
285        }
286    }
287
288    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
289        let concurrent = args.concurrent();
290        let writer = UpyunWriter::new(self.core.clone(), args, path.to_string());
291
292        let w = oio::MultipartWriter::new(self.core.info.clone(), writer, concurrent);
293
294        Ok((RpWrite::default(), w))
295    }
296
297    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
298        Ok((
299            RpDelete::default(),
300            oio::OneShotDeleter::new(UpyunDeleter::new(self.core.clone())),
301        ))
302    }
303
304    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
305        let l = UpyunLister::new(self.core.clone(), path, args.limit());
306        Ok((RpList::default(), oio::PageLister::new(l)))
307    }
308
309    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
310        let resp = self.core.copy(from, to).await?;
311
312        let status = resp.status();
313
314        match status {
315            StatusCode::OK => Ok(RpCopy::default()),
316            _ => Err(parse_error(resp)),
317        }
318    }
319
320    async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
321        let resp = self.core.move_object(from, to).await?;
322
323        let status = resp.status();
324
325        match status {
326            StatusCode::OK => Ok(RpRename::default()),
327            _ => Err(parse_error(resp)),
328        }
329    }
330}