This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/oss-multipart-copy in repository https://gitbox.apache.org/repos/asf/opendal.git
commit 0bf0c72a6918584fecc5c7b604a1dfbab7aa0e0b Author: Xuanwo <[email protected]> AuthorDate: Wed Nov 25 17:44:51 2026 +0100 feat(services/oss): support native multipart copy --- core/services/oss/src/backend.rs | 84 +++++------ core/services/oss/src/copier.rs | 291 +++++++++++++++++++++++++++++++++++++++ core/services/oss/src/core.rs | 73 +++++++++- core/services/oss/src/docs.md | 6 + core/services/oss/src/lib.rs | 1 + 5 files changed, 399 insertions(+), 56 deletions(-) diff --git a/core/services/oss/src/backend.rs b/core/services/oss/src/backend.rs index a0b7d9537c..e44a0ec95d 100644 --- a/core/services/oss/src/backend.rs +++ b/core/services/oss/src/backend.rs @@ -35,6 +35,7 @@ use reqsign_file_read_tokio::TokioFileRead; use super::OSS_SCHEME; use super::config::OssConfig; +use super::copier::OssCopier; use super::core::parse_error; use super::core::*; use super::deleter::OssDeleter; @@ -48,6 +49,13 @@ use opendal_core::raw::*; use opendal_core::*; const DEFAULT_BATCH_MAX_OPERATIONS: usize = 1000; +// OSS multipart uploads use 100 KiB to 5 GiB parts, with a smaller final part allowed. +const MIN_MULTIPART_PART_SIZE: usize = 100 * 1024; +const MAX_MULTIPART_PART_SIZE: usize = if usize::BITS >= 64 { + (5_u64 * 1024 * 1024 * 1024) as usize +} else { + usize::MAX +}; /// Aliyun Object Storage Service (OSS) support #[doc = include_str!("docs.md")] @@ -624,18 +632,8 @@ impl Builder for OssBuilder { write_with_content_encoding: true, write_with_if_not_exists: true, - // The min multipart size of OSS is 100 KiB. - // - // ref: <https://www.alibabacloud.com/help/en/oss/user-guide/multipart-upload-12> - write_multi_min_size: Some(100 * 1024), - // The max multipart size of OSS is 5 GiB. - // - // ref: <https://www.alibabacloud.com/help/en/oss/user-guide/multipart-upload-12> - write_multi_max_size: if cfg!(target_pointer_width = "64") { - Some(5 * 1024 * 1024 * 1024) - } else { - Some(usize::MAX) - }, + write_multi_min_size: Some(MIN_MULTIPART_PART_SIZE), + write_multi_max_size: Some(MAX_MULTIPART_PART_SIZE), write_with_user_metadata: true, delete: true, @@ -643,6 +641,9 @@ impl Builder for OssBuilder { delete_max_size: Some(DEFAULT_BATCH_MAX_OPERATIONS), copy: true, + copy_can_multi: true, + copy_multi_min_size: Some(MIN_MULTIPART_PART_SIZE), + copy_multi_max_size: Some(MAX_MULTIPART_PART_SIZE), list: true, list_with_limit: true, @@ -693,7 +694,7 @@ impl Service for OssBackend { type Writer = OssWriters; type Lister = OssListers; type Deleter = oio::BatchDeleter<OssDeleter>; - type Copier = oio::OneShotCopier; + type Copier = TwoWays<oio::OneShotCopier, oio::MultipartCopier<OssCopier>>; type Composer = (); fn info(&self) -> ServiceInfo { @@ -807,44 +808,25 @@ impl Service for OssBackend { to: &str, args: OpCopy, ) -> Result<Self::Copier> { - let core = self.core.clone(); - let ctx = ctx.clone(); - let from = from.to_string(); - let to = to.to_string(); - Ok(oio::OneShotCopier::new(async move { - let source_size = match args.source_content_length_hint() { - Some(size) => size, - None => { - let stat_args: OpStat = options::StatOptions { - version: args.source_version().map(str::to_owned), - ..Default::default() - } - .into(); - let resp = core.oss_head_object(&ctx, &from, &stat_args).await?; - match resp.status() { - StatusCode::OK => { - parse_into_metadata(&from, resp.headers())?.content_length() - } - _ => { - return Err(parse_error( - ErrorContext::new(ServiceOperation("HeadObject")), - resp, - )); - } - } - } - }; - let resp = core.oss_copy_object(&ctx, &from, &to).await?; - let status = resp.status(); - - match status { - StatusCode::OK => Ok(MetadataBuilder::file(source_size).build()), - _ => Err(parse_error( - ErrorContext::new(ServiceOperation("CopyObject")), - resp, - )), - } - })) + let chunk = args.chunk(); + let part_size = chunk + .unwrap_or(MAX_MULTIPART_PART_SIZE) + .clamp(MIN_MULTIPART_PART_SIZE, MAX_MULTIPART_PART_SIZE) as u64; + let source_size_hint = args.source_content_length_hint(); + let concurrent = args.concurrent(); + let copier = OssCopier::new(self.core.clone(), ctx.clone(), from, to, args, part_size); + if chunk.is_none() { + return Ok(TwoWays::One(copier.into_one_shot())); + } + Ok(TwoWays::Two(oio::MultipartCopier::new( + ctx.executor().clone(), + self.core.capability, + copier, + source_size_hint, + part_size - 1, + part_size, + concurrent, + ))) } async fn rename( diff --git a/core/services/oss/src/copier.rs b/core/services/oss/src/copier.rs new file mode 100644 index 0000000000..b567193600 --- /dev/null +++ b/core/services/oss/src/copier.rs @@ -0,0 +1,291 @@ +// 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 std::sync::OnceLock; + +use bytes::Buf; +use http::HeaderMap; +use http::StatusCode; +use serde::Deserialize; + +use super::core::*; +use opendal_core::raw::*; +use opendal_core::*; + +const MAX_PARTS: u64 = 10_000; + +struct CopySource { + metadata: Metadata, + headers: HeaderMap, +} + +#[derive(Deserialize)] +struct CopyResult { + #[serde(rename = "ETag")] + etag: String, +} + +pub struct OssCopier { + core: Arc<OssCore>, + ctx: OperationContext, + from: String, + to: String, + args: OpCopy, + part_size: u64, + source: OnceLock<CopySource>, +} + +impl OssCopier { + pub fn new( + core: Arc<OssCore>, + ctx: OperationContext, + from: &str, + to: &str, + args: OpCopy, + part_size: u64, + ) -> Self { + Self { + core, + ctx, + from: from.to_string(), + to: to.to_string(), + args, + part_size, + source: OnceLock::new(), + } + } + + pub fn into_one_shot(self) -> oio::OneShotCopier { + oio::OneShotCopier::new(async move { + let size = match self.args.source_content_length_hint() { + Some(size) => size, + None => self.source().await?.metadata.content_length(), + }; + oio::MultipartCopy::copy_once(&self).await?; + Ok(MetadataBuilder::file(size).build()) + }) + } + + async fn source(&self) -> Result<&CopySource> { + if let Some(source) = self.source.get() { + return Ok(source); + } + + let args = options::StatOptions { + version: self.args.source_version().map(str::to_owned), + ..Default::default() + } + .into(); + let resp = self + .core + .oss_head_object(&self.ctx, &self.from, &args) + .await?; + if resp.status() != StatusCode::OK { + return Err(parse_error( + ErrorContext::new(ServiceOperation("HeadObject")), + resp, + )); + } + + let (parts, _) = resp.into_parts(); + let metadata = parse_into_metadata(&self.from, &parts.headers)?; + Ok(self.source.get_or_init(|| CopySource { + metadata, + headers: parts.headers, + })) + } +} + +impl oio::MultipartCopy for OssCopier { + async fn source_metadata(&self) -> Result<Metadata> { + Ok(self.source().await?.metadata.clone()) + } + + async fn copy_once(&self) -> Result<Metadata> { + let resp = self + .core + .oss_copy_object(&self.ctx, &self.from, &self.to) + .await?; + match resp.status() { + StatusCode::OK => Ok(MetadataBuilder::unknown().build()), + _ => Err(parse_error( + ErrorContext::new(ServiceOperation("CopyObject")), + resp, + )), + } + } + + async fn initiate_copy(&self) -> Result<String> { + // Read an ETag even with a length hint so all parts use the same source identity. + let source = self.source().await?; + let size = source.metadata.content_length(); + if self + .args + .source_content_length_hint() + .is_some_and(|hint| hint != size) + { + return Err(Error::new( + ErrorKind::Unexpected, + "OSS multipart copy source length does not match the supplied hint", + )); + } + if source.metadata.etag().is_none_or(str::is_empty) { + return Err(Error::new( + ErrorKind::Unexpected, + "OSS multipart copy requires a source ETag", + )); + } + if size.div_ceil(self.part_size) > MAX_PARTS { + return Err(Error::new( + ErrorKind::Unsupported, + "OSS multipart copy exceeds 10,000 parts, please increase `OpCopy::chunk`", + )); + } + + let resp = self + .core + .oss_initiate_copy(&self.ctx, &self.to, &source.headers) + .await?; + match resp.status() { + StatusCode::OK => { + let result: InitiateMultipartUploadResult = + quick_xml::de::from_reader(resp.into_body().reader()) + .map_err(new_xml_deserialize_error)?; + Ok(result.upload_id) + } + _ => Err(parse_error( + ErrorContext::new(ServiceOperation("InitiateMultipartUpload")), + resp, + )), + } + } + + async fn copy_part( + &self, + upload_id: &str, + part_number: usize, + range: BytesRange, + ) -> Result<oio::MultipartPart> { + let etag = self + .source + .get() + .and_then(|source| source.metadata.etag()) + .expect("initiate_copy requires a source ETag"); + let part_number = part_number + 1; + let resp = self + .core + .oss_upload_part_copy( + &self.ctx, + &self.from, + &self.to, + upload_id, + part_number, + range, + etag, + ) + .await?; + + match resp.status() { + StatusCode::OK => { + let result: CopyResult = quick_xml::de::from_reader(resp.into_body().reader()) + .map_err(new_xml_deserialize_error)?; + Ok(oio::MultipartPart { + part_number, + etag: result.etag, + checksum: None, + size: range.size(), + }) + } + StatusCode::PRECONDITION_FAILED => Err(Error::new( + ErrorKind::Conflict, + "OSS multipart copy source changed", + ) + .set_source(parse_error( + ErrorContext::new(ServiceOperation("UploadPartCopy")), + resp, + ))), + _ => Err(parse_error( + ErrorContext::new(ServiceOperation("UploadPartCopy")), + resp, + )), + } + } + + async fn complete_copy( + &self, + upload_id: &str, + parts: &[oio::MultipartPart], + ) -> Result<Metadata> { + let parts = parts + .iter() + .map(|part| MultipartUploadPart { + part_number: part.part_number, + etag: part.etag.clone(), + }) + .collect(); + let resp = self + .core + .oss_complete_multipart_upload_request( + &self.ctx, + &self.to, + upload_id, + false, + parts, + &OpWrite::new(), + ) + .await?; + + match resp.status() { + StatusCode::OK => { + let (parts, body) = resp.into_parts(); + let result: CopyResult = + quick_xml::de::from_reader(body.reader()).map_err(new_xml_deserialize_error)?; + let mut metadata = MetadataBuilder::unknown(); + metadata.etag(result.etag); + if let Some(version) = + parse_header_to_str(&parts.headers, constants::X_OSS_VERSION_ID)? + { + metadata.version(version); + } + Ok(metadata.build()) + } + _ => Err(parse_error( + ErrorContext::new(ServiceOperation("CompleteMultipartUpload")), + resp, + )), + } + } + + async fn abort_copy(&self, upload_id: &str) -> Result<()> { + let resp = self + .core + .oss_abort_multipart_upload(&self.ctx, &self.to, upload_id) + .await?; + if resp.status() == StatusCode::NO_CONTENT { + return Ok(()); + } + let error = parse_error( + ErrorContext::new(ServiceOperation("AbortMultipartUpload")), + resp, + ); + match error.kind() { + ErrorKind::NotFound => Ok(()), + _ => Err(error), + } + } +} diff --git a/core/services/oss/src/core.rs b/core/services/oss/src/core.rs index e9e00b6711..807a087ca7 100644 --- a/core/services/oss/src/core.rs +++ b/core/services/oss/src/core.rs @@ -30,6 +30,7 @@ use http::header::CONTENT_DISPOSITION; use http::header::CONTENT_ENCODING; use http::header::CONTENT_LENGTH; use http::header::CONTENT_TYPE; +use http::header::EXPIRES; use http::header::IF_MATCH; use http::header::IF_MODIFIED_SINCE; use http::header::IF_NONE_MATCH; @@ -668,6 +669,13 @@ impl OssCore { } } + fn initiate_upload_request(&self, path: &str, is_presign: bool) -> http::request::Builder { + let path = build_absolute_path(&self.root, path); + let endpoint = self.get_endpoint(is_presign); + let url = format!("{}/{}?uploads", endpoint, percent_encode_path(&path)); + self.insert_sse_headers(Request::post(&url)) + } + pub async fn oss_initiate_upload( &self, ctx: &OperationContext, @@ -675,10 +683,7 @@ impl OssCore { args: &OpWrite, is_presign: bool, ) -> Result<Response<Buffer>> { - let path = build_absolute_path(&self.root, path); - let endpoint = self.get_endpoint(is_presign); - let url = format!("{}/{}?uploads", endpoint, percent_encode_path(&path)); - let mut req = Request::post(&url); + let mut req = self.initiate_upload_request(path, is_presign); if let Some(mime) = args.content_type() { req = req.header(CONTENT_TYPE, mime); } @@ -698,7 +703,6 @@ impl OssCore { if args.if_not_exists() { req = req.header(X_OSS_FORBID_OVERWRITE, "true"); } - req = self.insert_sse_headers(req); let req = req .extension(Operation::Write) @@ -709,6 +713,32 @@ impl OssCore { self.send(ctx, req).await } + pub async fn oss_initiate_copy( + &self, + ctx: &OperationContext, + path: &str, + source_headers: &HeaderMap, + ) -> Result<Response<Buffer>> { + let mut req = self.initiate_upload_request(path, false); + // UploadPartCopy copies bytes. Set the source's object metadata on initiation. + for (name, value) in source_headers { + if matches!( + *name, + CACHE_CONTROL | CONTENT_DISPOSITION | CONTENT_ENCODING | CONTENT_TYPE | EXPIRES + ) || name.as_str().starts_with(X_OSS_META_PREFIX) + { + req = req.header(name, value); + } + } + let req = req + .extension(Operation::Copy) + .extension(ServiceOperation("InitiateMultipartUpload")) + .body(Buffer::new()) + .map_err(new_request_build_error)?; + let req = self.sign(ctx, req).await?; + self.send(ctx, req).await + } + /// Creates a request to upload a part #[allow(clippy::too_many_arguments)] pub async fn oss_upload_part_request( @@ -744,6 +774,39 @@ impl OssCore { self.send(ctx, req).await } + #[allow(clippy::too_many_arguments)] + pub async fn oss_upload_part_copy( + &self, + ctx: &OperationContext, + from: &str, + to: &str, + upload_id: &str, + part_number: usize, + range: BytesRange, + etag: &str, + ) -> Result<Response<Buffer>> { + let source = build_absolute_path(&self.root, from); + let target = build_absolute_path(&self.root, to); + let url = format!( + "{}/{}?partNumber={}&uploadId={}", + self.get_endpoint(false), + percent_encode_path(&target), + part_number, + percent_encode_path(upload_id), + ); + let source = format!("/{}/{}", self.bucket, percent_encode_path(&source)); + let req = Request::put(&url) + .header("x-oss-copy-source", source) + .header("x-oss-copy-source-range", range.to_header()) + .header("x-oss-copy-source-if-match", etag) + .extension(Operation::Copy) + .extension(ServiceOperation("UploadPartCopy")) + .body(Buffer::new()) + .map_err(new_request_build_error)?; + let req = self.sign(ctx, req).await?; + self.send(ctx, req).await + } + pub async fn oss_complete_multipart_upload_request( &self, ctx: &OperationContext, diff --git a/core/services/oss/src/docs.md b/core/services/oss/src/docs.md index f48ccde592..093b084dda 100644 --- a/core/services/oss/src/docs.md +++ b/core/services/oss/src/docs.md @@ -49,6 +49,12 @@ RAM Role settings do not override a custom chain. Set [`reqsign_aliyun_oss::Credential::expires_in`] for temporary credentials so that the reqsign signer can cache them and refresh them before expiration. +## Copy operations + +OSS uses `CopyObject` by default. Set a copy chunk size to request server-side +multipart copy. Multipart copy reads the source metadata and uses its ETag as +an `UploadPartCopy` precondition on every part. + ## Example ### Via Builder diff --git a/core/services/oss/src/lib.rs b/core/services/oss/src/lib.rs index dc6c51efac..bb20e7de94 100644 --- a/core/services/oss/src/lib.rs +++ b/core/services/oss/src/lib.rs @@ -22,6 +22,7 @@ mod backend; mod config; +mod copier; mod core; mod deleter; mod lister;
