This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new 9fbc31d390 feat(core): add compose to blocking::Operator (#9423)
9fbc31d390 is described below
commit 9fbc31d3904759e5c814084487cdea8118f819d5
Author: Chitral Verma <[email protected]>
AuthorDate: Mon Nov 30 14:44:39 2026 +0530
feat(core): add compose to blocking::Operator (#9423)
* feat(core): add compose to blocking::Operator
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(core): add compose to blocking::Operator
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(core): add compose to blocking::Operator
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
core/Cargo.toml | 2 +-
core/core/src/blocking/operator.rs | 70 +++++++++++++++++++++
core/core/src/docs/rfcs/8188_compose_api.md | 7 +++
core/core/src/types/operator/capability_tests.rs | 66 ++++++++++++++++++--
core/tests/behavior/blocking_compose.rs | 77 ++++++++++++++++++++++++
core/tests/behavior/main.rs | 17 ++++++
core/tests/behavior/utils.rs | 9 +++
7 files changed, 241 insertions(+), 7 deletions(-)
diff --git a/core/Cargo.toml b/core/Cargo.toml
index 90046b3ac9..9c676e664c 100644
--- a/core/Cargo.toml
+++ b/core/Cargo.toml
@@ -275,7 +275,7 @@ services-wasabi = ["dep:opendal-service-s3"]
services-webdav = ["dep:opendal-service-webdav"]
services-webhdfs = ["dep:opendal-service-webhdfs"]
services-yandex-disk = ["dep:opendal-service-yandex-disk"]
-tests = ["opendal-testkit"]
+tests = ["blocking", "opendal-testkit"]
[lib]
bench = false
diff --git a/core/core/src/blocking/operator.rs
b/core/core/src/blocking/operator.rs
index c9deeeab5c..8972178fa3 100644
--- a/core/core/src/blocking/operator.rs
+++ b/core/core/src/blocking/operator.rs
@@ -603,6 +603,76 @@ impl Operator {
Ok(blocking::Copier::new(self.handle.clone(), copier))
}
+ /// Compose complete source objects into `to` in iteration order.
+ ///
+ /// The input must be non-empty, and `to` must not be one of the inputs.
+ /// Composition preserves every source object. It does not read source
bytes
+ /// through the client when the service supports native composition.
+ ///
+ /// # Errors
+ ///
+ /// - [`ErrorKind::Unsupported`] if the service does not support
+ /// [`Capability::compose`] or a source option that is set.
+ /// - [`ErrorKind::ConfigInvalid`] if `inputs` is empty, or if a source
+ /// `if_not_changed` has no version and no non-weak ETag.
+ /// - [`ErrorKind::ConditionNotMatch`] if a source `if_not_changed`
conflicts
+ /// with its `version` or `if_match`.
+ /// - [`ErrorKind::IsSameFile`] if `to` is one of the inputs.
+ /// - [`ErrorKind::IsADirectory`] if `to` or an input is a directory path.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use opendal_core::Result;
+ /// use opendal_core::blocking;
+ ///
+ /// # fn test(op: blocking::Operator) -> Result<()> {
+ /// let _metadata = op.compose(["parts/0", "parts/1", "parts/2"],
"result")?;
+ /// # Ok(())
+ /// # }
+ /// ```
+ pub fn compose<I, D>(&self, inputs: I, to: &str) -> Result<Metadata>
+ where
+ I: IntoIterator<Item = D>,
+ D: IntoComposeInput,
+ {
+ self.compose_options(inputs, to, options::ComposeOptions::default())
+ }
+
+ /// Compose complete source objects into `to` with explicit options.
+ ///
+ /// Visit [`options::ComposeOptions`] for all available options.
+ ///
+ /// # Errors
+ ///
+ /// Returns the errors of [`Operator::compose`], and also:
+ ///
+ /// - [`ErrorKind::Unsupported`] if the service does not support a
+ /// destination option that is set.
+ /// - [`ErrorKind::ConfigInvalid`] if `if_not_changed` has no version and
no
+ /// non-weak ETag.
+ /// - [`ErrorKind::ConditionNotMatch`] if a destination condition is false,
+ /// or if `if_not_changed` conflicts with an explicit `if_match` or
+ /// `if_version_match`.
+ pub fn compose_options<I, D>(
+ &self,
+ inputs: I,
+ to: &str,
+ opts: options::ComposeOptions,
+ ) -> Result<Metadata>
+ where
+ I: IntoIterator<Item = D>,
+ D: IntoComposeInput,
+ {
+ let op = self.op.clone();
+ let inputs: Vec<_> = inputs
+ .into_iter()
+ .map(IntoComposeInput::into_compose_input)
+ .collect();
+ let to = to.to_string();
+ self.spawn_block(async move { op.compose_options(inputs, &to,
opts).await })?
+ }
+
/// Rename a file from `from` to `to`.
///
/// # Notes
diff --git a/core/core/src/docs/rfcs/8188_compose_api.md
b/core/core/src/docs/rfcs/8188_compose_api.md
index 98781f9c33..ec2443fdb4 100644
--- a/core/core/src/docs/rfcs/8188_compose_api.md
+++ b/core/core/src/docs/rfcs/8188_compose_api.md
@@ -290,3 +290,10 @@ copies with
[`Put Block From
URL`](https://learn.microsoft.com/en-us/rest/api/storageservices/put-block-from-url)
and commits their order with
[`Put Block
List`](https://learn.microsoft.com/en-us/rest/api/storageservices/put-block-list).
+
+# Implementation notes
+
+After version 1,
[apache/opendal#9423](https://github.com/apache/opendal/pull/9423)
+adds `blocking::Operator::compose` and `blocking::Operator::compose_options`.
+Each call collects the inputs on the calling thread and runs the async
+`compose_options` once. The blocking API has no `Composer`.
diff --git a/core/core/src/types/operator/capability_tests.rs
b/core/core/src/types/operator/capability_tests.rs
index 03f9df0f0d..6333f04710 100644
--- a/core/core/src/types/operator/capability_tests.rs
+++ b/core/core/src/types/operator/capability_tests.rs
@@ -108,7 +108,7 @@ impl Service for MockService {
fn compose(&self, _: &OperationContext, _: &str, _: OpCompose) ->
Result<Self::Composer> {
self.calls.fetch_add(1, Ordering::Relaxed);
Ok(MockComposer {
- accepted: 0,
+ sources: Vec::new(),
calls: self.calls.clone(),
})
}
@@ -206,25 +206,27 @@ impl oio::Copy for MockCopier {
}
struct MockComposer {
- accepted: usize,
+ sources: Vec<String>,
calls: Arc<AtomicUsize>,
}
impl oio::Compose for MockComposer {
- async fn compose(&mut self, _: &str, _: OpRead) -> Result<()> {
+ async fn compose(&mut self, path: &str, _: OpRead) -> Result<()> {
self.calls.fetch_add(1, Ordering::Relaxed);
- self.accepted += 1;
+ self.sources.push(path.to_string());
Ok(())
}
async fn close(&mut self) -> Result<Metadata> {
- if self.accepted == 0 {
+ if self.sources.is_empty() {
return Err(Error::new(
ErrorKind::ConfigInvalid,
"compose requires at least one source object",
));
}
- Ok(MetadataBuilder::file(0).build())
+ let mut metadata = MetadataBuilder::file(self.sources.len() as u64);
+ metadata.etag(self.sources.join(","));
+ Ok(metadata.build())
}
}
@@ -753,6 +755,58 @@ async fn test_compose() {
.expect("supported compose options must be forwarded");
}
+#[cfg(feature = "blocking")]
+#[test]
+fn test_blocking_compose_forwards_inputs_and_options() {
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ let op = {
+ let _guard = rt.enter();
+ crate::blocking::Operator::new(new_test_operator(Capability {
+ compose: true,
+ ..Default::default()
+ }))
+ .unwrap()
+ };
+
+ let metadata = op
+ .compose(["a", "a", "b"], "to")
+ .expect("compose capability must compose");
+ assert_eq!(
+ metadata.etag(),
+ Some("a,a,b"),
+ "mock lists sources in order"
+ );
+
+ let err = op
+ .compose(
+ [(
+ "a",
+ options::ComposeSourceOptions {
+ version: Some("version".to_string()),
+ ..Default::default()
+ },
+ )],
+ "to",
+ )
+ .expect_err("source version must require a capability");
+ assert_eq!(err.kind(), ErrorKind::Unsupported);
+
+ let err = op
+ .compose_options(
+ ["a"],
+ "to",
+ options::ComposeOptions {
+ content_type: Some("text/plain".to_string()),
+ ..Default::default()
+ },
+ )
+ .expect_err("destination content type must require a capability");
+ assert_eq!(err.kind(), ErrorKind::Unsupported);
+}
+
#[tokio::test]
async fn test_copy_with_metadata_replacement() {
let op = new_test_operator(Capability {
diff --git a/core/tests/behavior/blocking_compose.rs
b/core/tests/behavior/blocking_compose.rs
new file mode 100644
index 0000000000..d7ce17fe05
--- /dev/null
+++ b/core/tests/behavior/blocking_compose.rs
@@ -0,0 +1,77 @@
+// 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 anyhow::Result;
+
+use crate::*;
+
+pub fn tests(op: &Operator, tests: &mut Vec<Trial>) {
+ let cap = op.info().capability();
+
+ if cap.read && cap.write && cap.compose {
+ tests.extend(blocking_trials!(op,
test_blocking_compose_ordered_sources));
+ }
+
+ if cap.read && cap.write && cap.stat && cap.compose &&
cap.compose_with_if_version_match {
+ tests.extend(blocking_trials!(
+ op,
+ test_blocking_compose_with_stale_version
+ ));
+ }
+}
+
+pub fn test_blocking_compose_ordered_sources(op: blocking::Operator) ->
Result<()> {
+ let first = TEST_FIXTURE.new_file_path();
+ let second = TEST_FIXTURE.new_file_path();
+ let target = TEST_FIXTURE.new_file_path();
+
+ op.write(&first, "a")?;
+ op.write(&second, "bc")?;
+
+ let metadata = op.compose([first.as_str(), first.as_str(),
second.as_str()], &target)?;
+
+ assert_eq!(metadata.content_length(), 4);
+ assert_eq!(op.read(&target)?.to_bytes().as_ref(), b"aabc");
+ Ok(())
+}
+
+pub fn test_blocking_compose_with_stale_version(op: blocking::Operator) ->
Result<()> {
+ let source = TEST_FIXTURE.new_file_path();
+ let target = TEST_FIXTURE.new_file_path();
+
+ op.write(&source, "new")?;
+ op.write(&target, "old")?;
+ let stale = op.stat(&target)?;
+ let version = stale
+ .version()
+ .expect("version match capability requires stat to return a version");
+ op.write(&target, "replacement")?;
+
+ let err = op
+ .compose_options(
+ [source.as_str()],
+ &target,
+ options::ComposeOptions {
+ if_version_match: Some(version.to_string()),
+ ..Default::default()
+ },
+ )
+ .expect_err("a stale destination version must fail");
+ assert_eq!(err.kind(), ErrorKind::ConditionNotMatch);
+ assert_eq!(op.read(&target)?.to_bytes().as_ref(), b"replacement");
+ Ok(())
+}
diff --git a/core/tests/behavior/main.rs b/core/tests/behavior/main.rs
index 5587659140..8bfedfc292 100644
--- a/core/tests/behavior/main.rs
+++ b/core/tests/behavior/main.rs
@@ -32,6 +32,7 @@ mod async_rename;
mod async_restore;
mod async_stat;
mod async_write;
+mod blocking_compose;
use std::future::Future;
@@ -64,6 +65,21 @@ where
})
}
+fn build_blocking_trial<F>(name: &str, op: &Operator, f: F) -> Trial
+where
+ F: FnOnce(blocking::Operator) -> anyhow::Result<()> + MaybeSend + 'static,
+{
+ let op = op.clone();
+
+ Trial::test(format!("behavior::{name}"), move || {
+ let op = {
+ let _guard = TEST_RUNTIME.enter();
+ blocking::Operator::new(op).map_err(|err|
Failed::from(err.to_string()))?
+ };
+ f(op).map_err(|err| Failed::from(err.to_string()))
+ })
+}
+
fn main() -> anyhow::Result<()> {
let args = Arguments::from_args();
@@ -86,6 +102,7 @@ fn main() -> anyhow::Result<()> {
async_restore::tests(&op, &mut tests);
async_stat::tests(&op, &mut tests);
async_write::tests(&op, &mut tests);
+ blocking_compose::tests(&op, &mut tests);
// Don't init logging while building operator which may break cargo
// nextest output
diff --git a/core/tests/behavior/utils.rs b/core/tests/behavior/utils.rs
index bc9bb2d69d..9b4f874030 100644
--- a/core/tests/behavior/utils.rs
+++ b/core/tests/behavior/utils.rs
@@ -85,6 +85,15 @@ macro_rules! async_trials {
};
}
+#[macro_export]
+macro_rules! blocking_trials {
+ ($op:ident, $($test:ident),*) => {
+ vec![$(
+ $crate::build_blocking_trial(stringify!($test), $op, $test),
+ )*]
+ };
+}
+
pub struct Fixture {
pub paths: Mutex<Vec<String>>,
}