Xuanwo commented on code in PR #3604:
URL: 
https://github.com/apache/incubator-opendal/pull/3604#discussion_r1397314107


##########
core/src/services/b2/backend.rs:
##########
@@ -0,0 +1,553 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::fmt::Formatter;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::Request;
+use http::StatusCode;
+use log::debug;
+use serde::Deserialize;
+use tokio::sync::Mutex;
+
+use crate::raw::*;
+use crate::services::b2::core::B2Signer;
+use crate::services::b2::core::ListFileNamesResponse;
+use crate::*;
+
+use super::core::constants;
+use super::core::B2Core;
+use super::error::parse_error;
+use super::lister::B2Lister;
+use super::writer::B2Writer;
+use super::writer::B2Writers;
+
+/// Config for backblaze b2 services support.
+#[derive(Default, Deserialize)]
+#[serde(default)]
+#[non_exhaustive]
+pub struct B2Config {
+    /// root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub root: Option<String>,
+    /// keyID of this backend.
+    ///
+    /// - If key_id is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub key_id: Option<String>,
+    /// applicationKey of this backend.
+    ///
+    /// - If application_key is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub application_key: Option<String>,
+    /// bucket of this backend.
+    ///
+    /// required.
+    pub bucket: String,
+    /// bucket id of this backend.
+    ///
+    /// required.
+    pub bucket_id: String,
+}
+
+impl Debug for B2Config {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("B2Config");
+
+        d.field("root", &self.root)
+            .field("key_id", &self.key_id)
+            .field("application_key", &self.application_key)

Review Comment:
   Please don't leak `application_key` in config's debug.



##########
core/src/services/b2/backend.rs:
##########
@@ -0,0 +1,553 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::fmt::Formatter;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::Request;
+use http::StatusCode;
+use log::debug;
+use serde::Deserialize;
+use tokio::sync::Mutex;
+
+use crate::raw::*;
+use crate::services::b2::core::B2Signer;
+use crate::services::b2::core::ListFileNamesResponse;
+use crate::*;
+
+use super::core::constants;
+use super::core::B2Core;
+use super::error::parse_error;
+use super::lister::B2Lister;
+use super::writer::B2Writer;
+use super::writer::B2Writers;
+
+/// Config for backblaze b2 services support.
+#[derive(Default, Deserialize)]
+#[serde(default)]
+#[non_exhaustive]
+pub struct B2Config {
+    /// root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub root: Option<String>,
+    /// keyID of this backend.
+    ///
+    /// - If key_id is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub key_id: Option<String>,
+    /// applicationKey of this backend.
+    ///
+    /// - If application_key is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub application_key: Option<String>,
+    /// bucket of this backend.
+    ///
+    /// required.
+    pub bucket: String,
+    /// bucket id of this backend.
+    ///
+    /// required.
+    pub bucket_id: String,
+}
+
+impl Debug for B2Config {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("B2Config");
+
+        d.field("root", &self.root)
+            .field("key_id", &self.key_id)
+            .field("application_key", &self.application_key)
+            .field("bucket", &self.bucket);
+
+        d.finish_non_exhaustive()
+    }
+}
+
+/// [b2](https://www.backblaze.com/cloud-storage) services support.
+#[doc = include_str!("docs.md")]
+#[derive(Default)]
+pub struct B2Builder {
+    config: B2Config,
+
+    http_client: Option<HttpClient>,
+}
+
+impl Debug for B2Builder {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("AlluxioBuilder");

Review Comment:
   typo



##########
core/src/services/b2/backend.rs:
##########
@@ -0,0 +1,553 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::fmt::Formatter;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::Request;
+use http::StatusCode;
+use log::debug;
+use serde::Deserialize;
+use tokio::sync::Mutex;
+
+use crate::raw::*;
+use crate::services::b2::core::B2Signer;
+use crate::services::b2::core::ListFileNamesResponse;
+use crate::*;
+
+use super::core::constants;
+use super::core::B2Core;
+use super::error::parse_error;
+use super::lister::B2Lister;
+use super::writer::B2Writer;
+use super::writer::B2Writers;
+
+/// Config for backblaze b2 services support.
+#[derive(Default, Deserialize)]
+#[serde(default)]
+#[non_exhaustive]
+pub struct B2Config {
+    /// root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub root: Option<String>,
+    /// keyID of this backend.
+    ///
+    /// - If key_id is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub key_id: Option<String>,
+    /// applicationKey of this backend.
+    ///
+    /// - If application_key is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub application_key: Option<String>,
+    /// bucket of this backend.
+    ///
+    /// required.
+    pub bucket: String,
+    /// bucket id of this backend.
+    ///
+    /// required.
+    pub bucket_id: String,
+}
+
+impl Debug for B2Config {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("B2Config");
+
+        d.field("root", &self.root)
+            .field("key_id", &self.key_id)
+            .field("application_key", &self.application_key)
+            .field("bucket", &self.bucket);
+
+        d.finish_non_exhaustive()
+    }
+}
+
+/// [b2](https://www.backblaze.com/cloud-storage) services support.
+#[doc = include_str!("docs.md")]
+#[derive(Default)]
+pub struct B2Builder {
+    config: B2Config,
+
+    http_client: Option<HttpClient>,
+}
+
+impl Debug for B2Builder {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("AlluxioBuilder");
+
+        d.field("config", &self.config);
+        d.finish_non_exhaustive()
+    }
+}
+
+impl B2Builder {
+    /// Set root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub fn root(&mut self, root: &str) -> &mut Self {
+        self.config.root = if root.is_empty() {
+            None
+        } else {
+            Some(root.to_string())
+        };
+
+        self
+    }
+
+    /// key_id of this backend.
+    pub fn key_id(&mut self, key_id: &str) -> &mut Self {
+        self.config.key_id = if key_id.is_empty() {
+            None
+        } else {
+            Some(key_id.to_string())
+        };
+
+        self
+    }
+
+    /// application_key of this backend.
+    pub fn application_key(&mut self, application_key: &str) -> &mut Self {
+        self.config.application_key = if application_key.is_empty() {
+            None
+        } else {
+            Some(application_key.to_string())
+        };
+
+        self
+    }
+
+    /// Set bucket name of this backend.
+    pub fn bucket(&mut self, bucket: &str) -> &mut Self {
+        self.config.bucket = bucket.to_string();
+
+        self
+    }
+
+    /// Set bucket id of this backend.
+    pub fn bucket_id(&mut self, bucket_id: &str) -> &mut Self {
+        self.config.bucket_id = bucket_id.to_string();
+
+        self
+    }
+
+    /// Specify the http client that used by this service.
+    ///
+    /// # Notes
+    ///
+    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
+    /// during minor updates.
+    pub fn http_client(&mut self, client: HttpClient) -> &mut Self {
+        self.http_client = Some(client);
+        self
+    }
+}
+
+impl Builder for B2Builder {
+    const SCHEME: Scheme = Scheme::B2;
+    type Accessor = B2Backend;
+
+    /// Converts a HashMap into an B2Builder instance.
+    ///
+    /// # Arguments
+    ///
+    /// * `map` - A HashMap containing the configuration values.
+    ///
+    /// # Returns
+    ///
+    /// Returns an instance of B2Builder.
+    fn from_map(map: HashMap<String, String>) -> Self {
+        // Deserialize the configuration from the HashMap.
+        let config = B2Config::deserialize(ConfigDeserializer::new(map))
+            .expect("config deserialize must succeed");
+
+        // Create an B2Builder instance with the deserialized config.
+        B2Builder {
+            config,
+            http_client: None,
+        }
+    }
+
+    /// Builds the backend and returns the result of B2Backend.
+    fn build(&mut self) -> Result<Self::Accessor> {
+        debug!("backend build started: {:?}", &self);
+
+        let root = 
normalize_root(&self.config.root.clone().unwrap_or_default());
+        debug!("backend use root {}", &root);
+
+        // Handle bucket.
+        if self.config.bucket.is_empty() {
+            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket is empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2));
+        }
+
+        debug!("backend use bucket {}", &self.config.bucket);
+
+        // Handle bucket_id.
+        if self.config.bucket_id.is_empty() {
+            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is 
empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2));
+        }
+
+        debug!("backend bucket_id {}", &self.config.bucket_id);
+
+        let key_id = match &self.config.key_id {
+            Some(key_id) => Ok(key_id.clone()),
+            None => Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is 
empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2)),
+        }?;
+
+        let application_key = match &self.config.application_key {
+            Some(key_id) => Ok(key_id.clone()),
+            None => Err(
+                Error::new(ErrorKind::ConfigInvalid, "application_key is 
empty")
+                    .with_operation("Builder::build")
+                    .with_context("service", Scheme::B2),
+            ),
+        }?;
+
+        let client = if let Some(client) = self.http_client.take() {
+            client
+        } else {
+            HttpClient::new().map_err(|err| {
+                err.with_operation("Builder::build")
+                    .with_context("service", Scheme::Alluxio)
+            })?
+        };
+
+        let cluster_number = key_id[0..3].to_string();
+
+        let api_url = format!("https://api{}.backblazeb2.com";, cluster_number);
+        let download_url = format!("https://f{}.backblazeb2.com";, 
cluster_number);
+
+        let signer = B2Signer {
+            key_id,
+            application_key,
+            ..Default::default()
+        };
+
+        Ok(B2Backend {
+            core: Arc::new(B2Core {
+                signer: Arc::new(Mutex::new(signer)),
+                root,
+                api_url,
+                download_url,
+
+                bucket: self.config.bucket.clone(),
+                bucket_id: self.config.bucket_id.clone(),
+                client,
+            }),
+        })
+    }
+}
+
+/// Backend for s3 services.
+#[derive(Debug, Clone)]
+pub struct B2Backend {
+    core: Arc<B2Core>,
+}
+
+#[async_trait]
+impl Accessor for B2Backend {
+    type Reader = IncomingAsyncBody;
+
+    type BlockingReader = ();
+
+    type Writer = B2Writers;
+
+    type BlockingWriter = ();
+
+    type Lister = oio::PageLister<B2Lister>;
+
+    type BlockingLister = ();
+
+    fn info(&self) -> AccessorInfo {
+        let mut am = AccessorInfo::default();
+        am.set_scheme(Scheme::B2)
+            .set_root(&self.core.root)
+            .set_native_capability(Capability {
+                stat: true,
+
+                read: true,
+                read_can_next: true,
+                read_with_range: true,
+                read_with_if_match: false,
+                read_with_if_none_match: false,
+                read_with_override_cache_control: false,
+                read_with_override_content_disposition: false,
+                read_with_override_content_type: false,
+
+                write: true,
+                write_can_empty: true,
+                write_can_multi: true,
+                // write_with_cache_control: true,

Review Comment:
   The same.



##########
core/src/services/b2/backend.rs:
##########
@@ -0,0 +1,553 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::fmt::Formatter;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::Request;
+use http::StatusCode;
+use log::debug;
+use serde::Deserialize;
+use tokio::sync::Mutex;
+
+use crate::raw::*;
+use crate::services::b2::core::B2Signer;
+use crate::services::b2::core::ListFileNamesResponse;
+use crate::*;
+
+use super::core::constants;
+use super::core::B2Core;
+use super::error::parse_error;
+use super::lister::B2Lister;
+use super::writer::B2Writer;
+use super::writer::B2Writers;
+
+/// Config for backblaze b2 services support.
+#[derive(Default, Deserialize)]
+#[serde(default)]
+#[non_exhaustive]
+pub struct B2Config {
+    /// root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub root: Option<String>,
+    /// keyID of this backend.
+    ///
+    /// - If key_id is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub key_id: Option<String>,
+    /// applicationKey of this backend.
+    ///
+    /// - If application_key is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub application_key: Option<String>,
+    /// bucket of this backend.
+    ///
+    /// required.
+    pub bucket: String,
+    /// bucket id of this backend.
+    ///
+    /// required.
+    pub bucket_id: String,
+}
+
+impl Debug for B2Config {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("B2Config");
+
+        d.field("root", &self.root)
+            .field("key_id", &self.key_id)
+            .field("application_key", &self.application_key)
+            .field("bucket", &self.bucket);
+
+        d.finish_non_exhaustive()
+    }
+}
+
+/// [b2](https://www.backblaze.com/cloud-storage) services support.
+#[doc = include_str!("docs.md")]
+#[derive(Default)]
+pub struct B2Builder {
+    config: B2Config,
+
+    http_client: Option<HttpClient>,
+}
+
+impl Debug for B2Builder {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("AlluxioBuilder");
+
+        d.field("config", &self.config);
+        d.finish_non_exhaustive()
+    }
+}
+
+impl B2Builder {
+    /// Set root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub fn root(&mut self, root: &str) -> &mut Self {
+        self.config.root = if root.is_empty() {
+            None
+        } else {
+            Some(root.to_string())
+        };
+
+        self
+    }
+
+    /// key_id of this backend.
+    pub fn key_id(&mut self, key_id: &str) -> &mut Self {
+        self.config.key_id = if key_id.is_empty() {
+            None
+        } else {
+            Some(key_id.to_string())
+        };
+
+        self
+    }
+
+    /// application_key of this backend.
+    pub fn application_key(&mut self, application_key: &str) -> &mut Self {
+        self.config.application_key = if application_key.is_empty() {
+            None
+        } else {
+            Some(application_key.to_string())
+        };
+
+        self
+    }
+
+    /// Set bucket name of this backend.
+    pub fn bucket(&mut self, bucket: &str) -> &mut Self {
+        self.config.bucket = bucket.to_string();
+
+        self
+    }
+
+    /// Set bucket id of this backend.
+    pub fn bucket_id(&mut self, bucket_id: &str) -> &mut Self {
+        self.config.bucket_id = bucket_id.to_string();
+
+        self
+    }
+
+    /// Specify the http client that used by this service.
+    ///
+    /// # Notes
+    ///
+    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
+    /// during minor updates.
+    pub fn http_client(&mut self, client: HttpClient) -> &mut Self {
+        self.http_client = Some(client);
+        self
+    }
+}
+
+impl Builder for B2Builder {
+    const SCHEME: Scheme = Scheme::B2;
+    type Accessor = B2Backend;
+
+    /// Converts a HashMap into an B2Builder instance.
+    ///
+    /// # Arguments
+    ///
+    /// * `map` - A HashMap containing the configuration values.
+    ///
+    /// # Returns
+    ///
+    /// Returns an instance of B2Builder.
+    fn from_map(map: HashMap<String, String>) -> Self {
+        // Deserialize the configuration from the HashMap.
+        let config = B2Config::deserialize(ConfigDeserializer::new(map))
+            .expect("config deserialize must succeed");
+
+        // Create an B2Builder instance with the deserialized config.
+        B2Builder {
+            config,
+            http_client: None,
+        }
+    }
+
+    /// Builds the backend and returns the result of B2Backend.
+    fn build(&mut self) -> Result<Self::Accessor> {
+        debug!("backend build started: {:?}", &self);
+
+        let root = 
normalize_root(&self.config.root.clone().unwrap_or_default());
+        debug!("backend use root {}", &root);
+
+        // Handle bucket.
+        if self.config.bucket.is_empty() {
+            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket is empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2));
+        }
+
+        debug!("backend use bucket {}", &self.config.bucket);
+
+        // Handle bucket_id.
+        if self.config.bucket_id.is_empty() {
+            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is 
empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2));
+        }
+
+        debug!("backend bucket_id {}", &self.config.bucket_id);
+
+        let key_id = match &self.config.key_id {
+            Some(key_id) => Ok(key_id.clone()),
+            None => Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is 
empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2)),
+        }?;
+
+        let application_key = match &self.config.application_key {
+            Some(key_id) => Ok(key_id.clone()),
+            None => Err(
+                Error::new(ErrorKind::ConfigInvalid, "application_key is 
empty")
+                    .with_operation("Builder::build")
+                    .with_context("service", Scheme::B2),
+            ),
+        }?;
+
+        let client = if let Some(client) = self.http_client.take() {
+            client
+        } else {
+            HttpClient::new().map_err(|err| {
+                err.with_operation("Builder::build")
+                    .with_context("service", Scheme::Alluxio)
+            })?
+        };
+
+        let cluster_number = key_id[0..3].to_string();
+
+        let api_url = format!("https://api{}.backblazeb2.com";, cluster_number);
+        let download_url = format!("https://f{}.backblazeb2.com";, 
cluster_number);
+
+        let signer = B2Signer {
+            key_id,
+            application_key,
+            ..Default::default()
+        };
+
+        Ok(B2Backend {
+            core: Arc::new(B2Core {
+                signer: Arc::new(Mutex::new(signer)),
+                root,
+                api_url,
+                download_url,
+
+                bucket: self.config.bucket.clone(),
+                bucket_id: self.config.bucket_id.clone(),
+                client,
+            }),
+        })
+    }
+}
+
+/// Backend for s3 services.
+#[derive(Debug, Clone)]
+pub struct B2Backend {
+    core: Arc<B2Core>,
+}
+
+#[async_trait]
+impl Accessor for B2Backend {
+    type Reader = IncomingAsyncBody;
+
+    type BlockingReader = ();
+
+    type Writer = B2Writers;
+
+    type BlockingWriter = ();
+
+    type Lister = oio::PageLister<B2Lister>;
+
+    type BlockingLister = ();
+
+    fn info(&self) -> AccessorInfo {
+        let mut am = AccessorInfo::default();
+        am.set_scheme(Scheme::B2)
+            .set_root(&self.core.root)
+            .set_native_capability(Capability {
+                stat: true,
+
+                read: true,
+                read_can_next: true,
+                read_with_range: true,
+                read_with_if_match: false,
+                read_with_if_none_match: false,
+                read_with_override_cache_control: false,
+                read_with_override_content_disposition: false,
+                read_with_override_content_type: false,
+
+                write: true,
+                write_can_empty: true,
+                write_can_multi: true,
+                // write_with_cache_control: true,
+                write_with_content_type: true,
+                // The min multipart size of b2 is 5 MiB.
+                //
+                // ref: 
<https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html>
+                write_multi_min_size: Some(5 * 1024 * 1024),
+                // The max multipart size of b2 is 5 GiB.
+                //
+                // ref: 
<https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html>

Review Comment:
   ref is wrong.



##########
core/src/services/b2/backend.rs:
##########
@@ -0,0 +1,553 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::fmt::Formatter;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::Request;
+use http::StatusCode;
+use log::debug;
+use serde::Deserialize;
+use tokio::sync::Mutex;
+
+use crate::raw::*;
+use crate::services::b2::core::B2Signer;
+use crate::services::b2::core::ListFileNamesResponse;
+use crate::*;
+
+use super::core::constants;
+use super::core::B2Core;
+use super::error::parse_error;
+use super::lister::B2Lister;
+use super::writer::B2Writer;
+use super::writer::B2Writers;
+
+/// Config for backblaze b2 services support.
+#[derive(Default, Deserialize)]
+#[serde(default)]
+#[non_exhaustive]
+pub struct B2Config {
+    /// root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub root: Option<String>,
+    /// keyID of this backend.
+    ///
+    /// - If key_id is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub key_id: Option<String>,
+    /// applicationKey of this backend.
+    ///
+    /// - If application_key is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub application_key: Option<String>,
+    /// bucket of this backend.
+    ///
+    /// required.
+    pub bucket: String,
+    /// bucket id of this backend.
+    ///
+    /// required.
+    pub bucket_id: String,
+}
+
+impl Debug for B2Config {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("B2Config");
+
+        d.field("root", &self.root)
+            .field("key_id", &self.key_id)
+            .field("application_key", &self.application_key)
+            .field("bucket", &self.bucket);
+
+        d.finish_non_exhaustive()
+    }
+}
+
+/// [b2](https://www.backblaze.com/cloud-storage) services support.
+#[doc = include_str!("docs.md")]
+#[derive(Default)]
+pub struct B2Builder {
+    config: B2Config,
+
+    http_client: Option<HttpClient>,
+}
+
+impl Debug for B2Builder {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("AlluxioBuilder");
+
+        d.field("config", &self.config);
+        d.finish_non_exhaustive()
+    }
+}
+
+impl B2Builder {
+    /// Set root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub fn root(&mut self, root: &str) -> &mut Self {
+        self.config.root = if root.is_empty() {
+            None
+        } else {
+            Some(root.to_string())
+        };
+
+        self
+    }
+
+    /// key_id of this backend.
+    pub fn key_id(&mut self, key_id: &str) -> &mut Self {
+        self.config.key_id = if key_id.is_empty() {
+            None
+        } else {
+            Some(key_id.to_string())
+        };
+
+        self
+    }
+
+    /// application_key of this backend.
+    pub fn application_key(&mut self, application_key: &str) -> &mut Self {
+        self.config.application_key = if application_key.is_empty() {
+            None
+        } else {
+            Some(application_key.to_string())
+        };
+
+        self
+    }
+
+    /// Set bucket name of this backend.
+    pub fn bucket(&mut self, bucket: &str) -> &mut Self {
+        self.config.bucket = bucket.to_string();
+
+        self
+    }
+
+    /// Set bucket id of this backend.
+    pub fn bucket_id(&mut self, bucket_id: &str) -> &mut Self {
+        self.config.bucket_id = bucket_id.to_string();
+
+        self
+    }
+
+    /// Specify the http client that used by this service.
+    ///
+    /// # Notes
+    ///
+    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
+    /// during minor updates.
+    pub fn http_client(&mut self, client: HttpClient) -> &mut Self {
+        self.http_client = Some(client);
+        self
+    }
+}
+
+impl Builder for B2Builder {
+    const SCHEME: Scheme = Scheme::B2;
+    type Accessor = B2Backend;
+
+    /// Converts a HashMap into an B2Builder instance.
+    ///
+    /// # Arguments
+    ///
+    /// * `map` - A HashMap containing the configuration values.
+    ///
+    /// # Returns
+    ///
+    /// Returns an instance of B2Builder.
+    fn from_map(map: HashMap<String, String>) -> Self {
+        // Deserialize the configuration from the HashMap.
+        let config = B2Config::deserialize(ConfigDeserializer::new(map))
+            .expect("config deserialize must succeed");
+
+        // Create an B2Builder instance with the deserialized config.
+        B2Builder {
+            config,
+            http_client: None,
+        }
+    }
+
+    /// Builds the backend and returns the result of B2Backend.
+    fn build(&mut self) -> Result<Self::Accessor> {
+        debug!("backend build started: {:?}", &self);
+
+        let root = 
normalize_root(&self.config.root.clone().unwrap_or_default());
+        debug!("backend use root {}", &root);
+
+        // Handle bucket.
+        if self.config.bucket.is_empty() {
+            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket is empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2));
+        }
+
+        debug!("backend use bucket {}", &self.config.bucket);
+
+        // Handle bucket_id.
+        if self.config.bucket_id.is_empty() {
+            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is 
empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2));
+        }
+
+        debug!("backend bucket_id {}", &self.config.bucket_id);
+
+        let key_id = match &self.config.key_id {
+            Some(key_id) => Ok(key_id.clone()),
+            None => Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is 
empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2)),
+        }?;
+
+        let application_key = match &self.config.application_key {
+            Some(key_id) => Ok(key_id.clone()),
+            None => Err(
+                Error::new(ErrorKind::ConfigInvalid, "application_key is 
empty")
+                    .with_operation("Builder::build")
+                    .with_context("service", Scheme::B2),
+            ),
+        }?;
+
+        let client = if let Some(client) = self.http_client.take() {
+            client
+        } else {
+            HttpClient::new().map_err(|err| {
+                err.with_operation("Builder::build")
+                    .with_context("service", Scheme::Alluxio)
+            })?
+        };
+
+        let cluster_number = key_id[0..3].to_string();

Review Comment:
   Interesting.



##########
core/src/services/b2/writer.rs:
##########
@@ -0,0 +1,164 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::StatusCode;
+
+use crate::raw::*;
+use crate::*;
+
+use super::core::{B2Core, StartLargeFileResponse, UploadPartResponse};
+use super::error::parse_error;
+
+pub type B2Writers = oio::MultipartUploadWriter<B2Writer>;
+
+pub struct B2Writer {
+    core: Arc<B2Core>,
+
+    op: OpWrite,
+    path: String,
+}
+
+impl B2Writer {
+    pub fn new(core: Arc<B2Core>, path: &str, op: OpWrite) -> Self {
+        B2Writer {
+            core,
+            path: path.to_string(),
+            op,
+        }
+    }
+}
+
+#[async_trait]
+impl oio::MultipartUploadWrite for B2Writer {
+    async fn write_once(&self, size: u64, body: AsyncBody) -> Result<()> {
+        let resp = self
+            .core
+            .upload_file(&self.path, Some(size), &self.op, body)
+            .await?;
+
+        let status = resp.status();
+
+        match status {
+            StatusCode::OK => {
+                resp.into_body().consume().await?;
+                Ok(())
+            }
+            _ => Err(parse_error(resp).await?),
+        }
+    }
+
+    async fn initiate_part(&self) -> Result<String> {
+        let resp = self.core.start_large_file(&self.path, &self.op).await?;
+
+        let status = resp.status();
+
+        match status {
+            StatusCode::OK => {
+                let bs = resp.into_body().bytes().await?;
+
+                let result: StartLargeFileResponse =
+                    serde_json::from_reader(bytes::Buf::reader(bs))
+                        .map_err(new_json_deserialize_error)?;
+
+                Ok(result.file_id)
+            }
+            _ => Err(parse_error(resp).await?),
+        }
+    }
+
+    async fn write_part(
+        &self,
+        upload_id: &str,
+        part_number: usize,
+        size: u64,
+        body: AsyncBody,
+    ) -> Result<oio::MultipartUploadPart> {
+        // AWS S3 requires part number must between [1..=10000]

Review Comment:
   wrong comment



##########
core/src/services/b2/writer.rs:
##########
@@ -0,0 +1,164 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::StatusCode;
+
+use crate::raw::*;
+use crate::*;
+
+use super::core::{B2Core, StartLargeFileResponse, UploadPartResponse};
+use super::error::parse_error;
+
+pub type B2Writers = oio::MultipartUploadWriter<B2Writer>;
+
+pub struct B2Writer {
+    core: Arc<B2Core>,
+
+    op: OpWrite,
+    path: String,
+}
+
+impl B2Writer {
+    pub fn new(core: Arc<B2Core>, path: &str, op: OpWrite) -> Self {
+        B2Writer {
+            core,
+            path: path.to_string(),
+            op,
+        }
+    }
+}
+
+#[async_trait]
+impl oio::MultipartUploadWrite for B2Writer {
+    async fn write_once(&self, size: u64, body: AsyncBody) -> Result<()> {
+        let resp = self
+            .core
+            .upload_file(&self.path, Some(size), &self.op, body)
+            .await?;
+
+        let status = resp.status();
+
+        match status {
+            StatusCode::OK => {
+                resp.into_body().consume().await?;
+                Ok(())
+            }
+            _ => Err(parse_error(resp).await?),
+        }
+    }
+
+    async fn initiate_part(&self) -> Result<String> {
+        let resp = self.core.start_large_file(&self.path, &self.op).await?;
+
+        let status = resp.status();
+
+        match status {
+            StatusCode::OK => {
+                let bs = resp.into_body().bytes().await?;
+
+                let result: StartLargeFileResponse =
+                    serde_json::from_reader(bytes::Buf::reader(bs))
+                        .map_err(new_json_deserialize_error)?;
+
+                Ok(result.file_id)
+            }
+            _ => Err(parse_error(resp).await?),
+        }
+    }
+
+    async fn write_part(
+        &self,
+        upload_id: &str,
+        part_number: usize,
+        size: u64,
+        body: AsyncBody,
+    ) -> Result<oio::MultipartUploadPart> {
+        // AWS S3 requires part number must between [1..=10000]
+        let part_number = part_number + 1;
+
+        let resp = self
+            .core
+            .upload_part(upload_id, part_number, size, body)
+            .await?;
+
+        let status = resp.status();
+
+        match status {
+            StatusCode::OK => {
+                let bs = resp.into_body().bytes().await?;
+
+                let result: UploadPartResponse = 
serde_json::from_reader(bytes::Buf::reader(bs))

Review Comment:
   Please use `serde_json::from_slice`



##########
core/src/services/b2/backend.rs:
##########
@@ -0,0 +1,553 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::fmt::Formatter;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::Request;
+use http::StatusCode;
+use log::debug;
+use serde::Deserialize;
+use tokio::sync::Mutex;
+
+use crate::raw::*;
+use crate::services::b2::core::B2Signer;
+use crate::services::b2::core::ListFileNamesResponse;
+use crate::*;
+
+use super::core::constants;
+use super::core::B2Core;
+use super::error::parse_error;
+use super::lister::B2Lister;
+use super::writer::B2Writer;
+use super::writer::B2Writers;
+
+/// Config for backblaze b2 services support.
+#[derive(Default, Deserialize)]
+#[serde(default)]
+#[non_exhaustive]
+pub struct B2Config {
+    /// root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub root: Option<String>,
+    /// keyID of this backend.
+    ///
+    /// - If key_id is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub key_id: Option<String>,
+    /// applicationKey of this backend.
+    ///
+    /// - If application_key is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub application_key: Option<String>,
+    /// bucket of this backend.
+    ///
+    /// required.
+    pub bucket: String,
+    /// bucket id of this backend.
+    ///
+    /// required.
+    pub bucket_id: String,
+}
+
+impl Debug for B2Config {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("B2Config");
+
+        d.field("root", &self.root)
+            .field("key_id", &self.key_id)
+            .field("application_key", &self.application_key)
+            .field("bucket", &self.bucket);
+
+        d.finish_non_exhaustive()
+    }
+}
+
+/// [b2](https://www.backblaze.com/cloud-storage) services support.
+#[doc = include_str!("docs.md")]
+#[derive(Default)]
+pub struct B2Builder {
+    config: B2Config,
+
+    http_client: Option<HttpClient>,
+}
+
+impl Debug for B2Builder {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("AlluxioBuilder");
+
+        d.field("config", &self.config);
+        d.finish_non_exhaustive()
+    }
+}
+
+impl B2Builder {
+    /// Set root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub fn root(&mut self, root: &str) -> &mut Self {
+        self.config.root = if root.is_empty() {
+            None
+        } else {
+            Some(root.to_string())
+        };
+
+        self
+    }
+
+    /// key_id of this backend.
+    pub fn key_id(&mut self, key_id: &str) -> &mut Self {
+        self.config.key_id = if key_id.is_empty() {
+            None
+        } else {
+            Some(key_id.to_string())
+        };
+
+        self
+    }
+
+    /// application_key of this backend.
+    pub fn application_key(&mut self, application_key: &str) -> &mut Self {
+        self.config.application_key = if application_key.is_empty() {
+            None
+        } else {
+            Some(application_key.to_string())
+        };
+
+        self
+    }
+
+    /// Set bucket name of this backend.
+    pub fn bucket(&mut self, bucket: &str) -> &mut Self {
+        self.config.bucket = bucket.to_string();
+
+        self
+    }
+
+    /// Set bucket id of this backend.

Review Comment:
   It's a bit confused for me to set `bucket` and `bucket_id`, would you like 
to add comments about what are they and how to get them?



##########
core/src/services/b2/backend.rs:
##########
@@ -0,0 +1,553 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::fmt::Formatter;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::Request;
+use http::StatusCode;
+use log::debug;
+use serde::Deserialize;
+use tokio::sync::Mutex;
+
+use crate::raw::*;
+use crate::services::b2::core::B2Signer;
+use crate::services::b2::core::ListFileNamesResponse;
+use crate::*;
+
+use super::core::constants;
+use super::core::B2Core;
+use super::error::parse_error;
+use super::lister::B2Lister;
+use super::writer::B2Writer;
+use super::writer::B2Writers;
+
+/// Config for backblaze b2 services support.
+#[derive(Default, Deserialize)]
+#[serde(default)]
+#[non_exhaustive]
+pub struct B2Config {
+    /// root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub root: Option<String>,
+    /// keyID of this backend.
+    ///
+    /// - If key_id is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub key_id: Option<String>,
+    /// applicationKey of this backend.
+    ///
+    /// - If application_key is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub application_key: Option<String>,
+    /// bucket of this backend.
+    ///
+    /// required.
+    pub bucket: String,
+    /// bucket id of this backend.
+    ///
+    /// required.
+    pub bucket_id: String,
+}
+
+impl Debug for B2Config {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("B2Config");
+
+        d.field("root", &self.root)
+            .field("key_id", &self.key_id)
+            .field("application_key", &self.application_key)
+            .field("bucket", &self.bucket);
+
+        d.finish_non_exhaustive()
+    }
+}
+
+/// [b2](https://www.backblaze.com/cloud-storage) services support.
+#[doc = include_str!("docs.md")]
+#[derive(Default)]
+pub struct B2Builder {
+    config: B2Config,
+
+    http_client: Option<HttpClient>,
+}
+
+impl Debug for B2Builder {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("AlluxioBuilder");
+
+        d.field("config", &self.config);
+        d.finish_non_exhaustive()
+    }
+}
+
+impl B2Builder {
+    /// Set root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub fn root(&mut self, root: &str) -> &mut Self {
+        self.config.root = if root.is_empty() {
+            None
+        } else {
+            Some(root.to_string())
+        };
+
+        self
+    }
+
+    /// key_id of this backend.
+    pub fn key_id(&mut self, key_id: &str) -> &mut Self {
+        self.config.key_id = if key_id.is_empty() {
+            None
+        } else {
+            Some(key_id.to_string())
+        };
+
+        self
+    }
+
+    /// application_key of this backend.
+    pub fn application_key(&mut self, application_key: &str) -> &mut Self {
+        self.config.application_key = if application_key.is_empty() {
+            None
+        } else {
+            Some(application_key.to_string())
+        };
+
+        self
+    }
+
+    /// Set bucket name of this backend.
+    pub fn bucket(&mut self, bucket: &str) -> &mut Self {
+        self.config.bucket = bucket.to_string();
+
+        self
+    }
+
+    /// Set bucket id of this backend.
+    pub fn bucket_id(&mut self, bucket_id: &str) -> &mut Self {
+        self.config.bucket_id = bucket_id.to_string();
+
+        self
+    }
+
+    /// Specify the http client that used by this service.
+    ///
+    /// # Notes
+    ///
+    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
+    /// during minor updates.
+    pub fn http_client(&mut self, client: HttpClient) -> &mut Self {
+        self.http_client = Some(client);
+        self
+    }
+}
+
+impl Builder for B2Builder {
+    const SCHEME: Scheme = Scheme::B2;
+    type Accessor = B2Backend;
+
+    /// Converts a HashMap into an B2Builder instance.
+    ///
+    /// # Arguments
+    ///
+    /// * `map` - A HashMap containing the configuration values.
+    ///
+    /// # Returns
+    ///
+    /// Returns an instance of B2Builder.
+    fn from_map(map: HashMap<String, String>) -> Self {
+        // Deserialize the configuration from the HashMap.
+        let config = B2Config::deserialize(ConfigDeserializer::new(map))
+            .expect("config deserialize must succeed");
+
+        // Create an B2Builder instance with the deserialized config.
+        B2Builder {
+            config,
+            http_client: None,
+        }
+    }
+
+    /// Builds the backend and returns the result of B2Backend.
+    fn build(&mut self) -> Result<Self::Accessor> {
+        debug!("backend build started: {:?}", &self);
+
+        let root = 
normalize_root(&self.config.root.clone().unwrap_or_default());
+        debug!("backend use root {}", &root);
+
+        // Handle bucket.
+        if self.config.bucket.is_empty() {
+            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket is empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2));
+        }
+
+        debug!("backend use bucket {}", &self.config.bucket);
+
+        // Handle bucket_id.
+        if self.config.bucket_id.is_empty() {
+            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is 
empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2));
+        }
+
+        debug!("backend bucket_id {}", &self.config.bucket_id);
+
+        let key_id = match &self.config.key_id {
+            Some(key_id) => Ok(key_id.clone()),
+            None => Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is 
empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2)),
+        }?;
+
+        let application_key = match &self.config.application_key {
+            Some(key_id) => Ok(key_id.clone()),
+            None => Err(
+                Error::new(ErrorKind::ConfigInvalid, "application_key is 
empty")
+                    .with_operation("Builder::build")
+                    .with_context("service", Scheme::B2),
+            ),
+        }?;
+
+        let client = if let Some(client) = self.http_client.take() {
+            client
+        } else {
+            HttpClient::new().map_err(|err| {
+                err.with_operation("Builder::build")
+                    .with_context("service", Scheme::Alluxio)
+            })?
+        };
+
+        let cluster_number = key_id[0..3].to_string();
+
+        let api_url = format!("https://api{}.backblazeb2.com";, cluster_number);
+        let download_url = format!("https://f{}.backblazeb2.com";, 
cluster_number);
+
+        let signer = B2Signer {
+            key_id,
+            application_key,
+            ..Default::default()
+        };
+
+        Ok(B2Backend {
+            core: Arc::new(B2Core {
+                signer: Arc::new(Mutex::new(signer)),
+                root,
+                api_url,
+                download_url,
+
+                bucket: self.config.bucket.clone(),
+                bucket_id: self.config.bucket_id.clone(),
+                client,
+            }),
+        })
+    }
+}
+
+/// Backend for s3 services.
+#[derive(Debug, Clone)]
+pub struct B2Backend {
+    core: Arc<B2Core>,
+}
+
+#[async_trait]
+impl Accessor for B2Backend {
+    type Reader = IncomingAsyncBody;
+
+    type BlockingReader = ();
+
+    type Writer = B2Writers;
+
+    type BlockingWriter = ();
+
+    type Lister = oio::PageLister<B2Lister>;
+
+    type BlockingLister = ();
+
+    fn info(&self) -> AccessorInfo {
+        let mut am = AccessorInfo::default();
+        am.set_scheme(Scheme::B2)
+            .set_root(&self.core.root)
+            .set_native_capability(Capability {
+                stat: true,
+
+                read: true,
+                read_can_next: true,
+                read_with_range: true,
+                read_with_if_match: false,

Review Comment:
   We don't need to specify the field that are `false`



##########
core/src/services/b2/backend.rs:
##########
@@ -0,0 +1,553 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::fmt::Formatter;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::Request;
+use http::StatusCode;
+use log::debug;
+use serde::Deserialize;
+use tokio::sync::Mutex;
+
+use crate::raw::*;
+use crate::services::b2::core::B2Signer;
+use crate::services::b2::core::ListFileNamesResponse;
+use crate::*;
+
+use super::core::constants;
+use super::core::B2Core;
+use super::error::parse_error;
+use super::lister::B2Lister;
+use super::writer::B2Writer;
+use super::writer::B2Writers;
+
+/// Config for backblaze b2 services support.
+#[derive(Default, Deserialize)]
+#[serde(default)]
+#[non_exhaustive]
+pub struct B2Config {
+    /// root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub root: Option<String>,
+    /// keyID of this backend.
+    ///
+    /// - If key_id is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub key_id: Option<String>,
+    /// applicationKey of this backend.
+    ///
+    /// - If application_key is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub application_key: Option<String>,
+    /// bucket of this backend.
+    ///
+    /// required.
+    pub bucket: String,
+    /// bucket id of this backend.
+    ///
+    /// required.
+    pub bucket_id: String,
+}
+
+impl Debug for B2Config {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("B2Config");
+
+        d.field("root", &self.root)
+            .field("key_id", &self.key_id)
+            .field("application_key", &self.application_key)
+            .field("bucket", &self.bucket);
+
+        d.finish_non_exhaustive()
+    }
+}
+
+/// [b2](https://www.backblaze.com/cloud-storage) services support.
+#[doc = include_str!("docs.md")]
+#[derive(Default)]
+pub struct B2Builder {
+    config: B2Config,
+
+    http_client: Option<HttpClient>,
+}
+
+impl Debug for B2Builder {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("AlluxioBuilder");
+
+        d.field("config", &self.config);
+        d.finish_non_exhaustive()
+    }
+}
+
+impl B2Builder {
+    /// Set root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub fn root(&mut self, root: &str) -> &mut Self {
+        self.config.root = if root.is_empty() {
+            None
+        } else {
+            Some(root.to_string())
+        };
+
+        self
+    }
+
+    /// key_id of this backend.
+    pub fn key_id(&mut self, key_id: &str) -> &mut Self {
+        self.config.key_id = if key_id.is_empty() {
+            None
+        } else {
+            Some(key_id.to_string())
+        };
+
+        self
+    }
+
+    /// application_key of this backend.
+    pub fn application_key(&mut self, application_key: &str) -> &mut Self {
+        self.config.application_key = if application_key.is_empty() {
+            None
+        } else {
+            Some(application_key.to_string())
+        };
+
+        self
+    }
+
+    /// Set bucket name of this backend.
+    pub fn bucket(&mut self, bucket: &str) -> &mut Self {
+        self.config.bucket = bucket.to_string();
+
+        self
+    }
+
+    /// Set bucket id of this backend.
+    pub fn bucket_id(&mut self, bucket_id: &str) -> &mut Self {
+        self.config.bucket_id = bucket_id.to_string();
+
+        self
+    }
+
+    /// Specify the http client that used by this service.
+    ///
+    /// # Notes
+    ///
+    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
+    /// during minor updates.
+    pub fn http_client(&mut self, client: HttpClient) -> &mut Self {
+        self.http_client = Some(client);
+        self
+    }
+}
+
+impl Builder for B2Builder {
+    const SCHEME: Scheme = Scheme::B2;
+    type Accessor = B2Backend;
+
+    /// Converts a HashMap into an B2Builder instance.
+    ///
+    /// # Arguments
+    ///
+    /// * `map` - A HashMap containing the configuration values.
+    ///
+    /// # Returns
+    ///
+    /// Returns an instance of B2Builder.
+    fn from_map(map: HashMap<String, String>) -> Self {
+        // Deserialize the configuration from the HashMap.
+        let config = B2Config::deserialize(ConfigDeserializer::new(map))
+            .expect("config deserialize must succeed");
+
+        // Create an B2Builder instance with the deserialized config.
+        B2Builder {
+            config,
+            http_client: None,
+        }
+    }
+
+    /// Builds the backend and returns the result of B2Backend.
+    fn build(&mut self) -> Result<Self::Accessor> {
+        debug!("backend build started: {:?}", &self);
+
+        let root = 
normalize_root(&self.config.root.clone().unwrap_or_default());
+        debug!("backend use root {}", &root);
+
+        // Handle bucket.
+        if self.config.bucket.is_empty() {
+            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket is empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2));
+        }
+
+        debug!("backend use bucket {}", &self.config.bucket);
+
+        // Handle bucket_id.
+        if self.config.bucket_id.is_empty() {
+            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is 
empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2));
+        }
+
+        debug!("backend bucket_id {}", &self.config.bucket_id);
+
+        let key_id = match &self.config.key_id {
+            Some(key_id) => Ok(key_id.clone()),
+            None => Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is 
empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2)),
+        }?;
+
+        let application_key = match &self.config.application_key {
+            Some(key_id) => Ok(key_id.clone()),
+            None => Err(
+                Error::new(ErrorKind::ConfigInvalid, "application_key is 
empty")
+                    .with_operation("Builder::build")
+                    .with_context("service", Scheme::B2),
+            ),
+        }?;
+
+        let client = if let Some(client) = self.http_client.take() {
+            client
+        } else {
+            HttpClient::new().map_err(|err| {
+                err.with_operation("Builder::build")
+                    .with_context("service", Scheme::Alluxio)
+            })?
+        };
+
+        let cluster_number = key_id[0..3].to_string();
+
+        let api_url = format!("https://api{}.backblazeb2.com";, cluster_number);
+        let download_url = format!("https://f{}.backblazeb2.com";, 
cluster_number);
+
+        let signer = B2Signer {
+            key_id,
+            application_key,
+            ..Default::default()
+        };
+
+        Ok(B2Backend {
+            core: Arc::new(B2Core {
+                signer: Arc::new(Mutex::new(signer)),
+                root,
+                api_url,
+                download_url,
+
+                bucket: self.config.bucket.clone(),
+                bucket_id: self.config.bucket_id.clone(),
+                client,
+            }),
+        })
+    }
+}
+
+/// Backend for s3 services.
+#[derive(Debug, Clone)]
+pub struct B2Backend {
+    core: Arc<B2Core>,
+}
+
+#[async_trait]
+impl Accessor for B2Backend {
+    type Reader = IncomingAsyncBody;
+
+    type BlockingReader = ();
+
+    type Writer = B2Writers;
+
+    type BlockingWriter = ();
+
+    type Lister = oio::PageLister<B2Lister>;
+
+    type BlockingLister = ();
+
+    fn info(&self) -> AccessorInfo {
+        let mut am = AccessorInfo::default();
+        am.set_scheme(Scheme::B2)
+            .set_root(&self.core.root)
+            .set_native_capability(Capability {
+                stat: true,
+
+                read: true,
+                read_can_next: true,
+                read_with_range: true,
+                read_with_if_match: false,
+                read_with_if_none_match: false,
+                read_with_override_cache_control: false,
+                read_with_override_content_disposition: false,
+                read_with_override_content_type: false,
+
+                write: true,
+                write_can_empty: true,
+                write_can_multi: true,
+                // write_with_cache_control: true,
+                write_with_content_type: true,
+                // The min multipart size of b2 is 5 MiB.
+                //
+                // ref: 
<https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html>
+                write_multi_min_size: Some(5 * 1024 * 1024),
+                // The max multipart size of b2 is 5 GiB.
+                //
+                // ref: 
<https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html>
+                write_multi_max_size: if cfg!(target_pointer_width = "64") {
+                    Some(5 * 1024 * 1024 * 1024)
+                } else {
+                    Some(usize::MAX)
+                },
+
+                create_dir: true,
+                delete: true,
+                copy: true,
+
+                list: true,
+                list_with_limit: true,
+                list_with_start_after: true,
+                list_with_recursive: true,
+                list_without_recursive: true,
+
+                presign: true,
+                presign_read: true,
+                presign_write: true,
+                presign_stat: true,
+
+                ..Default::default()
+            });
+
+        am
+    }
+
+    async fn read(&self, path: &str, _args: OpRead) -> Result<(RpRead, 
Self::Reader)> {
+        let resp = self.core.download_file_by_name(path).await?;
+
+        let status = resp.status();
+
+        match status {
+            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
+                let size = parse_content_length(resp.headers())?;
+                Ok((RpRead::new().with_size(size), resp.into_body()))
+            }
+            StatusCode::RANGE_NOT_SATISFIABLE => Ok((RpRead::new(), 
IncomingAsyncBody::empty())),
+            _ => Err(parse_error(resp).await?),
+        }
+    }
+
+    async fn create_dir(&self, path: &str, _: OpCreateDir) -> 
Result<RpCreateDir> {
+        let resp: http::Response<IncomingAsyncBody> = self
+            .core
+            .upload_file(path, Some(0), &OpWrite::default(), AsyncBody::Empty)
+            .await?;
+
+        let status = resp.status();
+
+        match status {
+            StatusCode::OK => {
+                resp.into_body().consume().await?;
+                Ok(RpCreateDir::default())
+            }
+            _ => Err(parse_error(resp).await?),
+        }
+    }
+
+    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, 
Self::Writer)> {
+        let writer = B2Writer::new(self.core.clone(), path, args);
+
+        let w = oio::MultipartUploadWriter::new(writer);
+
+        Ok((RpWrite::default(), w))
+    }
+
+    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
+        let delimiter = if path.ends_with('/') { Some("/") } else { None };
+        let resp = self
+            .core
+            .list_file_names(Some(path), delimiter, None, None)

