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::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/// [b2](https://www.backblaze.com/cloud-storage) services support.
42#[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    /// Set root of this backend.
61    ///
62    /// All operations will happen under this root.
63    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    /// application_key_id of this backend.
74    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    /// application_key of this backend.
85    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    /// Set bucket name of this backend.
96    /// You can find it in <https://secure.backblaze.com/b2_buckets.html>
97    pub fn bucket(mut self, bucket: &str) -> Self {
98        self.config.bucket = bucket.to_string();
99
100        self
101    }
102
103    /// Set bucket id of this backend.
104    /// You can find it in <https://secure.backblaze.com/b2_buckets.html>
105    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    /// Specify the http client that used by this service.
112    ///
113    /// # Notes
114    ///
115    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
116    /// during minor updates.
117    #[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    /// Builds the backend and returns the result of B2Backend.
129    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        // Handle bucket.
136        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        // Handle bucket_id.
145        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                            // The min multipart size of b2 is 5 MiB.
193                            //
194                            // ref: <https://www.backblaze.com/docs/cloud-storage-large-files>
195                            write_multi_min_size: Some(5 * 1024 * 1024),
196                            // The max multipart size of b2 is 5 Gb.
197                            //
198                            // ref: <https://www.backblaze.com/docs/cloud-storage-large-files>
199                            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 api here for compatibility
224                    #[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/// Backend for b2 services.
242#[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    /// 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
258    /// So we call list api to get file info
259    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
260        // Stat root always returns a DIR.
261        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                // We don't need this request anymore, consume
360                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                // We don't need this request anymore, consume
387                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                // We don't need this request anymore, consume it directly.
407                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}