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 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#[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 const SCHEME: Scheme = Scheme::YandexDisk;
108 type Config = YandexDiskConfig;
109
110 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 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)]
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#[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}