opendal/services/yandex_disk/
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 http::Response;
24use http::StatusCode;
25use log::debug;
26
27use super::core::*;
28use super::delete::YandexDiskDeleter;
29use super::error::parse_error;
30use super::lister::YandexDiskLister;
31use super::writer::YandexDiskWriter;
32use super::writer::YandexDiskWriters;
33use crate::raw::*;
34use crate::services::YandexDiskConfig;
35use crate::*;
36
37impl Configurator for YandexDiskConfig {
38    type Builder = YandexDiskBuilder;
39
40    #[allow(deprecated)]
41    fn into_builder(self) -> Self::Builder {
42        YandexDiskBuilder {
43            config: self,
44            http_client: None,
45        }
46    }
47}
48
49/// [YandexDisk](https://360.yandex.com/disk/) services support.
50#[doc = include_str!("docs.md")]
51#[derive(Default)]
52pub struct YandexDiskBuilder {
53    config: YandexDiskConfig,
54
55    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
56    http_client: Option<HttpClient>,
57}
58
59impl Debug for YandexDiskBuilder {
60    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
61        let mut d = f.debug_struct("YandexDiskBuilder");
62
63        d.field("config", &self.config);
64        d.finish_non_exhaustive()
65    }
66}
67
68impl YandexDiskBuilder {
69    /// Set root of this backend.
70    ///
71    /// All operations will happen under this root.
72    pub fn root(mut self, root: &str) -> Self {
73        self.config.root = if root.is_empty() {
74            None
75        } else {
76            Some(root.to_string())
77        };
78
79        self
80    }
81
82    /// yandex disk oauth access_token.
83    /// The valid token will looks like `y0_XXXXXXqihqIWAADLWwAAAAD3IXXXXXX0gtVeSPeIKM0oITMGhXXXXXX`.
84    /// We can fetch the debug token from <https://yandex.com/dev/disk/poligon>.
85    /// To use it in production, please register an app at <https://oauth.yandex.com> instead.
86    pub fn access_token(mut self, access_token: &str) -> Self {
87        self.config.access_token = access_token.to_string();
88
89        self
90    }
91
92    /// Specify the http client that used by this service.
93    ///
94    /// # Notes
95    ///
96    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
97    /// during minor updates.
98    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
99    #[allow(deprecated)]
100    pub fn http_client(mut self, client: HttpClient) -> Self {
101        self.http_client = Some(client);
102        self
103    }
104}
105
106impl Builder for YandexDiskBuilder {
107    const SCHEME: Scheme = Scheme::YandexDisk;
108    type Config = YandexDiskConfig;
109
110    /// Builds the backend and returns the result of YandexDiskBackend.
111    fn build(self) -> Result<impl Access> {
112        debug!("backend build started: {:?}", &self);
113
114        let root = normalize_root(&self.config.root.clone().unwrap_or_default());
115        debug!("backend use root {}", &root);
116
117        // Handle oauth access_token.
118        if self.config.access_token.is_empty() {
119            return Err(
120                Error::new(ErrorKind::ConfigInvalid, "access_token is empty")
121                    .with_operation("Builder::build")
122                    .with_context("service", Scheme::YandexDisk),
123            );
124        }
125
126        Ok(YandexDiskBackend {
127            core: Arc::new(YandexDiskCore {
128                info: {
129                    let am = AccessorInfo::default();
130                    am.set_scheme(Scheme::YandexDisk)
131                        .set_root(&root)
132                        .set_native_capability(Capability {
133                            stat: true,
134
135                            create_dir: true,
136
137                            read: true,
138
139                            write: true,
140                            write_can_empty: true,
141
142                            delete: true,
143                            rename: true,
144                            copy: true,
145
146                            list: true,
147                            list_with_limit: true,
148
149                            shared: true,
150
151                            ..Default::default()
152                        });
153
154                    // allow deprecated api here for compatibility
155                    #[allow(deprecated)]
156                    if let Some(client) = self.http_client {
157                        am.update_http_client(|_| client);
158                    }
159
160                    am.into()
161                },
162                root,
163                access_token: self.config.access_token.clone(),
164            }),
165        })
166    }
167}
168
169/// Backend for YandexDisk services.
170#[derive(Debug, Clone)]
171pub struct YandexDiskBackend {
172    core: Arc<YandexDiskCore>,
173}
174
175impl Access for YandexDiskBackend {
176    type Reader = HttpBody;
177    type Writer = YandexDiskWriters;
178    type Lister = oio::PageLister<YandexDiskLister>;
179    type Deleter = oio::OneShotDeleter<YandexDiskDeleter>;
180
181    fn info(&self) -> Arc<AccessorInfo> {
182        self.core.info.clone()
183    }
184
185    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
186        self.core.ensure_dir_exists(path).await?;
187
188        Ok(RpCreateDir::default())
189    }
190
191    async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
192        self.core.ensure_dir_exists(to).await?;
193
194        let resp = self.core.move_object(from, to).await?;
195
196        let status = resp.status();
197
198        match status {
199            StatusCode::OK | StatusCode::CREATED => Ok(RpRename::default()),
200            _ => Err(parse_error(resp)),
201        }
202    }
203
204    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
205        self.core.ensure_dir_exists(to).await?;
206
207        let resp = self.core.copy(from, to).await?;
208
209        let status = resp.status();
210
211        match status {
212            StatusCode::OK | StatusCode::CREATED => Ok(RpCopy::default()),
213            _ => Err(parse_error(resp)),
214        }
215    }
216
217    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
218        let resp = self.core.download(path, args.range()).await?;
219
220        let status = resp.status();
221        match status {
222            StatusCode::OK | StatusCode::PARTIAL_CONTENT => Ok((RpRead::new(), resp.into_body())),
223            _ => {
224                let (part, mut body) = resp.into_parts();
225                let buf = body.to_buffer().await?;
226                Err(parse_error(Response::from_parts(part, buf)))
227            }
228        }
229    }
230
231    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
232        let resp = self.core.metainformation(path, None, None).await?;
233
234        let status = resp.status();
235
236        match status {
237            StatusCode::OK => {
238                let bs = resp.into_body();
239
240                let mf: MetainformationResponse =
241                    serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
242
243                parse_info(mf).map(RpStat::new)
244            }
245            _ => Err(parse_error(resp)),
246        }
247    }
248
249    async fn write(&self, path: &str, _args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
250        let writer = YandexDiskWriter::new(self.core.clone(), path.to_string());
251
252        let w = oio::OneShotWriter::new(writer);
253
254        Ok((RpWrite::default(), w))
255    }
256
257    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
258        Ok((
259            RpDelete::default(),
260            oio::OneShotDeleter::new(YandexDiskDeleter::new(self.core.clone())),
261        ))
262    }
263
264    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
265        let l = YandexDiskLister::new(self.core.clone(), path, args.limit());
266        Ok((RpList::default(), oio::PageLister::new(l)))
267    }
268}