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 222a828449 feat(bindings/cpp): generate ReaderOptions from core (#9382)
222a828449 is described below
commit 222a8284495dbbbcbb863d516bfc7e747f9263a5
Author: Chitral Verma <[email protected]>
AuthorDate: Sun Nov 29 22:20:20 2026 +0530
feat(bindings/cpp): generate ReaderOptions from core (#9382)
* feat(bindings/cpp): generate ReaderOptions from core
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/cpp): generate ReaderOptions from core
With `content_length_hint` set, a `Read` at or past the hint returns 0
without reaching storage, so say that a missing file or a failed condition
surfaces when a read from the reader reaches storage. `ReadAt` ignores the
hint, so only `Read` and `Seek` take it as the file length. Name the stat
capability next to each condition's read capability, because `GetReader`
needs both unless the hint is set. Ignore comment lines when checking that
the methods the docs name are declared.
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/cpp): generate ReaderOptions from core
Regenerate the `ReaderOptions::prefetch` doc from the core text that #9384
corrected: up to `prefetch` finished reads can each free a slot for another
range read before OpenDAL collects their results, while reads already
submitted under `concurrent` can still finish and wait to be collected.
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/cpp/include/data_structure.hpp | 17 --
bindings/cpp/include/options.hpp | 130 ++++++++++
bindings/cpp/src/lib.rs | 48 +---
bindings/cpp/src/operator.cpp | 42 +---
bindings/cpp/src/options.rs | 37 +++
bindings/cpp/src/options_test.rs | 103 +++++++-
bindings/cpp/src/utils/options_converter.cpp | 15 ++
bindings/cpp/src/utils/options_converter.hpp | 1 +
bindings/cpp/tests/options_test.cpp | 325 +++++++++++++++++++++++++
dev/src/generate/cpp.rs | 345 ++++++++++++++++++++++++++-
10 files changed, 949 insertions(+), 114 deletions(-)
diff --git a/bindings/cpp/include/data_structure.hpp
b/bindings/cpp/include/data_structure.hpp
index 08a635ac4d..d3de91e4a5 100644
--- a/bindings/cpp/include/data_structure.hpp
+++ b/bindings/cpp/include/data_structure.hpp
@@ -41,23 +41,6 @@ class Entry {
std::string path;
};
-/**
- * @struct ReaderOptions
- * @brief Options for creating readers.
- */
-struct ReaderOptions {
- std::optional<std::string> version;
- std::optional<std::string> if_match;
- std::optional<std::string> if_none_match;
- std::optional<std::chrono::system_clock::time_point> if_modified_since;
- std::optional<std::chrono::system_clock::time_point> if_unmodified_since;
- std::optional<std::uint64_t> content_length_hint;
- std::size_t concurrent{0};
- std::optional<std::size_t> chunk;
- std::optional<std::size_t> gap;
- std::size_t prefetch{0};
-};
-
/**
* @struct WriteOptions
* @brief Options for write and writer operations.
diff --git a/bindings/cpp/include/options.hpp b/bindings/cpp/include/options.hpp
index 7a1610fbcf..f8cde743d3 100644
--- a/bindings/cpp/include/options.hpp
+++ b/bindings/cpp/include/options.hpp
@@ -345,4 +345,134 @@ struct ReadOptions {
std::optional<std::string> override_content_disposition;
};
+/**
+ * @struct ReaderOptions
+ * @brief Options for creating readers.
+ */
+/// Each condition checks the file being read, and every condition must hold
for
+/// the reader to produce data. Once the option and capability checks pass, a
+/// read that reaches storage fails with `NotFound` for a missing file, no
+/// matter which conditions are set. An existing file that fails a condition
+/// returns `ConditionNotMatch`, and a condition the service does not advertise
+/// through its capability returns `Unsupported`; OpenDAL never silently drops
a
+/// condition. Unless `content_length_hint` is set,
+/// `opendal::Operator::GetReader` first stats the file to learn its length.
+/// That stat carries `version` and the conditions, so a missing file or a
+/// failed condition fails `GetReader`, and each of them also needs its stat
+/// capability, such as `opendal::Capability::stat_with_if_modified_since` for
+/// `if_modified_since`; otherwise `GetReader` fails with `Unsupported`. With
+/// `content_length_hint` set, `GetReader` checks the options and capabilities
+/// without accessing storage, so a missing file or a failed condition surfaces
+/// when a read from the reader reaches storage.
+///
+/// See the conditional operation specification for the complete
cross-operation
+/// contract.
+///
+/// When the operation fails with an error kind that these docs name, such as
+/// `NotFound`, it throws a `std::exception` whose `what()` starts with that
+/// kind.
+struct ReaderOptions {
+ /// Read the given version of the file instead of the current one.
+ ///
+ /// This selects which stored version the reader returns; it is not a
+ /// condition on the file. A version that does not exist returns `NotFound`.
+ ///
+ /// Check `opendal::Capability::read_with_version` before using this option,
+ /// and also `opendal::Capability::stat_with_version` unless
+ /// `content_length_hint` is set.
+ std::optional<std::string> version;
+ /// Read only when the file has this exact ETag.
+ ///
+ /// The condition succeeds when the file exists and its ETag equals this
+ /// value. A file with a different ETag returns `ConditionNotMatch`; a
missing
+ /// file returns `NotFound`. Only concrete ETag values are portable; a
+ /// wildcard such as `"*"` has no portable meaning here.
+ ///
+ /// The operation returns `Unsupported` when the service does not advertise
+ /// `opendal::Capability::read_with_if_match`, or, unless
+ /// `content_length_hint` is set, `opendal::Capability::stat_with_if_match`.
+ std::optional<std::string> if_match;
+ /// Read only when the file does not have this ETag.
+ ///
+ /// With a concrete ETag value, the condition succeeds when the file exists
+ /// with a different ETag. A file whose ETag equals this value returns
+ /// `ConditionNotMatch`; a missing file returns `NotFound`. Only concrete
ETag
+ /// values are portable; a wildcard such as `"*"` has no portable meaning
+ /// here.
+ ///
+ /// The operation returns `Unsupported` when the service does not advertise
+ /// `opendal::Capability::read_with_if_none_match`, or, unless
+ /// `content_length_hint` is set,
+ /// `opendal::Capability::stat_with_if_none_match`.
+ std::optional<std::string> if_none_match;
+ /// Read only when the file was modified after this timestamp.
+ ///
+ /// The condition succeeds when the file exists and was modified after this
+ /// time. A file not modified since this time returns `ConditionNotMatch`; a
+ /// missing file returns `NotFound`.
+ ///
+ /// The operation returns `Unsupported` when the service does not advertise
+ /// `opendal::Capability::read_with_if_modified_since`, or, unless
+ /// `content_length_hint` is set,
+ /// `opendal::Capability::stat_with_if_modified_since`.
+ std::optional<std::chrono::system_clock::time_point> if_modified_since;
+ /// Read only when the file was not modified after this timestamp.
+ ///
+ /// The condition succeeds when the file exists and was not modified after
+ /// this time. A file modified after this time returns `ConditionNotMatch`; a
+ /// missing file returns `NotFound`.
+ ///
+ /// The operation returns `Unsupported` when the service does not advertise
+ /// `opendal::Capability::read_with_if_unmodified_since`, or, unless
+ /// `content_length_hint` is set,
+ /// `opendal::Capability::stat_with_if_unmodified_since`.
+ std::optional<std::chrono::system_clock::time_point> if_unmodified_since;
+ /// Known content length of the object.
+ ///
+ /// This is an execution hint that allows OpenDAL to avoid extra metadata
+ /// requests while planning reads. It must not be used as an object identity
+ /// or consistency condition. When it is set, `opendal::Operator::GetReader`
+ /// does not stat the file, and `opendal::Reader::Read` and
+ /// `opendal::Reader::Seek` take this value as the file length: `Read`
returns
+ /// 0 once the position reaches it, without accessing storage, and seeking
+ /// relative to the end starts there. With a value larger than the file, a
+ /// `Read` that reaches past the end of the file fails.
+ /// `opendal::Reader::ReadAt` ignores this value and reads the range it is
+ /// given.
+ std::optional<std::uint64_t> content_length_hint;
+ /// Set `concurrent` for the operation.
+ ///
+ /// OpenDAL reads a file without concurrency by default. This is not
efficient
+ /// for cases when users read large chunks of data. By setting `concurrent`
+ /// together with `chunk`, opendal will read files concurrently on supported
+ /// storage services.
+ ///
+ /// By setting `concurrent`, opendal will fetch chunks concurrently with the
+ /// given chunk size. Without `chunk`, OpenDAL does not read concurrently.
+ std::size_t concurrent{0};
+ /// Set `chunk` for the operation.
+ ///
+ /// By default, OpenDAL reads each range with a single request instead of in
+ /// chunks. Users can set chunk based on their own needs. `0` has the same
+ /// behavior as `std::nullopt`.
+ ///
+ /// `opendal::Reader::Read` and `opendal::Reader::ReadAt` read a range with
an
+ /// end, so a positive `chunk` does not make them stat the file.
+ std::optional<std::size_t> chunk;
+ /// Each call to `opendal::Reader::Read` or `opendal::Reader::ReadAt` reads a
+ /// single byte range, so `gap` has no effect.
+ std::optional<std::size_t> gap;
+ /// Controls read-ahead during concurrent range reads.
+ ///
+ /// Up to `prefetch` finished reads can each free a slot for another range
+ /// read before OpenDAL collects their results.
+ ///
+ /// The default, `0`, disables these extra slots. Reads already submitted
+ /// under `concurrent` can still finish and wait to be collected.
+ ///
+ /// Serial reads collect each result before starting the next read. Higher
+ /// values can increase memory use.
+ std::size_t prefetch{0};
+};
+
} // namespace opendal
diff --git a/bindings/cpp/src/lib.rs b/bindings/cpp/src/lib.rs
index 1df98bcd06..73080c039f 100644
--- a/bindings/cpp/src/lib.rs
+++ b/bindings/cpp/src/lib.rs
@@ -39,7 +39,6 @@ use std::sync::LazyLock;
use anyhow::Result;
use lister::Lister;
-use od::raw::Timestamp;
use opendal as od;
use reader::Reader;
use writer::Writer;
@@ -68,25 +67,6 @@ mod ffi {
value: usize,
}
- struct OptionalTimestamp {
- has_value: bool,
- seconds: i64,
- nanoseconds: u32,
- }
-
- struct FfiReaderOptions {
- version: OptionalString,
- if_match: OptionalString,
- if_none_match: OptionalString,
- if_modified_since: OptionalTimestamp,
- if_unmodified_since: OptionalTimestamp,
- content_length_hint: OptionalU64,
- concurrent: usize,
- chunk: OptionalUsize,
- gap: OptionalUsize,
- prefetch: usize,
- }
-
struct FfiWriteOptions {
append: bool,
cache_control: OptionalString,
@@ -160,6 +140,8 @@ mod ffi {
type FfiDeleteOptions = crate::options::ffi::FfiDeleteOptions;
#[namespace = "opendal::ffi::options"]
type FfiReadOptions = crate::options::ffi::FfiReadOptions;
+ #[namespace = "opendal::ffi::options"]
+ type FfiReaderOptions = crate::options::ffi::FfiReaderOptions;
}
extern "Rust" {
@@ -357,14 +339,6 @@ fn optional_usize(v: ffi::OptionalUsize) -> Option<usize> {
v.has_value.then_some(v.value)
}
-fn optional_timestamp(v: ffi::OptionalTimestamp) -> Result<Option<Timestamp>> {
- if v.has_value {
- Ok(Some(Timestamp::new(v.seconds, v.nanoseconds as i32)?))
- } else {
- Ok(None)
- }
-}
-
fn user_metadata(
has_value: bool,
values: Vec<ffi::HashMapValue>,
@@ -377,22 +351,6 @@ fn user_metadata(
})
}
-fn reader_options(opts: ffi::FfiReaderOptions) ->
Result<od::options::ReaderOptions> {
- Ok(od::options::ReaderOptions {
- version: optional_string(opts.version),
- if_match: optional_string(opts.if_match),
- if_none_match: optional_string(opts.if_none_match),
- if_modified_since: optional_timestamp(opts.if_modified_since)?,
- if_unmodified_since: optional_timestamp(opts.if_unmodified_since)?,
- content_length_hint: optional_u64(opts.content_length_hint),
- concurrent: opts.concurrent,
- chunk: optional_usize(opts.chunk),
- gap: optional_usize(opts.gap),
- prefetch: opts.prefetch,
- ..Default::default()
- })
-}
-
fn write_options(opts: ffi::FfiWriteOptions) -> od::options::WriteOptions {
od::options::WriteOptions {
append: opts.append,
@@ -518,7 +476,7 @@ impl Operator {
}
fn reader_options(&self, path: &str, opts: ffi::FfiReaderOptions) ->
Result<*mut Reader> {
- let opts = reader_options(opts)?;
+ let opts: od::options::ReaderOptions = opts.try_into()?;
let content_length = match opts.content_length_hint {
Some(v) => v,
None => {
diff --git a/bindings/cpp/src/operator.cpp b/bindings/cpp/src/operator.cpp
index 6bb95c7d49..c89b619736 100644
--- a/bindings/cpp/src/operator.cpp
+++ b/bindings/cpp/src/operator.cpp
@@ -17,7 +17,6 @@
* under the License.
*/
-#include <chrono>
#include <cstdint>
#include <stdexcept>
@@ -55,28 +54,6 @@ ffi::OptionalUsize ToFfiOptionalUsize(const
std::optional<std::size_t> &value) {
return ffi::OptionalUsize{false, 0};
}
-ffi::OptionalTimestamp ToFfiOptionalTimestamp(
- const std::optional<std::chrono::system_clock::time_point> &value) {
- if (!value.has_value()) {
- return ffi::OptionalTimestamp{false, 0, 0};
- }
-
- auto duration = value->time_since_epoch();
- auto seconds_duration =
- std::chrono::duration_cast<std::chrono::seconds>(duration);
- auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(
- duration - seconds_duration)
- .count();
- auto seconds = seconds_duration.count();
- if (nanoseconds < 0) {
- --seconds;
- nanoseconds += 1000000000;
- }
-
- return ffi::OptionalTimestamp{true, static_cast<std::int64_t>(seconds),
- static_cast<std::uint32_t>(nanoseconds)};
-}
-
rust::Vec<ffi::HashMapValue> ToFfiHashMap(
const std::unordered_map<std::string, std::string> &map) {
rust::Vec<ffi::HashMapValue> values;
@@ -87,21 +64,6 @@ rust::Vec<ffi::HashMapValue> ToFfiHashMap(
return values;
}
-ffi::FfiReaderOptions ToFfiOptions(const ReaderOptions &options) {
- return ffi::FfiReaderOptions{
- ToFfiOptionalString(options.version),
- ToFfiOptionalString(options.if_match),
- ToFfiOptionalString(options.if_none_match),
- ToFfiOptionalTimestamp(options.if_modified_since),
- ToFfiOptionalTimestamp(options.if_unmodified_since),
- ToFfiOptionalU64(options.content_length_hint),
- options.concurrent,
- ToFfiOptionalUsize(options.chunk),
- ToFfiOptionalUsize(options.gap),
- options.prefetch,
- };
-}
-
ffi::FfiWriteOptions ToFfiOptions(const WriteOptions &options) {
auto metadata = options.user_metadata.has_value()
? ToFfiHashMap(*options.user_metadata)
@@ -322,8 +284,8 @@ Reader Operator::GetReader(std::string_view path) {
Reader Operator::GetReader(std::string_view path,
const ReaderOptions &options) {
- return CheckedOperator(operator_).reader_options(utils::rust_str(path),
- ToFfiOptions(options));
+ return CheckedOperator(operator_).reader_options(
+ utils::rust_str(path), utils::ToFfiOptions(options));
}
Writer Operator::GetWriter(std::string_view path) {
diff --git a/bindings/cpp/src/options.rs b/bindings/cpp/src/options.rs
index e7b2734816..aedd5b0cc4 100644
--- a/bindings/cpp/src/options.rs
+++ b/bindings/cpp/src/options.rs
@@ -91,6 +91,19 @@ pub mod ffi {
override_cache_control: OptionalString,
override_content_disposition: OptionalString,
}
+
+ struct FfiReaderOptions {
+ version: OptionalString,
+ if_match: OptionalString,
+ if_none_match: OptionalString,
+ if_modified_since: OptionalTimestamp,
+ if_unmodified_since: OptionalTimestamp,
+ content_length_hint: OptionalU64,
+ concurrent: usize,
+ chunk: OptionalUsize,
+ gap: OptionalUsize,
+ prefetch: usize,
+ }
}
fn optional_string(v: ffi::OptionalString) -> Option<String> {
@@ -207,3 +220,27 @@ impl TryFrom<ffi::FfiReadOptions> for
opendal::options::ReadOptions {
})
}
}
+
+impl TryFrom<ffi::FfiReaderOptions> for opendal::options::ReaderOptions {
+ type Error = opendal::Error;
+
+ fn try_from(opts: ffi::FfiReaderOptions) -> Result<Self, Self::Error> {
+ Ok(Self {
+ version: optional_string(opts.version),
+ if_match: optional_string(opts.if_match),
+ if_none_match: optional_string(opts.if_none_match),
+ if_modified_since: optional_timestamp(opts.if_modified_since)?,
+ if_unmodified_since: optional_timestamp(opts.if_unmodified_since)?,
+ content_length_hint: optional_u64(opts.content_length_hint),
+ concurrent: opts.concurrent,
+ chunk: optional_usize(opts.chunk),
+ gap: optional_usize(opts.gap),
+ prefetch: opts.prefetch,
+ // Not exposed in C++ yet:
+ // - `if_version_match`
+ // - `if_version_not_match`
+ // - `checksum`
+ ..Default::default()
+ })
+ }
+}
diff --git a/bindings/cpp/src/options_test.rs b/bindings/cpp/src/options_test.rs
index bf02cfb7ed..2be040b8c5 100644
--- a/bindings/cpp/src/options_test.rs
+++ b/bindings/cpp/src/options_test.rs
@@ -15,14 +15,16 @@
// specific language governing permissions and limitations
// under the License.
-//! The generated `ListOptions`, `StatOptions`, `DeleteOptions`, and
-//! `ReadOptions` conversions in `options.rs` carry every bridge field to the
-//! core field of the same name, and absent values stay absent.
+//! The generated `ListOptions`, `StatOptions`, `DeleteOptions`,
+//! `ReadOptions`, and `ReaderOptions` conversions in `options.rs` carry every
+//! bridge field to the core field of the same name, and absent values stay
+//! absent.
use opendal::BytesRange;
use opendal::options::DeleteOptions;
use opendal::options::ListOptions;
use opendal::options::ReadOptions;
+use opendal::options::ReaderOptions;
use opendal::options::StatOptions;
use opendal::raw::Timestamp;
@@ -343,3 +345,98 @@ fn test_read_options_reject_out_of_range_timestamps() {
);
}
}
+
+fn absent_reader_options() -> ffi::FfiReaderOptions {
+ ffi::FfiReaderOptions {
+ version: bridge_string(None),
+ if_match: bridge_string(None),
+ if_none_match: bridge_string(None),
+ if_modified_since: bridge_timestamp(None),
+ if_unmodified_since: bridge_timestamp(None),
+ content_length_hint: bridge_u64(None),
+ concurrent: 0,
+ chunk: bridge_usize(None),
+ gap: bridge_usize(None),
+ prefetch: 0,
+ }
+}
+
+#[test]
+fn test_reader_options_carry_every_field() {
+ let opts = ffi::FfiReaderOptions {
+ version: bridge_string(Some("version")),
+ if_match: bridge_string(Some("if_match")),
+ if_none_match: bridge_string(Some("if_none_match")),
+ if_modified_since: bridge_timestamp(Some((1_700_000_000, 250_000))),
+ if_unmodified_since: bridge_timestamp(Some((-1, 999_999_000))),
+ content_length_hint: bridge_u64(Some(u64::MAX)),
+ concurrent: 4,
+ chunk: bridge_usize(Some(16)),
+ gap: bridge_usize(Some(32)),
+ prefetch: 8,
+ };
+
+ // The options that C++ does not expose keep their core defaults, as on
+ // `main`.
+ let expected = ReaderOptions {
+ version: Some("version".to_string()),
+ if_match: Some("if_match".to_string()),
+ if_none_match: Some("if_none_match".to_string()),
+ if_modified_since: Some(Timestamp::new(1_700_000_000,
250_000).unwrap()),
+ if_unmodified_since: Some(Timestamp::new(-1, 999_999_000).unwrap()),
+ content_length_hint: Some(u64::MAX),
+ concurrent: 4,
+ chunk: Some(16),
+ gap: Some(32),
+ prefetch: 8,
+ ..Default::default()
+ };
+ assert_eq!(ReaderOptions::try_from(opts).unwrap(), expected);
+}
+
+#[test]
+fn test_reader_options_keep_explicit_zeros() {
+ let opts = ffi::FfiReaderOptions {
+ content_length_hint: bridge_u64(Some(0)),
+ chunk: bridge_usize(Some(0)),
+ gap: bridge_usize(Some(0)),
+ ..absent_reader_options()
+ };
+
+ let options = ReaderOptions::try_from(opts).unwrap();
+ assert_eq!(options.content_length_hint, Some(0));
+ assert_eq!(options.chunk, Some(0));
+ assert_eq!(options.gap, Some(0));
+}
+
+#[test]
+fn test_reader_options_keep_absent_values_absent() {
+ // C++ sends a value behind `has_value == false`; it must not reach core.
+ assert_eq!(
+ ReaderOptions::try_from(absent_reader_options()).unwrap(),
+ ReaderOptions::default()
+ );
+}
+
+#[test]
+fn test_reader_options_reject_out_of_range_timestamps() {
+ // Creating the reader fails before the stat, as it did on `main`.
+ for opts in [
+ ffi::FfiReaderOptions {
+ if_modified_since: bridge_timestamp(Some((i64::MAX, 0))),
+ ..absent_reader_options()
+ },
+ ffi::FfiReaderOptions {
+ if_unmodified_since: bridge_timestamp(Some((i64::MAX, 0))),
+ ..absent_reader_options()
+ },
+ ] {
+ let err = ReaderOptions::try_from(opts).unwrap_err();
+ assert_eq!(err.kind(), opendal::ErrorKind::Unexpected);
+ assert!(
+ err.to_string()
+ .contains("create timestamp from '9223372036854775807'
seconds"),
+ "{err}"
+ );
+ }
+}
diff --git a/bindings/cpp/src/utils/options_converter.cpp
b/bindings/cpp/src/utils/options_converter.cpp
index b83f2172da..75054b11cb 100644
--- a/bindings/cpp/src/utils/options_converter.cpp
+++ b/bindings/cpp/src/utils/options_converter.cpp
@@ -136,4 +136,19 @@ ffi::options::FfiReadOptions ToFfiOptions(const
ReadOptions &options) {
};
}
+ffi::options::FfiReaderOptions ToFfiOptions(const ReaderOptions &options) {
+ return ffi::options::FfiReaderOptions{
+ ToFfiOptionalString(options.version),
+ ToFfiOptionalString(options.if_match),
+ ToFfiOptionalString(options.if_none_match),
+ ToFfiOptionalTimestamp(options.if_modified_since),
+ ToFfiOptionalTimestamp(options.if_unmodified_since),
+ ToFfiOptionalU64(options.content_length_hint),
+ options.concurrent,
+ ToFfiOptionalUsize(options.chunk),
+ ToFfiOptionalUsize(options.gap),
+ options.prefetch,
+ };
+}
+
} // namespace opendal::utils
diff --git a/bindings/cpp/src/utils/options_converter.hpp
b/bindings/cpp/src/utils/options_converter.hpp
index 89b7c79591..bab5c53d3f 100644
--- a/bindings/cpp/src/utils/options_converter.hpp
+++ b/bindings/cpp/src/utils/options_converter.hpp
@@ -31,5 +31,6 @@ ffi::options::FfiListOptions ToFfiOptions(const ListOptions
&options);
ffi::options::FfiStatOptions ToFfiOptions(const StatOptions &options);
ffi::options::FfiDeleteOptions ToFfiOptions(const DeleteOptions &options);
ffi::options::FfiReadOptions ToFfiOptions(const ReadOptions &options);
+ffi::options::FfiReaderOptions ToFfiOptions(const ReaderOptions &options);
} // namespace opendal::utils
diff --git a/bindings/cpp/tests/options_test.cpp
b/bindings/cpp/tests/options_test.cpp
index 8270123459..3f6730633b 100644
--- a/bindings/cpp/tests/options_test.cpp
+++ b/bindings/cpp/tests/options_test.cpp
@@ -17,11 +17,16 @@
* under the License.
*/
+#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <exception>
+#include <filesystem>
+#include <ios>
+#include <optional>
#include <string>
+#include <system_error>
#include <utility>
#include "gmock/gmock.h"
@@ -564,3 +569,323 @@ TEST(OptionsTest, ReadOptionsErrorsStartWithErrorKind) {
}
}
}
+
+TEST(OptionsTest, ReaderOptionsPositionalInitializerReachesBridge) {
+ const std::chrono::system_clock::time_point modified{
+ std::chrono::seconds{1700000000} + std::chrono::microseconds{250}};
+ const std::chrono::system_clock::time_point unmodified{
+ std::chrono::microseconds{-1}};
+ // Every member in the order `data_structure.hpp` declared them before
+ // `ReaderOptions` was generated.
+ const opendal::ReaderOptions options{
+ /*version=*/"version",
+ /*if_match=*/"if_match",
+ /*if_none_match=*/"if_none_match",
+ /*if_modified_since=*/modified,
+ /*if_unmodified_since=*/unmodified,
+ /*content_length_hint=*/std::uint64_t{42},
+ /*concurrent=*/4,
+ /*chunk=*/16,
+ /*gap=*/32,
+ /*prefetch=*/8,
+ };
+
+ const auto ffi = opendal::utils::ToFfiOptions(options);
+
+ EXPECT_TRUE(ffi.version.has_value);
+ EXPECT_EQ(std::string(ffi.version.value), "version");
+ EXPECT_TRUE(ffi.if_match.has_value);
+ EXPECT_EQ(std::string(ffi.if_match.value), "if_match");
+ EXPECT_TRUE(ffi.if_none_match.has_value);
+ EXPECT_EQ(std::string(ffi.if_none_match.value), "if_none_match");
+ EXPECT_TRUE(ffi.if_modified_since.has_value);
+ EXPECT_EQ(ffi.if_modified_since.seconds, std::int64_t{1700000000});
+ EXPECT_EQ(ffi.if_modified_since.nanoseconds, std::uint32_t{250000});
+ // A time before the epoch keeps a non-negative nanosecond part.
+ EXPECT_TRUE(ffi.if_unmodified_since.has_value);
+ EXPECT_EQ(ffi.if_unmodified_since.seconds, std::int64_t{-1});
+ EXPECT_EQ(ffi.if_unmodified_since.nanoseconds, std::uint32_t{999999000});
+ EXPECT_TRUE(ffi.content_length_hint.has_value);
+ EXPECT_EQ(ffi.content_length_hint.value, std::uint64_t{42});
+ EXPECT_EQ(ffi.concurrent, std::size_t{4});
+ EXPECT_TRUE(ffi.chunk.has_value);
+ EXPECT_EQ(ffi.chunk.value, std::size_t{16});
+ EXPECT_TRUE(ffi.gap.has_value);
+ EXPECT_EQ(ffi.gap.value, std::size_t{32});
+ EXPECT_EQ(ffi.prefetch, std::size_t{8});
+}
+
+TEST(OptionsTest, ReaderOptionsStructuredBindingsKeepMemberOrder) {
+ opendal::ReaderOptions options;
+ auto &[version, if_match, if_none_match, if_modified_since,
+ if_unmodified_since, content_length_hint, concurrent, chunk, gap,
+ prefetch] = options;
+
+ EXPECT_EQ(&version, &options.version);
+ EXPECT_EQ(&if_match, &options.if_match);
+ EXPECT_EQ(&if_none_match, &options.if_none_match);
+ EXPECT_EQ(&if_modified_since, &options.if_modified_since);
+ EXPECT_EQ(&if_unmodified_since, &options.if_unmodified_since);
+ EXPECT_EQ(&content_length_hint, &options.content_length_hint);
+ EXPECT_EQ(&concurrent, &options.concurrent);
+ EXPECT_EQ(&chunk, &options.chunk);
+ EXPECT_EQ(&gap, &options.gap);
+ EXPECT_EQ(&prefetch, &options.prefetch);
+}
+
+TEST(OptionsTest, DefaultReaderOptionsReachBridgeAbsent) {
+ const opendal::ReaderOptions options;
+
+ const auto ffi = opendal::utils::ToFfiOptions(options);
+
+ EXPECT_FALSE(ffi.version.has_value);
+ EXPECT_FALSE(ffi.if_match.has_value);
+ EXPECT_FALSE(ffi.if_none_match.has_value);
+ EXPECT_FALSE(ffi.if_modified_since.has_value);
+ EXPECT_FALSE(ffi.if_unmodified_since.has_value);
+ EXPECT_FALSE(ffi.content_length_hint.has_value);
+ EXPECT_EQ(ffi.concurrent, std::size_t{0});
+ EXPECT_FALSE(ffi.chunk.has_value);
+ EXPECT_FALSE(ffi.gap.has_value);
+ EXPECT_EQ(ffi.prefetch, std::size_t{0});
+}
+
+namespace {
+
+// Read `reader` to its end with `opendal::Reader::Read`, `size` bytes at a
+// time.
+std::string ReadToEnd(opendal::Reader &reader, std::streamsize size = 4096) {
+ std::string out;
+ std::string buf(static_cast<std::size_t>(size), '\0');
+ while (true) {
+ const auto n = reader.Read(buf.data(), size);
+ if (n == 0) {
+ return out;
+ }
+ out.append(buf.data(), static_cast<std::size_t>(n));
+ }
+}
+
+class ReaderOptionsTempDir {
+ public:
+ ReaderOptionsTempDir() {
+ static std::atomic<unsigned> next_id{0};
+ path_ = std::filesystem::temp_directory_path() /
+ ("opendal-cpp-reader-options-" +
+ std::to_string(
+ std::chrono::steady_clock::now().time_since_epoch().count()) +
+ "-" + std::to_string(next_id.fetch_add(1)));
+ std::filesystem::create_directories(path_);
+ }
+
+ ~ReaderOptionsTempDir() {
+ std::error_code ignored;
+ std::filesystem::remove_all(path_, ignored);
+ }
+
+ ReaderOptionsTempDir(const ReaderOptionsTempDir &) = delete;
+ ReaderOptionsTempDir &operator=(const ReaderOptionsTempDir &) = delete;
+
+ std::string path() const { return path_.string(); }
+
+ private:
+ std::filesystem::path path_;
+};
+
+} // namespace
+
+TEST(OptionsTest, ReaderOptionsSucceedOnMemory) {
+ opendal::Operator op("memory");
+ op.Write("reader_succeed", "0123456789");
+
+ opendal::ReaderOptions content_length_hint;
+ content_length_hint.content_length_hint = 10;
+ opendal::ReaderOptions concurrent;
+ concurrent.chunk = 3;
+ concurrent.concurrent = 2;
+ concurrent.prefetch = 1;
+ opendal::ReaderOptions no_chunk;
+ no_chunk.chunk = 0;
+ opendal::ReaderOptions gap;
+ gap.gap = 0;
+ for (const auto &options : {opendal::ReaderOptions{}, content_length_hint,
+ concurrent, no_chunk, gap}) {
+ auto reader = op.GetReader("reader_succeed", options);
+ EXPECT_EQ(ReadToEnd(reader, 4), "0123456789");
+ }
+
+ // `chunk` reaches core: on `memory`, a read that ends past the end of the
+ // file fails with `RangeNotSatisfied` only when a chunk starts there, and
+ // `0` reads as `std::nullopt` does.
+ opendal::ReaderOptions past_end;
+ past_end.content_length_hint = 12;
+ for (const std::optional<std::size_t> chunk :
+ {std::optional<std::size_t>{}, std::optional<std::size_t>{0}}) {
+ past_end.chunk = chunk;
+ auto reader = op.GetReader("reader_succeed", past_end);
+ EXPECT_THAT([&] { ReadToEnd(reader); },
+ ::testing::ThrowsMessage<std::exception>(
+ ::testing::StartsWith("Unexpected")));
+ }
+ past_end.chunk = 2;
+ auto reader = op.GetReader("reader_succeed", past_end);
+ EXPECT_THAT([&] { ReadToEnd(reader); },
+ ::testing::ThrowsMessage<std::exception>(
+ ::testing::StartsWith("RangeNotSatisfied")));
+}
+
+TEST(OptionsTest, ReaderOptionsContentLengthHintSetsReaderLength) {
+ opendal::Operator op("memory");
+ op.Write("reader_hint", "0123456789");
+
+ // The reader takes the hint as the file length.
+ opendal::ReaderOptions shorter;
+ shorter.content_length_hint = 4;
+ auto reader = op.GetReader("reader_hint", shorter);
+ EXPECT_EQ(ReadToEnd(reader, 3), "0123");
+ EXPECT_EQ(reader.Seek(0, std::ios_base::end), std::streampos{4});
+ EXPECT_EQ(reader.Seek(-2, std::ios_base::end), std::streampos{2});
+ EXPECT_EQ(ReadToEnd(reader), "23");
+ // `ReadAt` ignores the hint and reads the range it is given.
+ char range[6];
+ EXPECT_EQ(reader.ReadAt(range, sizeof(range), 4), 6);
+ EXPECT_EQ(std::string(range, sizeof(range)), "456789");
+
+ // A larger hint fails the read that reaches past the end of the file.
+ opendal::ReaderOptions longer;
+ longer.content_length_hint = 12;
+ auto past_end = op.GetReader("reader_hint", longer);
+ EXPECT_EQ(past_end.Seek(0, std::ios_base::end), std::streampos{12});
+ past_end.Seek(0, std::ios_base::beg);
+ char buf[3];
+ for (int i = 0; i < 3; i++) {
+ EXPECT_EQ(past_end.Read(buf, sizeof(buf)), 3);
+ }
+ EXPECT_THROW(past_end.Read(buf, sizeof(buf)), std::exception);
+
+ // Without the hint, the reader takes the length from its stat.
+ auto stat = op.GetReader("reader_hint", opendal::ReaderOptions{});
+ EXPECT_EQ(stat.Seek(0, std::ios_base::end), std::streampos{10});
+}
+
+TEST(OptionsTest, ReaderOptionsErrorsStartWithErrorKind) {
+ using ::testing::AllOf;
+ using ::testing::HasSubstr;
+ using ::testing::StartsWith;
+ using ::testing::ThrowsMessage;
+
+ opendal::Operator op("memory");
+ op.Write("reader_errors", "hello");
+
+ // Without `content_length_hint`, `GetReader` stats the file, so a missing
+ // file fails `GetReader` with `NotFound`. With it, the first read does.
+ EXPECT_THAT(
+ [&] { op.GetReader("reader_errors_missing", opendal::ReaderOptions{}); },
+ ThrowsMessage<std::exception>(
+ AllOf(StartsWith("NotFound"), HasSubstr(" at stat"))));
+ opendal::ReaderOptions hint;
+ hint.content_length_hint = 5;
+ auto missing = op.GetReader("reader_errors_missing", hint);
+ EXPECT_THAT([&] { ReadToEnd(missing); },
+ ThrowsMessage<std::exception>(StartsWith("NotFound")));
+ // A `Read` at the hint does not reach storage, so it returns 0 instead,
+ // while `ReadAt` still fails.
+ char buf[4];
+ missing.Seek(5, std::ios_base::beg);
+ EXPECT_EQ(missing.Read(buf, sizeof(buf)), 0);
+ opendal::ReaderOptions zero;
+ zero.content_length_hint = 0;
+ auto empty = op.GetReader("reader_errors_missing", zero);
+ EXPECT_EQ(empty.Read(buf, sizeof(buf)), 0);
+ EXPECT_THAT([&] { empty.ReadAt(buf, sizeof(buf), 0); },
+ ThrowsMessage<std::exception>(StartsWith("NotFound")));
+
+ // The memory service advertises none of these conditions for stat or read.
+ // Without the hint, the stat rejects each one; with it, creating the reader
+ // does. Neither looks for the file.
+ const auto info = op.Info();
+ ASSERT_FALSE(info.stat_with_version || info.read_with_version);
+ ASSERT_FALSE(info.stat_with_if_match || info.read_with_if_match);
+ ASSERT_FALSE(info.stat_with_if_none_match || info.read_with_if_none_match);
+ ASSERT_FALSE(info.stat_with_if_modified_since ||
+ info.read_with_if_modified_since);
+ ASSERT_FALSE(info.stat_with_if_unmodified_since ||
+ info.read_with_if_unmodified_since);
+ opendal::ReaderOptions version;
+ version.version = "version";
+ opendal::ReaderOptions if_match;
+ if_match.if_match = "etag";
+ opendal::ReaderOptions if_none_match;
+ if_none_match.if_none_match = "etag";
+ opendal::ReaderOptions if_modified_since;
+ if_modified_since.if_modified_since = std::chrono::system_clock::now();
+ opendal::ReaderOptions if_unmodified_since;
+ if_unmodified_since.if_unmodified_since = std::chrono::system_clock::now();
+ const std::pair<std::string, opendal::ReaderOptions> cases[] = {
+ {"version", version},
+ {"if_match", if_match},
+ {"if_none_match", if_none_match},
+ {"if_modified_since", if_modified_since},
+ {"if_unmodified_since", if_unmodified_since},
+ };
+ for (const auto &item : cases) {
+ for (const bool with_hint : {false, true}) {
+ for (const char *path : {"reader_errors", "reader_errors_missing"}) {
+ auto options = item.second;
+ if (with_hint) {
+ options.content_length_hint = 5;
+ }
+ const std::string operation = with_hint ? "read" : "stat";
+ EXPECT_THAT([&] { op.GetReader(path, options); },
+ ThrowsMessage<std::exception>(AllOf(
+ StartsWith("Unsupported"),
+ HasSubstr("operation " + operation +
+ " with the arguments " + item.first + "."))))
+ << item.first << " on " << path << " with hint " << with_hint;
+ }
+ }
+ }
+}
+
+TEST(OptionsTest, ReaderOptionsStatNeedsStatCapabilityOnFs) {
+ using ::testing::AllOf;
+ using ::testing::HasSubstr;
+ using ::testing::StartsWith;
+ using ::testing::ThrowsMessage;
+
+ ReaderOptionsTempDir dir;
+ opendal::Operator op("fs", {{"root", dir.path()}});
+ op.Write("reader_fs", "0123456789");
+
+ // `fs` reads with `if_modified_since` but cannot stat with it.
+ const auto info = op.Info();
+ ASSERT_TRUE(info.read_with_if_modified_since);
+ ASSERT_FALSE(info.stat_with_if_modified_since);
+
+ opendal::ReaderOptions past;
+ past.if_modified_since =
+ std::chrono::system_clock::time_point{std::chrono::seconds{1546300800}};
+ for (const char *path : {"reader_fs", "reader_fs_missing"}) {
+ EXPECT_THAT([&] { op.GetReader(path, past); },
+ ThrowsMessage<std::exception>(
+ AllOf(StartsWith("Unsupported"),
+ HasSubstr("operation stat with the arguments "
+ "if_modified_since."))))
+ << path;
+ }
+
+ // With `content_length_hint`, `GetReader` skips the stat, and the condition
+ // and a missing file surface when reading.
+ past.content_length_hint = 10;
+ auto reader = op.GetReader("reader_fs", past);
+ EXPECT_EQ(ReadToEnd(reader), "0123456789");
+ auto missing = op.GetReader("reader_fs_missing", past);
+ EXPECT_THAT([&] { ReadToEnd(missing); },
+ ThrowsMessage<std::exception>(StartsWith("NotFound")));
+ opendal::ReaderOptions future = past;
+ future.if_modified_since =
+ std::chrono::system_clock::now() + std::chrono::hours{24};
+ auto unmodified = op.GetReader("reader_fs", future);
+ EXPECT_THAT([&] { ReadToEnd(unmodified); },
+ ThrowsMessage<std::exception>(StartsWith("ConditionNotMatch")));
+}
diff --git a/dev/src/generate/cpp.rs b/dev/src/generate/cpp.rs
index 5fc219745d..56f9f701a2 100644
--- a/dev/src/generate/cpp.rs
+++ b/dev/src/generate/cpp.rs
@@ -671,6 +671,113 @@ const OPTIONS: &[OptionsSpec] = {
(", including for presigned read requests.", "."),
],
},
+ OptionsSpec {
+ name: "ReaderOptions",
+ brief: "Options for creating readers.",
+ fields: &[
+ ("version", OptionString),
+ ("if_match", OptionString),
+ ("if_none_match", OptionString),
+ ("if_modified_since", OptionTimestamp),
+ ("if_unmodified_since", OptionTimestamp),
+ ("content_length_hint", OptionU64),
+ ("concurrent", Usize),
+ ("chunk", OptionUsize),
+ ("gap", OptionUsize),
+ ("prefetch", Usize),
+ ],
+ cpp_doc: &[],
+ // Core documents `gap` for `Reader::fetch`, which C++ does not
+ // expose.
+ cpp_member_docs: &[(
+ "gap",
+ &[
+ "Each call to `opendal::Reader::Read` or
`opendal::Reader::ReadAt` reads a",
+ "single byte range, so `gap` has no effect.",
+ ],
+ )],
+ // `Operator::GetReader` stats the file before it creates the
+ // reader, unless `content_length_hint` is set, so each condition
+ // also needs its stat capability. `Reader::Read` and `Seek` take
+ // the length from that stat or the hint, and `Reader::Read` and
+ // `Reader::ReadAt` read ranges with an end, so `chunk` adds no
+ // stat. C++ has no `Reader::fetch`.
+ cpp_rewrites: &[
+ (
+ "Creating the reader checks the options and capabilities
without \
+ accessing storage, so a missing file or a failed
condition surfaces \
+ when reading from it.",
+ "Unless `content_length_hint` is set,
`opendal::Operator::GetReader` \
+ first stats the file to learn its length. That stat
carries `version` \
+ and the conditions, so a missing file or a failed
condition fails \
+ `GetReader`, and each of them also needs its stat
capability, such as \
+ [`crate::Capability::stat_with_if_modified_since`] for \
+ `if_modified_since`; otherwise `GetReader` fails with \
+ [`crate::ErrorKind::Unsupported`]. With
`content_length_hint` set, \
+ `GetReader` checks the options and capabilities without
accessing \
+ storage, so a missing file or a failed condition surfaces
when a read \
+ from the reader reaches storage.",
+ ),
+ (
+ "Check [`crate::Capability::read_with_version`] before
using this option.",
+ "Check [`crate::Capability::read_with_version`] before
using this option, \
+ and also [`crate::Capability::stat_with_version`] unless \
+ `content_length_hint` is set.",
+ ),
+ (
+ "[`crate::Capability::read_with_if_match`].",
+ "[`crate::Capability::read_with_if_match`], or, unless \
+ `content_length_hint` is set,
[`crate::Capability::stat_with_if_match`].",
+ ),
+ (
+ "[`crate::Capability::read_with_if_none_match`].",
+ "[`crate::Capability::read_with_if_none_match`], or,
unless \
+ `content_length_hint` is set, \
+ [`crate::Capability::stat_with_if_none_match`].",
+ ),
+ (
+ "[`crate::Capability::read_with_if_modified_since`].",
+ "[`crate::Capability::read_with_if_modified_since`], or,
unless \
+ `content_length_hint` is set, \
+ [`crate::Capability::stat_with_if_modified_since`].",
+ ),
+ (
+ "[`crate::Capability::read_with_if_unmodified_since`].",
+ "[`crate::Capability::read_with_if_unmodified_since`], or,
unless \
+ `content_length_hint` is set, \
+ [`crate::Capability::stat_with_if_unmodified_since`].",
+ ),
+ (
+ "It must not be used as an object identity or consistency
condition.",
+ "It must not be used as an object identity or consistency
condition. \
+ When it is set, `opendal::Operator::GetReader` does not
stat the file, \
+ and `opendal::Reader::Read` and `opendal::Reader::Seek`
take this value \
+ as the file length: `Read` returns 0 once the position
reaches it, \
+ without accessing storage, and seeking relative to the
end starts \
+ there. With a value larger than the file, a `Read` that
reaches past \
+ the end of the file fails. `opendal::Reader::ReadAt`
ignores this value \
+ and reads the range it is given.",
+ ),
+ (
+ "Without `chunk`, only [`crate::Reader::fetch`] reads
concurrently, with \
+ one request per merged range.",
+ "Without `chunk`, OpenDAL does not read concurrently.",
+ ),
+ (
+ "A read with a positive `chunk` and an open-ended or
suffix range first \
+ stats the file to learn its length, unless
`content_length_hint` is set \
+ or an earlier read from this reader observed the length.
Unlike with \
+ [`ReadOptions::chunk`], an empty suffix range also stats
the file. \
+ That stat carries the reader's version and conditions, so
each of them \
+ also needs its stat capability, such as \
+ [`crate::Capability::stat_with_if_modified_since`] for \
+ `if_modified_since`; otherwise the read returns \
+ [`crate::ErrorKind::Unsupported`].",
+ "`opendal::Reader::Read` and `opendal::Reader::ReadAt`
read a range with \
+ an end, so a positive `chunk` does not make them stat the
file.",
+ ),
+ ],
+ },
]
};
@@ -1356,9 +1463,10 @@ mod tests {
assert!(err.contains("`cache_control` is missing from core"));
}
- /// `ListOptions`, `StatOptions`, `DeleteOptions`, `ReadRange`, and
- /// `ReadOptions` as `bindings/cpp/include/data_structure.hpp` declared
- /// them on `main` before they were generated, copied verbatim.
+ /// `ListOptions`, `StatOptions`, `DeleteOptions`, `ReadRange`,
+ /// `ReadOptions`, and `ReaderOptions` as
+ /// `bindings/cpp/include/data_structure.hpp` declared them on `main`
+ /// before they were generated, copied verbatim.
/// Callers depend on each member's name, type, default member initializer,
/// and position. The generated header adds doc comments, which these texts
/// omit.
@@ -1449,6 +1557,23 @@ struct ReadOptions {
std::optional<std::string> override_content_disposition;
};"#;
+ const MAIN_READER_OPTIONS: &str = r#"/**
+ * @struct ReaderOptions
+ * @brief Options for creating readers.
+ */
+struct ReaderOptions {
+ std::optional<std::string> version;
+ std::optional<std::string> if_match;
+ std::optional<std::string> if_none_match;
+ std::optional<std::chrono::system_clock::time_point> if_modified_since;
+ std::optional<std::chrono::system_clock::time_point> if_unmodified_since;
+ std::optional<std::uint64_t> content_length_hint;
+ std::size_t concurrent{0};
+ std::optional<std::size_t> chunk;
+ std::optional<std::size_t> gap;
+ std::size_t prefetch{0};
+};"#;
+
fn core_names() -> CppNames {
CppNames::parse(&workspace_dir()).expect("parse core names")
}
@@ -1490,6 +1615,7 @@ struct ReadOptions {
MAIN_DELETE_OPTIONS,
MAIN_READ_RANGE,
MAIN_READ_OPTIONS,
+ MAIN_READER_OPTIONS,
] {
assert!(
code.contains(&code_lines(main)),
@@ -1499,7 +1625,7 @@ struct ReadOptions {
let head: String = main.lines().take(3).map(|l|
format!("{l}\n")).collect();
assert!(header.contains(&head), "header lacks:\n{head}");
}
- assert_eq!(header.matches("\nstruct ").count(), 5);
+ assert_eq!(header.matches("\nstruct ").count(), 6);
// `ReadOptions` needs `ReadRange` declared before it.
let position = |name: &str| header.find(&format!("\nstruct {name}
{{\n")).unwrap();
assert!(position("ReadRange") < position("ReadOptions"));
@@ -1651,6 +1777,12 @@ A `ReadRange::Range` whose `end` is not after `start`
reads nothing. Otherwise,
"Each call to `opendal::Operator::Read` reads a single byte range,
so `gap`
has no effect.",
),
+ (
+ "ReaderOptions",
+ "gap",
+ "Each call to `opendal::Reader::Read` or `opendal::Reader::ReadAt`
reads a
+single byte range, so `gap` has no effect.",
+ ),
];
/// C++ wording, as `(struct, core text, C++ text)`, that must replace core
@@ -1666,6 +1798,51 @@ has no effect.",
", including for presigned read requests.",
".",
),
+ (
+ "ReaderOptions",
+ "Creating the reader checks the options and capabilities without
accessing storage, so a missing file or a failed condition surfaces when
reading from it.",
+ "Unless `content_length_hint` is set,
`opendal::Operator::GetReader` first stats the file to learn its length. That
stat carries `version` and the conditions, so a missing file or a failed
condition fails `GetReader`, and each of them also needs its stat capability,
such as [`crate::Capability::stat_with_if_modified_since`] for
`if_modified_since`; otherwise `GetReader` fails with
[`crate::ErrorKind::Unsupported`]. With `content_length_hint` set, `GetReader`
checks the option [...]
+ ),
+ (
+ "ReaderOptions",
+ "Check [`crate::Capability::read_with_version`] before using this
option.",
+ "Check [`crate::Capability::read_with_version`] before using this
option, and also [`crate::Capability::stat_with_version`] unless
`content_length_hint` is set.",
+ ),
+ (
+ "ReaderOptions",
+ "[`crate::Capability::read_with_if_match`].",
+ "[`crate::Capability::read_with_if_match`], or, unless
`content_length_hint` is set, [`crate::Capability::stat_with_if_match`].",
+ ),
+ (
+ "ReaderOptions",
+ "[`crate::Capability::read_with_if_none_match`].",
+ "[`crate::Capability::read_with_if_none_match`], or, unless
`content_length_hint` is set, [`crate::Capability::stat_with_if_none_match`].",
+ ),
+ (
+ "ReaderOptions",
+ "[`crate::Capability::read_with_if_modified_since`].",
+ "[`crate::Capability::read_with_if_modified_since`], or, unless
`content_length_hint` is set,
[`crate::Capability::stat_with_if_modified_since`].",
+ ),
+ (
+ "ReaderOptions",
+ "[`crate::Capability::read_with_if_unmodified_since`].",
+ "[`crate::Capability::read_with_if_unmodified_since`], or, unless
`content_length_hint` is set,
[`crate::Capability::stat_with_if_unmodified_since`].",
+ ),
+ (
+ "ReaderOptions",
+ "It must not be used as an object identity or consistency
condition.",
+ "It must not be used as an object identity or consistency
condition. When it is set, `opendal::Operator::GetReader` does not stat the
file, and `opendal::Reader::Read` and `opendal::Reader::Seek` take this value
as the file length: `Read` returns 0 once the position reaches it, without
accessing storage, and seeking relative to the end starts there. With a value
larger than the file, a `Read` that reaches past the end of the file fails.
`opendal::Reader::ReadAt` ignores this [...]
+ ),
+ (
+ "ReaderOptions",
+ "Without `chunk`, only [`crate::Reader::fetch`] reads
concurrently, with one request per merged range.",
+ "Without `chunk`, OpenDAL does not read concurrently.",
+ ),
+ (
+ "ReaderOptions",
+ "A read with a positive `chunk` and an open-ended or suffix range
first stats the file to learn its length, unless `content_length_hint` is set
or an earlier read from this reader observed the length. Unlike with
[`ReadOptions::chunk`], an empty suffix range also stats the file. That stat
carries the reader's version and conditions, so each of them also needs its
stat capability, such as [`crate::Capability::stat_with_if_modified_since`] for
`if_modified_since`; otherwise the [...]
+ "`opendal::Reader::Read` and `opendal::Reader::ReadAt` read a
range with an end, so a positive `chunk` does not make them stat the file.",
+ ),
];
#[test]
@@ -1768,6 +1945,11 @@ has no effect.",
let read = &header[header.find(" * @struct ReadOptions\n").unwrap()..];
let read = &read[..read.find("\n};\n").unwrap()];
assert!(!read.to_lowercase().contains("presign"), "{read}");
+ // C++ has no `Reader::fetch`, so the `ReaderOptions` docs do not
+ // mention it.
+ let reader = &header[header.find(" * @struct
ReaderOptions\n").unwrap()..];
+ let reader = &reader[..reader.find("\n};\n").unwrap()];
+ assert!(!reader.contains("::fetch"), "{reader}");
// The rules for `Some(0)` and the performance guide match exact core
// text, so a reworded one must not slip through.
for rust in [
@@ -1806,11 +1988,41 @@ has no effect.",
}
let operator =
fs::read_to_string(workspace_dir().join("bindings/cpp/include/opendal.hpp"))
.expect("read opendal.hpp");
- assert!(
- operator.contains(
- " std::string Read(std::string_view path, const ReadOptions
&options);\n"
- )
- );
+ for declaration in [
+ " std::string Read(std::string_view path, const ReadOptions
&options);\n",
+ " Reader GetReader(std::string_view path, const ReaderOptions
&options);\n",
+ ] {
+ assert!(
+ operator.contains(declaration),
+ "opendal.hpp lacks {declaration}"
+ );
+ }
+ // Each `Operator` and `Reader` method that the docs name is declared
+ // in its class.
+ let class = |name: &str| {
+ let body = &operator[operator.find(&format!("\nclass {name}
{{\n")).unwrap()..];
+ body[..body.find("\n};\n").unwrap()]
+ .lines()
+ .filter(|line| {
+ let line = line.trim_start();
+ !["//", "/*", "*"]
+ .iter()
+ .any(|start| line.starts_with(start))
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+ };
+ let methods =
Regex::new(r"`opendal::(Operator|Reader)::(\w+)`").unwrap();
+ let named: Vec<_> = methods.captures_iter(&header).collect();
+ assert!(!named.is_empty());
+ for method in named {
+ assert!(
+ class(&method[1]).contains(&format!(" {}(", &method[2])),
+ "`opendal::{}` lacks `{}`",
+ &method[1],
+ &method[2]
+ );
+ }
}
#[test]
@@ -2100,6 +2312,7 @@ has no effect.",
("StatOptions", true),
("DeleteOptions", false),
("ReadOptions", true),
+ ("ReaderOptions", true),
]
);
@@ -2119,6 +2332,9 @@ has no effect.",
assert!(rust.contains(
"impl TryFrom<ffi::FfiReadOptions> for
opendal::options::ReadOptions {\n type Error = opendal::Error;\n"
));
+ assert!(rust.contains(
+ "impl TryFrom<ffi::FfiReaderOptions> for
opendal::options::ReaderOptions {\n type Error = opendal::Error;\n"
+ ));
}
#[test]
@@ -2210,6 +2426,30 @@ has no effect.",
OptionU64,
"core `ReadOptions::chunk` has kind OptionU64, but OPTIONS
lists OptionUsize",
),
+ (
+ "ReaderOptions",
+ "content_length_hint",
+ OptionUsize,
+ "core `ReaderOptions::content_length_hint` has kind
OptionUsize, but OPTIONS lists OptionU64",
+ ),
+ (
+ "ReaderOptions",
+ "concurrent",
+ OptionUsize,
+ "core `ReaderOptions::concurrent` has kind OptionUsize, but
OPTIONS lists Usize",
+ ),
+ (
+ "ReaderOptions",
+ "gap",
+ OptionU64,
+ "core `ReaderOptions::gap` has kind OptionU64, but OPTIONS
lists OptionUsize",
+ ),
+ (
+ "ReaderOptions",
+ "prefetch",
+ OptionUsize,
+ "core `ReaderOptions::prefetch` has kind OptionUsize, but
OPTIONS lists Usize",
+ ),
] {
let mut changed = parsed.clone();
changed
@@ -2254,6 +2494,19 @@ has no effect.",
.to_string(),
"OPTIONS member `ReadOptions::range` is missing from core"
);
+ let mut without_prefetch = parsed.clone();
+ without_prefetch
+ .iter_mut()
+ .find(|s| s.name == "ReaderOptions")
+ .unwrap()
+ .fields
+ .retain(|f| f.name != "prefetch");
+ assert_eq!(
+ options_models(&without_prefetch, OPTIONS, &core_names())
+ .unwrap_err()
+ .to_string(),
+ "OPTIONS member `ReaderOptions::prefetch` is missing from core"
+ );
assert_eq!(
error("WriteOptions", &[("expires", OptionDuration)]),
"the C++ bridge cannot carry `WriteOptions::expires` of kind
OptionDuration yet"
@@ -2315,6 +2568,80 @@ has no effect.",
format!("core `ReadOptions` docs no longer contain `{from}`;
review its C++ rewrite")
);
+ // Each `ReaderOptions` rewrite is checked where it applies: the
+ // struct doc (`None`) or a member doc.
+ let reader = OPTIONS.iter().find(|s| s.name ==
"ReaderOptions").unwrap();
+ let rewordings = [
+ (None, "surfaces when reading from it.", "surfaces later."),
+ (Some("version"), "before using this", "before you use this"),
+ (
+ Some("if_match"),
+ "read_with_if_match`].",
+ "read_with_if_match`] first.",
+ ),
+ (
+ Some("if_none_match"),
+ "read_with_if_none_match`].",
+ "read_with_if_none_match`] first.",
+ ),
+ (
+ Some("if_modified_since"),
+ "read_with_if_modified_since`].",
+ "read_with_if_modified_since`] first.",
+ ),
+ (
+ Some("if_unmodified_since"),
+ "read_with_if_unmodified_since`].",
+ "read_with_if_unmodified_since`] first.",
+ ),
+ (
+ Some("content_length_hint"),
+ "or consistency condition.",
+ "or consistency check.",
+ ),
+ (
+ Some("concurrent"),
+ "with one request per merged range.",
+ "with a request per merged range.",
+ ),
+ (Some("chunk"), "observed the length", "saw the length"),
+ ];
+ assert_eq!(rewordings.len(), reader.cpp_rewrites.len());
+ for (i, (field, core_text, reworded_text)) in
rewordings.into_iter().enumerate() {
+ let (from, _) = reader.cpp_rewrites[i];
+ let mut reworded = parsed_options();
+ let core = reworded
+ .iter_mut()
+ .find(|s| s.name == "ReaderOptions")
+ .unwrap();
+ let doc = match field {
+ None => &mut core.doc,
+ Some(field) => {
+ &mut core
+ .fields
+ .iter_mut()
+ .find(|f| f.name == field)
+ .unwrap()
+ .doc
+ }
+ };
+ assert!(
+ doc.iter().any(|line| line.contains(core_text)),
+ "{core_text}"
+ );
+ for line in doc.iter_mut() {
+ *line = line.replace(core_text, reworded_text);
+ }
+ assert_eq!(
+ options_models(&reworded, OPTIONS, &core_names())
+ .unwrap_err()
+ .to_string(),
+ format!(
+ "core `ReaderOptions` docs no longer contain `{from}`;
review its C++ rewrite"
+ )
+ );
+ }
+
// A rewrite also applies to member docs, and a match there counts.
let spec = OptionsSpec {
name: "ReadOptions",