Xuanwo commented on code in PR #3771: URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429818355
########## core/src/services/seafile/backend.rs: ########## @@ -0,0 +1,343 @@ +// 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 async_trait::async_trait; +use http::StatusCode; +use log::debug; +use serde::Deserialize; +use std::collections::HashMap; +use std::fmt::Debug; +use std::fmt::Formatter; +use std::sync::Arc; +use tokio::sync::RwLock; + +use super::core::parse_dir_detail; +use super::core::parse_file_detail; +use super::core::SeafileCore; +use super::error::parse_error; +use super::lister::SeafileLister; +use super::writer::SeafileWriter; +use super::writer::SeafileWriters; +use crate::raw::*; +use crate::services::seafile::core::AuthInfo; +use crate::*; + +/// Config for backblaze seafile services support. +#[derive(Default, Deserialize)] +#[serde(default)] +#[non_exhaustive] +pub struct SeafileConfig { + /// root of this backend. + /// + /// All operations will happen under this root. + pub root: Option<String>, + /// server address of this backend. + /// + /// - If server is set, we will take user's input first. + /// - If not, we will try to load it from environment. + pub server: Option<String>, Review Comment: How about using `endpoint` to align with other services? ########## core/src/services/seafile/backend.rs: ########## @@ -0,0 +1,343 @@ +// 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 async_trait::async_trait; +use http::StatusCode; +use log::debug; +use serde::Deserialize; +use std::collections::HashMap; +use std::fmt::Debug; +use std::fmt::Formatter; +use std::sync::Arc; +use tokio::sync::RwLock; + +use super::core::parse_dir_detail; +use super::core::parse_file_detail; +use super::core::SeafileCore; +use super::error::parse_error; +use super::lister::SeafileLister; +use super::writer::SeafileWriter; +use super::writer::SeafileWriters; +use crate::raw::*; +use crate::services::seafile::core::AuthInfo; +use crate::*; + +/// Config for backblaze seafile services support. +#[derive(Default, Deserialize)] +#[serde(default)] +#[non_exhaustive] +pub struct SeafileConfig { + /// root of this backend. + /// + /// All operations will happen under this root. + pub root: Option<String>, + /// server address of this backend. + /// + /// - If server is set, we will take user's input first. + /// - If not, we will try to load it from environment. + pub server: Option<String>, + /// username of this backend. + /// + /// - If username is set, we will take user's input first. + /// - If not, we will try to load it from environment. + pub username: Option<String>, + /// password of this backend. + /// + /// - If password is set, we will take user's input first. + /// - If not, we will try to load it from environment. Review Comment: Why env will we use? ########## core/src/services/seafile/backend.rs: ########## @@ -0,0 +1,343 @@ +// 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 async_trait::async_trait; +use http::StatusCode; +use log::debug; +use serde::Deserialize; +use std::collections::HashMap; +use std::fmt::Debug; +use std::fmt::Formatter; +use std::sync::Arc; +use tokio::sync::RwLock; + +use super::core::parse_dir_detail; +use super::core::parse_file_detail; +use super::core::SeafileCore; +use super::error::parse_error; +use super::lister::SeafileLister; +use super::writer::SeafileWriter; +use super::writer::SeafileWriters; +use crate::raw::*; +use crate::services::seafile::core::AuthInfo; +use crate::*; + +/// Config for backblaze seafile services support. +#[derive(Default, Deserialize)] +#[serde(default)] +#[non_exhaustive] +pub struct SeafileConfig { + /// root of this backend. + /// + /// All operations will happen under this root. + pub root: Option<String>, + /// server address of this backend. + /// + /// - If server is set, we will take user's input first. + /// - If not, we will try to load it from environment. + pub server: Option<String>, + /// username of this backend. + /// + /// - If username is set, we will take user's input first. + /// - If not, we will try to load it from environment. + pub username: Option<String>, + /// password of this backend. + /// + /// - If password is set, we will take user's input first. + /// - If not, we will try to load it from environment. + pub password: Option<String>, + /// repo_name of this backend. + /// + /// required. + pub repo_name: String, +} + +impl Debug for SeafileConfig { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut d = f.debug_struct("SeafileConfig"); + + d.field("root", &self.root) + .field("server", &self.server) + .field("username", &self.username) + .field("repo_name", &self.repo_name); + + d.finish_non_exhaustive() + } +} + +/// [seafile](https://www.seafile.com) services support. +#[doc = include_str!("docs.md")] +#[derive(Default)] +pub struct SeafileBuilder { + config: SeafileConfig, + + http_client: Option<HttpClient>, +} + +impl Debug for SeafileBuilder { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut d = f.debug_struct("SeafileBuilder"); + + d.field("config", &self.config); + d.finish_non_exhaustive() + } +} + +impl SeafileBuilder { + /// 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 + } + + /// server of this backend. + pub fn server(&mut self, server: &str) -> &mut Self { + self.config.server = if server.is_empty() { + None + } else { + Some(server.to_string()) + }; + + self + } + + /// username of this backend. + pub fn username(&mut self, username: &str) -> &mut Self { + self.config.username = if username.is_empty() { + None + } else { + Some(username.to_string()) + }; + + self + } + + /// password of this backend. + pub fn password(&mut self, password: &str) -> &mut Self { + self.config.password = if password.is_empty() { + None + } else { + Some(password.to_string()) + }; + + self + } + + /// Set repo name of this backend. + /// You can find it in {server}/sys/all-libraries/ + pub fn repo_name(&mut self, repo_name: &str) -> &mut Self { + self.config.repo_name = repo_name.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 SeafileBuilder { + const SCHEME: Scheme = Scheme::Seafile; + type Accessor = SeafileBackend; + + /// Converts a HashMap into an SeafileBuilder instance. + /// + /// # Arguments + /// + /// * `map` - A HashMap containing the configuration values. + /// + /// # Returns + /// + /// Returns an instance of SeafileBuilder. + fn from_map(map: HashMap<String, String>) -> Self { + // Deserialize the configuration from the HashMap. + let config = SeafileConfig::deserialize(ConfigDeserializer::new(map)) + .expect("config deserialize must succeed"); + + // Create an SeafileBuilder instance with the deserialized config. + SeafileBuilder { + config, + http_client: None, + } + } + + /// Builds the backend and returns the result of SeafileBackend. + 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.repo_name.is_empty() { + return Err(Error::new(ErrorKind::ConfigInvalid, "repo_name is empty") + .with_operation("Builder::build") + .with_context("service", Scheme::Seafile)); + } + + debug!("backend use repo_name {}", &self.config.repo_name); + + let server = match &self.config.server { + Some(server) => Ok(server.clone()), + None => Err(Error::new(ErrorKind::ConfigInvalid, "server is empty") + .with_operation("Builder::build") + .with_context("service", Scheme::Seafile)), + }?; + + let username = match &self.config.username { + Some(username) => Ok(username.clone()), + None => Err(Error::new(ErrorKind::ConfigInvalid, "username is empty") + .with_operation("Builder::build") + .with_context("service", Scheme::Seafile)), + }?; + + let password = match &self.config.password { + Some(password) => Ok(password.clone()), + None => Err(Error::new(ErrorKind::ConfigInvalid, "password is empty") + .with_operation("Builder::build") + .with_context("service", Scheme::Seafile)), + }?; + + 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::Seafile) + })? + }; + + Ok(SeafileBackend { + core: Arc::new(SeafileCore { + root, + server, + username, + password, + repo_name: self.config.repo_name.clone(), + auth_info: Arc::new(RwLock::new(AuthInfo::default())), + client, + }), + }) + } +} + +/// Backend for seafile services. +#[derive(Debug, Clone)] +pub struct SeafileBackend { + core: Arc<SeafileCore>, +} + +#[async_trait] +impl Accessor for SeafileBackend { + type Reader = IncomingAsyncBody; + + type BlockingReader = (); + + type Writer = SeafileWriters; + + type BlockingWriter = (); + + type Lister = oio::PageLister<SeafileLister>; + + type BlockingLister = (); + + fn info(&self) -> AccessorInfo { + let mut am = AccessorInfo::default(); + am.set_scheme(Scheme::Seafile) + .set_root(&self.core.root) + .set_native_capability(Capability { + stat: true, + + read: true, + read_can_next: true, + + write: true, + write_can_empty: true, + + delete: true, + + list: true, + + ..Default::default() + }); + + am + } + + async fn read(&self, path: &str, _args: OpRead) -> Result<(RpRead, Self::Reader)> { + let resp = self.core.download_file(path).await?; + + let status = resp.status(); + + match status { + StatusCode::OK => { + let size = parse_content_length(resp.headers())?; + Ok((RpRead::new().with_size(size), resp.into_body())) + } + _ => Err(parse_error(resp).await?), + } + } + + async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> { + if path == "/" { + return Ok(RpStat::new(Metadata::new(EntryMode::DIR))); + } + + let metadata = if path.ends_with('/') { Review Comment: Please don't depend on path to decide the entry mode. ########## fixtures/seafile/docker-compose-seafile.yml: ########## @@ -0,0 +1,61 @@ +# 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. + +version: "3.8" +services: + db: + image: mariadb:10.11 + container_name: seafile-mysql + environment: + - MYSQL_ROOT_PASSWORD=db_dev # Requested, set the root's password of MySQL service. + - MYSQL_LOG_CONSOLE=true + # volumes: + # - /opt/seafile-mysql/db:/var/lib/mysql # Requested, specifies the path to MySQL data persistent store. + networks: + - seafile-net + + memcached: + image: memcached:1.6.18 + container_name: seafile-memcached + entrypoint: memcached -m 256 + networks: + - seafile-net + + seafile: + image: seafileltd/seafile-mc:latest + container_name: seafile + ports: + - "80:80" +# - "443:443" # If https is enabled, cancel the comment. Review Comment: Remove not used code. ########## core/src/services/seafile/core.rs: ########## @@ -0,0 +1,405 @@ +// 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 bytes::Bytes; +use http::header; +use http::Request; +use http::Response; +use http::StatusCode; +use serde::Deserialize; +use std::sync::Arc; +use tokio::sync::RwLock; + +use std::fmt::Debug; +use std::fmt::Formatter; + +use crate::raw::*; +use crate::*; + +use super::error::parse_error; + +/// Core of [seafile](https://www.seafile.com) services support. +#[derive(Clone)] +pub struct SeafileCore { + /// The root of this core. + pub root: String, + /// The server of this backend. + pub server: String, + /// The username of this backend. + pub username: String, + /// The password id of this backend. + pub password: String, + /// The repo name of this backend. + pub repo_name: String, + + /// auth info of this backend. + pub auth_info: Arc<RwLock<AuthInfo>>, + + pub client: HttpClient, +} + +impl Debug for SeafileCore { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Backend") + .field("root", &self.root) + .field("server", &self.server) + .field("username", &self.username) + .field("repo_name", &self.repo_name) + .finish_non_exhaustive() + } +} + +impl SeafileCore { + #[inline] + pub async fn send(&self, req: Request<AsyncBody>) -> Result<Response<IncomingAsyncBody>> { + self.client.send(req).await + } + + /// get auth info + pub async fn get_auth_info(&self) -> Result<AuthInfo> { + { + let auth_info = self.auth_info.read().await; + + if !auth_info.token.is_empty() { + return Ok(auth_info.clone()); + } + } + + { + let mut auth_info = self.auth_info.write().await; + let body = format!( + "username={}&password={}", + percent_encode_path(&self.username), + percent_encode_path(&self.password) + ); + let req = Request::post(format!("{}/api2/auth-token/", self.server)) + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") + .body(AsyncBody::Bytes(Bytes::from(body))) + .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 auth_response = serde_json::from_slice::<AuthTokenResponse>(resp_body) + .map_err(new_json_deserialize_error)?; + auth_info.token = auth_response.token; + } + _ => { + return Err(parse_error(resp).await?); + } + } + + let url = format!("{}/api2/repos", self.server); + + let req = Request::get(url) + .header(header::AUTHORIZATION, format!("Token {}", auth_info.token)) + .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 list_library_response = + serde_json::from_slice::<Vec<ListLibraryResponse>>(resp_body) + .map_err(new_json_deserialize_error)?; + + for library in list_library_response { + if library.name == self.repo_name { + auth_info.repo_id = library.id; + break; + } + } + + // repo not found + if auth_info.repo_id.is_empty() { + return Err(Error::new( + ErrorKind::NotFound, + &format!("repo {} not found", self.repo_name), + )); + } + } + _ => { + return Err(parse_error(resp).await?); + } + } + Ok(auth_info.clone()) + } + } +} + +impl SeafileCore { + /// get upload url + pub async fn get_upload_url(&self) -> Result<String> { + let auth_info = self.get_auth_info().await?; + + let req = Request::get(format!( + "{}/api2/repos/{}/upload-link/", + self.server, auth_info.repo_id + )); + + let req = req + .header(header::AUTHORIZATION, format!("Token {}", auth_info.token)) + .body(AsyncBody::Empty) + .map_err(new_request_build_error)?; + + let resp = self.send(req).await?; + let status = resp.status(); + + match status { + StatusCode::OK => { + let resp_body = &resp.into_body().bytes().await?; + let upload_url = serde_json::from_slice::<String>(resp_body) + .map_err(new_json_deserialize_error)?; + Ok(upload_url) + } + _ => Err(parse_error(resp).await?), + } + } + + /// get download + pub async fn get_download_url(&self, path: &str) -> Result<String> { + let path = build_abs_path(&self.root, path); + let path = percent_encode_path(&path); + + let auth_info = self.get_auth_info().await?; + + let req = Request::get(format!( + "{}/api2/repos/{}/file/?p={}", + self.server, auth_info.repo_id, path + )); + + let req = req + .header(header::AUTHORIZATION, format!("Token {}", auth_info.token)) Review Comment: It's better to hide those signer related staff inside `SeafileSigner`. ########## core/src/services/seafile/lister.rs: ########## @@ -0,0 +1,121 @@ +// 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::{header, Request, StatusCode}; +use serde::Deserialize; + +use super::core::SeafileCore; +use super::error::parse_error; + +use crate::raw::oio::Entry; +use crate::raw::*; +use crate::*; + +pub struct SeafileLister { + core: Arc<SeafileCore>, + + path: String, +} + +impl SeafileLister { + pub(super) fn new(core: Arc<SeafileCore>, path: &str) -> Self { + SeafileLister { + core, + path: path.to_string(), + } + } +} + +#[async_trait] +impl oio::PageList for SeafileLister { + async fn next_page(&self, ctx: &mut oio::PageContext) -> Result<()> { + let path = build_rooted_abs_path(&self.core.root, &self.path); + + let auth_info = self.core.get_auth_info().await?; + + let url = format!( + "{}/api2/repos/{}/dir/?p={}", + self.core.server, + auth_info.repo_id, + percent_encode_path(&path) + ); + + let req = Request::get(url); + + let req = req + .header(header::AUTHORIZATION, format!("Token {}", auth_info.token)) + .body(AsyncBody::Empty) + .map_err(new_request_build_error)?; + + let resp = self.core.send(req).await?; + + let status = resp.status(); + + match status { + StatusCode::OK => { + let resp_body = &resp.into_body().bytes().await?; + let infos = serde_json::from_slice::<Vec<Info>>(resp_body) + .map_err(new_json_deserialize_error)?; + + for info in infos { + if !info.name.is_empty() { + let rel_path = + build_rel_path(&self.core.root, &format!("{}{}", path, info.name)); + + let entry = if info.type_field == "file" { + let meta = Metadata::new(EntryMode::FILE) + .with_last_modified(parse_datetime_from_from_timestamp_millis( Review Comment: How about using or adding a `parse_datetime_from_from_timestamp`? -- 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]
