You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opendal.apache.org by "hoslo (via GitHub)" <gi...@apache.org> on 2023/12/18 06:53:35 UTC
[PR] feat(services): add seafile support [incubator-opendal]
hoslo opened a new pull request, #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771
Part #3752
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1430294285
##########
core/src/raw/chrono_util.rs:
##########
@@ -53,3 +53,12 @@ pub fn parse_datetime_from_from_timestamp_millis(s: i64) -> Result<DateTime<Utc>
Ok(st.into())
}
+
+/// parse datetime from given timestamp
+pub fn parse_datetime_from_from_timestamp(s: i64) -> Result<DateTime<Utc>> {
Review Comment:
Feel free to submit a PR if you believe it's worthwhile. Let's avoid continuously adding tasks to a single PR. This API aligned with existing `parse_datetime_from_from_timestamp_milies`, which seems fine.
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429904604
##########
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:
Ok, this behavior also LGTM.
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429854879
##########
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:
Azblob is an object storage service that allows both `abc` and `abc/` to coexist simultaneously. Does Seafile offer this same capability?
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo merged PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429877080
##########
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:
> In Seafile, abc/ should be a folder, while abc is a file.
What will happen if we try to stat a dir with path `abc`?
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "Zheaoli (via GitHub)" <gi...@apache.org>.
Zheaoli commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1430285086
##########
core/src/raw/chrono_util.rs:
##########
@@ -53,3 +53,12 @@ pub fn parse_datetime_from_from_timestamp_millis(s: i64) -> Result<DateTime<Utc>
Ok(st.into())
}
+
+/// parse datetime from given timestamp
+pub fn parse_datetime_from_from_timestamp(s: i64) -> Result<DateTime<Utc>> {
Review Comment:
nits: I think `s: u64` would be better?
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "hoslo (via GitHub)" <gi...@apache.org>.
hoslo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429872975
##########
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:
In Seafile, abc/ should be a folder, while abc is a file.
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "hoslo (via GitHub)" <gi...@apache.org>.
hoslo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429868748
##########
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:
Are you suggesting that we shouldn't use environment variables as passwords?
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "hoslo (via GitHub)" <gi...@apache.org>.
hoslo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429886323
##########
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:
Based on the current code, it seems it will proceed with the file attribute query API, so the expected return should be "NOT_FOUND"
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "hoslo (via GitHub)" <gi...@apache.org>.
hoslo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429850058
##########
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:
How can I determine if the file attributes and folder attributes in Seafile are two different APIs? Here's a reference to the stat function in azfile.
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "hoslo (via GitHub)" <gi...@apache.org>.
hoslo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429850058
##########
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:
How can I determine if file attributes and folder attributes in Seafile are two different APIs? I've written this based on the stat function in azfile.
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "Zheaoli (via GitHub)" <gi...@apache.org>.
Zheaoli commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1430295143
##########
core/src/raw/http_util/multipart.rs:
##########
@@ -291,7 +291,19 @@ impl Part for FormDataPart {
// Building pre-content.
for (k, v) in self.headers.iter() {
- bs.extend_from_slice(k.as_str().as_bytes());
+ // Trick!
+ //
+ // Seafile could not recognize header names like `content-disposition`
+ // and requires to use `Content-Disposition`. So we hardcode the part
+ // headers name here.
+ match k.as_str() {
+ "content-disposition" => {
Review Comment:
The HTTP header is case-insensitive, so both `content-disposition` and `Content-Disposition` have the same semantic. But the hard code will make us to get two different header style.
So would you mind to submit a issue to the seafile and discuss the header style with them?
I think we need to to keep the same style as mush as we can
##########
core/src/raw/http_util/multipart.rs:
##########
@@ -291,7 +291,19 @@ impl Part for FormDataPart {
// Building pre-content.
for (k, v) in self.headers.iter() {
- bs.extend_from_slice(k.as_str().as_bytes());
+ // Trick!
+ //
+ // Seafile could not recognize header names like `content-disposition`
+ // and requires to use `Content-Disposition`. So we hardcode the part
+ // headers name here.
+ match k.as_str() {
+ "content-disposition" => {
Review Comment:
The HTTP header is case-insensitive, so both `content-disposition` and `Content-Disposition` have the same semantic. But the hard code will make us to get two different header style.
So would you mind to submit an issue to the seafile and discuss the header style with them?
I think we need to to keep the same style as mush as we can
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "hoslo (via GitHub)" <gi...@apache.org>.
hoslo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429927777
##########
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:
The description of the environment variable has been removed.
##########
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:
fix
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "hoslo (via GitHub)" <gi...@apache.org>.
hoslo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429928799
##########
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:
add a parse_datetime_from_from_timestamp func to fix it
##########
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:
fix
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1430294285
##########
core/src/raw/chrono_util.rs:
##########
@@ -53,3 +53,12 @@ pub fn parse_datetime_from_from_timestamp_millis(s: i64) -> Result<DateTime<Utc>
Ok(st.into())
}
+
+/// parse datetime from given timestamp
+pub fn parse_datetime_from_from_timestamp(s: i64) -> Result<DateTime<Utc>> {
Review Comment:
Feel free to submit a PR if you believe it's worthwhile. Let's avoid continuously adding tasks to a single PR.
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429873895
##########
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:
> Are you suggesting that we shouldn't use environment variables as passwords?
Sorry for my typo. I'm asking `What env will we use?`.
It looks we didn't read any seafile env in the builder.
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "hoslo (via GitHub)" <gi...@apache.org>.
hoslo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429920177
##########
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:
fix
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(services): add seafile support [incubator-opendal]
Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #3771:
URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1430298067
##########
core/src/raw/http_util/multipart.rs:
##########
@@ -291,7 +291,19 @@ impl Part for FormDataPart {
// Building pre-content.
for (k, v) in self.headers.iter() {
- bs.extend_from_slice(k.as_str().as_bytes());
+ // Trick!
+ //
+ // Seafile could not recognize header names like `content-disposition`
+ // and requires to use `Content-Disposition`. So we hardcode the part
+ // headers name here.
+ match k.as_str() {
+ "content-disposition" => {
Review Comment:
They are not http headers. Tricky things do happen inside HTTP form.
--
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: commits-unsubscribe@opendal.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org