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
178                            create_dir: true,
179
180                            read: true,
181
182                            write: true,
183                            write_can_empty: true,
184                            write_can_multi: true,
185                            write_with_cache_control: true,
186                            write_with_content_type: true,
187
188                            // https://help.upyun.com/knowledge-base/rest_api/#e5b9b6e8a18ce5bc8fe696ade782b9e7bbade4bca0
189                            write_multi_min_size: Some(1024 * 1024),
190                            write_multi_max_size: Some(50 * 1024 * 1024),
191
192                            delete: true,
193                            rename: true,
194                            copy: true,
195
196                            list: true,
197                            list_with_limit: true,
198
199                            shared: true,
200
201                            ..Default::default()
202                        });
203
204                    // allow deprecated api here for compatibility
205                    #[allow(deprecated)]
206                    if let Some(client) = self.http_client {
207                        am.update_http_client(|_| client);
208                    }
209
210                    am.into()
211                },
212                root,
213                operator,
214                bucket: self.config.bucket.clone(),
215                signer,
216            }),
217        })
218    }
219}
220
221/// Backend for upyun services.
222#[derive(Debug, Clone)]
223pub struct UpyunBackend {
224    core: Arc<UpyunCore>,
225}
226
227impl Access for UpyunBackend {
228    type Reader = HttpBody;
229    type Writer = UpyunWriters;
230    type Lister = oio::PageLister<UpyunLister>;
231    type Deleter = oio::OneShotDeleter<UpyunDeleter>;
232
233    fn info(&self) -> Arc<AccessorInfo> {
234        self.core.info.clone()
235    }
236
237    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
238        let resp = self.core.create_dir(path).await?;
239
240        let status = resp.status();
241
242        match status {
243            StatusCode::OK => Ok(RpCreateDir::default()),
244            _ => Err(parse_error(resp)),
245        }
246    }
247
248    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
249        let resp = self.core.info(path).await?;
250
251        let status = resp.status();
252
253        match status {
254            StatusCode::OK => parse_info(resp.headers()).map(RpStat::new),
255            _ => Err(parse_error(resp)),
256        }
257    }
258
259    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
260        let resp = self.core.download_file(path, args.range()).await?;
261
262        let status = resp.status();
263
264        match status {
265            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
266                Ok((RpRead::default(), resp.into_body()))
267            }
268            _ => {
269                let (part, mut body) = resp.into_parts();
270                let buf = body.to_buffer().await?;
271                Err(parse_error(Response::from_parts(part, buf)))
272            }
273        }
274    }
275
276    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
277        let concurrent = args.concurrent();
278        let writer = UpyunWriter::new(self.core.clone(), args, path.to_string());
279
280        let w = oio::MultipartWriter::new(self.core.info.clone(), writer, concurrent);
281
282        Ok((RpWrite::default(), w))
283    }
284
285    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
286        Ok((
287            RpDelete::default(),
288            oio::OneShotDeleter::new(UpyunDeleter::new(self.core.clone())),
289        ))
290    }
291
292    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
293        let l = UpyunLister::new(self.core.clone(), path, args.limit());
294        Ok((RpList::default(), oio::PageLister::new(l)))
295    }
296
297    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
298        let resp = self.core.copy(from, to).await?;
299
300        let status = resp.status();
301
302        match status {
303            StatusCode::OK => Ok(RpCopy::default()),
304            _ => Err(parse_error(resp)),
305        }
306    }
307
308    async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
309        let resp = self.core.move_object(from, to).await?;
310
311        let status = resp.status();
312
313        match status {
314            StatusCode::OK => Ok(RpRename::default()),
315            _ => Err(parse_error(resp)),
316        }
317    }
318}