You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opendal.apache.org by su...@apache.org on 2023/05/26 09:22:26 UTC

[incubator-opendal] branch append-cos created (now 7bdad0c5)

This is an automated email from the ASF dual-hosted git repository.

suyanhanx pushed a change to branch append-cos
in repository https://gitbox.apache.org/repos/asf/incubator-opendal.git


      at 7bdad0c5 feat(core): append support for cos

This branch includes the following new commits:

     new 7bdad0c5 feat(core): append support for cos

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



[incubator-opendal] 01/01: feat(core): append support for cos

Posted by su...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

suyanhanx pushed a commit to branch append-cos
in repository https://gitbox.apache.org/repos/asf/incubator-opendal.git

commit 7bdad0c5f2fd078c5533dd2dfac385c6cfbb0b83
Author: suyanhanx <su...@gmail.com>
AuthorDate: Fri May 26 17:21:57 2023 +0800

    feat(core): append support for cos
    
    Signed-off-by: suyanhanx <su...@gmail.com>
---
 core/src/services/cos/appender.rs | 142 ++++++++++++++++++++++++++++++++++++++
 core/src/services/cos/backend.rs  |  15 +++-
 core/src/services/cos/core.rs     |  37 ++++++++++
 core/src/services/cos/mod.rs      |   1 +
 4 files changed, 194 insertions(+), 1 deletion(-)

diff --git a/core/src/services/cos/appender.rs b/core/src/services/cos/appender.rs
new file mode 100644
index 00000000..2ebaa505
--- /dev/null
+++ b/core/src/services/cos/appender.rs
@@ -0,0 +1,142 @@
+// 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 bytes::Bytes;
+use http::StatusCode;
+
+use super::core::*;
+use super::error::parse_error;
+use crate::raw::*;
+use crate::*;
+
+pub const X_COS_NEXT_APPEND_POSITION: &str = "x-cos-next-append-position";
+
+pub struct CosAppender {
+    core: Arc<CosCore>,
+
+    op: OpAppend,
+    path: String,
+
+    position: Option<u64>,
+}
+
+impl CosAppender {
+    pub fn new(core: Arc<CosCore>, path: &str, op: OpAppend) -> Self {
+        Self {
+            core,
+            op,
+            path: path.to_string(),
+            position: None,
+        }
+    }
+}
+
+#[async_trait]
+impl oio::Append for CosAppender {
+    async fn append(&mut self, bs: Bytes) -> Result<()> {
+        // If the position is not set, we need to get the current position.
+        if self.position.is_none() {
+            let resp = self.core.cos_head_object(&self.path, None, None).await?;
+
+            let status = resp.status();
+            match status {
+                StatusCode::OK => {
+                    let position = resp
+                        .headers()
+                        .get(X_COS_NEXT_APPEND_POSITION)
+                        .and_then(|v| v.to_str().ok())
+                        .and_then(|v| v.parse::<u64>().ok())
+                        .ok_or_else(|| {
+                            Error::new(
+                                ErrorKind::Unexpected,
+                                "missing x-cos-next-append-position, the object may not be appendable",
+                            )
+                        })?;
+                    self.position = Some(position);
+                }
+                StatusCode::NOT_FOUND => {
+                    self.position = Some(0);
+                }
+                _ => {
+                    return Err(parse_error(resp).await?);
+                }
+            }
+        }
+
+        let mut req = self.core.cos_append_object_request(
+            &self.path,
+            self.position.expect("position is not set"),
+            bs.len(),
+            &self.op,
+            AsyncBody::Bytes(bs),
+        )?;
+
+        self.core.sign(&mut req).await?;
+
+        let resp = self.core.send(req).await?;
+
+        let status = resp.status();
+
+        match status {
+            StatusCode::OK => {
+                let position = resp
+                    .headers()
+                    .get(X_COS_NEXT_APPEND_POSITION)
+                    .and_then(|v| v.to_str().ok())
+                    .and_then(|v| v.parse::<u64>().ok())
+                    .ok_or_else(|| {
+                        Error::new(
+                            ErrorKind::Unexpected,
+                            "missing x-cos-next-append-position, the object may not be appendable",
+                        )
+                    })?;
+                self.position = Some(position);
+                Ok(())
+            }
+            StatusCode::CONFLICT => {
+                // The object is not appendable or the position is not match with the object's length.
+                // If the position is not match, we could get the current position and retry.
+                let position = resp
+                    .headers()
+                    .get(X_COS_NEXT_APPEND_POSITION)
+                    .and_then(|v| v.to_str().ok())
+                    .and_then(|v| v.parse::<u64>().ok())
+                    .ok_or_else(|| {
+                        Error::new(
+                            ErrorKind::Unexpected,
+                            "missing x-cos-next-append-position, the object may not be appendable",
+                        )
+                    })?;
+                self.position = Some(position);
+
+                // Then return the error to the caller, so the caller could retry.
+                Err(Error::new(
+                    ErrorKind::ConditionNotMatch,
+                    "the position is not match with the object's length. position has been updated.",
+                ))
+            }
+            _ => Err(parse_error(resp).await?),
+        }
+    }
+
+    async fn close(&mut self) -> Result<()> {
+        Ok(())
+    }
+}
diff --git a/core/src/services/cos/backend.rs b/core/src/services/cos/backend.rs
index a40d1b29..8cd50ae0 100644
--- a/core/src/services/cos/backend.rs
+++ b/core/src/services/cos/backend.rs
@@ -33,6 +33,7 @@ use super::pager::CosPager;
 use super::writer::CosWriter;
 use crate::raw::*;
 use crate::*;
