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                            stat_has_last_modified: true,
135                            stat_has_content_md5: true,
136                            stat_has_content_type: true,
137                            stat_has_content_length: true,
138
139                            create_dir: true,
140
141                            read: true,
142
143                            write: true,
144                            write_can_empty: true,
145
146                            delete: true,
147                            rename: true,
148                            copy: true,
149
150                            list: true,
151                            list_with_limit: true,
152                            list_has_last_modified: true,
153                            list_has_content_md5: true,
154                            list_has_content_type: true,
155                            list_has_content_length: true,
156
157                            shared: true,
158
159                            ..Default::default()
160                        });
161
162                    // allow deprecated api here for compatibility
163                    #[allow(deprecated)]
164                    if let Some(client) = self.http_client {
165                        am.update_http_client(|_| client);
166                    }
167
168                    am.into()
169                },
170                root,
171                access_token: self.config.access_token.clone(),
172            }),
173        })
174    }
175}
176
177/// Backend for YandexDisk services.
178#[derive(Debug, Clone)]
179pub struct YandexDiskBackend {
180    core: Arc<YandexDiskCore>,
181}
182
183impl Access for YandexDiskBackend {
184    type Reader = HttpBody;
185    type Writer = YandexDiskWriters;
186    type Lister = oio::PageLister<YandexDiskLister>;
187    type Deleter = oio::OneShotDeleter<YandexDiskDeleter>;
188    type BlockingReader = ();
189    type BlockingWriter = ();
190    type BlockingLister = ();
191    type BlockingDeleter = ();
192
193    fn info(&self) -> Arc<AccessorInfo> {
194        self.core.info.clone()
195    }
196
197    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
198        self.core.ensure_dir_exists(path).await?;
199
200        Ok(RpCreateDir::default())
201    }
202
203    async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
204        self.core.ensure_dir_exists(to).await?;
205
206        let resp = self.core.move_object(from, to).await?;
207
208        let status = resp.status();
209
210        match status {
211            StatusCode::OK | StatusCode::CREATED => Ok(RpRename::default()),
212            _ => Err(parse_error(resp)),
213        }
214    }
215
216    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
217        self.core.ensure_dir_exists(to).await?;
218
219        let resp = self.core.copy(from, to).await?;
220
221        let status = resp.status();
222
223        match status {
224            StatusCode::OK | StatusCode::CREATED => Ok(RpCopy::default()),
225            _ => Err(parse_error(resp)),
226        }
227    }
228
229    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
230        let resp = self.core.download(path, args.range()).await?;
231
232        let status = resp.status();
233        match status {
234            StatusCode::OK | StatusCode::PARTIAL_CONTENT => Ok((RpRead::new(), resp.into_body())),
235            _ => {
236                let (part, mut body) = resp.into_parts();
237                let buf = body.to_buffer().await?;
238                Err(parse_error(Response::from_parts(part, buf)))
239            }
240        }
241    }
242
243    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
244        let resp = self.core.metainformation(path, None, None).await?;
245
246        let status = resp.status();
247
248        match status {
249            StatusCode::OK => {
250                let bs = resp.into_body();
251
252                let mf: MetainformationResponse =
253                    serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
254
255                parse_info(mf).map(RpStat::new)
256            }
257            _ => Err(parse_error(resp)),
258        }
259    }
260
261    async fn write(&self, path: &str, _args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
262        let writer = YandexDiskWriter::new(self.core.clone(), path.to_string());
263
264        let w = oio::OneShotWriter::new(writer);
265
266        Ok((RpWrite::default(), w))
267    }
268
269    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
270        Ok((
271            RpDelete::default(),
272            oio::OneShotDeleter::new(YandexDiskDeleter::new(self.core.clone())),
273        ))
274    }
275
276    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
277        let l = YandexDiskLister::new(self.core.clone(), path, args.limit());
278        Ok((RpList::default(), oio::PageLister::new(l)))
279    }
280}