opendal/services/koofr/
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;
26use tokio::sync::Mutex;
27use tokio::sync::OnceCell;
28
29use super::core::File;
30use super::core::KoofrCore;
31use super::core::KoofrSigner;
32use super::delete::KoofrDeleter;
33use super::error::parse_error;
34use super::lister::KoofrLister;
35use super::writer::KoofrWriter;
36use super::writer::KoofrWriters;
37use crate::raw::*;
38use crate::services::KoofrConfig;
39use crate::*;
40
41impl Configurator for KoofrConfig {
42 type Builder = KoofrBuilder;
43
44 #[allow(deprecated)]
45 fn into_builder(self) -> Self::Builder {
46 KoofrBuilder {
47 config: self,
48 http_client: None,
49 }
50 }
51}
52
53#[doc = include_str!("docs.md")]
55#[derive(Default)]
56pub struct KoofrBuilder {
57 config: KoofrConfig,
58
59 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
60 http_client: Option<HttpClient>,
61}
62
63impl Debug for KoofrBuilder {
64 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
65 let mut d = f.debug_struct("KoofrBuilder");
66
67 d.field("config", &self.config);
68 d.finish_non_exhaustive()
69 }
70}
71
72impl KoofrBuilder {
73 pub fn root(mut self, root: &str) -> Self {
77 self.config.root = if root.is_empty() {
78 None
79 } else {
80 Some(root.to_string())
81 };
82
83 self
84 }
85
86 pub fn endpoint(mut self, endpoint: &str) -> Self {
90 self.config.endpoint = endpoint.to_string();
91
92 self
93 }
94
95 pub fn email(mut self, email: &str) -> Self {
99 self.config.email = email.to_string();
100
101 self
102 }
103
104 pub fn password(mut self, password: &str) -> Self {
115 self.config.password = if password.is_empty() {
116 None
117 } else {
118 Some(password.to_string())
119 };
120
121 self
122 }
123
124 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
131 #[allow(deprecated)]
132 pub fn http_client(mut self, client: HttpClient) -> Self {
133 self.http_client = Some(client);
134 self
135 }
136}
137
138impl Builder for KoofrBuilder {
139 const SCHEME: Scheme = Scheme::Koofr;
140 type Config = KoofrConfig;
141
142 fn build(self) -> Result<impl Access> {
144 debug!("backend build started: {:?}", &self);
145
146 let root = normalize_root(&self.config.root.clone().unwrap_or_default());
147 debug!("backend use root {}", &root);
148
149 if self.config.endpoint.is_empty() {
150 return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
151 .with_operation("Builder::build")
152 .with_context("service", Scheme::Koofr));
153 }
154
155 debug!("backend use endpoint {}", &self.config.endpoint);
156
157 if self.config.email.is_empty() {
158 return Err(Error::new(ErrorKind::ConfigInvalid, "email is empty")
159 .with_operation("Builder::build")
160 .with_context("service", Scheme::Koofr));
161 }
162
163 debug!("backend use email {}", &self.config.email);
164
165 let password = match &self.config.password {
166 Some(password) => Ok(password.clone()),
167 None => Err(Error::new(ErrorKind::ConfigInvalid, "password is empty")
168 .with_operation("Builder::build")
169 .with_context("service", Scheme::Koofr)),
170 }?;
171
172 let signer = Arc::new(Mutex::new(KoofrSigner::default()));
173
174 Ok(KoofrBackend {
175 core: Arc::new(KoofrCore {
176 info: {
177 let am = AccessorInfo::default();
178 am.set_scheme(Scheme::Koofr)
179 .set_root(&root)
180 .set_native_capability(Capability {
181 stat: true,
182
183 create_dir: true,
184
185 read: true,
186
187 write: true,
188 write_can_empty: true,
189
190 delete: true,
191
192 rename: true,
193
194 copy: true,
195
196 list: true,
197
198 shared: true,
199
200 ..Default::default()
201 });
202
203 #[allow(deprecated)]
205 if let Some(client) = self.http_client {
206 am.update_http_client(|_| client);
207 }
208
209 am.into()
210 },
211 root,
212 endpoint: self.config.endpoint.clone(),
213 email: self.config.email.clone(),
214 password,
215 mount_id: OnceCell::new(),
216 signer,
217 }),
218 })
219 }
220}
221
222#[derive(Debug, Clone)]
224pub struct KoofrBackend {
225 core: Arc<KoofrCore>,
226}
227
228impl Access for KoofrBackend {
229 type Reader = HttpBody;
230 type Writer = KoofrWriters;
231 type Lister = oio::PageLister<KoofrLister>;
232 type Deleter = oio::OneShotDeleter<KoofrDeleter>;
233
234 fn info(&self) -> Arc<AccessorInfo> {
235 self.core.info.clone()
236 }
237
238 async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
239 self.core.ensure_dir_exists(path).await?;
240 self.core
241 .create_dir(&build_abs_path(&self.core.root, path))
242 .await?;
243 Ok(RpCreateDir::default())
244 }
245
246 async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
247 let path = build_rooted_abs_path(&self.core.root, path);
248 let resp = self.core.info(&path).await?;
249
250 let status = resp.status();
251
252 match status {
253 StatusCode::OK => {
254 let bs = resp.into_body();
255
256 let file: File =
257 serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
258
259 let mode = if file.ty == "dir" {
260 EntryMode::DIR
261 } else {
262 EntryMode::FILE
263 };
264
265 let mut md = Metadata::new(mode);
266
267 md.set_content_length(file.size)
268 .set_content_type(&file.content_type)
269 .set_last_modified(parse_datetime_from_from_timestamp_millis(file.modified)?);
270
271 Ok(RpStat::new(md))
272 }
273 _ => Err(parse_error(resp)),
274 }
275 }
276
277 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
278 let resp = self.core.get(path, args.range()).await?;
279
280 let status = resp.status();
281 match status {
282 StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
283 Ok((RpRead::default(), resp.into_body()))
284 }
285 _ => {
286 let (part, mut body) = resp.into_parts();
287 let buf = body.to_buffer().await?;
288 Err(parse_error(Response::from_parts(part, buf)))
289 }
290 }
291 }
292
293 async fn write(&self, path: &str, _args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
294 let writer = KoofrWriter::new(self.core.clone(), path.to_string());
295
296 let w = oio::OneShotWriter::new(writer);
297
298 Ok((RpWrite::default(), w))
299 }
300
301 async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
302 Ok((
303 RpDelete::default(),
304 oio::OneShotDeleter::new(KoofrDeleter::new(self.core.clone())),
305 ))
306 }
307
308 async fn list(&self, path: &str, _args: OpList) -> Result<(RpList, Self::Lister)> {
309 let l = KoofrLister::new(self.core.clone(), path);
310 Ok((RpList::default(), oio::PageLister::new(l)))
311 }
312
313 async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
314 self.core.ensure_dir_exists(to).await?;
315
316 if from == to {
317 return Ok(RpCopy::default());
318 }
319
320 let resp = self.core.remove(to).await?;
321
322 let status = resp.status();
323
324 if status != StatusCode::OK && status != StatusCode::NOT_FOUND {
325 return Err(parse_error(resp));
326 }
327
328 let resp = self.core.copy(from, to).await?;
329
330 let status = resp.status();
331
332 match status {
333 StatusCode::OK => Ok(RpCopy::default()),
334 _ => Err(parse_error(resp)),
335 }
336 }
337
338 async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
339 self.core.ensure_dir_exists(to).await?;
340
341 if from == to {
342 return Ok(RpRename::default());
343 }
344
345 let resp = self.core.remove(to).await?;
346
347 let status = resp.status();
348
349 if status != StatusCode::OK && status != StatusCode::NOT_FOUND {
350 return Err(parse_error(resp));
351 }
352
353 let resp = self.core.move_object(from, to).await?;
354
355 let status = resp.status();
356
357 match status {
358 StatusCode::OK => Ok(RpRename::default()),
359 _ => Err(parse_error(resp)),
360 }
361 }
362}