opendal/services/b2/
backend.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use 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/// [b2](https://www.backblaze.com/cloud-storage) services support.
54#[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    /// Set root of this backend.
74    ///
75    /// All operations will happen under this root.
76    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    /// application_key_id of this backend.
87    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    /// application_key of this backend.
98    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    /// Set bucket name of this backend.
109    /// You can find it in <https://secure.backblaze.com/b2_buckets.html>
110    pub fn bucket(mut self, bucket: &str) -> Self {
111        self.config.bucket = bucket.to_string();
112
113        self
114    }
115
116    /// Set bucket id of this backend.
117    /// You can find it in <https://secure.backblaze.com/b2_buckets.html>
118    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    /// Specify the http client that used by this service.
125    ///
126    /// # Notes
127    ///
128    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
129    /// during minor updates.
130    #[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    /// Builds the backend and returns the result of B2Backend.
143    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        // Handle bucket.
150        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        // Handle bucket_id.
159        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
200                            read: true,
201
202                            write: true,
203                            write_can_empty: true,
204                            write_can_multi: true,
205                            write_with_content_type: true,
206                            // The min multipart size of b2 is 5 MiB.
207                            //
208                            // ref: <https://www.backblaze.com/docs/cloud-storage-large-files>
209                            write_multi_min_size: Some(5 * 1024 * 1024),
210                            // The max multipart size of b2 is 5 Gb.
211                            //
212                            // ref: <https://www.backblaze.com/docs/cloud-storage-large-files>
213                            write_multi_max_size: if cfg!(target_pointer_width = "64") {
214                                Some(5 * 1024 * 1024 * 1024)
215                            } else {
216                                Some(usize::MAX)
217                            },
218
219                            delete: true,
220                            copy: true,
221
222                            list: true,
223                            list_with_limit: true,
224                            list_with_start_after: true,
225                            list_with_recursive: true,
226
227                            presign: true,
228                            presign_read: true,
229                            presign_write: true,
230                            presign_stat: true,
231
232                            shared: true,
233
234                            ..Default::default()
235                        });
236
237                    // allow deprecated api here for compatibility
238                    #[allow(deprecated)]
239                    if let Some(client) = self.http_client {
240                        am.update_http_client(|_| client);
241                    }
242
243                    am.into()
244                },
245                signer: Arc::new(RwLock::new(signer)),
246                root,
247
248                bucket: self.config.bucket.clone(),
249                bucket_id: self.config.bucket_id.clone(),
250            }),
251        })
252    }
253}
254
255/// Backend for b2 services.
256#[derive(Debug, Clone)]
257pub struct B2Backend {
258    core: Arc<B2Core>,
259}
260
261impl Access for B2Backend {
262    type Reader = HttpBody;
263    type Writer = B2Writers;
264    type Lister = oio::PageLister<B2Lister>;
265    type Deleter = oio::OneShotDeleter<B2Deleter>;
266
267    fn info(&self) -> Arc<AccessorInfo> {
268        self.core.info.clone()
269    }
270
271    /// B2 have a get_file_info api required a file_id field, but field_id need call list api, list api also return file info
272    /// So we call list api to get file info
273    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
274        // Stat root always returns a DIR.
275        if path == "/" {
276            return Ok(RpStat::new(Metadata::new(EntryMode::DIR)));
277        }
278
279        let delimiter = if path.ends_with('/') { Some("/") } else { None };
280
281        let file_info = self.core.get_file_info(path, delimiter).await?;
282        let meta = parse_file_info(&file_info);
283        Ok(RpStat::new(meta))
284    }
285
286    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
287        let resp = self
288            .core
289            .download_file_by_name(path, args.range(), &args)
290            .await?;
291
292        let status = resp.status();
293        match status {
294            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
295                Ok((RpRead::default(), resp.into_body()))
296            }
297            _ => {
298                let (part, mut body) = resp.into_parts();
299                let buf = body.to_buffer().await?;
300                Err(parse_error(Response::from_parts(part, buf)))
301            }
302        }
303    }
304
305    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
306        let concurrent = args.concurrent();
307        let writer = B2Writer::new(self.core.clone(), path, args);
308
309        let w = oio::MultipartWriter::new(self.core.info.clone(), writer, concurrent);
310
311        Ok((RpWrite::default(), w))
312    }
313
314    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
315        Ok((
316            RpDelete::default(),
317            oio::OneShotDeleter::new(B2Deleter::new(self.core.clone())),
318        ))
319    }
320
321    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
322        Ok((
323            RpList::default(),
324            oio::PageLister::new(B2Lister::new(
325                self.core.clone(),
326                path,
327                args.recursive(),
328                args.limit(),
329                args.start_after(),
330            )),
331        ))
332    }
333
334    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
335        let file_info = self.core.get_file_info(from, None).await?;
336
337        let source_file_id = file_info.file_id;
338
339        let Some(source_file_id) = source_file_id else {
340            return Err(Error::new(ErrorKind::IsADirectory, "is a directory"));
341        };
342
343        let resp = self.core.copy_file(source_file_id, to).await?;
344
345        let status = resp.status();
346
347        match status {
348            StatusCode::OK => Ok(RpCopy::default()),
349            _ => Err(parse_error(resp)),
350        }
351    }
352
353    async fn presign(&self, path: &str, args: OpPresign) -> Result<RpPresign> {
354        match args.operation() {
355            PresignOperation::Stat(_) => {
356                let resp = self
357                    .core
358                    .get_download_authorization(path, args.expire())
359                    .await?;
360                let path = build_abs_path(&self.core.root, path);
361
362                let auth_info = self.core.get_auth_info().await?;
363
364                let url = format!(
365                    "{}/file/{}/{}?Authorization={}",
366                    auth_info.download_url, self.core.bucket, path, resp.authorization_token
367                );
368
369                let req = Request::get(url);
370
371                let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
372
373                // We don't need this request anymore, consume
374                let (parts, _) = req.into_parts();
375
376                Ok(RpPresign::new(PresignedRequest::new(
377                    parts.method,
378                    parts.uri,
379                    parts.headers,
380                )))
381            }
382            PresignOperation::Read(_) => {
383                let resp = self
384                    .core
385                    .get_download_authorization(path, args.expire())
386                    .await?;
387                let path = build_abs_path(&self.core.root, path);
388
389                let auth_info = self.core.get_auth_info().await?;
390
391                let url = format!(
392                    "{}/file/{}/{}?Authorization={}",
393                    auth_info.download_url, self.core.bucket, path, resp.authorization_token
394                );
395
396                let req = Request::get(url);
397
398                let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
399
400                // We don't need this request anymore, consume
401                let (parts, _) = req.into_parts();
402
403                Ok(RpPresign::new(PresignedRequest::new(
404                    parts.method,
405                    parts.uri,
406                    parts.headers,
407                )))
408            }
409            PresignOperation::Write(_) => {
410                let resp = self.core.get_upload_url().await?;
411
412                let mut req = Request::post(&resp.upload_url);
413
414                req = req.header(http::header::AUTHORIZATION, resp.authorization_token);
415                req = req.header("X-Bz-File-Name", build_abs_path(&self.core.root, path));
416                req = req.header(http::header::CONTENT_TYPE, "b2/x-auto");
417                req = req.header(constants::X_BZ_CONTENT_SHA1, "do_not_verify");
418
419                let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
420                // We don't need this request anymore, consume it directly.
421                let (parts, _) = req.into_parts();
422
423                Ok(RpPresign::new(PresignedRequest::new(
424                    parts.method,
425                    parts.uri,
426                    parts.headers,
427                )))
428            }
429            PresignOperation::Delete(_) => Err(Error::new(
430                ErrorKind::Unsupported,
431                "operation is not supported",
432            )),
433        }
434    }
435}