1use std::fmt::Debug;
19use std::fmt::Formatter;
20use std::sync::Arc;
21
22use http::Request;
23use http::Response;
24use http::StatusCode;
25use log::debug;
26use tokio::sync::RwLock;
27
28use super::core::constants;
29use super::core::parse_file_info;
30use super::core::B2Core;
31use super::core::B2Signer;
32use super::delete::B2Deleter;
33use super::error::parse_error;
34use super::lister::B2Lister;
35use super::writer::B2Writer;
36use super::writer::B2Writers;
37use super::DEFAULT_SCHEME;
38use crate::raw::*;
39use crate::services::B2Config;
40use crate::*;
41impl Configurator for B2Config {
42 type Builder = B2Builder;
43
44 #[allow(deprecated)]
45 fn into_builder(self) -> Self::Builder {
46 B2Builder {
47 config: self,
48 http_client: None,
49 }
50 }
51}
52
53#[doc = include_str!("docs.md")]
55#[derive(Default)]
56pub struct B2Builder {
57 config: B2Config,
58
59 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
60 http_client: Option<HttpClient>,
61}
62
63impl Debug for B2Builder {
64 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
65 let mut d = f.debug_struct("B2Builder");
66
67 d.field("config", &self.config);
68 d.finish_non_exhaustive()
69 }
70}
71
72impl B2Builder {
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 application_key_id(mut self, application_key_id: &str) -> Self {
88 self.config.application_key_id = if application_key_id.is_empty() {
89 None
90 } else {
91 Some(application_key_id.to_string())
92 };
93
94 self
95 }
96
97 pub fn application_key(mut self, application_key: &str) -> Self {
99 self.config.application_key = if application_key.is_empty() {
100 None
101 } else {
102 Some(application_key.to_string())
103 };
104
105 self
106 }
107
108 pub fn bucket(mut self, bucket: &str) -> Self {
111 self.config.bucket = bucket.to_string();
112
113 self
114 }
115
116 pub fn bucket_id(mut self, bucket_id: &str) -> Self {
119 self.config.bucket_id = bucket_id.to_string();
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 B2Builder {
139 type Config = B2Config;
140
141 fn build(self) -> Result<impl Access> {
143 debug!("backend build started: {:?}", &self);
144
145 let root = normalize_root(&self.config.root.clone().unwrap_or_default());
146 debug!("backend use root {}", &root);
147
148 if self.config.bucket.is_empty() {
150 return Err(Error::new(ErrorKind::ConfigInvalid, "bucket is empty")
151 .with_operation("Builder::build")
152 .with_context("service", Scheme::B2));
153 }
154
155 debug!("backend use bucket {}", &self.config.bucket);
156
157 if self.config.bucket_id.is_empty() {
159 return Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is empty")
160 .with_operation("Builder::build")
161 .with_context("service", Scheme::B2));
162 }
163
164 debug!("backend bucket_id {}", &self.config.bucket_id);
165
166 let application_key_id = match &self.config.application_key_id {
167 Some(application_key_id) => Ok(application_key_id.clone()),
168 None => Err(
169 Error::new(ErrorKind::ConfigInvalid, "application_key_id is empty")
170 .with_operation("Builder::build")
171 .with_context("service", Scheme::B2),
172 ),
173 }?;
174
175 let application_key = match &self.config.application_key {
176 Some(key_id) => Ok(key_id.clone()),
177 None => Err(
178 Error::new(ErrorKind::ConfigInvalid, "application_key is empty")
179 .with_operation("Builder::build")
180 .with_context("service", Scheme::B2),
181 ),
182 }?;
183
184 let signer = B2Signer {
185 application_key_id,
186 application_key,
187 ..Default::default()
188 };
189
190 Ok(B2Backend {
191 core: Arc::new(B2Core {
192 info: {
193 let am = AccessorInfo::default();
194 am.set_scheme(DEFAULT_SCHEME)
195 .set_root(&root)
196 .set_native_capability(Capability {
197 stat: true,
198
199 read: true,
200
201 write: true,
202 write_can_empty: true,
203 write_can_multi: true,
204 write_with_content_type: true,
205 write_multi_min_size: Some(5 * 1024 * 1024),
209 write_multi_max_size: if cfg!(target_pointer_width = "64") {
213 Some(5 * 1024 * 1024 * 1024)
214 } else {
215 Some(usize::MAX)
216 },
217
218 delete: true,
219 copy: true,
220
221 list: true,
222 list_with_limit: true,
223 list_with_start_after: true,
224 list_with_recursive: true,
225
226 presign: true,
227 presign_read: true,
228 presign_write: true,
229 presign_stat: true,
230
231 shared: true,
232
233 ..Default::default()
234 });
235
236 #[allow(deprecated)]
238 if let Some(client) = self.http_client {
239 am.update_http_client(|_| client);
240 }
241
242 am.into()
243 },
244 signer: Arc::new(RwLock::new(signer)),
245 root,
246
247 bucket: self.config.bucket.clone(),
248 bucket_id: self.config.bucket_id.clone(),
249 }),
250 })
251 }
252}
253
254#[derive(Debug, Clone)]
256pub struct B2Backend {
257 core: Arc<B2Core>,
258}
259
260impl Access for B2Backend {
261 type Reader = HttpBody;
262 type Writer = B2Writers;
263 type Lister = oio::PageLister<B2Lister>;
264 type Deleter = oio::OneShotDeleter<B2Deleter>;
265
266 fn info(&self) -> Arc<AccessorInfo> {
267 self.core.info.clone()
268 }
269
270 async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
273 if path == "/" {
275 return Ok(RpStat::new(Metadata::new(EntryMode::DIR)));
276 }
277
278 let delimiter = if path.ends_with('/') { Some("/") } else { None };
279
280 let file_info = self.core.get_file_info(path, delimiter).await?;
281 let meta = parse_file_info(&file_info);
282 Ok(RpStat::new(meta))
283 }
284
285 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
286 let resp = self
287 .core
288 .download_file_by_name(path, args.range(), &args)
289 .await?;
290
291 let status = resp.status();
292 match status {
293 StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
294 Ok((RpRead::default(), resp.into_body()))
295 }
296 _ => {
297 let (part, mut body) = resp.into_parts();
298 let buf = body.to_buffer().await?;
299 Err(parse_error(Response::from_parts(part, buf)))
300 }
301 }
302 }
303
304 async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
305 let concurrent = args.concurrent();
306 let writer = B2Writer::new(self.core.clone(), path, args);
307
308 let w = oio::MultipartWriter::new(self.core.info.clone(), writer, concurrent);
309
310 Ok((RpWrite::default(), w))
311 }
312
313 async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
314 Ok((
315 RpDelete::default(),
316 oio::OneShotDeleter::new(B2Deleter::new(self.core.clone())),
317 ))
318 }
319
320 async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
321 Ok((
322 RpList::default(),
323 oio::PageLister::new(B2Lister::new(
324 self.core.clone(),
325 path,
326 args.recursive(),
327 args.limit(),
328 args.start_after(),
329 )),
330 ))
331 }
332
333 async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
334 let file_info = self.core.get_file_info(from, None).await?;
335
336 let source_file_id = file_info.file_id;
337
338 let Some(source_file_id) = source_file_id else {
339 return Err(Error::new(ErrorKind::IsADirectory, "is a directory"));
340 };
341
342 let resp = self.core.copy_file(source_file_id, to).await?;
343
344 let status = resp.status();
345
346 match status {
347 StatusCode::OK => Ok(RpCopy::default()),
348 _ => Err(parse_error(resp)),
349 }
350 }
351
352 async fn presign(&self, path: &str, args: OpPresign) -> Result<RpPresign> {
353 match args.operation() {
354 PresignOperation::Stat(_) => {
355 let resp = self
356 .core
357 .get_download_authorization(path, args.expire())
358 .await?;
359 let path = build_abs_path(&self.core.root, path);
360
361 let auth_info = self.core.get_auth_info().await?;
362
363 let url = format!(
364 "{}/file/{}/{}?Authorization={}",
365 auth_info.download_url, self.core.bucket, path, resp.authorization_token
366 );
367
368 let req = Request::get(url);
369
370 let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
371
372 let (parts, _) = req.into_parts();
374
375 Ok(RpPresign::new(PresignedRequest::new(
376 parts.method,
377 parts.uri,
378 parts.headers,
379 )))
380 }
381 PresignOperation::Read(_) => {
382 let resp = self
383 .core
384 .get_download_authorization(path, args.expire())
385 .await?;
386 let path = build_abs_path(&self.core.root, path);
387
388 let auth_info = self.core.get_auth_info().await?;
389
390 let url = format!(
391 "{}/file/{}/{}?Authorization={}",
392 auth_info.download_url, self.core.bucket, path, resp.authorization_token
393 );
394
395 let req = Request::get(url);
396
397 let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
398
399 let (parts, _) = req.into_parts();
401
402 Ok(RpPresign::new(PresignedRequest::new(
403 parts.method,
404 parts.uri,
405 parts.headers,
406 )))
407 }
408 PresignOperation::Write(_) => {
409 let resp = self.core.get_upload_url().await?;
410
411 let mut req = Request::post(&resp.upload_url);
412
413 req = req.header(http::header::AUTHORIZATION, resp.authorization_token);
414 req = req.header("X-Bz-File-Name", build_abs_path(&self.core.root, path));
415 req = req.header(http::header::CONTENT_TYPE, "b2/x-auto");
416 req = req.header(constants::X_BZ_CONTENT_SHA1, "do_not_verify");
417
418 let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
419 let (parts, _) = req.into_parts();
421
422 Ok(RpPresign::new(PresignedRequest::new(
423 parts.method,
424 parts.uri,
425 parts.headers,
426 )))
427 }
428 PresignOperation::Delete(_) => Err(Error::new(
429 ErrorKind::Unsupported,
430 "operation is not supported",
431 )),
432 }
433 }
434}