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 crate::raw::*;
38use crate::services::B2Config;
39use crate::*;
40
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 const SCHEME: Scheme = Scheme::B2;
140 type Config = B2Config;
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.bucket.is_empty() {
151 return Err(Error::new(ErrorKind::ConfigInvalid, "bucket is empty")
152 .with_operation("Builder::build")
153 .with_context("service", Scheme::B2));
154 }
155
156 debug!("backend use bucket {}", &self.config.bucket);
157
158 if self.config.bucket_id.is_empty() {
160 return Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is empty")
161 .with_operation("Builder::build")
162 .with_context("service", Scheme::B2));
163 }
164
165 debug!("backend bucket_id {}", &self.config.bucket_id);
166
167 let application_key_id = match &self.config.application_key_id {
168 Some(application_key_id) => Ok(application_key_id.clone()),
169 None => Err(
170 Error::new(ErrorKind::ConfigInvalid, "application_key_id is empty")
171 .with_operation("Builder::build")
172 .with_context("service", Scheme::B2),
173 ),
174 }?;
175
176 let application_key = match &self.config.application_key {
177 Some(key_id) => Ok(key_id.clone()),
178 None => Err(
179 Error::new(ErrorKind::ConfigInvalid, "application_key is empty")
180 .with_operation("Builder::build")
181 .with_context("service", Scheme::B2),
182 ),
183 }?;
184
185 let signer = B2Signer {
186 application_key_id,
187 application_key,
188 ..Default::default()
189 };
190
191 Ok(B2Backend {
192 core: Arc::new(B2Core {
193 info: {
194 let am = AccessorInfo::default();
195 am.set_scheme(Scheme::B2)
196 .set_root(&root)
197 .set_native_capability(Capability {
198 stat: true,
199 stat_has_content_length: true,
200 stat_has_content_md5: true,
201 stat_has_content_type: true,
202
203 read: true,
204
205 write: true,
206 write_can_empty: true,
207 write_can_multi: true,
208 write_with_content_type: true,
209 write_multi_min_size: Some(5 * 1024 * 1024),
213 write_multi_max_size: if cfg!(target_pointer_width = "64") {
217 Some(5 * 1024 * 1024 * 1024)
218 } else {
219 Some(usize::MAX)
220 },
221
222 delete: true,
223 copy: true,
224
225 list: true,
226 list_with_limit: true,
227 list_with_start_after: true,
228 list_with_recursive: true,
229 list_has_content_length: true,
230 list_has_content_md5: true,
231 list_has_content_type: true,
232
233 presign: true,
234 presign_read: true,
235 presign_write: true,
236 presign_stat: true,
237
238 shared: true,
239
240 ..Default::default()
241 });
242
243 #[allow(deprecated)]
245 if let Some(client) = self.http_client {
246 am.update_http_client(|_| client);
247 }
248
249 am.into()
250 },
251 signer: Arc::new(RwLock::new(signer)),
252 root,
253
254 bucket: self.config.bucket.clone(),
255 bucket_id: self.config.bucket_id.clone(),
256 }),
257 })
258 }
259}
260
261#[derive(Debug, Clone)]
263pub struct B2Backend {
264 core: Arc<B2Core>,
265}
266
267impl Access for B2Backend {
268 type Reader = HttpBody;
269 type Writer = B2Writers;
270 type Lister = oio::PageLister<B2Lister>;
271 type Deleter = oio::OneShotDeleter<B2Deleter>;
272
273 fn info(&self) -> Arc<AccessorInfo> {
274 self.core.info.clone()
275 }
276
277 async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
280 if path == "/" {
282 return Ok(RpStat::new(Metadata::new(EntryMode::DIR)));
283 }
284
285 let delimiter = if path.ends_with('/') { Some("/") } else { None };
286
287 let file_info = self.core.get_file_info(path, delimiter).await?;
288 let meta = parse_file_info(&file_info);
289 Ok(RpStat::new(meta))
290 }
291
292 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
293 let resp = self
294 .core
295 .download_file_by_name(path, args.range(), &args)
296 .await?;
297
298 let status = resp.status();
299 match status {
300 StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
301 Ok((RpRead::default(), resp.into_body()))
302 }
303 _ => {
304 let (part, mut body) = resp.into_parts();
305 let buf = body.to_buffer().await?;
306 Err(parse_error(Response::from_parts(part, buf)))
307 }
308 }
309 }
310
311 async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
312 let concurrent = args.concurrent();
313 let writer = B2Writer::new(self.core.clone(), path, args);
314
315 let w = oio::MultipartWriter::new(self.core.info.clone(), writer, concurrent);
316
317 Ok((RpWrite::default(), w))
318 }
319
320 async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
321 Ok((
322 RpDelete::default(),
323 oio::OneShotDeleter::new(B2Deleter::new(self.core.clone())),
324 ))
325 }
326
327 async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
328 Ok((
329 RpList::default(),
330 oio::PageLister::new(B2Lister::new(
331 self.core.clone(),
332 path,
333 args.recursive(),
334 args.limit(),
335 args.start_after(),
336 )),
337 ))
338 }
339
340 async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
341 let file_info = self.core.get_file_info(from, None).await?;
342
343 let source_file_id = file_info.file_id;
344
345 let Some(source_file_id) = source_file_id else {
346 return Err(Error::new(ErrorKind::IsADirectory, "is a directory"));
347 };
348
349 let resp = self.core.copy_file(source_file_id, to).await?;
350
351 let status = resp.status();
352
353 match status {
354 StatusCode::OK => Ok(RpCopy::default()),
355 _ => Err(parse_error(resp)),
356 }
357 }
358
359 async fn presign(&self, path: &str, args: OpPresign) -> Result<RpPresign> {
360 match args.operation() {
361 PresignOperation::Stat(_) => {
362 let resp = self
363 .core
364 .get_download_authorization(path, args.expire())
365 .await?;
366 let path = build_abs_path(&self.core.root, path);
367
368 let auth_info = self.core.get_auth_info().await?;
369
370 let url = format!(
371 "{}/file/{}/{}?Authorization={}",
372 auth_info.download_url, self.core.bucket, path, resp.authorization_token
373 );
374
375 let req = Request::get(url);
376
377 let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
378
379 let (parts, _) = req.into_parts();
381
382 Ok(RpPresign::new(PresignedRequest::new(
383 parts.method,
384 parts.uri,
385 parts.headers,
386 )))
387 }
388 PresignOperation::Read(_) => {
389 let resp = self
390 .core
391 .get_download_authorization(path, args.expire())
392 .await?;
393 let path = build_abs_path(&self.core.root, path);
394
395 let auth_info = self.core.get_auth_info().await?;
396
397 let url = format!(
398 "{}/file/{}/{}?Authorization={}",
399 auth_info.download_url, self.core.bucket, path, resp.authorization_token
400 );
401
402 let req = Request::get(url);
403
404 let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
405
406 let (parts, _) = req.into_parts();
408
409 Ok(RpPresign::new(PresignedRequest::new(
410 parts.method,
411 parts.uri,
412 parts.headers,
413 )))
414 }
415 PresignOperation::Write(_) => {
416 let resp = self.core.get_upload_url().await?;
417
418 let mut req = Request::post(&resp.upload_url);
419
420 req = req.header(http::header::AUTHORIZATION, resp.authorization_token);
421 req = req.header("X-Bz-File-Name", build_abs_path(&self.core.root, path));
422 req = req.header(http::header::CONTENT_TYPE, "b2/x-auto");
423 req = req.header(constants::X_BZ_CONTENT_SHA1, "do_not_verify");
424
425 let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
426 let (parts, _) = req.into_parts();
428
429 Ok(RpPresign::new(PresignedRequest::new(
430 parts.method,
431 parts.uri,
432 parts.headers,
433 )))
434 }
435 PresignOperation::Delete(_) => Err(Error::new(
436 ErrorKind::Unsupported,
437 "operation is not supported",
438 )),
439 }
440 }
441}