opendal/services/yandex_disk/
backend.rs1use 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 super::DEFAULT_SCHEME;
34use crate::raw::*;
35use crate::services::YandexDiskConfig;
36use crate::*;
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#[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 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 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 #[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 type Config = YandexDiskConfig;
108
109 fn build(self) -> Result<impl Access> {
111 debug!("backend build started: {:?}", &self);
112
113 let root = normalize_root(&self.config.root.clone().unwrap_or_default());
114 debug!("backend use root {}", &root);
115
116 if self.config.access_token.is_empty() {
118 return Err(
119 Error::new(ErrorKind::ConfigInvalid, "access_token is empty")
120 .with_operation("Builder::build")
121 .with_context("service", Scheme::YandexDisk),
122 );
123 }
124
125 Ok(YandexDiskBackend {
126 core: Arc::new(YandexDiskCore {
127 info: {
128 let am = AccessorInfo::default();
129 am.set_scheme(DEFAULT_SCHEME)
130 .set_root(&root)
131 .set_native_capability(Capability {
132 stat: true,
133
134 create_dir: true,
135
136 read: true,
137
138 write: true,
139 write_can_empty: true,
140
141 delete: true,
142 rename: true,
143 copy: true,
144
145 list: true,
146 list_with_limit: true,
147
148 shared: true,
149
150 ..Default::default()
151 });
152
153 #[allow(deprecated)]
155 if let Some(client) = self.http_client {
156 am.update_http_client(|_| client);
157 }
158
159 am.into()
160 },
161 root,
162 access_token: self.config.access_token.clone(),
163 }),
164 })
165 }
166}
167
168#[derive(Debug, Clone)]
170pub struct YandexDiskBackend {
171 core: Arc<YandexDiskCore>,
172}
173
174impl Access for YandexDiskBackend {
175 type Reader = HttpBody;
176 type Writer = YandexDiskWriters;
177 type Lister = oio::PageLister<YandexDiskLister>;
178 type Deleter = oio::OneShotDeleter<YandexDiskDeleter>;
179
180 fn info(&self) -> Arc<AccessorInfo> {
181 self.core.info.clone()
182 }
183
184 async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
185 self.core.ensure_dir_exists(path).await?;
186
187 Ok(RpCreateDir::default())
188 }
189
190 async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
191 self.core.ensure_dir_exists(to).await?;
192
193 let resp = self.core.move_object(from, to).await?;
194
195 let status = resp.status();
196
197 match status {
198 StatusCode::OK | StatusCode::CREATED => Ok(RpRename::default()),
199 _ => Err(parse_error(resp)),
200 }
201 }
202
203 async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
204 self.core.ensure_dir_exists(to).await?;
205
206 let resp = self.core.copy(from, to).await?;
207
208 let status = resp.status();
209
210 match status {
211 StatusCode::OK | StatusCode::CREATED => Ok(RpCopy::default()),
212 _ => Err(parse_error(resp)),
213 }
214 }
215
216 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
217 let resp = self.core.download(path, args.range()).await?;
218
219 let status = resp.status();
220 match status {
221 StatusCode::OK | StatusCode::PARTIAL_CONTENT => Ok((RpRead::new(), resp.into_body())),
222 _ => {
223 let (part, mut body) = resp.into_parts();
224 let buf = body.to_buffer().await?;
225 Err(parse_error(Response::from_parts(part, buf)))
226 }
227 }
228 }
229
230 async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
231 let resp = self.core.metainformation(path, None, None).await?;
232
233 let status = resp.status();
234
235 match status {
236 StatusCode::OK => {
237 let bs = resp.into_body();
238
239 let mf: MetainformationResponse =
240 serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
241
242 parse_info(mf).map(RpStat::new)
243 }
244 _ => Err(parse_error(resp)),
245 }
246 }
247
248 async fn write(&self, path: &str, _args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
249 let writer = YandexDiskWriter::new(self.core.clone(), path.to_string());
250
251 let w = oio::OneShotWriter::new(writer);
252
253 Ok((RpWrite::default(), w))
254 }
255
256 async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
257 Ok((
258 RpDelete::default(),
259 oio::OneShotDeleter::new(YandexDiskDeleter::new(self.core.clone())),
260 ))
261 }
262
263 async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
264 let l = YandexDiskLister::new(self.core.clone(), path, args.limit());
265 Ok((RpList::default(), oio::PageLister::new(l)))
266 }
267}