Review Comment:
   Using the `list` API to retrieve metadata seems a bit odd. Could you provide 
some explanation?



##########
core/src/services/b2/backend.rs:
##########
@@ -0,0 +1,553 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::fmt::Formatter;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::Request;
+use http::StatusCode;
+use log::debug;
+use serde::Deserialize;
+use tokio::sync::Mutex;
+
+use crate::raw::*;
+use crate::services::b2::core::B2Signer;
+use crate::services::b2::core::ListFileNamesResponse;
+use crate::*;
+
+use super::core::constants;
+use super::core::B2Core;
+use super::error::parse_error;
+use super::lister::B2Lister;
+use super::writer::B2Writer;
+use super::writer::B2Writers;
+
+/// Config for backblaze b2 services support.
+#[derive(Default, Deserialize)]
+#[serde(default)]
+#[non_exhaustive]
+pub struct B2Config {
+    /// root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub root: Option<String>,
+    /// keyID of this backend.
+    ///
+    /// - If key_id is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub key_id: Option<String>,
+    /// applicationKey of this backend.
+    ///
+    /// - If application_key is set, we will take user's input first.
+    /// - If not, we will try to load it from environment.
+    pub application_key: Option<String>,
+    /// bucket of this backend.
+    ///
+    /// required.
+    pub bucket: String,
+    /// bucket id of this backend.
+    ///
+    /// required.
+    pub bucket_id: String,
+}
+
+impl Debug for B2Config {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("B2Config");
+
+        d.field("root", &self.root)
+            .field("key_id", &self.key_id)
+            .field("application_key", &self.application_key)
+            .field("bucket", &self.bucket);
+
+        d.finish_non_exhaustive()
+    }
+}
+
+/// [b2](https://www.backblaze.com/cloud-storage) services support.
+#[doc = include_str!("docs.md")]
+#[derive(Default)]
+pub struct B2Builder {
+    config: B2Config,
+
+    http_client: Option<HttpClient>,
+}
+
+impl Debug for B2Builder {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        let mut d = f.debug_struct("AlluxioBuilder");
+
+        d.field("config", &self.config);
+        d.finish_non_exhaustive()
+    }
+}
+
+impl B2Builder {
+    /// Set root of this backend.
+    ///
+    /// All operations will happen under this root.
+    pub fn root(&mut self, root: &str) -> &mut Self {
+        self.config.root = if root.is_empty() {
+            None
+        } else {
+            Some(root.to_string())
+        };
+
+        self
+    }
+
+    /// key_id of this backend.
+    pub fn key_id(&mut self, key_id: &str) -> &mut Self {
+        self.config.key_id = if key_id.is_empty() {
+            None
+        } else {
+            Some(key_id.to_string())
+        };
+
+        self
+    }
+
+    /// application_key of this backend.
+    pub fn application_key(&mut self, application_key: &str) -> &mut Self {
+        self.config.application_key = if application_key.is_empty() {
+            None
+        } else {
+            Some(application_key.to_string())
+        };
+
+        self
+    }
+
+    /// Set bucket name of this backend.
+    pub fn bucket(&mut self, bucket: &str) -> &mut Self {
+        self.config.bucket = bucket.to_string();
+
+        self
+    }
+
+    /// Set bucket id of this backend.
+    pub fn bucket_id(&mut self, bucket_id: &str) -> &mut Self {
+        self.config.bucket_id = bucket_id.to_string();
+
+        self
+    }
+
+    /// Specify the http client that used by this service.
+    ///
+    /// # Notes
+    ///
+    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
+    /// during minor updates.
+    pub fn http_client(&mut self, client: HttpClient) -> &mut Self {
+        self.http_client = Some(client);
+        self
+    }
+}
+
+impl Builder for B2Builder {
+    const SCHEME: Scheme = Scheme::B2;
+    type Accessor = B2Backend;
+
+    /// Converts a HashMap into an B2Builder instance.
+    ///
+    /// # Arguments
+    ///
+    /// * `map` - A HashMap containing the configuration values.
+    ///
+    /// # Returns
+    ///
+    /// Returns an instance of B2Builder.
+    fn from_map(map: HashMap<String, String>) -> Self {
+        // Deserialize the configuration from the HashMap.
+        let config = B2Config::deserialize(ConfigDeserializer::new(map))
+            .expect("config deserialize must succeed");
+
+        // Create an B2Builder instance with the deserialized config.
+        B2Builder {
+            config,
+            http_client: None,
+        }
+    }
+
+    /// Builds the backend and returns the result of B2Backend.
+    fn build(&mut self) -> Result<Self::Accessor> {
+        debug!("backend build started: {:?}", &self);
+
+        let root = 
normalize_root(&self.config.root.clone().unwrap_or_default());
+        debug!("backend use root {}", &root);
+
+        // Handle bucket.
+        if self.config.bucket.is_empty() {
+            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket is empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2));
+        }
+
+        debug!("backend use bucket {}", &self.config.bucket);
+
+        // Handle bucket_id.
+        if self.config.bucket_id.is_empty() {
+            return Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is 
empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2));
+        }
+
+        debug!("backend bucket_id {}", &self.config.bucket_id);
+
+        let key_id = match &self.config.key_id {
+            Some(key_id) => Ok(key_id.clone()),
+            None => Err(Error::new(ErrorKind::ConfigInvalid, "bucket_id is 
empty")
+                .with_operation("Builder::build")
+                .with_context("service", Scheme::B2)),
+        }?;
+
+        let application_key = match &self.config.application_key {
+            Some(key_id) => Ok(key_id.clone()),
+            None => Err(
+                Error::new(ErrorKind::ConfigInvalid, "application_key is 
empty")
+                    .with_operation("Builder::build")
+                    .with_context("service", Scheme::B2),
+            ),
+        }?;
+
+        let client = if let Some(client) = self.http_client.take() {
+            client
+        } else {
+            HttpClient::new().map_err(|err| {
+                err.with_operation("Builder::build")
+                    .with_context("service", Scheme::Alluxio)
+            })?
+        };
+
+        let cluster_number = key_id[0..3].to_string();
+
+        let api_url = format!("https://api{}.backblazeb2.com";, cluster_number);
+        let download_url = format!("https://f{}.backblazeb2.com";, 
cluster_number);
+
+        let signer = B2Signer {
+            key_id,
+            application_key,
+            ..Default::default()
+        };
+
+        Ok(B2Backend {
+            core: Arc::new(B2Core {
+                signer: Arc::new(Mutex::new(signer)),
+                root,
+                api_url,
+                download_url,
+
+                bucket: self.config.bucket.clone(),
+                bucket_id: self.config.bucket_id.clone(),
+                client,
+            }),
+        })
+    }
+}
+
+/// Backend for s3 services.
+#[derive(Debug, Clone)]
+pub struct B2Backend {
+    core: Arc<B2Core>,
+}
+
+#[async_trait]
+impl Accessor for B2Backend {
+    type Reader = IncomingAsyncBody;
+
+    type BlockingReader = ();
+
+    type Writer = B2Writers;
+
+    type BlockingWriter = ();
+
+    type Lister = oio::PageLister<B2Lister>;
+
+    type BlockingLister = ();
+
+    fn info(&self) -> AccessorInfo {
+        let mut am = AccessorInfo::default();
+        am.set_scheme(Scheme::B2)
+            .set_root(&self.core.root)
+            .set_native_capability(Capability {
+                stat: true,
+
+                read: true,
+                read_can_next: true,
+                read_with_range: true,
+                read_with_if_match: false,
+                read_with_if_none_match: false,
+                read_with_override_cache_control: false,
+                read_with_override_content_disposition: false,
+                read_with_override_content_type: false,
+
+                write: true,
+                write_can_empty: true,
+                write_can_multi: true,
+                // write_with_cache_control: true,
+                write_with_content_type: true,
+                // The min multipart size of b2 is 5 MiB.
+                //
+                // ref: 
<https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html>
+                write_multi_min_size: Some(5 * 1024 * 1024),
+                // The max multipart size of b2 is 5 GiB.
+                //
+                // ref: 
<https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html>
+                write_multi_max_size: if cfg!(target_pointer_width = "64") {
+                    Some(5 * 1024 * 1024 * 1024)
+                } else {
+                    Some(usize::MAX)
+                },
+
+                create_dir: true,
+                delete: true,
+                copy: true,
+
+                list: true,
+                list_with_limit: true,
+                list_with_start_after: true,
+                list_with_recursive: true,
+                list_without_recursive: true,
+
+                presign: true,
+                presign_read: true,
+                presign_write: true,
+                presign_stat: true,
+
+                ..Default::default()
+            });
+
+        am
+    }
+
+    async fn read(&self, path: &str, _args: OpRead) -> Result<(RpRead, 
Self::Reader)> {
+        let resp = self.core.download_file_by_name(path).await?;
+
+        let status = resp.status();
+
+        match status {
+            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
+                let size = parse_content_length(resp.headers())?;
+                Ok((RpRead::new().with_size(size), resp.into_body()))
+            }
+            StatusCode::RANGE_NOT_SATISFIABLE => Ok((RpRead::new(), 
IncomingAsyncBody::empty())),
+            _ => Err(parse_error(resp).await?),
+        }
+    }
+
+    async fn create_dir(&self, path: &str, _: OpCreateDir) -> 
Result<RpCreateDir> {
+        let resp: http::Response<IncomingAsyncBody> = self
+            .core
+            .upload_file(path, Some(0), &OpWrite::default(), AsyncBody::Empty)
+            .await?;
+
+        let status = resp.status();
+
+        match status {
+            StatusCode::OK => {
+                resp.into_body().consume().await?;
+                Ok(RpCreateDir::default())
+            }
+            _ => Err(parse_error(resp).await?),
+        }
+    }
+
+    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, 
Self::Writer)> {
+        let writer = B2Writer::new(self.core.clone(), path, args);
+
+        let w = oio::MultipartUploadWriter::new(writer);
+
+        Ok((RpWrite::default(), w))
+    }
+
+    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
+        let delimiter = if path.ends_with('/') { Some("/") } else { None };
+        let resp = self
+            .core
+            .list_file_names(Some(path), delimiter, None, None)
+            .await?;
+
+        let status = resp.status();
+
+        match status {
+            StatusCode::OK => {
+                let bs = resp.into_body().bytes().await?;
+
+                let resp: ListFileNamesResponse =
+                    
serde_json::from_slice(&bs).map_err(new_json_deserialize_error)?;
+                if resp.files.is_empty() {
+                    return Err(Error::new(ErrorKind::NotFound, "no such file 
or directory"));
+                }
+                let meta: Metadata = (&resp.files[0]).into();

Review Comment:
   Please don't implement `From<Xxx> for Metadata` which could leak our 
internal struct types. Implement a `parse_file_info` instead.



##########
core/src/services/b2/core.rs:
##########
@@ -0,0 +1,656 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::fmt::{Debug, Formatter};
+use std::sync::Arc;
+use std::time::Duration;
+
+use chrono::{DateTime, Utc};
+use http::{header, Request, Response, StatusCode};
+use serde::{Deserialize, Serialize};
+use tokio::sync::Mutex;
+
+use crate::raw::*;
+use crate::services::b2::core::constants::X_BZ_PART_NUMBER;
+use crate::services::b2::error::parse_error;
+use crate::*;
+
+use self::constants::{X_BZ_CONTENT_SHA1, X_BZ_FILE_NAME};
+
+pub(super) mod constants {
+    pub const X_BZ_FILE_NAME: &str = "X-Bz-File-Name";
+    pub const X_BZ_CONTENT_SHA1: &str = "X-Bz-Content-Sha1";
+    pub const X_BZ_PART_NUMBER: &str = "X-Bz-Part-Number";
+}
+
+/// Core of [b2](https://www.backblaze.com/cloud-storage) services support.
+#[derive(Clone)]
+pub struct B2Core {
+    /// The base URL to use for all API calls except for uploading and 
downloading files.
+    pub api_url: String,
+    /// The base URL to use for downloading files.
+    pub download_url: String,
+    /// The bucket id of this backend.
+    pub bucket_id: String,
+    pub signer: Arc<Mutex<B2Signer>>,
+
+    /// The root of this core.
+    pub root: String,
+    /// The bucket name of this backend.
+    pub bucket: String,
+
+    pub client: HttpClient,
+}
+
+impl Debug for B2Core {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("Backend")
+            .field("root", &self.root)
+            .field("api_url", &self.api_url)
+            .field("download_url", &self.download_url)
+            .field("bucket", &self.bucket)
+            .finish_non_exhaustive()
+    }
+}
+
+impl B2Core {
+    #[inline]
+    pub async fn send(&self, req: Request<AsyncBody>) -> 
Result<Response<IncomingAsyncBody>> {
+        self.client.send(req).await
+    }
+
+    pub async fn sign<T>(&self, req: &mut Request<T>) -> Result<()> {
+        let mut signer = self.signer.lock().await;
+
+        if !signer.authorization_token.is_empty() && signer.expires_in > 
Utc::now() {
+            let value = signer
+                .authorization_token
+                .to_string()
+                .parse()
+                .expect("access token must be valid header value");
+
+            req.headers_mut().insert(header::AUTHORIZATION, value);
+            return Ok(());
+        }
+
+        {
+            let req = 
Request::get("https://api.backblazeb2.com/b2api/v3/b2_authorize_account";)
+                .header(
+                    header::AUTHORIZATION,
+                    format_authorization_by_basic(&signer.key_id, 
&signer.application_key)?,
+                )
+                .body(AsyncBody::Empty)
+                .map_err(new_request_build_error)?;
+
+            let resp = self.client.send(req).await?;
+            let status = resp.status();
+
+            match status {
+                StatusCode::OK => {
+                    let resp_body = &resp.into_body().bytes().await?;
+                    let token = 
serde_json::from_slice::<AuthorizeAccountResponse>(resp_body)
+                        .map_err(new_json_deserialize_error)?;
+                    signer.authorization_token = token.authorization_token;
+
+                    signer.expires_in =
+                        Utc::now() + chrono::Duration::hours(20) - 
chrono::Duration::seconds(120);
+                }
+                _ => {
+                    return Err(parse_error(resp).await?);
+                }
+            }
+        }
+
+        req.headers_mut().insert(
+            header::AUTHORIZATION,
+            signer.authorization_token.parse().unwrap(),
+        );
+
+        Ok(())
+    }
+}
+
+impl B2Core {
+    pub async fn download_file_by_name(&self, path: &str) -> 
Result<Response<IncomingAsyncBody>> {
+        let path = build_abs_path(&self.root, path);
+
+        // Construct headers to add to the request
+        let url = format!(
+            "{}/file/{}/{}",
+            self.download_url,
+            self.bucket,
+            percent_encode_path(&path)
+        );
+
+        let req = Request::get(&url);
+
+        let mut req = req
+            .body(AsyncBody::Empty)
+            .map_err(new_request_build_error)?;
+
+        self.sign(&mut req).await?;
+
+        self.send(req).await
+    }
+
+    pub(super) async fn get_upload_url(&self) -> Result<GetUploadUrlResponse> {
+        let mut url = format!("{}/b2api/v2/b2_get_upload_url", self.api_url);
+
+        url.push_str(&format!("?bucketId={}", self.bucket_id));
+
+        let req = Request::get(&url);
+
+        // Set body
+        let mut req = req
+            .body(AsyncBody::Empty)
+            .map_err(new_request_build_error)?;
+
+        self.sign(&mut req).await?;
+
+        let resp = self.send(req).await?;
+        let status = resp.status();
+        match status {
+            StatusCode::OK => {
+                let resp_body = &resp.into_body().bytes().await?;
+                let resp = 
serde_json::from_slice::<GetUploadUrlResponse>(resp_body)
+                    .map_err(new_json_deserialize_error)?;
+                Ok(resp)
+            }
+            _ => Err(parse_error(resp).await?),
+        }
+    }
+
+    pub async fn get_download_authorization(
+        &self,
+        path: &str,
+        args: &OpRead,
+        expire: Duration,
+    ) -> Result<GetDownloadAuthorizationResponse> {
+        let path = build_abs_path(&self.root, path);
+
+        // Construct headers to add to the request
+        let url = format!("{}/b2api/v2/b2_get_download_authorization", 
self.api_url);
+        let mut req = Request::post(&url);
+
+        let range = args.range();
+        if !range.is_full() {
+            req = req.header(http::header::RANGE, range.to_header());
+        }
+        let body = GetDownloadAuthorizationRequest {
+            bucket_id: self.bucket_id.clone(),
+            file_name_prefix: path,
+            valid_duration_in_seconds: expire.as_secs(),
+        };
+        let body = 
serde_json::to_vec(&body).map_err(new_json_serialize_error)?;
+        let body = bytes::Bytes::from(body);
+
+        let mut req = req
+            .body(AsyncBody::Bytes(body))
+            .map_err(new_request_build_error)?;
+
+        self.sign(&mut req).await?;
+
+        let resp = self.send(req).await?;
+
+        let status = resp.status();
+        match status {
+            StatusCode::OK => {
+                let resp_body = &resp.into_body().bytes().await?;
+                let resp = 
serde_json::from_slice::<GetDownloadAuthorizationResponse>(resp_body)
+                    .map_err(new_json_deserialize_error)?;
+                Ok(resp)
+            }
+            _ => Err(parse_error(resp).await?),
+        }
+    }
+
+    pub async fn upload_file(
+        &self,
+        path: &str,
+        size: Option<u64>,
+        args: &OpWrite,
+        body: AsyncBody,
+    ) -> Result<Response<IncomingAsyncBody>> {
+        let resp = self.get_upload_url().await?;
+
+        let p = build_abs_path(&self.root, path);
+
+        let mut req = Request::post(resp.upload_url);
+
+        req = req.header(X_BZ_FILE_NAME, percent_encode_path(&p));
+
+        req = req.header(header::AUTHORIZATION, resp.authorization_token);
+
+        req = req.header(X_BZ_CONTENT_SHA1, "do_not_verify");
+
+        if let Some(size) = size {
+            req = req.header(header::CONTENT_LENGTH, size.to_string())
+        }
+
+        if let Some(mime) = args.content_type() {
+            req = req.header(header::CONTENT_TYPE, mime)
+        } else {
+            req = req.header(header::CONTENT_TYPE, "b2/x-auto")
+        }
+
+        if let Some(pos) = args.content_disposition() {
+            req = req.header(header::CONTENT_DISPOSITION, pos)
+        }
+
+        // if let Some(cache_control) = args.cache_control() {

Review Comment:
   Remove not needed code.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to