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 24cb38311a feat(bindings/java): expose remaining operation options and
toBuilder (#9234)
24cb38311a is described below
commit 24cb38311a1875e548374ec8843865a27a964110
Author: 纪华裕 <[email protected]>
AuthorDate: Sat Nov 28 23:45:24 2026 +0800
feat(bindings/java): expose remaining operation options and toBuilder
(#9234)
* feat(bindings/java): expose remaining operation options and toBuilder
* fix(services/gcs): reject unsupported write precondition combinations
---
bindings/java/src/convert.rs | 129 ++++++---
.../java/org/apache/opendal/DeleteOptions.java | 2 +-
.../main/java/org/apache/opendal/ListOptions.java | 16 +-
.../src/main/java/org/apache/opendal/Operator.java | 8 +
.../org/apache/opendal/OperatorInputStream.java | 4 +
.../main/java/org/apache/opendal/ReadOptions.java | 14 +-
.../java/org/apache/opendal/ReaderOptions.java | 2 +-
.../main/java/org/apache/opendal/StatOptions.java | 2 +-
.../main/java/org/apache/opendal/WriteOptions.java | 52 +++-
bindings/java/src/options.rs | 59 ++--
.../org/apache/opendal/test/DeleteOptionsTest.java | 9 +
.../org/apache/opendal/test/ListOptionsTest.java | 93 +++++++
.../test/OperatorInputOutputStreamTest.java | 12 +
.../org/apache/opendal/test/ReadOptionsTest.java | 53 ++++
.../org/apache/opendal/test/ReaderOptionsTest.java | 10 +
.../org/apache/opendal/test/StatOptionsTest.java | 30 ++
.../org/apache/opendal/test/WriteOptionsTest.java | 303 +++++++++++++++++++++
core/services/gcs/src/backend.rs | 7 +
core/services/gcs/src/core.rs | 157 ++++++++---
dev/src/generate/java.rs | 285 ++++++++++++++-----
dev/src/generate/java/options_java.j2 | 2 +-
dev/src/generate/java/options_rs.j2 | 33 +--
22 files changed, 1079 insertions(+), 203 deletions(-)
diff --git a/bindings/java/src/convert.rs b/bindings/java/src/convert.rs
index ba0dafe110..be03daf788 100644
--- a/bindings/java/src/convert.rs
+++ b/bindings/java/src/convert.rs
@@ -27,7 +27,7 @@ use jni::objects::JValue;
use jni::strings::JNIString;
use jni::sys::jint;
use jni::sys::jlong;
-use opendal::raw::Timestamp;
+use opendal::raw::{Duration, Timestamp};
use opendal::{BytesRange, EntryMode, Error, ErrorKind, Metadata,
MetadataBuilder};
use std::collections::HashMap;
use std::ops::Bound;
@@ -206,60 +206,105 @@ pub(crate) fn read_map_field(
}
}
+pub(crate) fn read_positive_jint_to_usize(
+ env: &mut Env<'_>,
+ options: &JObject,
+ field: &str,
+ invalid_kind: ErrorKind,
+) -> Result<usize> {
+ let value = read_int_field(env, options, field)?;
+ if value <= 0 {
+ return Err(Error::new(invalid_kind, format!("{field} must be
positive")).into());
+ }
+ Ok(usize::try_from(value)
+ .map_err(|_| Error::new(invalid_kind, format!("{field} is too
large")))?)
+}
+
+pub(crate) fn read_non_negative_jint_to_usize(
+ env: &mut Env<'_>,
+ options: &JObject,
+ field: &str,
+) -> Result<usize> {
+ let value = read_int_field(env, options, field)?;
+ Ok(usize::try_from(value).map_err(|_| {
+ Error::new(
+ ErrorKind::ConfigInvalid,
+ format!("{field} must be non-negative"),
+ )
+ })?)
+}
+
pub(crate) fn read_jlong_field_to_usize(
- env: &mut Env,
+ env: &mut Env<'_>,
options: &JObject,
- field_name: &str,
+ field: &str,
+ invalid_kind: ErrorKind,
) -> Result<Option<usize>> {
- match read_int64_field(env, options, field_name)? {
+ match read_int64_field(env, options, field)? {
-1 => Ok(None),
- v if v > 0 => Ok(Some(usize::try_from(v).map_err(|_| {
- Error::new(
- ErrorKind::Unexpected,
- format!("{field_name} is too large: {v}"),
- )
+ value if value > 0 => Ok(Some(usize::try_from(value).map_err(|_| {
+ Error::new(invalid_kind, format!("{field} is too large: {value}"))
})?)),
- v => Err(Error::new(
- ErrorKind::Unexpected,
- format!("{field_name} must be positive, instead got: {v}"),
+ value => Err(Error::new(
+ invalid_kind,
+ format!("{field} must be -1 or positive, instead got: {value}"),
)
.into()),
}
}
-pub(crate) fn validate_read_execution_options(
- concurrent: i32,
- chunk: i64,
- content_length_hint: i64,
-) -> Result<(usize, Option<usize>, Option<u64>)> {
- if concurrent <= 0 {
- return Err(Error::new(ErrorKind::ConfigInvalid, "concurrent must be
positive").into());
- }
- let concurrent = usize::try_from(concurrent)
- .map_err(|_| Error::new(ErrorKind::ConfigInvalid, "concurrent is too
large"))?;
- let chunk = match chunk {
- -1 => None,
- value if value > 0 => Some(
- usize::try_from(value)
- .map_err(|_| Error::new(ErrorKind::ConfigInvalid, "chunk is
too large"))?,
- ),
- _ => {
- return Err(
- Error::new(ErrorKind::ConfigInvalid, "chunk must be -1 or
positive").into(),
- );
- }
- };
- let content_length_hint = match content_length_hint {
- -1 => None,
- value => Some(u64::try_from(value).map_err(|_| {
+pub(crate) fn read_non_negative_jlong_to_u64(
+ env: &mut Env<'_>,
+ options: &JObject,
+ field: &str,
+) -> Result<Option<u64>> {
+ match read_int64_field(env, options, field)? {
+ -1 => Ok(None),
+ value => Ok(Some(u64::try_from(value).map_err(|_| {
Error::new(
ErrorKind::ConfigInvalid,
- "contentLengthHint must be -1 or non-negative",
+ format!("{field} must be -1 or non-negative"),
)
- })?),
- };
+ })?)),
+ }
+}
- Ok((concurrent, chunk, content_length_hint))
+pub(crate) fn read_duration_field(
+ env: &mut Env<'_>,
+ options: &JObject,
+ field: &str,
+) -> Result<Option<Duration>> {
+ let duration = env
+ .get_field(
+ options,
+ JNIString::new(field),
+ jni_sig!("Ljava/time/Duration;"),
+ )?
+ .l()?;
+ if duration.is_null() {
+ return Ok(None);
+ }
+
+ let seconds = env
+ .call_method(&duration, jni_str!("getSeconds"), jni_sig!("()J"), &[])?
+ .j()?;
+ let nanos = env
+ .call_method(&duration, jni_str!("getNano"), jni_sig!("()I"), &[])?
+ .i()?;
+ if seconds < 0 || (seconds == 0 && nanos <= 0) {
+ return Err(Error::new(
+ ErrorKind::ConfigInvalid,
+ format!("{field} must be a positive duration"),
+ )
+ .into());
+ }
+ let secs = u64::try_from(seconds)
+ .map_err(|_| Error::new(ErrorKind::ConfigInvalid, "invalid duration
seconds"))?;
+ let subsec_nanos = u32::try_from(nanos)
+ .ok()
+ .filter(|&value| value < 1_000_000_000)
+ .ok_or_else(|| Error::new(ErrorKind::ConfigInvalid, "invalid duration
nanoseconds"))?;
+ Ok(Some(Duration::new(secs, subsec_nanos)))
}
pub(crate) fn read_instant_field_to_timestamp(
@@ -307,7 +352,7 @@ pub(crate) fn read_metadata_condition_field(
return Ok(None);
}
- // Delete conditions use only the version and ETag from the snapshot.
+ // Conditional operations use only the version and ETag from the snapshot.
let mut builder = MetadataBuilder::unknown();
if let Some(version) = read_string_field(env, &metadata, "version")? {
builder.version(version);
diff --git a/bindings/java/src/main/java/org/apache/opendal/DeleteOptions.java
b/bindings/java/src/main/java/org/apache/opendal/DeleteOptions.java
index 175992d4fd..202af8d7de 100644
--- a/bindings/java/src/main/java/org/apache/opendal/DeleteOptions.java
+++ b/bindings/java/src/main/java/org/apache/opendal/DeleteOptions.java
@@ -30,7 +30,7 @@ import lombok.Builder;
*
* <p>Optional reference fields default to {@code null}.
*/
-@Builder
+@Builder(toBuilder = true)
public class DeleteOptions {
/**
diff --git a/bindings/java/src/main/java/org/apache/opendal/ListOptions.java
b/bindings/java/src/main/java/org/apache/opendal/ListOptions.java
index 07ed91c051..1b6965ef92 100644
--- a/bindings/java/src/main/java/org/apache/opendal/ListOptions.java
+++ b/bindings/java/src/main/java/org/apache/opendal/ListOptions.java
@@ -26,11 +26,11 @@ import lombok.Builder;
/**
* Options for list operations.
*
- * <p>Options that require an unsupported service capability fail with {@link
OpenDALException.Code#Unsupported}. {@link #limit} is a pagination hint that
services may ignore even when {@link Capability#listWithLimit} is supported.
+ * <p>Options that require an unsupported service capability fail with {@link
OpenDALException.Code#Unsupported}. When globbing is supported, invalid {@link
#glob} patterns fail with {@link OpenDALException.Code#ConfigInvalid}. {@link
#limit} is a pagination hint that services may ignore even when {@link
Capability#listWithLimit} is supported.
*
* <p>Optional reference fields default to {@code null}.
*/
-@Builder
+@Builder(toBuilder = true)
public class ListOptions {
/**
@@ -68,4 +68,16 @@ public class ListOptions {
* @see Capability#listWithDeleted
*/
public final boolean deleted;
+
+ /**
+ * Filter entries with a case-sensitive Unix shell style glob pattern.
+ *
+ * <p>The pattern is relative to the listed directory, or to the parent
directory when the list path is a prefix without a trailing slash. Entries must
also satisfy the list prefix. The pattern determines which depths can match,
independently of {@link #recursive}.
+ *
+ * <p>Requires {@link Capability#listWithGlob}. OpenDAL simulates glob
matching client-side when the service lacks native support. A simulated pattern
spanning multiple directories also requires {@link
Capability#listWithRecursive} when combined with {@link #startAfter}, {@link
#versions}, or {@link #deleted}. Missing required capabilities fail with {@link
OpenDALException.Code#Unsupported}. When globbing is supported, empty or
malformed patterns fail with {@link OpenDALException.Cod [...]
+ *
+ * @see Capability#listWithGlob
+ * @see Capability#listWithRecursive
+ */
+ public final String glob;
}
diff --git a/bindings/java/src/main/java/org/apache/opendal/Operator.java
b/bindings/java/src/main/java/org/apache/opendal/Operator.java
index a7862112e3..8f1dfb9fb2 100644
--- a/bindings/java/src/main/java/org/apache/opendal/Operator.java
+++ b/bindings/java/src/main/java/org/apache/opendal/Operator.java
@@ -159,6 +159,14 @@ public class Operator extends NativeObject {
return createInputStream(path, ReadOptions.builder().build());
}
+ /**
+ * Opens a stream using the supplied read options.
+ *
+ * @param path the path to read
+ * @param options the read options
+ * @return the input stream
+ * @throws OpenDALException if a read limit is set or the read options are
invalid or unsupported
+ */
public OperatorInputStream createInputStream(String path, ReadOptions
options) {
return new OperatorInputStream(this, path, options);
}
diff --git
a/bindings/java/src/main/java/org/apache/opendal/OperatorInputStream.java
b/bindings/java/src/main/java/org/apache/opendal/OperatorInputStream.java
index e755a2efd6..3186116068 100644
--- a/bindings/java/src/main/java/org/apache/opendal/OperatorInputStream.java
+++ b/bindings/java/src/main/java/org/apache/opendal/OperatorInputStream.java
@@ -51,6 +51,10 @@ public class OperatorInputStream extends InputStream {
public OperatorInputStream(Operator operator, String path, ReadOptions
options) {
Objects.requireNonNull(options, "options");
+ if (options.limit != -1L) {
+ throw new OpenDALException(
+ OpenDALException.Code.ConfigInvalid, "limit is only
supported by read operations");
+ }
ReaderOptions readerOptions = ReaderOptions.builder()
.version(options.version)
.ifMatch(options.ifMatch)
diff --git a/bindings/java/src/main/java/org/apache/opendal/ReadOptions.java
b/bindings/java/src/main/java/org/apache/opendal/ReadOptions.java
index 08844a1d1f..d9714a3727 100644
--- a/bindings/java/src/main/java/org/apache/opendal/ReadOptions.java
+++ b/bindings/java/src/main/java/org/apache/opendal/ReadOptions.java
@@ -37,7 +37,7 @@ import lombok.Builder;
*
* <p>Optional reference fields default to {@code null}.
*/
-@Builder
+@Builder(toBuilder = true)
public class ReadOptions {
/**
@@ -174,4 +174,16 @@ public class ReadOptions {
* <p>This option is only meaningful when used along with presign.
*/
public final String overrideContentDisposition;
+
+ /**
+ * Return at most this many bytes from the start of the selected range,
accepting EOF after a valid starting byte.
+ *
+ * <p>The default of {@code -1L} leaves the limit unset. Without a limit,
bounded forward ranges require the full requested length. Values below {@code
-1L} fail with {@link OpenDALException.Code#ConfigInvalid}.
+ *
+ * <p>On direct whole-buffer reads, {@code 0L} validates options and
capabilities, then returns an empty result without accessing storage or
evaluating conditions against the file. With a positive limit, a nonempty
forward selection starting at or beyond EOF fails with {@link
OpenDALException.Code#RangeNotSatisfied}.
+ *
+ * <p>Setting a limit ({@code limit != -1L}) with a positive {@link
#chunk}, with {@link #concurrent} greater than {@code 1}, with {@link
OperatorInputStream}, or with presigned read requests fails with {@link
OpenDALException.Code#ConfigInvalid}.
+ */
+ @Builder.Default
+ public final long limit = -1L;
}
diff --git a/bindings/java/src/main/java/org/apache/opendal/ReaderOptions.java
b/bindings/java/src/main/java/org/apache/opendal/ReaderOptions.java
index 95467b265e..e23383884f 100644
--- a/bindings/java/src/main/java/org/apache/opendal/ReaderOptions.java
+++ b/bindings/java/src/main/java/org/apache/opendal/ReaderOptions.java
@@ -37,7 +37,7 @@ import lombok.Builder;
*
* <p>Optional reference fields default to {@code null}.
*/
-@Builder
+@Builder(toBuilder = true)
public final class ReaderOptions {
/**
diff --git a/bindings/java/src/main/java/org/apache/opendal/StatOptions.java
b/bindings/java/src/main/java/org/apache/opendal/StatOptions.java
index 091fa81db6..ff2a7c3de4 100644
--- a/bindings/java/src/main/java/org/apache/opendal/StatOptions.java
+++ b/bindings/java/src/main/java/org/apache/opendal/StatOptions.java
@@ -35,7 +35,7 @@ import lombok.Data;
* <p>Optional reference fields default to {@code null}.
*/
@Data
-@Builder
+@Builder(toBuilder = true)
public class StatOptions {
/**
diff --git a/bindings/java/src/main/java/org/apache/opendal/WriteOptions.java
b/bindings/java/src/main/java/org/apache/opendal/WriteOptions.java
index 51590ad1ed..b55a38028a 100644
--- a/bindings/java/src/main/java/org/apache/opendal/WriteOptions.java
+++ b/bindings/java/src/main/java/org/apache/opendal/WriteOptions.java
@@ -21,17 +21,18 @@
package org.apache.opendal;
+import java.time.Duration;
import java.util.Map;
import lombok.Builder;
/**
* Options for write operations.
*
- * <p>All supplied conditions must hold for the write to commit. Unsupported
conditions or {@link #append} fail with {@link
OpenDALException.Code#Unsupported}. Unsupported metadata options may be
ignored. Failed conditions fail with {@link
OpenDALException.Code#ConditionNotMatch}. Presigned write requests validate
options and capabilities without executing against storage.
+ * <p>All supplied conditions must hold for the write to commit. Unsupported
conditions, {@link #append}, or {@link #expires} fail with {@link
OpenDALException.Code#Unsupported}. Unsupported metadata options may be
ignored. Failed conditions fail with {@link
OpenDALException.Code#ConditionNotMatch}. Invalid {@link #expires} or {@link
#ifNotChanged} values fail with {@link OpenDALException.Code#ConfigInvalid}.
Presigned write requests validate options and capabilities without executing ag
[...]
*
* <p>Optional reference fields default to {@code null}.
*/
-@Builder
+@Builder(toBuilder = true)
public class WriteOptions {
/**
@@ -121,4 +122,51 @@ public class WriteOptions {
*/
@Builder.Default
public final long chunk = -1L;
+
+ /**
+ * Sets Content-Language system metadata on the object being written.
+ *
+ * <p>Use a language tag or a comma-separated list of tags, such as {@code
fr-CA, en}. Check {@link Capability#writeWithContentLanguage} for support. A
subsequent stat can retrieve the stored value with {@link
Metadata#contentLanguage}. Services without support may ignore this option.
+ *
+ * @see Capability#writeWithContentLanguage
+ */
+ public final String contentLanguage;
+
+ /**
+ * Sets how long the new file lives after the write commits.
+ *
+ * <p>A supplied duration overrides the service's default TTL. When unset,
the service uses its usual expiration policy. Services round positive durations
up to their supported precision.
+ *
+ * <p>Supply a positive {@link Duration}. Zero, negative, or
unrepresentable durations fail with {@link
OpenDALException.Code#ConfigInvalid}. The write fails with {@link
OpenDALException.Code#Unsupported} when the service does not advertise {@link
Capability#writeWithExpires}.
+ *
+ * @see Capability#writeWithExpires
+ */
+ public final Duration expires;
+
+ /**
+ * Write only when the file at the write path has this exact version.
+ *
+ * <p>The condition succeeds when the file exists and its version equals
this value. A file with a different version, or a missing file, fails the write
with {@link OpenDALException.Code#ConditionNotMatch}.
+ *
+ * @see Capability#writeWithIfVersionMatch
+ */
+ public final String ifVersionMatch;
+
+ /**
+ * Write only when the file at the write path does not have this version.
+ *
+ * <p>The condition succeeds when the file exists with a different
version. A file whose version equals this value fails the write with {@link
OpenDALException.Code#ConditionNotMatch}. When no file exists at the write
path, no portable behavior is defined.
+ *
+ * @see Capability#writeWithIfVersionNotMatch
+ */
+ public final String ifVersionNotMatch;
+
+ /**
+ * Write only when the file at the write path still has the identity
recorded in this metadata.
+ *
+ * <p>Pass metadata previously returned by OpenDAL for the same path.
OpenDAL derives a version match when the service supports version conditions
and the metadata contains a version. Otherwise it uses a non-weak ETag if
present. A changed or missing file fails the write with {@link
OpenDALException.Code#ConditionNotMatch}, as does combining this option with a
conflicting {@link #ifMatch} or {@link #ifVersionMatch} value.
+ *
+ * <p>The operation returns {@link OpenDALException.Code#Unsupported} when
the service does not support the derived primitive condition, and {@link
OpenDALException.Code#ConfigInvalid} when the metadata contains neither a
version nor a non-weak ETag.
+ */
+ public final Metadata ifNotChanged;
}
diff --git a/bindings/java/src/options.rs b/bindings/java/src/options.rs
index dcbb1e0d65..d2c197a596 100644
--- a/bindings/java/src/options.rs
+++ b/bindings/java/src/options.rs
@@ -21,7 +21,7 @@ use crate::Result;
use crate::convert;
use jni::Env;
use jni::objects::JObject;
-use opendal::{Error, ErrorKind};
+use opendal::ErrorKind;
pub(crate) fn make_delete_options(
env: &mut Env<'_>,
@@ -44,12 +44,12 @@ pub(crate) fn make_list_options(
options: &JObject,
) -> Result<opendal::options::ListOptions> {
Ok(opendal::options::ListOptions {
- limit: convert::read_jlong_field_to_usize(env, options, "limit")?,
+ limit: convert::read_jlong_field_to_usize(env, options, "limit",
ErrorKind::Unexpected)?,
start_after: convert::read_string_field(env, options, "startAfter")?,
recursive: convert::read_bool_field(env, options,
"recursive").unwrap_or_default(),
versions: convert::read_bool_field(env, options,
"versions").unwrap_or_default(),
deleted: convert::read_bool_field(env, options,
"deleted").unwrap_or_default(),
- glob: None,
+ glob: convert::read_string_field(env, options, "glob")?,
})
}
@@ -57,14 +57,16 @@ pub(crate) fn make_read_options(
env: &mut Env<'_>,
options: &JObject,
) -> Result<opendal::options::ReadOptions> {
- let concurrent = convert::read_int_field(env, options, "concurrent")?;
- let chunk = convert::read_int64_field(env, options, "chunk")?;
- let content_length_hint = convert::read_int64_field(env, options,
"contentLengthHint")?;
- let (concurrent, chunk, content_length_hint) =
- convert::validate_read_execution_options(concurrent, chunk,
content_length_hint)?;
+ let concurrent =
+ convert::read_positive_jint_to_usize(env, options, "concurrent",
ErrorKind::ConfigInvalid)?;
+ let chunk =
+ convert::read_jlong_field_to_usize(env, options, "chunk",
ErrorKind::ConfigInvalid)?;
+ let content_length_hint =
+ convert::read_non_negative_jlong_to_u64(env, options,
"contentLengthHint")?;
+ let limit = convert::read_non_negative_jlong_to_u64(env, options,
"limit")?;
Ok(opendal::options::ReadOptions {
range: convert::read_range_fields(env, options)?,
- limit: None,
+ limit,
version: convert::read_string_field(env, options, "version")?,
if_match: convert::read_string_field(env, options, "ifMatch")?,
if_none_match: convert::read_string_field(env, options,
"ifNoneMatch")?,
@@ -99,14 +101,13 @@ pub(crate) fn make_reader_options(
env: &mut Env<'_>,
options: &JObject,
) -> Result<opendal::options::ReaderOptions> {
- let concurrent = convert::read_int_field(env, options, "concurrent")?;
- let chunk = convert::read_int64_field(env, options, "chunk")?;
- let prefetch = convert::read_int_field(env, options, "prefetch")?;
- let content_length_hint = convert::read_int64_field(env, options,
"contentLengthHint")?;
- let (concurrent, chunk, content_length_hint) =
- convert::validate_read_execution_options(concurrent, chunk,
content_length_hint)?;
- let prefetch = usize::try_from(prefetch)
- .map_err(|_| Error::new(ErrorKind::ConfigInvalid, "prefetch must be
non-negative"))?;
+ let concurrent =
+ convert::read_positive_jint_to_usize(env, options, "concurrent",
ErrorKind::ConfigInvalid)?;
+ let chunk =
+ convert::read_jlong_field_to_usize(env, options, "chunk",
ErrorKind::ConfigInvalid)?;
+ let content_length_hint =
+ convert::read_non_negative_jlong_to_u64(env, options,
"contentLengthHint")?;
+ let prefetch = convert::read_non_negative_jint_to_usize(env, options,
"prefetch")?;
Ok(opendal::options::ReaderOptions {
version: convert::read_string_field(env, options, "version")?,
if_match: convert::read_string_field(env, options, "ifMatch")?,
@@ -167,33 +168,25 @@ pub(crate) fn make_write_options(
env: &mut Env<'_>,
options: &JObject,
) -> Result<opendal::options::WriteOptions> {
- let value = convert::read_int_field(env, options, "concurrent")?;
- let concurrent = usize::try_from(value)
- .ok()
- .filter(|&value| value > 0)
- .ok_or_else(|| {
- Error::new(
- ErrorKind::Unexpected,
- format!("Concurrent must be positive, instead got: {value}"),
- )
- })?;
+ let concurrent =
+ convert::read_positive_jint_to_usize(env, options, "concurrent",
ErrorKind::Unexpected)?;
Ok(opendal::options::WriteOptions {
append: convert::read_bool_field(env, options,
"append").unwrap_or_default(),
cache_control: convert::read_string_field(env, options,
"cacheControl")?,
content_type: convert::read_string_field(env, options, "contentType")?,
content_disposition: convert::read_string_field(env, options,
"contentDisposition")?,
content_encoding: convert::read_string_field(env, options,
"contentEncoding")?,
- content_language: None,
+ content_language: convert::read_string_field(env, options,
"contentLanguage")?,
user_metadata: convert::read_map_field(env, options, "userMetadata")?,
- expires: None,
+ expires: convert::read_duration_field(env, options, "expires")?,
if_match: convert::read_string_field(env, options, "ifMatch")?,
if_none_match: convert::read_string_field(env, options,
"ifNoneMatch")?,
- if_version_match: None,
- if_version_not_match: None,
+ if_version_match: convert::read_string_field(env, options,
"ifVersionMatch")?,
+ if_version_not_match: convert::read_string_field(env, options,
"ifVersionNotMatch")?,
if_not_exists: convert::read_bool_field(env, options,
"ifNotExists").unwrap_or_default(),
- if_not_changed: None,
+ if_not_changed: convert::read_metadata_condition_field(env, options,
"ifNotChanged")?,
concurrent,
- chunk: convert::read_jlong_field_to_usize(env, options, "chunk")?,
+ chunk: convert::read_jlong_field_to_usize(env, options, "chunk",
ErrorKind::Unexpected)?,
..Default::default()
})
}
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/DeleteOptionsTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/DeleteOptionsTest.java
index 24ce9efd79..7badf7bed4 100644
--- a/bindings/java/src/test/java/org/apache/opendal/test/DeleteOptionsTest.java
+++ b/bindings/java/src/test/java/org/apache/opendal/test/DeleteOptionsTest.java
@@ -22,6 +22,7 @@ package org.apache.opendal.test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.file.Path;
+import java.time.Instant;
import java.util.Collections;
import java.util.stream.Stream;
import org.apache.opendal.AsyncOperator;
@@ -93,6 +94,14 @@ public class DeleteOptionsTest {
"ifVersionNotMatch",
DeleteOptions.builder().ifVersionNotMatch("v1").build()),
Arguments.of("ifNotChanged with an ETag",
deleteIfNotChanged("\"etag\"", null)),
+ Arguments.of(
+ "ifNotChanged ignores timestamps outside the native
range",
+ DeleteOptions.builder()
+ .ifNotChanged(Metadata.builder()
+ .etag("\"etag\"")
+ .lastModified(Instant.MAX)
+ .build())
+ .build()),
Arguments.of("ifNotChanged with a version",
deleteIfNotChanged(null, "v1")));
}
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/ListOptionsTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/ListOptionsTest.java
new file mode 100644
index 0000000000..9b5a8788e1
--- /dev/null
+++ b/bindings/java/src/test/java/org/apache/opendal/test/ListOptionsTest.java
@@ -0,0 +1,93 @@
+/*
+ * 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.
+ */
+
+package org.apache.opendal.test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import org.apache.opendal.AsyncOperator;
+import org.apache.opendal.Entry;
+import org.apache.opendal.ListOptions;
+import org.apache.opendal.OpenDALException.Code;
+import org.apache.opendal.Operator;
+import org.apache.opendal.ServiceConfig;
+import org.apache.opendal.test.condition.OpenDALExceptionCondition;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+public class ListOptionsTest {
+ @Test
+ void testGlobFiltersBlockingAndAsyncLists() {
+ try (AsyncOperator async =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ Operator op = async.blocking()) {
+ assertThat(op.info.capability.listWithGlob).isTrue();
+ op.write("dir/one.txt", "one");
+ op.write("dir/nested/two.txt", "two");
+ op.write("dir/three.bin", "three");
+ op.write("outside.txt", "outside");
+ ListOptions options =
ListOptions.builder().glob("**/*.txt").build();
+
+ assertThat(op.list("dir/", options))
+ .extracting(Entry::getPath)
+ .containsExactlyInAnyOrder("dir/one.txt",
"dir/nested/two.txt");
+ assertThat(async.list("dir/", options).join())
+ .extracting(Entry::getPath)
+ .containsExactlyInAnyOrder("dir/one.txt",
"dir/nested/two.txt");
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"", "["})
+ void testInvalidGlob(String glob) {
+ try (AsyncOperator async =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ Operator op = async.blocking()) {
+ ListOptions options = ListOptions.builder().glob(glob).build();
+ assertThatThrownBy(() -> op.list("/",
options)).is(OpenDALExceptionCondition.ofSync(Code.ConfigInvalid));
+ assertThatThrownBy(async.list("/", options)::join)
+ .is(OpenDALExceptionCondition.ofAsync(Code.ConfigInvalid));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(longs = {0, -2})
+ void testInvalidLimitKeepsUnexpectedCode(long limit) {
+ try (AsyncOperator async =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ Operator op = async.blocking()) {
+ ListOptions options = ListOptions.builder().limit(limit).build();
+ assertThatThrownBy(() -> op.list("/",
options)).is(OpenDALExceptionCondition.ofSync(Code.Unexpected));
+ assertThatThrownBy(() -> async.list("/",
options)).is(OpenDALExceptionCondition.ofSync(Code.Unexpected));
+ }
+ }
+
+ @Test
+ void testToBuilder() {
+ ListOptions original =
+ ListOptions.builder().glob("*.txt").recursive(true).build();
+ ListOptions updated = original.toBuilder().glob("*.bin").build();
+ assertThat(updated.glob).isEqualTo("*.bin");
+ assertThat(updated.recursive).isTrue();
+ assertThat(updated.limit).isEqualTo(-1L);
+ assertThat(original.glob).isEqualTo("*.txt");
+ assertThat(original).isNotEqualTo(original.toBuilder().build());
+ }
+}
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
index f9673e6903..b02de0b67b 100644
---
a/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
+++
b/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
@@ -102,6 +102,18 @@ public class OperatorInputOutputStreamTest {
}
}
+ @ParameterizedTest
+ @ValueSource(longs = {0, 4})
+ void testCreateInputStreamRejectsReadLimit(long limit) {
+ try (Operator op =
Operator.of(ServiceConfig.Memory.builder().build())) {
+ op.write("file", "content");
+ ReadOptions options = ReadOptions.builder().limit(limit).build();
+ assertThatThrownBy(() -> op.createInputStream("file", options))
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.ConfigInvalid))
+ .hasMessage("limit is only supported by read operations");
+ }
+ }
+
@Test
void testChunkedInputStream() throws Exception {
final byte[] content = new byte[4 * 1024 + 13];
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/ReadOptionsTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/ReadOptionsTest.java
index 8b0b1226af..842cba557a 100644
--- a/bindings/java/src/test/java/org/apache/opendal/test/ReadOptionsTest.java
+++ b/bindings/java/src/test/java/org/apache/opendal/test/ReadOptionsTest.java
@@ -27,6 +27,7 @@ import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
+import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashSet;
@@ -255,6 +256,7 @@ public class ReadOptionsTest {
assertThat(defaults.length).isEqualTo(-1);
assertThat(defaults.concurrent).isEqualTo(1);
assertThat(defaults.chunk).isEqualTo(-1);
+ assertThat(defaults.limit).isEqualTo(-1);
assertThat(defaults.contentLengthHint).isEqualTo(-1);
try (AsyncOperator async =
AsyncOperator.of(ServiceConfig.Memory.builder().build());
@@ -273,13 +275,64 @@ public class ReadOptionsTest {
}
}
+ @Test
+ void testReadLimit() {
+ try (AsyncOperator async =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ Operator op = async.blocking()) {
+ op.write("file", CONTENT);
+ ReadOptions limited = ReadOptions.builder().limit(4).build();
+ assertThat(op.read("file", limited)).containsExactly('0', '1',
'2', '3');
+ assertThat(async.read("file",
limited).join()).containsExactly('0', '1', '2', '3');
+
+ ReadOptions ranged =
limited.toBuilder().offset(6).length(8).build();
+ assertThat(ranged.limit).isEqualTo(4);
+ assertThat(limited.offset).isZero();
+ assertThat(op.read("file", ranged)).containsExactly('6', '7', '8',
'9');
+ assertThat(async.read("file", ranged).join()).containsExactly('6',
'7', '8', '9');
+ assertThatThrownBy(
+ () -> op.read("file",
ranged.toBuilder().limit(-1).build()))
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.Unexpected));
+ assertThatThrownBy(() -> op.read(
+ "file",
limited.toBuilder().offset(CONTENT.length).build()))
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.RangeNotSatisfied));
+
+ assertThatThrownBy(
+ () -> op.read("file",
limited.toBuilder().chunk(2).build()))
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.ConfigInvalid));
+ assertThatThrownBy(() ->
+ op.read("file",
limited.toBuilder().concurrent(2).build()))
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.ConfigInvalid));
+
+ ReadOptions empty = limited.toBuilder().limit(0).build();
+ assertThat(op.read("missing", empty)).isEmpty();
+ assertThat(async.read("missing", empty).join()).isEmpty();
+ assertThatThrownBy(() ->
+ op.read("missing",
empty.toBuilder().ifMatch("etag").build()))
+
.is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.Unsupported));
+ }
+ }
+
+ @Test
+ void testPresignReadRejectsLimit() {
+ try (AsyncOperator async =
+ AsyncOperator.of(ServiceConfig.Memory.builder().build())) {
+ ReadOptions options = ReadOptions.builder().limit(4).build();
+ assertThatThrownBy(async.presignRead("file",
Duration.ofMinutes(1), options)::join)
+
.is(OpenDALExceptionCondition.ofAsync(OpenDALException.Code.ConfigInvalid));
+ }
+ }
+
static Stream<Arguments> invalidOptions() {
return Stream.of(
Arguments.of(ReadOptions.builder().concurrent(0).build(),
OpenDALException.Code.ConfigInvalid),
Arguments.of(ReadOptions.builder().concurrent(-1).build(),
OpenDALException.Code.ConfigInvalid),
Arguments.of(ReadOptions.builder().chunk(0).build(),
OpenDALException.Code.ConfigInvalid),
Arguments.of(ReadOptions.builder().chunk(-2).build(),
OpenDALException.Code.ConfigInvalid),
+ Arguments.of(ReadOptions.builder().limit(-2).build(),
OpenDALException.Code.ConfigInvalid),
Arguments.of(ReadOptions.builder().contentLengthHint(-2).build(),
OpenDALException.Code.ConfigInvalid),
+
Arguments.of(ReadOptions.builder().chunk(0).offset(-1).build(),
OpenDALException.Code.ConfigInvalid),
+
Arguments.of(ReadOptions.builder().limit(-2).offset(-1).build(),
OpenDALException.Code.ConfigInvalid),
Arguments.of(ReadOptions.builder().offset(-1).build(),
OpenDALException.Code.RangeNotSatisfied),
Arguments.of(ReadOptions.builder().length(-2).build(),
OpenDALException.Code.RangeNotSatisfied),
Arguments.of(
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/ReaderOptionsTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/ReaderOptionsTest.java
index 1a8a90ea69..686e8f658c 100644
--- a/bindings/java/src/test/java/org/apache/opendal/test/ReaderOptionsTest.java
+++ b/bindings/java/src/test/java/org/apache/opendal/test/ReaderOptionsTest.java
@@ -217,4 +217,14 @@ public class ReaderOptionsTest {
}
}
}
+
+ @Test
+ void testToBuilder() {
+ ReaderOptions original = ReaderOptions.builder().concurrent(2).build();
+ ReaderOptions updated = original.toBuilder().chunk(4).build();
+ assertThat(updated.chunk).isEqualTo(4);
+ assertThat(updated.concurrent).isEqualTo(2);
+ assertThat(original.chunk).isEqualTo(-1);
+ assertThat(original).isNotEqualTo(original.toBuilder().build());
+ }
}
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/StatOptionsTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/StatOptionsTest.java
index af2a7f0421..e2435088be 100644
--- a/bindings/java/src/test/java/org/apache/opendal/test/StatOptionsTest.java
+++ b/bindings/java/src/test/java/org/apache/opendal/test/StatOptionsTest.java
@@ -21,6 +21,7 @@ package org.apache.opendal.test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import java.time.Instant;
import java.util.UUID;
import org.apache.opendal.OpenDALException;
import org.apache.opendal.Operator;
@@ -31,6 +32,35 @@ import org.junit.jupiter.api.Test;
public class StatOptionsTest {
+ @Test
+ void testSettersAndToBuilder() {
+ StatOptions options = StatOptions.builder().build();
+ options.setIfMatch("\"etag\"");
+ options.setIfNoneMatch("\"other\"");
+ options.setIfVersionMatch("v1");
+ options.setIfVersionNotMatch("v2");
+ options.setIfModifiedSince(Instant.EPOCH);
+ options.setIfUnmodifiedSince(Instant.EPOCH.plusSeconds(1));
+ options.setVersion("v1");
+ options.setOverrideContentType("text/plain");
+ options.setOverrideCacheControl("no-cache");
+ options.setOverrideContentDisposition("inline");
+
+ assertThat(options.toBuilder().build()).isEqualTo(options);
+ StatOptions updated = options.toBuilder().version("v3").build();
+ assertThat(updated.getIfMatch()).isEqualTo("\"etag\"");
+ assertThat(updated.getIfNoneMatch()).isEqualTo("\"other\"");
+ assertThat(updated.getIfVersionMatch()).isEqualTo("v1");
+ assertThat(updated.getIfVersionNotMatch()).isEqualTo("v2");
+ assertThat(updated.getIfModifiedSince()).isEqualTo(Instant.EPOCH);
+
assertThat(updated.getIfUnmodifiedSince()).isEqualTo(Instant.EPOCH.plusSeconds(1));
+ assertThat(updated.getVersion()).isEqualTo("v3");
+ assertThat(updated.getOverrideContentType()).isEqualTo("text/plain");
+ assertThat(updated.getOverrideCacheControl()).isEqualTo("no-cache");
+
assertThat(updated.getOverrideContentDisposition()).isEqualTo("inline");
+ assertThat(options.getVersion()).isEqualTo("v1");
+ }
+
/**
* The memory service supports neither version condition, so core rejects
each one as
* unsupported. A condition dropped by the binding would let the stat
succeed instead.
diff --git
a/bindings/java/src/test/java/org/apache/opendal/test/WriteOptionsTest.java
b/bindings/java/src/test/java/org/apache/opendal/test/WriteOptionsTest.java
new file mode 100644
index 0000000000..c78d20e701
--- /dev/null
+++ b/bindings/java/src/test/java/org/apache/opendal/test/WriteOptionsTest.java
@@ -0,0 +1,303 @@
+/*
+ * 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.
+ */
+
+package org.apache.opendal.test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import com.sun.net.httpserver.HttpServer;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.security.KeyPairGenerator;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.stream.Stream;
+import org.apache.opendal.AsyncOperator;
+import org.apache.opendal.Metadata;
+import org.apache.opendal.OpenDALException.Code;
+import org.apache.opendal.Operator;
+import org.apache.opendal.OperatorOutputStream;
+import org.apache.opendal.PresignedRequest;
+import org.apache.opendal.ServiceConfig;
+import org.apache.opendal.WriteOptions;
+import org.apache.opendal.layer.CapabilityCheckLayer;
+import org.apache.opendal.test.condition.OpenDALExceptionCondition;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+@Timeout(10)
+public class WriteOptionsTest {
+ private static final String CONTENT_LANGUAGE = "fr-CA, en";
+ private static final byte[] CONTENT =
"content".getBytes(StandardCharsets.UTF_8);
+ private static final Duration PRESIGN_EXPIRY = Duration.ofMinutes(1);
+
+ @TempDir
+ Path root;
+
+ @Test
+ void testContentLanguageRoundTripOnMemory() throws Exception {
+ try (AsyncOperator async =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ Operator op = async.blocking()) {
+ assertThat(op.info.capability.writeWithContentLanguage).isTrue();
+ WriteOptions options =
+
WriteOptions.builder().contentLanguage(CONTENT_LANGUAGE).build();
+
+ op.write("blocking", CONTENT, options);
+
assertThat(op.stat("blocking").contentLanguage).isEqualTo(CONTENT_LANGUAGE);
+ async.write("async", CONTENT, options).join();
+
assertThat(async.stat("async").join().contentLanguage).isEqualTo(CONTENT_LANGUAGE);
+ try (OperatorOutputStream out = op.createOutputStream("stream",
options)) {
+ out.write(CONTENT);
+ }
+
assertThat(op.stat("stream").contentLanguage).isEqualTo(CONTENT_LANGUAGE);
+ }
+ }
+
+ @Test
+ void testContentLanguageIsUnsupportedOnFilesystem() {
+ try (AsyncOperator fs = AsyncOperator.of(
+
ServiceConfig.Fs.builder().root(root.toString()).build());
+ AsyncOperator checked = fs.layer(new CapabilityCheckLayer());
+ Operator op = checked.blocking()) {
+ assertThat(fs.info.capability.writeWithContentLanguage).isFalse();
+ WriteOptions options =
+
WriteOptions.builder().contentLanguage(CONTENT_LANGUAGE).build();
+ assertThatThrownBy(() -> op.write("file", CONTENT, options))
+ .is(OpenDALExceptionCondition.ofSync(Code.Unsupported));
+ }
+ }
+
+ static Stream<Arguments> invalidOptions() {
+ return Stream.of(
+ Arguments.of(WriteOptions.builder().concurrent(0).build(),
Code.Unexpected),
+ Arguments.of(WriteOptions.builder().concurrent(-2).build(),
Code.Unexpected),
+ Arguments.of(WriteOptions.builder().chunk(0).build(),
Code.Unexpected),
+ Arguments.of(WriteOptions.builder().chunk(-2).build(),
Code.Unexpected),
+
Arguments.of(WriteOptions.builder().expires(Duration.ZERO).build(),
Code.ConfigInvalid),
+ Arguments.of(
+
WriteOptions.builder().expires(Duration.ofSeconds(-1)).build(),
Code.ConfigInvalid),
+ Arguments.of(
+
WriteOptions.builder().expires(Duration.ofNanos(-1)).build(),
Code.ConfigInvalid));
+ }
+
+ @ParameterizedTest
+ @MethodSource("invalidOptions")
+ void testInvalidOptions(WriteOptions options, Code code) {
+ try (AsyncOperator async =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ Operator op = async.blocking()) {
+ assertThatThrownBy(() -> op.write("file", CONTENT,
options)).is(OpenDALExceptionCondition.ofSync(code));
+ assertThatThrownBy(() -> async.write("file", CONTENT,
options)).is(OpenDALExceptionCondition.ofSync(code));
+ }
+ }
+
+ @Test
+ void testIfNotChangedRequiresMetadataIdentity() {
+ try (AsyncOperator async =
+
AsyncOperator.of(ServiceConfig.Memory.builder().build());
+ Operator op = async.blocking()) {
+ WriteOptions options = WriteOptions.builder()
+ .ifNotChanged(Metadata.builder().build())
+ .build();
+ assertThatThrownBy(() -> op.write("file", CONTENT, options))
+ .is(OpenDALExceptionCondition.ofSync(Code.ConfigInvalid));
+ assertThatThrownBy(async.write("file", CONTENT, options)::join)
+ .is(OpenDALExceptionCondition.ofAsync(Code.ConfigInvalid));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"memory", "fs"})
+ void testUnsupportedConditionsAndExpires(String scheme) {
+ ServiceConfig config = "memory".equals(scheme)
+ ? ServiceConfig.Memory.builder().build()
+ : ServiceConfig.Fs.builder().root(root.toString()).build();
+ try (AsyncOperator async = AsyncOperator.of(config);
+ Operator op = async.blocking()) {
+ assertThat(op.info.capability.writeWithIfVersionMatch).isFalse();
+
assertThat(op.info.capability.writeWithIfVersionNotMatch).isFalse();
+ assertThat(op.info.capability.writeWithIfMatch).isFalse();
+ assertThat(op.info.capability.writeWithExpires).isFalse();
+
+ op.write("file", CONTENT);
+ Metadata snapshot = Metadata.builder()
+ .etag("\"etag\"")
+ .lastModified(Instant.MAX)
+ .build();
+ for (WriteOptions options : new WriteOptions[] {
+ WriteOptions.builder().ifVersionMatch("17").build(),
+ WriteOptions.builder().ifVersionNotMatch("18").build(),
+ WriteOptions.builder().ifNotChanged(snapshot).build(),
+ WriteOptions.builder().expires(Duration.ofNanos(1)).build(),
+ WriteOptions.builder()
+ .expires(Duration.ofSeconds(Long.MAX_VALUE,
999_999_999))
+ .build()
+ }) {
+ assertThatThrownBy(() -> op.write("file", "updated", options))
+
.is(OpenDALExceptionCondition.ofSync(Code.Unsupported));
+ assertThatThrownBy(async.write("file", "updated",
options)::join)
+
.is(OpenDALExceptionCondition.ofAsync(Code.Unsupported));
+ }
+ assertThat(op.read("file")).isEqualTo(CONTENT);
+ }
+ }
+
+ @Test
+ void testVersionConditionsReachGcsUploadRequest() throws Exception {
+ List<String> queries = new CopyOnWriteArrayList<>();
+ HttpServer server = HttpServer.create(new
InetSocketAddress("127.0.0.1", 0), 0);
+ String endpoint = "http://127.0.0.1:" + server.getAddress().getPort();
+ server.createContext("/upload/storage/v1/b/bucket/o", exchange -> {
+ try {
+ exchange.getRequestBody().close();
+ queries.add(exchange.getRequestURI().getQuery());
+ byte[] metadata =
"{\"size\":\"7\",\"generation\":\"20\"}".getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().set("Content-Type",
"application/json");
+ exchange.sendResponseHeaders(200, metadata.length);
+ exchange.getResponseBody().write(metadata);
+ } finally {
+ exchange.close();
+ }
+ });
+ server.start();
+ try (AsyncOperator async = AsyncOperator.of(ServiceConfig.Gcs.builder()
+ .bucket("bucket")
+ .endpoint(endpoint)
+ .skipSignature(true)
+ .build());
+ Operator op = async.blocking()) {
+ assertThat(op.info.capability.writeWithIfVersionMatch).isTrue();
+ assertThat(op.info.capability.writeWithIfVersionNotMatch).isTrue();
+ WriteOptions direct = WriteOptions.builder()
+ .ifVersionMatch("17")
+ .ifVersionNotMatch("18")
+ .build();
+ op.write("file", CONTENT, direct);
+
+ Metadata snapshot = Metadata.builder()
+ .version("19")
+ .etag("\"etag\"")
+ .lastModified(Instant.MAX)
+ .build();
+ WriteOptions fromSnapshot = direct.toBuilder()
+ .ifVersionMatch(null)
+ .ifNotChanged(snapshot)
+ .build();
+ async.write("file", CONTENT, fromSnapshot).join();
+
+ WriteOptions createOnly =
WriteOptions.builder().ifNotExists(true).build();
+ WriteOptions versionMatch =
+ WriteOptions.builder().ifVersionMatch("42").build();
+ WriteOptions snapshotMatch = WriteOptions.builder()
+ .ifNotChanged(Metadata.builder().version("42").build())
+ .build();
+ op.write("file", CONTENT, createOnly);
+ op.write("file", CONTENT, versionMatch);
+ async.write("file", CONTENT, snapshotMatch).join();
+
+ for (WriteOptions matching : new WriteOptions[] {versionMatch,
snapshotMatch}) {
+ WriteOptions conflicting =
+ matching.toBuilder().ifNotExists(true).build();
+ assertThatThrownBy(() -> op.write("file", CONTENT,
conflicting))
+
.is(OpenDALExceptionCondition.ofSync(Code.Unsupported));
+ assertThatThrownBy(
+ () -> async.write("file", CONTENT,
conflicting).join())
+
.is(OpenDALExceptionCondition.ofAsync(Code.Unsupported));
+ assertThatThrownBy(() -> async.presignWrite("file",
PRESIGN_EXPIRY, conflicting)
+ .join())
+
.is(OpenDALExceptionCondition.ofAsync(Code.Unsupported));
+ }
+ } finally {
+ server.stop(0);
+ }
+
+ assertThat(queries).hasSize(5);
+ assertThat(queries.get(0)).contains("uploadType=media",
"ifGenerationMatch=17", "ifGenerationNotMatch=18");
+ assertThat(queries.get(1)).contains("uploadType=media",
"ifGenerationMatch=19", "ifGenerationNotMatch=18");
+ assertThat(queries.get(2)).contains("ifGenerationMatch=0");
+ assertThat(queries.get(3)).contains("ifGenerationMatch=42");
+ assertThat(queries.get(4)).contains("ifGenerationMatch=42");
+ }
+
+ @Test
+ void testGcsPresignWriteGenerationConditions() throws Exception {
+ // An ephemeral RSA key lets GCS sign locally with a test service
account.
+ KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
+ keyGenerator.initialize(2048);
+ String privateKey = Base64.getMimeEncoder(64, new byte[] {'\n'})
+
.encodeToString(keyGenerator.generateKeyPair().getPrivate().getEncoded());
+ String credential =
"{\"type\":\"service_account\",\"client_email\":\"[email protected]\","
+ + "\"private_key\":\"-----BEGIN PRIVATE KEY-----\\n"
+ + privateKey.replace("\n", "\\n")
+ + "\\n-----END PRIVATE KEY-----\\n\"}";
+
+ try (AsyncOperator async = AsyncOperator.of(ServiceConfig.Gcs.builder()
+ .bucket("bucket")
+
.credential(Base64.getEncoder().encodeToString(credential.getBytes(StandardCharsets.UTF_8)))
+ .disableConfigLoad(true)
+ .disableVmMetadata(true)
+ .build())) {
+ WriteOptions versionNotMatch =
+ WriteOptions.builder().ifVersionNotMatch("42").build();
+ assertThatThrownBy(() -> async.presignWrite("file",
PRESIGN_EXPIRY, versionNotMatch)
+ .join())
+ .is(OpenDALExceptionCondition.ofAsync(Code.Unsupported));
+
+ WriteOptions versionMatch =
+ WriteOptions.builder().ifVersionMatch("42").build();
+ WriteOptions createOnly =
WriteOptions.builder().ifNotExists(true).build();
+ PresignedRequest match =
+ async.presignWrite("file", PRESIGN_EXPIRY,
versionMatch).join();
+ PresignedRequest create =
+ async.presignWrite("file", PRESIGN_EXPIRY,
createOnly).join();
+
assertThat(match.getHeaders()).containsEntry("x-goog-if-generation-match",
"42");
+
assertThat(create.getHeaders()).containsEntry("x-goog-if-generation-match",
"0");
+ for (PresignedRequest request : new PresignedRequest[] {match,
create}) {
+ assertThat(request.getMethod()).isEqualTo("PUT");
+ assertThat(URI.create(request.getUri()).getQuery())
+
.contains("X-Goog-SignedHeaders=host;x-goog-if-generation-match",
"X-Goog-Signature=");
+ }
+ }
+ }
+
+ @Test
+ void testToBuilder() {
+ WriteOptions original = WriteOptions.builder()
+ .contentLanguage(CONTENT_LANGUAGE)
+ .expires(Duration.ofSeconds(60))
+ .build();
+ WriteOptions updated = original.toBuilder().chunk(1024).build();
+ assertThat(updated.contentLanguage).isEqualTo(CONTENT_LANGUAGE);
+ assertThat(updated.expires).isEqualTo(original.expires);
+ assertThat(updated.chunk).isEqualTo(1024);
+ assertThat(original.chunk).isEqualTo(-1);
+ assertThat(original).isNotEqualTo(original.toBuilder().build());
+ }
+}
diff --git a/core/services/gcs/src/backend.rs b/core/services/gcs/src/backend.rs
index d331e93b66..de9f8d75bf 100644
--- a/core/services/gcs/src/backend.rs
+++ b/core/services/gcs/src/backend.rs
@@ -536,6 +536,13 @@ impl Service for GcsBackend {
}
fn write(&self, ctx: &OperationContext, path: &str, args: OpWrite) ->
Result<Self::Writer> {
+ if args.if_not_exists() && args.if_version_match().is_some() {
+ return Err(Error::new(
+ ErrorKind::Unsupported,
+ "GCS writes do not support combining if_not_exists with
if_version_match",
+ ));
+ }
+
let conditional = args.if_not_exists()
|| args.if_version_match().is_some()
|| args.if_version_not_match().is_some();
diff --git a/core/services/gcs/src/core.rs b/core/services/gcs/src/core.rs
index 29396c7786..3d4d0f606a 100644
--- a/core/services/gcs/src/core.rs
+++ b/core/services/gcs/src/core.rs
@@ -324,6 +324,13 @@ impl GcsCore {
idempotency_token: Option<&str>,
crc32c: Option<[u8; 4]>,
) -> Result<Request<Buffer>> {
+ if op.if_not_exists() && op.if_version_match().is_some() {
+ return Err(Error::new(
+ ErrorKind::Unsupported,
+ "GCS writes do not support combining if_not_exists with
if_version_match",
+ ));
+ }
+
let p = build_absolute_path(&self.root, path);
let request_metadata = InsertRequestMetadata {
@@ -423,6 +430,13 @@ impl GcsCore {
op: &OpWrite,
idempotency_token: &str,
) -> Result<Request<Buffer>> {
+ if op.if_not_exists() && op.if_version_match().is_some() {
+ return Err(Error::new(
+ ErrorKind::Unsupported,
+ "GCS writes do not support combining if_not_exists with
if_version_match",
+ ));
+ }
+
let p = build_absolute_path(&self.root, path);
let base = format!("{}/upload/storage/v1/b/{}/o", self.endpoint,
self.bucket);
let mut url = QueryPairsWriter::new(&base)
@@ -549,6 +563,19 @@ impl GcsCore {
args: &OpWrite,
body: Buffer,
) -> Result<Request<Buffer>> {
+ if args.if_version_not_match().is_some() {
+ return Err(Error::new(
+ ErrorKind::Unsupported,
+ "GCS XML writes do not support if_version_not_match",
+ ));
+ }
+ if args.if_not_exists() && args.if_version_match().is_some() {
+ return Err(Error::new(
+ ErrorKind::Unsupported,
+ "GCS writes do not support combining if_not_exists with
if_version_match",
+ ));
+ }
+
let p = build_absolute_path(&self.root, path);
let url = format!("{}/{}/{}", self.endpoint, self.bucket, p);
@@ -1681,24 +1708,6 @@ mod tests {
.contains("ifGenerationNotMatch=456")
);
- let write = core
- .gcs_insert_object_request(
- "object",
- Some(0),
- &write_args(options::WriteOptions {
- if_not_exists: true,
- if_version_match: Some("123".to_owned()),
- ..Default::default()
- }),
- Buffer::new(),
- None,
- None,
- )
- .expect("write request must build");
- let query = write.uri().query().unwrap();
- assert!(query.contains("ifGenerationMatch=123"));
- assert_eq!(query.matches("ifGenerationMatch=").count(), 1);
-
let delete = core
.gcs_delete_object_request(
"object",
@@ -1720,21 +1729,6 @@ mod tests {
.contains("ifGenerationNotMatch=456")
);
- let resumable = core
- .gcs_initiate_resumable_upload_request(
- "object",
- &write_args(options::WriteOptions {
- if_not_exists: true,
- if_version_match: Some("123".to_owned()),
- ..Default::default()
- }),
- "token",
- )
- .expect("resumable request must build");
- let query = resumable.uri().query().unwrap();
- assert!(query.contains("ifGenerationMatch=123"));
- assert_eq!(query.matches("ifGenerationMatch=").count(), 1);
-
let rewrite = core
.gcs_rewrite_object_request(
"source",
@@ -2018,6 +2012,87 @@ mod tests {
);
}
+ #[test]
+ fn test_write_generation_preconditions_are_mapped_to_json_api() {
+ let core = test_core();
+
+ for (options, expected) in [
+ (
+ options::WriteOptions {
+ if_not_exists: true,
+ ..Default::default()
+ },
+ &["ifGenerationMatch=0"][..],
+ ),
+ (
+ options::WriteOptions {
+ if_version_match: Some("123".to_owned()),
+ ..Default::default()
+ },
+ &["ifGenerationMatch=123"][..],
+ ),
+ (
+ options::WriteOptions {
+ if_version_not_match: Some("456".to_owned()),
+ ..Default::default()
+ },
+ &["ifGenerationNotMatch=456"][..],
+ ),
+ (
+ options::WriteOptions {
+ if_not_exists: true,
+ if_version_not_match: Some("456".to_owned()),
+ ..Default::default()
+ },
+ &["ifGenerationMatch=0", "ifGenerationNotMatch=456"][..],
+ ),
+ ] {
+ let args = write_args(options);
+ let insert = core
+ .gcs_insert_object_request("object", Some(0), &args,
Buffer::new(), None, None)
+ .unwrap();
+ let resumable = core
+ .gcs_initiate_resumable_upload_request("object", &args,
"token")
+ .unwrap();
+
+ for request in [insert, resumable] {
+ let conditions: Vec<_> = request
+ .uri()
+ .query()
+ .unwrap()
+ .split('&')
+ .filter(|param| param.starts_with("ifGeneration"))
+ .collect();
+ assert_eq!(conditions, expected, "{}", request.uri());
+ }
+ }
+ }
+
+ #[test]
+ fn test_write_requests_reject_combining_if_not_exists_with_version_match()
{
+ let core = test_core();
+ let args = write_args(options::WriteOptions {
+ if_not_exists: true,
+ if_version_match: Some("123".to_owned()),
+ ..Default::default()
+ });
+
+ let insert = core
+ .gcs_insert_object_request("object", Some(0), &args,
Buffer::new(), None, None)
+ .unwrap_err();
+ assert_eq!(insert.kind(), ErrorKind::Unsupported);
+
+ let resumable = core
+ .gcs_initiate_resumable_upload_request("object", &args, "token")
+ .unwrap_err();
+ assert_eq!(resumable.kind(), ErrorKind::Unsupported);
+
+ let xml = core
+ .gcs_insert_object_xml_request("object", &args, Buffer::new())
+ .unwrap_err();
+ assert_eq!(xml.kind(), ErrorKind::Unsupported);
+ }
+
#[test]
fn test_generation_match_is_mapped_to_xml_api() {
let core = test_core();
@@ -2050,7 +2125,6 @@ mod tests {
.gcs_insert_object_xml_request(
"object",
&write_args(options::WriteOptions {
- if_not_exists: true,
if_version_match: Some("123".to_owned()),
..Default::default()
}),
@@ -2080,6 +2154,21 @@ mod tests {
assert_eq!(create.headers()["x-goog-if-generation-match"], "0");
}
+ #[test]
+ fn test_gcs_insert_object_xml_request_rejects_version_not_match() {
+ let err = test_core()
+ .gcs_insert_object_xml_request(
+ "object",
+ &write_args(options::WriteOptions {
+ if_version_not_match: Some("456".to_owned()),
+ ..Default::default()
+ }),
+ Buffer::new(),
+ )
+ .unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::Unsupported);
+ }
+
#[test]
fn
test_gcs_insert_object_xml_request_with_cache_control_and_content_disposition()
{
let content_disposition = "attachment; filename=\"greeting.txt\"";
diff --git a/dev/src/generate/java.rs b/dev/src/generate/java.rs
index 16843066d6..a1781c49df 100644
--- a/dev/src/generate/java.rs
+++ b/dev/src/generate/java.rs
@@ -129,8 +129,9 @@ struct OptionsSpec {
fields: &'static [(&'static str, OptionKind)],
}
-/// Field order and kinds used by the existing Java constructors and builders.
-const EXISTING_OPTIONS_FIELDS: &[OptionsSpec] = {
+/// Field order and kinds used by the Java constructors and builders.
+/// Gap requires multi-range reads, and checksum support requires Java
checksum metadata.
+const JAVA_OPTIONS_FIELDS: &[OptionsSpec] = {
use OptionKind::*;
&[
@@ -154,6 +155,7 @@ const EXISTING_OPTIONS_FIELDS: &[OptionsSpec] = {
("start_after", OptionString),
("versions", Bool),
("deleted", Bool),
+ ("glob", OptionString),
],
},
OptionsSpec {
@@ -173,6 +175,7 @@ const EXISTING_OPTIONS_FIELDS: &[OptionsSpec] = {
("override_content_type", OptionString),
("override_cache_control", OptionString),
("override_content_disposition", OptionString),
+ ("limit", OptionU64),
],
},
OptionsSpec {
@@ -220,6 +223,11 @@ const EXISTING_OPTIONS_FIELDS: &[OptionsSpec] = {
("if_not_exists", Bool),
("concurrent", Usize),
("chunk", OptionUsize),
+ ("content_language", OptionString),
+ ("expires", OptionDuration),
+ ("if_version_match", OptionString),
+ ("if_version_not_match", OptionString),
+ ("if_not_changed", OptionMetadata),
],
},
]
@@ -500,12 +508,12 @@ fn options_classes<'a>(
metadata_fields: &[MetadataField],
) -> Result<Vec<OptionsClass<'a>>> {
let mut classes = Vec::new();
- for spec in EXISTING_OPTIONS_FIELDS {
+ for spec in JAVA_OPTIONS_FIELDS {
let Some(options) = parsed.iter().find(|options| options.name ==
spec.name) else {
bail!("core options are missing Java struct `{}`", spec.name);
};
let fields = select_options_fields(options, spec)?;
- classes.push(options_class(options, spec, &fields, metadata_fields)?);
+ classes.push(options_class(options, spec, &fields, metadata_fields));
}
Ok(classes)
}
@@ -558,6 +566,8 @@ fn option_class_details(name: &str) -> Vec<String> {
"ListOptions" => vec![concat!(
"Options that require an unsupported service capability fail with
",
"{@link OpenDALException.Code#Unsupported}. ",
+ "When globbing is supported, invalid {@link #glob} patterns fail
with ",
+ "{@link OpenDALException.Code#ConfigInvalid}. ",
"{@link #limit} is a pagination hint that services may ignore even
when ",
"{@link Capability#listWithLimit} is supported."
)],
@@ -610,9 +620,11 @@ fn option_class_details(name: &str) -> Vec<String> {
],
"WriteOptions" => vec![concat!(
"All supplied conditions must hold for the write to commit. ",
- "Unsupported conditions or {@link #append} fail with {@link
OpenDALException.Code#Unsupported}. ",
+ "Unsupported conditions, {@link #append}, or {@link #expires} fail
with {@link OpenDALException.Code#Unsupported}. ",
"Unsupported metadata options may be ignored. ",
"Failed conditions fail with {@link
OpenDALException.Code#ConditionNotMatch}. ",
+ "Invalid {@link #expires} or {@link #ifNotChanged} values fail
with ",
+ "{@link OpenDALException.Code#ConfigInvalid}. ",
"Presigned write requests validate options and capabilities
without executing against storage."
)],
_ => Vec::new(),
@@ -626,7 +638,7 @@ fn options_class<'a>(
spec: &OptionsSpec,
fields: &[&OptionField],
metadata_fields: &[MetadataField],
-) -> Result<OptionsClass<'a>> {
+) -> OptionsClass<'a> {
let mut imports = BTreeSet::new();
let mut properties = Vec::new();
for field in fields {
@@ -641,6 +653,10 @@ fn options_class<'a>(
imports.insert("java.time.Instant");
("Instant", None)
}
+ OptionKind::OptionDuration => {
+ imports.insert("java.time.Duration");
+ ("Duration", None)
+ }
OptionKind::OptionStringMap => {
imports.insert("java.util.Map");
("Map<String, String>", None)
@@ -685,7 +701,6 @@ fn options_class<'a>(
]);
continue;
}
- OptionKind::OptionDuration => bail!("unsupported Java option
{}::{name}", options.name),
};
let (summary, details) = option_field_javadoc(spec, field,
metadata_fields);
properties.push(OptionProperty {
@@ -698,7 +713,7 @@ fn options_class<'a>(
});
}
- Ok(OptionsClass {
+ OptionsClass {
name: &options.name,
summary: match spec.name {
"ReadOptions" => "Options for a single read or a compatibility
{@link OperatorInputStream}.".to_owned(),
@@ -714,7 +729,7 @@ fn options_class<'a>(
.iter()
.map(|field| {
let expr = if fields.iter().any(|exposed| exposed.name ==
field.name) {
- option_rs_expr(&options.name, field)?
+ option_rs_expr(&options.name, field)
} else {
match field.kind {
OptionKind::Bool => "false",
@@ -730,14 +745,14 @@ fn options_class<'a>(
}
.to_owned()
};
- Ok(OptionRsField {
+ OptionRsField {
name: &field.name,
expr,
- })
+ }
})
- .collect::<Result<_>>()?,
+ .collect(),
has_unmirrored_fields: options.has_unmirrored_fields,
- })
+ }
}
fn option_field_javadoc(
@@ -747,23 +762,62 @@ fn option_field_javadoc(
) -> (String, Vec<String>) {
let name = field.name.as_str();
let render = |lines: &[String]| option_javadoc(lines, spec, Some(name),
metadata_fields);
+ let paragraphs = || field.doc.split(|line| line.is_empty());
let mut summary = render(&field.doc);
let mut details = Vec::new();
match (spec.name, name) {
- ("DeleteOptions", "if_not_changed") => details.extend(field
- .doc
- .split(|line| line.is_empty())
+ ("DeleteOptions" | "WriteOptions", "if_not_changed") =>
details.extend(paragraphs()
.skip(1)
.filter(|paragraph| !paragraph.is_empty())
.map(render)),
("DeleteOptions", "recursive")
+ | ("WriteOptions", "content_language")
| (_, "version" | "if_match" | "if_none_match" | "if_version_match" |
"if_version_not_match"
| "if_modified_since" | "if_unmodified_since" | "if_not_exists"
| "override_content_type" | "override_cache_control" |
"override_content_disposition") => {
- if let Some(paragraph) = field.doc.split(|line|
line.is_empty()).nth(1) {
+ if let Some(paragraph) = paragraphs().nth(1) {
details.push(render(paragraph));
}
}
+ ("ListOptions", "glob") => {
+ details.extend(paragraphs().nth(1).map(render));
+ details.push(concat!(
+ "Requires {@link Capability#listWithGlob}. OpenDAL simulates
glob matching client-side ",
+ "when the service lacks native support. A simulated pattern
spanning multiple directories ",
+ "also requires {@link Capability#listWithRecursive} when
combined with ",
+ "{@link #startAfter}, {@link #versions}, or {@link #deleted}.
",
+ "Missing required capabilities fail with {@link
OpenDALException.Code#Unsupported}. ",
+ "When globbing is supported, empty or malformed patterns fail
with ",
+ "{@link OpenDALException.Code#ConfigInvalid}."
+ ).to_owned());
+ }
+ ("ReadOptions", "limit") => details.extend([
+ concat!(
+ "The default of {@code -1L} leaves the limit unset. Without a
limit, bounded forward ",
+ "ranges require the full requested length. Values below {@code
-1L} fail with ",
+ "{@link OpenDALException.Code#ConfigInvalid}."
+ ).to_owned(),
+ concat!(
+ "On direct whole-buffer reads, {@code 0L} validates options
and capabilities, then ",
+ "returns an empty result without accessing storage or
evaluating conditions against the file. ",
+ "With a positive limit, a nonempty forward selection starting
at or beyond EOF fails with ",
+ "{@link OpenDALException.Code#RangeNotSatisfied}."
+ ).to_owned(),
+ concat!(
+ "Setting a limit ({@code limit != -1L}) with a positive {@link
#chunk}, with ",
+ "{@link #concurrent} greater than {@code 1}, with {@link
OperatorInputStream}, or with ",
+ "presigned read requests fails with {@link
OpenDALException.Code#ConfigInvalid}."
+ ).to_owned(),
+ ]),
+ ("WriteOptions", "expires") => {
+ details.extend(paragraphs().nth(1).map(render));
+ details.push(concat!(
+ "Supply a positive {@link Duration}. Zero, negative, or
unrepresentable durations fail ",
+ "with {@link OpenDALException.Code#ConfigInvalid}. The write
fails with ",
+ "{@link OpenDALException.Code#Unsupported} when the service
does not advertise ",
+ "{@link Capability#writeWithExpires}."
+ ).to_owned());
+ }
("ReadOptions" | "ReaderOptions", "chunk") => {
summary = "Target size of each internal range request in
bytes.".to_owned();
details.push(concat!(
@@ -846,7 +900,7 @@ fn option_field_javadoc(
(summary, details)
}
-fn option_rs_expr(options: &str, field: &OptionField) -> Result<String> {
+fn option_rs_expr(options: &str, field: &OptionField) -> String {
let name = field.name.as_str();
let camel = case_java_field_name(name);
let (converter, suffix) = match field.kind {
@@ -855,29 +909,34 @@ fn option_rs_expr(options: &str, field: &OptionField) ->
Result<String> {
}
OptionKind::Bool => ("read_bool_field", "?"),
OptionKind::OptionUsize if matches!(options, "ListOptions" |
"WriteOptions") => {
- ("read_jlong_field_to_usize", "?")
+ return format!(
+ "convert::read_jlong_field_to_usize(env, options, \"{camel}\",
ErrorKind::Unexpected)?"
+ );
+ }
+ OptionKind::OptionMetadata if options == "WriteOptions" => {
+ ("read_metadata_condition_field", "?")
}
OptionKind::Usize
| OptionKind::OptionUsize
| OptionKind::OptionU64
| OptionKind::OptionMetadata => {
// These fields are read before building the struct to keep
validation precedence.
- return Ok(name.to_owned());
+ return name.to_owned();
}
OptionKind::OptionString => ("read_string_field", "?"),
OptionKind::OptionTimestamp => ("read_instant_field_to_timestamp",
"?"),
+ OptionKind::OptionDuration => ("read_duration_field", "?"),
OptionKind::OptionStringMap => ("read_map_field", "?"),
- OptionKind::BytesRange => return Ok("convert::read_range_fields(env,
options)?".to_owned()),
- OptionKind::OptionDuration => bail!("unsupported Java option
{options}::{name}"),
+ OptionKind::BytesRange => return "convert::read_range_fields(env,
options)?".to_owned(),
};
let expr = format!("convert::{converter}(env, options,
\"{camel}\"){suffix}");
if 8 + name.len() + 2 + expr.len() + 1 > 100 {
- return Ok(format!(
+ return format!(
"convert::{converter}(\n env,\n options,\n
\"{camel}\",\n ){suffix}"
- ));
+ );
}
- Ok(expr)
+ expr
}
/// Translate inline Rustdoc links and code spans in the first paragraph.
@@ -961,11 +1020,11 @@ fn option_javadoc_token(
),
("ErrorKind", "") => "{@link OpenDALException.Code}".to_owned(),
("ErrorKind", variant) => format!("{{@link
OpenDALException.Code#{variant}}}"),
- (ty, "") if EXISTING_OPTIONS_FIELDS.iter().any(|spec| spec.name == ty)
=> {
+ (ty, "") if JAVA_OPTIONS_FIELDS.iter().any(|spec| spec.name == ty) => {
format!("{{@link {ty}}}")
}
(ty, field)
- if EXISTING_OPTIONS_FIELDS.iter().any(|spec| {
+ if JAVA_OPTIONS_FIELDS.iter().any(|spec| {
spec.name == ty
&& spec
.fields
@@ -1125,16 +1184,19 @@ mod tests {
}
#[test]
- fn test_options_fields_follow_existing_java_order() {
+ fn test_options_fields_follow_java_order() {
let expected = [
(
"DeleteOptions",
"version recursive ifMatch ifNoneMatch ifVersionMatch
ifVersionNotMatch ifNotChanged",
),
- ("ListOptions", "recursive limit startAfter versions deleted"),
+ (
+ "ListOptions",
+ "recursive limit startAfter versions deleted glob",
+ ),
(
"ReadOptions",
- "offset length version ifMatch ifNoneMatch ifVersionMatch
ifVersionNotMatch ifModifiedSince ifUnmodifiedSince concurrent chunk
contentLengthHint overrideContentType overrideCacheControl
overrideContentDisposition",
+ "offset length version ifMatch ifNoneMatch ifVersionMatch
ifVersionNotMatch ifModifiedSince ifUnmodifiedSince concurrent chunk
contentLengthHint overrideContentType overrideCacheControl
overrideContentDisposition limit",
),
(
"ReaderOptions",
@@ -1146,18 +1208,18 @@ mod tests {
),
(
"WriteOptions",
- "contentType contentDisposition cacheControl contentEncoding
ifMatch ifNoneMatch userMetadata append ifNotExists concurrent chunk",
+ "contentType contentDisposition cacheControl contentEncoding
ifMatch ifNoneMatch userMetadata append ifNotExists concurrent chunk
contentLanguage expires ifVersionMatch ifVersionNotMatch ifNotChanged",
),
];
let mut structs = core_options_structs();
let metadata_fields =
build_metadata_fields(core_metadata_fields()).unwrap();
- assert_eq!(EXISTING_OPTIONS_FIELDS.len(), expected.len());
+ assert_eq!(JAVA_OPTIONS_FIELDS.len(), expected.len());
let env = Environment::new();
let template = env
.template_from_str(include_str!("java/options_java.j2"))
.unwrap();
- for (spec, (name, names)) in
EXISTING_OPTIONS_FIELDS.iter().zip(expected) {
+ for (spec, (name, names)) in JAVA_OPTIONS_FIELDS.iter().zip(expected) {
assert_eq!(spec.name, name);
let options = structs
.iter_mut()
@@ -1165,7 +1227,7 @@ mod tests {
.unwrap();
options.fields.reverse();
let fields = select_options_fields(options, spec).unwrap();
- let class = options_class(options, spec, &fields,
&metadata_fields).unwrap();
+ let class = options_class(options, spec, &fields,
&metadata_fields);
let names: Vec<_> = names.split_whitespace().collect();
assert_eq!(
class
@@ -1179,13 +1241,15 @@ mod tests {
let rendered = template.render(context! { class => Serde(class)
}).unwrap();
let (annotations, modifiers) = match name {
- "StatOptions" => ("@Data\n@Builder\npublic class", "private"),
- "ReaderOptions" => ("@Builder\npublic final class", "public
final"),
- _ => ("@Builder\npublic class", "public final"),
+ "StatOptions" => ("@Data\n@Builder(toBuilder = true)\npublic
class", "private"),
+ "ReaderOptions" => (
+ "@Builder(toBuilder = true)\npublic final class",
+ "public final",
+ ),
+ _ => ("@Builder(toBuilder = true)\npublic class", "public
final"),
};
assert!(rendered.contains(&format!("{annotations} {name} {{")));
assert_eq!(rendered.contains("@Data"), name == "StatOptions");
- assert!(!rendered.contains("toBuilder"));
assert_eq!(
rendered.matches(&format!(" {modifiers} ")).count(),
names.len()
@@ -1314,7 +1378,10 @@ mod tests {
"class",
class_doc,
&[
- "Options that require an unsupported service
capability fail with {@link OpenDALException.Code#Unsupported}.",
+ concat!(
+ "Options that require an unsupported service
capability fail with {@link OpenDALException.Code#Unsupported}. ",
+ "When globbing is supported, invalid {@link
#glob} patterns fail with {@link OpenDALException.Code#ConfigInvalid}."
+ ),
"{@link #limit} is a pagination hint that services
may ignore even when {@link Capability#listWithLimit} is supported.",
],
);
@@ -1327,6 +1394,23 @@ mod tests {
"{@code 0L}, other negative values, and values
that do not fit fail with {@link OpenDALException.Code#Unexpected}",
],
);
+ assert_field(
+ "glob",
+ &[
+ "Filter entries with a case-sensitive Unix shell
style glob pattern.",
+ "relative to the listed directory, or to the
parent directory when the list path is a prefix without a trailing slash",
+ "Entries must also satisfy the list prefix.",
+ "independently of {@link #recursive}",
+ "Requires {@link Capability#listWithGlob}. OpenDAL
simulates glob matching client-side when the service lacks native support.",
+ "A simulated pattern spanning multiple directories
also requires {@link Capability#listWithRecursive} when combined with {@link
#startAfter}, {@link #versions}, or {@link #deleted}.",
+ concat!(
+ "Missing required capabilities fail with
{@link OpenDALException.Code#Unsupported}. ",
+ "When globbing is supported, empty or
malformed patterns fail with {@link OpenDALException.Code#ConfigInvalid}."
+ ),
+ "@see Capability#listWithGlob",
+ "@see Capability#listWithRecursive",
+ ],
+ );
}
"ReadOptions" | "ReaderOptions" => {
assert_doc(
@@ -1370,6 +1454,19 @@ mod tests {
],
);
if class.name == "ReadOptions" {
+ assert!(rendered.contains("public final long limit =
-1L;"));
+ assert_field(
+ "limit",
+ &[
+ "Return at most this many bytes from the start
of the selected range, accepting EOF after a valid starting byte.",
+ "The default of {@code -1L} leaves the limit
unset.",
+ "Without a limit, bounded forward ranges
require the full requested length.",
+ "Values below {@code -1L} fail with {@link
OpenDALException.Code#ConfigInvalid}.",
+ "On direct whole-buffer reads, {@code 0L}
validates options and capabilities, then returns an empty result without
accessing storage or evaluating conditions against the file.",
+ "With a positive limit, a nonempty forward
selection starting at or beyond EOF fails with {@link
OpenDALException.Code#RangeNotSatisfied}.",
+ "Setting a limit ({@code limit != -1L}) with a
positive {@link #chunk}, with {@link #concurrent} greater than {@code 1}, with
{@link OperatorInputStream}, or with presigned read requests fails with {@link
OpenDALException.Code#ConfigInvalid}.",
+ ],
+ );
assert_doc(
"class",
class_doc,
@@ -1440,9 +1537,13 @@ mod tests {
class_doc,
&[
"for the write to commit",
- "Unsupported conditions or {@link #append} fail
with {@link OpenDALException.Code#Unsupported}",
+ "Unsupported conditions, {@link #append}, or
{@link #expires} fail with {@link OpenDALException.Code#Unsupported}.",
"Unsupported metadata options may be ignored.",
- "Presigned write requests validate options and
capabilities without executing against storage.",
+ concat!(
+ "Failed conditions fail with {@link
OpenDALException.Code#ConditionNotMatch}. ",
+ "Invalid {@link #expires} or {@link
#ifNotChanged} values fail with {@link OpenDALException.Code#ConfigInvalid}. ",
+ "Presigned write requests validate options and
capabilities without executing against storage."
+ ),
],
);
assert_field(
@@ -1467,6 +1568,55 @@ mod tests {
"{@code 0L}, other negative values, and values
that do not fit fail with {@link OpenDALException.Code#Unexpected}",
],
);
+ assert_field(
+ "contentLanguage",
+ &[
+ "Use a language tag or a comma-separated list of
tags, such as {@code fr-CA, en}.",
+ "A subsequent stat can retrieve the stored value
with {@link Metadata#contentLanguage}.",
+ "Services without support may ignore this option.",
+ "@see Capability#writeWithContentLanguage",
+ ],
+ );
+ assert!(rendered.contains("import java.time.Duration;"));
+ assert!(rendered.contains("public final Duration
expires;"));
+ assert_field(
+ "expires",
+ &[
+ "A supplied duration overrides the service's
default TTL. When unset, the service uses its usual expiration policy.",
+ "Services round positive durations up to their
supported precision.",
+ "Supply a positive {@link Duration}.",
+ "Zero, negative, or unrepresentable durations fail
with {@link OpenDALException.Code#ConfigInvalid}.",
+ "The write fails with {@link
OpenDALException.Code#Unsupported} when the service does not advertise {@link
Capability#writeWithExpires}.",
+ "@see Capability#writeWithExpires",
+ ],
+ );
+ assert_field(
+ "ifVersionMatch",
+ &[
+ "The condition succeeds when the file exists and
its version equals this value.",
+ "A file with a different version, or a missing
file, fails the write with {@link OpenDALException.Code#ConditionNotMatch}.",
+ "@see Capability#writeWithIfVersionMatch",
+ ],
+ );
+ assert_field(
+ "ifVersionNotMatch",
+ &[
+ "The condition succeeds when the file exists with
a different version.",
+ "A file whose version equals this value fails the
write with {@link OpenDALException.Code#ConditionNotMatch}.",
+ "When no file exists at the write path, no
portable behavior is defined.",
+ "@see Capability#writeWithIfVersionNotMatch",
+ ],
+ );
+ assert_field(
+ "ifNotChanged",
+ &[
+ "Pass metadata previously returned by OpenDAL for
the same path.",
+ "OpenDAL derives a version match when the service
supports version conditions and the metadata contains a version. Otherwise it
uses a non-weak ETag if present.",
+ "A changed or missing file fails the write with
{@link OpenDALException.Code#ConditionNotMatch}, as does combining this option
with a conflicting {@link #ifMatch} or {@link #ifVersionMatch} value.",
+ "{@link OpenDALException.Code#Unsupported} when
the service does not support the derived primitive condition",
+ "{@link OpenDALException.Code#ConfigInvalid} when
the metadata contains neither a version nor a non-weak ETag.",
+ ],
+ );
}
name => panic!("missing Javadoc expectations for {name}"),
}
@@ -1528,7 +1678,7 @@ mod tests {
.into_iter()
.find(|options| options.name == "ListOptions")
.unwrap();
- let spec = EXISTING_OPTIONS_FIELDS
+ let spec = JAVA_OPTIONS_FIELDS
.iter()
.find(|spec| spec.name == options.name)
.unwrap();
@@ -1544,9 +1694,9 @@ mod tests {
fn test_options_fields_reject_duplicate_unexposed_field() {
let mut options = core_options_structs()
.into_iter()
- .find(|options| options.name == "ListOptions")
+ .find(|options| options.name == "ReadOptions")
.unwrap();
- let spec = EXISTING_OPTIONS_FIELDS
+ let spec = JAVA_OPTIONS_FIELDS
.iter()
.find(|spec| spec.name == options.name)
.unwrap();
@@ -1554,14 +1704,14 @@ mod tests {
options
.fields
.iter()
- .find(|field| field.name == "glob")
+ .find(|field| field.name == "gap")
.unwrap()
.clone(),
);
let err = select_options_fields(&options, spec).unwrap_err();
assert_eq!(
err.to_string(),
- "core ListOptions contains duplicate field `glob`"
+ "core ReadOptions contains duplicate field `gap`"
);
}
@@ -1571,7 +1721,7 @@ mod tests {
.into_iter()
.find(|options| options.name == "ListOptions")
.unwrap();
- let spec = EXISTING_OPTIONS_FIELDS
+ let spec = JAVA_OPTIONS_FIELDS
.iter()
.find(|spec| spec.name == options.name)
.unwrap();
@@ -1591,7 +1741,7 @@ mod tests {
#[test]
fn test_option_javadoc_translates_inline_links() {
let metadata_fields =
build_metadata_fields(core_metadata_fields()).unwrap();
- let spec = EXISTING_OPTIONS_FIELDS
+ let spec = JAVA_OPTIONS_FIELDS
.iter()
.find(|spec| spec.name == "ListOptions")
.unwrap();
@@ -1609,7 +1759,7 @@ mod tests {
concat!(
"Use {@link #startAfter} & {@link
Capability#listWithLimit} ",
"or <a href=\"https://example.com/list?a=b&c=d\">the
guide</a>. ",
- "See {@code Self::glob}, {@link ReadOptions#chunk}, {@code
ReadOptions::gap}, ",
+ "See {@link #glob}, {@link ReadOptions#chunk}, {@code
ReadOptions::gap}, ",
"{@code CopyOptions}, {@code Reader::fetch}, and {@code
Metadata::checksum}."
)
);
@@ -1631,7 +1781,7 @@ mod tests {
}
#[test]
- fn test_options_jni_defaults_for_unexposed_fields() {
+ fn test_options_jni_converter_contracts() {
let parsed = core_options_structs();
let metadata_fields =
build_metadata_fields(core_metadata_fields()).unwrap();
let classes = options_classes(&parsed, &metadata_fields).unwrap();
@@ -1644,24 +1794,16 @@ mod tests {
let expected: &[(&str, &[&str])] = &[
("delete", &[]),
- ("list", &["glob: None,"]),
- ("read", &["limit: None,", "gap: None,", "checksum: false,"]),
+ ("list", &[]),
+ ("read", &["gap: None,", "checksum: false,"]),
("reader", &["gap: None,", "checksum: false,"]),
("stat", &["checksum: false,"]),
- (
- "write",
- &[
- "content_language: None,",
- "expires: None,",
- "if_version_match: None,",
- "if_version_not_match: None,",
- "if_not_changed: None,",
- ],
- ),
+ ("write", &[]),
];
let converters: Vec<_> = rendered.split("pub(crate) fn
make_").skip(1).collect();
assert_eq!(converters.len(), expected.len());
- for (converter, &(name, defaults)) in converters.iter().zip(expected) {
+ for ((class, converter), &(name, defaults)) in
classes.iter().zip(converters).zip(expected)
+ {
assert!(converter.starts_with(&format!("{name}_options(")));
for default in defaults {
assert!(
@@ -1669,7 +1811,22 @@ mod tests {
"{name} must initialize {default}"
);
}
- assert_eq!(converter.contains("..Default::default()"), name ==
"write");
+ assert_eq!(class.has_unmirrored_fields, name == "write");
+ assert_eq!(
+ converter.contains("..Default::default()"),
+ class.has_unmirrored_fields
+ );
+ if class.has_unmirrored_fields {
+ assert!(!converter.contains("checksum:"));
+ }
+ if name == "read" {
+ assert!(converter.contains(concat!(
+ "let limit = convert::read_non_negative_jlong_to_u64(env,
options, \"limit\")?;\n",
+ " Ok(opendal::options::ReadOptions {\n",
+ " range: convert::read_range_fields(env,
options)?,\n",
+ " limit,\n"
+ )));
+ }
}
}
diff --git a/dev/src/generate/java/options_java.j2
b/dev/src/generate/java/options_java.j2
index badaac9c02..ef6b8ebc82 100644
--- a/dev/src/generate/java/options_java.j2
+++ b/dev/src/generate/java/options_java.j2
@@ -39,7 +39,7 @@ import lombok.Data;
{%- if class.name == "StatOptions" %}
@Data
{%- endif %}
-@Builder
+@Builder(toBuilder = true)
public {{ "final " if class.name == "ReaderOptions" else "" }}class {{
class.name }} {
{#- StatOptions has published setters. #}
{%- set field_modifiers = "private" if class.name == "StatOptions" else
"public final" %}
diff --git a/dev/src/generate/java/options_rs.j2
b/dev/src/generate/java/options_rs.j2
index 25606d7f01..6c3c2825e4 100644
--- a/dev/src/generate/java/options_rs.j2
+++ b/dev/src/generate/java/options_rs.j2
@@ -21,7 +21,7 @@ use crate::Result;
use crate::convert;
use jni::Env;
use jni::objects::JObject;
-use opendal::{Error, ErrorKind};
+use opendal::ErrorKind;
{%- for class in classes %}
pub(crate) fn make_{{ class.rs_name }}(
@@ -29,30 +29,21 @@ pub(crate) fn make_{{ class.rs_name }}(
options: &JObject,
) -> Result<opendal::options::{{ class.name }}> {
{%- if class.name == "ReadOptions" or class.name == "ReaderOptions" %}
- let concurrent = convert::read_int_field(env, options, "concurrent")?;
- let chunk = convert::read_int64_field(env, options, "chunk")?;
+ let concurrent =
+ convert::read_positive_jint_to_usize(env, options, "concurrent",
ErrorKind::ConfigInvalid)?;
+ let chunk =
+ convert::read_jlong_field_to_usize(env, options, "chunk",
ErrorKind::ConfigInvalid)?;
+ let content_length_hint =
+ convert::read_non_negative_jlong_to_u64(env, options,
"contentLengthHint")?;
{%- if class.name == "ReaderOptions" %}
- let prefetch = convert::read_int_field(env, options, "prefetch")?;
-{%- endif %}
- let content_length_hint = convert::read_int64_field(env, options,
"contentLengthHint")?;
- let (concurrent, chunk, content_length_hint) =
- convert::validate_read_execution_options(concurrent, chunk,
content_length_hint)?;
-{%- if class.name == "ReaderOptions" %}
- let prefetch = usize::try_from(prefetch)
- .map_err(|_| Error::new(ErrorKind::ConfigInvalid, "prefetch must be
non-negative"))?;
+ let prefetch = convert::read_non_negative_jint_to_usize(env, options,
"prefetch")?;
+{%- else %}
+ let limit = convert::read_non_negative_jlong_to_u64(env, options,
"limit")?;
{%- endif %}
{%- elif class.name == "WriteOptions" %}
- let value = convert::read_int_field(env, options, "concurrent")?;
- let concurrent = usize::try_from(value)
- .ok()
- .filter(|&value| value > 0)
- .ok_or_else(|| {
- Error::new(
- ErrorKind::Unexpected,
- format!("Concurrent must be positive, instead got: {value}"),
- )
- })?;
+ let concurrent =
+ convert::read_positive_jint_to_usize(env, options, "concurrent",
ErrorKind::Unexpected)?;
{%- elif class.name == "DeleteOptions" %}
let if_not_changed = convert::read_metadata_condition_field(env, options,
"ifNotChanged")?;