hoslo commented on code in PR #3604: URL: https://github.com/apache/incubator-opendal/pull/3604#discussion_r1398048948
########## 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: fixed -- 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]
