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