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