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 super::DEFAULT_SCHEME;
33use crate::raw::*;
34use crate::services::UpyunConfig;
35use crate::*;
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    type Config = UpyunConfig;
132
133    /// Builds the backend and returns the result of UpyunBackend.
134    fn build(self) -> Result<impl Access> {
135        debug!("backend build started: {:?}", &self);
136
137        let root = normalize_root(&self.config.root.clone().unwrap_or_default());
138        debug!("backend use root {}", &root);
139
140        // Handle bucket.
141        if self.config.bucket.is_empty() {
142            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket is empty")
143                .with_operation("Builder::build")
144                .with_context("service", Scheme::Upyun));
145        }
146
147        debug!("backend use bucket {}", &self.config.bucket);
148
149        let operator = match &self.config.operator {
150            Some(operator) => Ok(operator.clone()),
151            None => Err(Error::new(ErrorKind::ConfigInvalid, "operator is empty")
152                .with_operation("Builder::build")
153                .with_context("service", Scheme::Upyun)),
154        }?;
155
156        let password = match &self.config.password {
157            Some(password) => Ok(password.clone()),
158            None => Err(Error::new(ErrorKind::ConfigInvalid, "password is empty")
159                .with_operation("Builder::build")
160                .with_context("service", Scheme::Upyun)),
161        }?;
162
163        let signer = UpyunSigner {
164            operator: operator.clone(),
165            password: password.clone(),
166        };
167
168        Ok(UpyunBackend {
169            core: Arc::new(UpyunCore {
170                info: {
171                    let am = AccessorInfo::default();
172                    am.set_scheme(DEFAULT_SCHEME)
173                        .set_root(&root)
174                        .set_native_capability(Capability {
175                            stat: true,
176
177                            create_dir: true,
178
179                            read: true,
180
181                            write: true,
182                            write_can_empty: true,
183                            write_can_multi: true,
184                            write_with_cache_control: true,
185                            write_with_content_type: true,
186
187                            // https://help.upyun.com/knowledge-base/rest_api/#e5b9b6e8a18ce5bc8fe696ade782b9e7bbade4bca0
188                            write_multi_min_size: Some(1024 * 1024),
189                            write_multi_max_size: Some(50 * 1024 * 1024),
190
191                            delete: true,
192                            rename: true,
193                            copy: true,
194
195                            list: true,
196                            list_with_limit: true,
197
198                            shared: true,
199
200                            ..Default::default()
201                        });
202
203                    // allow deprecated api here for compatibility
204                    #[allow(deprecated)]
205                    if let Some(client) = self.http_client {
206                        am.update_http_client(|_| client);
207                    }
208
209                    am.into()
210                },
211                root,
212                operator,
213                bucket: self.config.bucket.clone(),
214                signer,
215            }),
216        })
217    }
218}
219
220/// Backend for upyun services.
221#[derive(Debug, Clone)]
222pub struct UpyunBackend {
223    core: Arc<UpyunCore>,
224}
225
226impl Access for UpyunBackend {
227    type Reader = HttpBody;
228    type Writer = UpyunWriters;
229    type Lister = oio::PageLister<UpyunLister>;
230    type Deleter = oio::OneShotDeleter<UpyunDeleter>;
231
232    fn info(&self) -> Arc<AccessorInfo> {
233        self.core.info.clone()
234    }
235
236    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
237        let resp = self.core.create_dir(path).await?;
238
239        let status = resp.status();
240
241        match status {
242            StatusCode::OK => Ok(RpCreateDir::default()),
243            _ => Err(parse_error(resp)),
244        }
245    }
246
247    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
248        let resp = self.core.info(path).await?;
249
250        let status = resp.status();
251
252        match status {
253            StatusCode::OK => parse_info(resp.headers()).map(RpStat::new),
254            _ => Err(parse_error(resp)),
255        }
256    }
257
258    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
259        let resp = self.core.download_file(path, args.range()).await?;
260
261        let status = resp.status();
262
263        match status {
264            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
265                Ok((RpRead::default(), resp.into_body()))
266            }
267            _ => {
268                let (part, mut body) = resp.into_parts();
269                let buf = body.to_buffer().await?;
270                Err(parse_error(Response::from_parts(part, buf)))
271            }
272        }
273    }
274
275    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
276        let concurrent = args.concurrent();
277        let writer = UpyunWriter::new(self.core.clone(), args, path.to_string());
278
279        let w = oio::MultipartWriter::new(self.core.info.clone(), writer, concurrent);
280
281        Ok((RpWrite::default(), w))
282    }
283
284    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
285        Ok((
286            RpDelete::default(),
287            oio::OneShotDeleter::new(UpyunDeleter::new(self.core.clone())),
288        ))
289    }
290
291    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
292        let l = UpyunLister::new(self.core.clone(), path, args.limit());
293        Ok((RpList::default(), oio::PageLister::new(l)))
294    }
295
296    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
297        let resp = self.core.copy(from, to).await?;
298
299        let status = resp.status();
300
301        match status {
302            StatusCode::OK => Ok(RpCopy::default()),
303            _ => Err(parse_error(resp)),
304        }
305    }
306
307    async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
308        let resp = self.core.move_object(from, to).await?;
309
310        let status = resp.status();
311
312        match status {
313            StatusCode::OK => Ok(RpRename::default()),
314            _ => Err(parse_error(resp)),
315        }
316    }
317}