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                            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                            // The min multipart size of b2 is 5 MiB.
210                            //
211                            // ref: <https://www.backblaze.com/docs/cloud-storage-large-files>
212                            write_multi_min_size: Some(5 * 1024 * 1024),
213                            // The max multipart size of b2 is 5 Gb.
214                            //
215                            // ref: <https://www.backblaze.com/docs/cloud-storage-large-files>
216                            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 api here for compatibility
244                    #[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/// Backend for b2 services.
262#[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    type BlockingReader = ();
273    type BlockingWriter = ();
274    type BlockingLister = ();
275    type BlockingDeleter = ();
276
277    fn info(&self) -> Arc<AccessorInfo> {
278        self.core.info.clone()
279    }
280
281    /// 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
282    /// So we call list api to get file info
283    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
284        // Stat root always returns a DIR.
285        if path == "/" {
286            return Ok(RpStat::new(Metadata::new(EntryMode::DIR)));
287        }
288
289        let delimiter = if path.ends_with('/') { Some("/") } else { None };
290
291        let file_info = self.core.get_file_info(path, delimiter).await?;
292        let meta = parse_file_info(&file_info);
293        Ok(RpStat::new(meta))
294    }
295
296    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
297        let resp = self
298            .core
299            .download_file_by_name(path, args.range(), &args)
300            .await?;
301
302        let status = resp.status();
303        match status {
304            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
305                Ok((RpRead::default(), resp.into_body()))
306            }
307            _ => {
308                let (part, mut body) = resp.into_parts();
309                let buf = body.to_buffer().await?;
310                Err(parse_error(Response::from_parts(part, buf)))
311            }
312        }
313    }
314
315    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
316        let concurrent = args.concurrent();
317        let writer = B2Writer::new(self.core.clone(), path, args);
318
319        let w = oio::MultipartWriter::new(self.core.info.clone(), writer, concurrent);
320
321        Ok((RpWrite::default(), w))
322    }
323
324    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
325        Ok((
326            RpDelete::default(),
327            oio::OneShotDeleter::new(B2Deleter::new(self.core.clone())),
328        ))
329    }
330
331    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
332        Ok((
333            RpList::default(),
334            oio::PageLister::new(B2Lister::new(
335                self.core.clone(),
336                path,
337                args.recursive(),
338                args.limit(),
339                args.start_after(),
340            )),
341        ))
342    }
343
344    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
345        let file_info = self.core.get_file_info(from, None).await?;
346
347        let source_file_id = file_info.file_id;
348
349        let Some(source_file_id) = source_file_id else {
350            return Err(Error::new(ErrorKind::IsADirectory, "is a directory"));
351        };
352
353        let resp = self.core.copy_file(source_file_id, to).await?;
354
355        let status = resp.status();
356
357        match status {
358            StatusCode::OK => Ok(RpCopy::default()),
359            _ => Err(parse_error(resp)),
360        }
361    }
362
363    async fn presign(&self, path: &str, args: OpPresign) -> Result<RpPresign> {
364        match args.operation() {
365            PresignOperation::Stat(_) => {
366                let resp = self
367                    .core
368                    .get_download_authorization(path, args.expire())
369                    .await?;
370                let path = build_abs_path(&self.core.root, path);
371
372                let auth_info = self.core.get_auth_info().await?;
373
374                let url = format!(
375                    "{}/file/{}/{}?Authorization={}",
376                    auth_info.download_url, self.core.bucket, path, resp.authorization_token
377                );
378
379                let req = Request::get(url);
380
381                let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
382
383                // We don't need this request anymore, consume
384                let (parts, _) = req.into_parts();
385
386                Ok(RpPresign::new(PresignedRequest::new(
387                    parts.method,
388                    parts.uri,
389                    parts.headers,
390                )))
391            }
392            PresignOperation::Read(_) => {
393                let resp = self
394                    .core
395                    .get_download_authorization(path, args.expire())
396                    .await?;
397                let path = build_abs_path(&self.core.root, path);
398
399                let auth_info = self.core.get_auth_info().await?;
400
401                let url = format!(
402                    "{}/file/{}/{}?Authorization={}",
403                    auth_info.download_url, self.core.bucket, path, resp.authorization_token
404                );
405
406                let req = Request::get(url);
407
408                let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
409
410                // We don't need this request anymore, consume
411                let (parts, _) = req.into_parts();
412
413                Ok(RpPresign::new(PresignedRequest::new(
414                    parts.method,
415                    parts.uri,
416                    parts.headers,
417                )))
418            }
419            PresignOperation::Write(_) => {
420                let resp = self.core.get_upload_url().await?;
421
422                let mut req = Request::post(&resp.upload_url);
423
424                req = req.header(http::header::AUTHORIZATION, resp.authorization_token);
425                req = req.header("X-Bz-File-Name", build_abs_path(&self.core.root, path));
426                req = req.header(http::header::CONTENT_TYPE, "b2/x-auto");
427                req = req.header(constants::X_BZ_CONTENT_SHA1, "do_not_verify");
428
429                let req = req.body(Buffer::new()).map_err(new_request_build_error)?;
430                // We don't need this request anymore, consume it directly.
431                let (parts, _) = req.into_parts();
432
433                Ok(RpPresign::new(PresignedRequest::new(
434                    parts.method,
435                    parts.uri,
436                    parts.headers,
437                )))
438            }
439            PresignOperation::Delete(_) => Err(Error::new(
440                ErrorKind::Unsupported,
441                "operation is not supported",
442            )),
443        }
444    }
445}