+use crate::services::cos::appender::CosAppender;
 
 /// Huawei Cloud COS services support.
 ///
@@ -301,7 +302,7 @@ impl Accessor for CosBackend {
     type BlockingReader = ();
     type Writer = CosWriter;
     type BlockingWriter = ();
-    type Appender = ();
+    type Appender = CosAppender;
     type Pager = CosPager;
     type BlockingPager = ();
 
@@ -325,6 +326,11 @@ impl Accessor for CosBackend {
                 write_with_content_type: true,
                 write_with_cache_control: true,
 
+                append: true,
+                append_with_cache_control: true,
+                append_with_content_disposition: true,
+                append_with_content_type: true,
+
                 delete: true,
                 create_dir: true,
                 copy: true,
@@ -395,6 +401,13 @@ impl Accessor for CosBackend {
         ))
     }
 
+    async fn append(&self, path: &str, args: OpAppend) -> Result<(RpAppend, Self::Appender)> {
+        Ok((
+            RpAppend::default(),
+            CosAppender::new(self.core.clone(), path, args),
+            ))
+    }
+
     async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
         let resp = self.core.cos_copy_object(from, to).await?;
 
diff --git a/core/src/services/cos/core.rs b/core/src/services/cos/core.rs
index bfcb8a2a..1037c555 100644
--- a/core/src/services/cos/core.rs
+++ b/core/src/services/cos/core.rs
@@ -20,6 +20,7 @@ use std::fmt::Formatter;
 use std::time::Duration;
 
 use http::header::CACHE_CONTROL;
+use http::header::CONTENT_DISPOSITION;
 use http::header::CONTENT_LENGTH;
 use http::header::CONTENT_TYPE;
 use http::header::IF_MATCH;
@@ -229,6 +230,42 @@ impl CosCore {
         self.send(req).await
     }
 
+    pub fn cos_append_object_request(
+        &self,
+        path: &str,
+        position: u64,
+        size: usize,
+        args: &OpAppend,
+        body: AsyncBody,
+    ) -> Result<Request<AsyncBody>> {
+        let p = build_abs_path(&self.root, path);
+        let url = format!(
+            "{}/{}?append&position={}",
+            self.endpoint,
+            percent_encode_path(&p),
+            position
+        );
+
+        let mut req = Request::post(&url);
+
+        req = req.header(CONTENT_LENGTH, size);
+
+        if let Some(mime) = args.content_type() {
+            req = req.header(CONTENT_TYPE, mime);
+        }
+
+        if let Some(pos) = args.content_disposition() {
+            req = req.header(CONTENT_DISPOSITION, pos);
+        }
+
+        if let Some(cache_control) = args.cache_control() {
+            req = req.header(CACHE_CONTROL, cache_control)
+        }
+
+        let req = req.body(body).map_err(new_request_build_error)?;
+        Ok(req)
+    }
+
     pub async fn cos_copy_object(
         &self,
         from: &str,
diff --git a/core/src/services/cos/mod.rs b/core/src/services/cos/mod.rs
index b51de4b7..ee38708a 100644
--- a/core/src/services/cos/mod.rs
+++ b/core/src/services/cos/mod.rs
@@ -18,6 +18,7 @@
 mod backend;
 pub use backend::CosBuilder as Cos;
 
+mod appender;
 mod core;
 mod error;
 mod pager;