opendal/services/aliyun_drive/
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 bytes::Buf;
23use chrono::Utc;
24use http::Response;
25use http::StatusCode;
26use log::debug;
27use tokio::sync::Mutex;
28
29use super::core::*;
30use super::delete::AliyunDriveDeleter;
31use super::error::parse_error;
32use super::lister::AliyunDriveLister;
33use super::lister::AliyunDriveParent;
34use super::writer::AliyunDriveWriter;
35use super::DEFAULT_SCHEME;
36use crate::raw::*;
37use crate::services::AliyunDriveConfig;
38use crate::*;
39impl Configurator for AliyunDriveConfig {
40    type Builder = AliyunDriveBuilder;
41
42    #[allow(deprecated)]
43    fn into_builder(self) -> Self::Builder {
44        AliyunDriveBuilder {
45            config: self,
46            http_client: None,
47        }
48    }
49}
50
51#[doc = include_str!("docs.md")]
52#[derive(Default)]
53pub struct AliyunDriveBuilder {
54    config: AliyunDriveConfig,
55
56    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
57    http_client: Option<HttpClient>,
58}
59
60impl Debug for AliyunDriveBuilder {
61    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
62        let mut d = f.debug_struct("AliyunDriveBuilder");
63
64        d.field("config", &self.config);
65        d.finish_non_exhaustive()
66    }
67}
68
69impl AliyunDriveBuilder {
70    /// Set the root of this backend.
71    ///
72    /// All operations will happen under this root.
73    pub fn root(mut self, root: &str) -> Self {
74        self.config.root = if root.is_empty() {
75            None
76        } else {
77            Some(root.to_string())
78        };
79
80        self
81    }
82
83    /// Set access_token of this backend.
84    pub fn access_token(mut self, access_token: &str) -> Self {
85        self.config.access_token = Some(access_token.to_string());
86
87        self
88    }
89
90    /// Set client_id of this backend.
91    pub fn client_id(mut self, client_id: &str) -> Self {
92        self.config.client_id = Some(client_id.to_string());
93
94        self
95    }
96
97    /// Set client_secret of this backend.
98    pub fn client_secret(mut self, client_secret: &str) -> Self {
99        self.config.client_secret = Some(client_secret.to_string());
100
101        self
102    }
103
104    /// Set refresh_token of this backend.
105    pub fn refresh_token(mut self, refresh_token: &str) -> Self {
106        self.config.refresh_token = Some(refresh_token.to_string());
107
108        self
109    }
110
111    /// Set drive_type of this backend.
112    pub fn drive_type(mut self, drive_type: &str) -> Self {
113        self.config.drive_type = drive_type.to_string();
114
115        self
116    }
117
118    /// Specify the http client that used by this service.
119    ///
120    /// # Notes
121    ///
122    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
123    /// during minor updates.
124    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
125    #[allow(deprecated)]
126    pub fn http_client(mut self, client: HttpClient) -> Self {
127        self.http_client = Some(client);
128        self
129    }
130}
131
132impl Builder for AliyunDriveBuilder {
133    type Config = AliyunDriveConfig;
134
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        let sign = match self.config.access_token.clone() {
142            Some(access_token) if !access_token.is_empty() => {
143                AliyunDriveSign::Access(access_token)
144            }
145            _ => match (
146                self.config.client_id.clone(),
147                self.config.client_secret.clone(),
148                self.config.refresh_token.clone(),
149            ) {
150                (Some(client_id), Some(client_secret), Some(refresh_token)) if
151                !client_id.is_empty() && !client_secret.is_empty() && !refresh_token.is_empty() => {
152                    AliyunDriveSign::Refresh(client_id, client_secret, refresh_token, None, 0)
153                }
154                _ => return Err(Error::new(
155                    ErrorKind::ConfigInvalid,
156                    "access_token and a set of client_id, client_secret, and refresh_token are both missing.")
157                    .with_operation("Builder::build")
158                    .with_context("service", Scheme::AliyunDrive)),
159            },
160        };
161
162        let drive_type = match self.config.drive_type.as_str() {
163            "" | "default" => DriveType::Default,
164            "resource" => DriveType::Resource,
165            "backup" => DriveType::Backup,
166            _ => {
167                return Err(Error::new(
168                    ErrorKind::ConfigInvalid,
169                    "drive_type is invalid.",
170                ))
171            }
172        };
173        debug!("backend use drive_type {drive_type:?}");
174
175        Ok(AliyunDriveBackend {
176            core: Arc::new(AliyunDriveCore {
177                info: {
178                    let am = AccessorInfo::default();
179                    am.set_scheme(DEFAULT_SCHEME)
180                        .set_root(&root)
181                        .set_native_capability(Capability {
182                            stat: true,
183                            create_dir: true,
184                            read: true,
185                            write: true,
186                            write_can_multi: true,
187                            // The min multipart size of AliyunDrive is 100 KiB.
188                            write_multi_min_size: Some(100 * 1024),
189                            // The max multipart size of AliyunDrive is 5 GiB.
190                            write_multi_max_size: if cfg!(target_pointer_width = "64") {
191                                Some(5 * 1024 * 1024 * 1024)
192                            } else {
193                                Some(usize::MAX)
194                            },
195                            delete: true,
196                            copy: true,
197                            rename: true,
198                            list: true,
199                            list_with_limit: true,
200                            shared: true,
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                endpoint: "https://openapi.alipan.com".to_string(),
213                root,
214                drive_type,
215                signer: Arc::new(Mutex::new(AliyunDriveSigner {
216                    drive_id: None,
217                    sign,
218                })),
219                dir_lock: Arc::new(Mutex::new(())),
220            }),
221        })
222    }
223}
224
225#[derive(Clone, Debug)]
226pub struct AliyunDriveBackend {
227    core: Arc<AliyunDriveCore>,
228}
229
230impl Access for AliyunDriveBackend {
231    type Reader = HttpBody;
232    type Writer = AliyunDriveWriter;
233    type Lister = oio::PageLister<AliyunDriveLister>;
234    type Deleter = oio::OneShotDeleter<AliyunDriveDeleter>;
235
236    fn info(&self) -> Arc<AccessorInfo> {
237        self.core.info.clone()
238    }
239
240    async fn create_dir(&self, path: &str, _args: OpCreateDir) -> Result<RpCreateDir> {
241        self.core.ensure_dir_exists(path).await?;
242
243        Ok(RpCreateDir::default())
244    }
245
246    async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
247        if from == to {
248            return Ok(RpRename::default());
249        }
250        let res = self.core.get_by_path(from).await?;
251        let file: AliyunDriveFile =
252            serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
253        // rename can overwrite.
254        match self.core.get_by_path(to).await {
255            Err(err) if err.kind() == ErrorKind::NotFound => {}
256            Err(err) => return Err(err),
257            Ok(res) => {
258                let file: AliyunDriveFile =
259                    serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
260                self.core.delete_path(&file.file_id).await?;
261            }
262        };
263
264        let parent_file_id = self.core.ensure_dir_exists(get_parent(to)).await?;
265        self.core.move_path(&file.file_id, &parent_file_id).await?;
266
267        let from_name = get_basename(from);
268        let to_name = get_basename(to);
269
270        if from_name != to_name {
271            self.core.update_path(&file.file_id, to_name).await?;
272        }
273
274        Ok(RpRename::default())
275    }
276
277    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
278        if from == to {
279            return Ok(RpCopy::default());
280        }
281        let res = self.core.get_by_path(from).await?;
282        let file: AliyunDriveFile =
283            serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
284        // copy can overwrite.
285        match self.core.get_by_path(to).await {
286            Err(err) if err.kind() == ErrorKind::NotFound => {}
287            Err(err) => return Err(err),
288            Ok(res) => {
289                let file: AliyunDriveFile =
290                    serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
291                self.core.delete_path(&file.file_id).await?;
292            }
293        };
294        // there is no direct copy in AliyunDrive.
295        // so we need to copy the path first and then rename it.
296        let parent_path = get_parent(to);
297        let parent_file_id = self.core.ensure_dir_exists(parent_path).await?;
298
299        // if from and to are going to be placed in the same folder,
300        // copy_path will fail as we cannot change the name during this action.
301        // it has to be auto renamed.
302        let auto_rename = file.parent_file_id == parent_file_id;
303        let res = self
304            .core
305            .copy_path(&file.file_id, &parent_file_id, auto_rename)
306            .await?;
307        let file: CopyResponse =
308            serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
309        let file_id = file.file_id;
310
311        let from_name = get_basename(from);
312        let to_name = get_basename(to);
313
314        if from_name != to_name {
315            self.core.update_path(&file_id, to_name).await?;
316        }
317
318        Ok(RpCopy::default())
319    }
320
321    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
322        let res = self.core.get_by_path(path).await?;
323        let file: AliyunDriveFile =
324            serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
325
326        if file.path_type == "folder" {
327            let meta = Metadata::new(EntryMode::DIR).with_last_modified(
328                file.updated_at
329                    .parse::<chrono::DateTime<Utc>>()
330                    .map_err(|e| {
331                        Error::new(ErrorKind::Unexpected, "parse last modified time").set_source(e)
332                    })?,
333            );
334
335            return Ok(RpStat::new(meta));
336        }
337
338        let mut meta = Metadata::new(EntryMode::FILE).with_last_modified(
339            file.updated_at
340                .parse::<chrono::DateTime<Utc>>()
341                .map_err(|e| {
342                    Error::new(ErrorKind::Unexpected, "parse last modified time").set_source(e)
343                })?,
344        );
345        if let Some(v) = file.size {
346            meta = meta.with_content_length(v);
347        }
348        if let Some(v) = file.content_type {
349            meta = meta.with_content_type(v);
350        }
351
352        Ok(RpStat::new(meta))
353    }
354
355    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
356        let res = self.core.get_by_path(path).await?;
357        let file: AliyunDriveFile =
358            serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
359        let resp = self.core.download(&file.file_id, args.range()).await?;
360
361        let status = resp.status();
362        match status {
363            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
364                Ok((RpRead::default(), resp.into_body()))
365            }
366            _ => {
367                let (part, mut body) = resp.into_parts();
368                let buf = body.to_buffer().await?;
369                Err(parse_error(Response::from_parts(part, buf)))
370            }
371        }
372    }
373
374    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
375        Ok((
376            RpDelete::default(),
377            oio::OneShotDeleter::new(AliyunDriveDeleter::new(self.core.clone())),
378        ))
379    }
380
381    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
382        let parent = match self.core.get_by_path(path).await {
383            Err(err) if err.kind() == ErrorKind::NotFound => None,
384            Err(err) => return Err(err),
385            Ok(res) => {
386                let file: AliyunDriveFile =
387                    serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
388                Some(AliyunDriveParent {
389                    file_id: file.file_id,
390                    path: path.to_string(),
391                    updated_at: file.updated_at,
392                })
393            }
394        };
395
396        let l = AliyunDriveLister::new(self.core.clone(), parent, args.limit());
397
398        Ok((RpList::default(), oio::PageLister::new(l)))
399    }
400
401    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
402        let parent_path = get_parent(path);
403        let parent_file_id = self.core.ensure_dir_exists(parent_path).await?;
404
405        // write can overwrite
406        match self.core.get_by_path(path).await {
407            Err(err) if err.kind() == ErrorKind::NotFound => {}
408            Err(err) => return Err(err),
409            Ok(res) => {
410                let file: AliyunDriveFile =
411                    serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
412                self.core.delete_path(&file.file_id).await?;
413            }
414        };
415
416        let writer =
417            AliyunDriveWriter::new(self.core.clone(), &parent_file_id, get_basename(path), args);
418
419        Ok((RpWrite::default(), writer))
420    }
421}