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 c275bf8ddb feat(bindings/nodejs): generate ReadOptions from core
(#9375)
c275bf8ddb is described below
commit c275bf8ddb7cb81f1bde349eb75c6298e179e6b3
Author: Chitral Verma <[email protected]>
AuthorDate: Sun Nov 29 18:18:23 2026 +0530
feat(bindings/nodejs): generate ReadOptions from core (#9375)
* feat(bindings/nodejs): generate ReadOptions from core
Generate the Node.js ReadOptions napi object, its JSDoc, and its
conversion to core from core's ReadOptions, as ListOptions, StatOptions,
and DeleteOptions already are. The 13 members keep their names, types,
optionality, and conversions, including the u32 chunk, the
parse_count-checked concurrent, the lossy gap, and the offset and size
range checks, and invalid values fail in the same order.
Each options table row now names the field's JS form, and each form
carries one core kind, so a kind change still fails generation. The
table can rename a field (read keeps contentType, cacheControl, and
contentDisposition for override_*) and replace a doc that does not hold
for JS (gap). Generated docs drop the Rust-only performance guide
paragraph and read `Some(0)`/`None` as JS.
Correct four core ReadOptions doc claims checked on memory, fs, and
Silo S3: NotFound for a missing file holds only with valid, supported
options; without chunk, a read is one request; concurrent needs chunk;
and S3 sends the override_* fields as response-* parameters on a plain
GetObject. Regenerate the Java and .NET ReadOptions override comments
and update the Java Javadoc contract test.
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/nodejs): generate ReadOptions from core
Address an internal pre-review:
- The core ReadOptions concurrent doc no longer says concurrent has no
effect without chunk: with a limit, concurrent above one still fails
with ConfigInvalid. It now says OpenDAL does not read concurrently
without chunk, and fixes the grammar of that paragraph.
- The offset JSDoc says an offset at or past the end can return an empty
buffer or fail depending on the service and on chunk. On memory and fs,
offset 100n reads nothing, while chunk 4 makes it RangeNotSatisfied.
- The surface test asserts that chunk reaches core, using that
difference, and that a zero chunk reads as if omitted.
- The offset and size docs move into the docs table, keyed by JS member,
and generation fails if a range member has no JS doc.
- js_doc drops only the exact performance guide paragraph, so a reworded
one fails the full-paragraph doc test instead of vanishing.
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/nodejs): generate ReadOptions from core
Address Xuanwo's review of 65584dbeb:
- Core ReadOptions::chunk: 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. That stat carries the read's version
and conditions, so each also needs its stat capability. On fs, read
and readSync with { chunk: 2, ifModifiedSince } fail with Unsupported
at stat for existing and missing files; with a size, the existing-file
read succeeds.
- Core ReadOptions struct doc: NotFound for a missing file applies once
the option and capability checks pass and the read reaches storage.
- Node.js wording, generated in dev/src/generate/nodejs.rs so the core
and Rust presign docs stay as they are: the empty-read example
{ size: 0n }, that presignRead(path, expires) takes no options so
presigned reads cannot request the response header overrides, and the
chunk paragraph in terms of size. Each rewrite must match core's
rendered doc, or generation fails.
- Regenerate the Java and .NET ReadOptions docs, which now link the stat
capability that the chunk doc names.
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/nodejs): generate ReadOptions from core
Address Xuanwo's second review of d9f4a4b05:
- The Node.js ReadOptions struct doc now reads "A read with
`{ size: 0n }` validates the read options and capabilities, ...".
Node.js does not expose limit: on a file containing abcdef, read and
readSync with { limit: 0 } return abcdef, and with { size: 0n } an
empty buffer. The Node.js wording test rejects "zero limit". Core
keeps its limit wording.
- Core ReadOptions::chunk says "nonempty suffix range": a read of
suffix(0) returns an empty buffer before any stat. With chunk 4 on
memory, suffix(0) of a missing path returns an empty buffer, while
suffix(3) fails with NotFound at stat.
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/dotnet/OpenDAL/Options/ReadOptions.cs | 7 +-
.../main/java/org/apache/opendal/ReadOptions.java | 14 +-
bindings/nodejs/generated.d.ts | 154 +++-
bindings/nodejs/src/options.rs | 168 +---
bindings/nodejs/src/options/read.rs | 198 +++++
.../nodejs/tests/read-options-surface.test.mjs | 157 ++++
core/core/src/types/options.rs | 44 +-
dev/src/generate/java.rs | 5 +-
dev/src/generate/nodejs.rs | 878 +++++++++++++++++++--
9 files changed, 1331 insertions(+), 294 deletions(-)
diff --git a/bindings/dotnet/OpenDAL/Options/ReadOptions.cs
b/bindings/dotnet/OpenDAL/Options/ReadOptions.cs
index ab01ef06e0..8084a21af4 100644
--- a/bindings/dotnet/OpenDAL/Options/ReadOptions.cs
+++ b/bindings/dotnet/OpenDAL/Options/ReadOptions.cs
@@ -105,6 +105,7 @@ public sealed class ReadOptions :
IOptions<OpenDALReadOptions>
/// <summary>
/// Set <see cref="Chunk"/> for the operation.
/// </summary>
+ /// <seealso cref="Capability.StatWithIfModifiedSince"/>
public long? Chunk { get; init; }
/// <summary>
@@ -113,17 +114,17 @@ public sealed class ReadOptions :
IOptions<OpenDALReadOptions>
public long? Gap { get; init; }
/// <summary>
- /// Specify the content-type header that should be sent back by the
operation.
+ /// Request a <c>content-type</c> response header override from services
that support it, including for presigned read requests.
/// </summary>
public string? OverrideContentType { get; init; }
/// <summary>
- /// Specify the <c>cache-control</c> header that should be sent back by
the operation.
+ /// Request a <c>cache-control</c> response header override from services
that support it, including for presigned read requests.
/// </summary>
public string? OverrideCacheControl { get; init; }
/// <summary>
- /// Specify the <c>content-disposition</c> header that should be sent back
by the operation.
+ /// Request a <c>content-disposition</c> response header override from
services that support it, including for presigned read requests.
/// </summary>
public string? OverrideContentDisposition { get; init; }
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 d9714a3727..be3e54dc87 100644
--- a/bindings/java/src/main/java/org/apache/opendal/ReadOptions.java
+++ b/bindings/java/src/main/java/org/apache/opendal/ReadOptions.java
@@ -140,6 +140,8 @@ public class ReadOptions {
* Target size of each internal range request in bytes.
*
* <p>The default of {@code -1L} keeps unchunked streaming. Positive
values enable chunked reads and must fit the native platform's unsigned
pointer-sized integer. {@code 0L}, other negative values, and values that do
not fit fail with {@link OpenDALException.Code#ConfigInvalid}.
+ *
+ * @see Capability#statWithIfModifiedSince
*/
@Builder.Default
public final long chunk = -1L;
@@ -155,23 +157,17 @@ public class ReadOptions {
public final long contentLengthHint = -1L;
/**
- * Specify the content-type header that should be sent back by the
operation.
- *
- * <p>This option is only meaningful when used along with presign.
+ * Request a {@code content-type} response header override from services
that support it, including for presigned read requests.
*/
public final String overrideContentType;
/**
- * Specify the {@code cache-control} header that should be sent back by
the operation.
- *
- * <p>This option is only meaningful when used along with presign.
+ * Request a {@code cache-control} response header override from services
that support it, including for presigned read requests.
*/
public final String overrideCacheControl;
/**
- * Specify the {@code content-disposition} header that should be sent back
by the operation.
- *
- * <p>This option is only meaningful when used along with presign.
+ * Request a {@code content-disposition} response header override from
services that support it, including for presigned read requests.
*/
public final String overrideContentDisposition;
diff --git a/bindings/nodejs/generated.d.ts b/bindings/nodejs/generated.d.ts
index ccc2817801..0f3425c467 100644
--- a/bindings/nodejs/generated.d.ts
+++ b/bindings/nodejs/generated.d.ts
@@ -1386,72 +1386,158 @@ export interface ReaderOptions {
ifUnmodifiedSince?: string
}
+/**
+ * Options for read operations.
+ *
+ * Each condition checks the file being read, and every condition must hold
+ * for the read to proceed. Once the option and capability checks pass, a
+ * read that reaches storage fails with an error whose message includes
`NotFound` for a
+ * missing file, no matter which conditions are set. An existing file that
+ * fails a condition produces an error whose message includes
`ConditionNotMatch`, and a
+ * condition the service does not advertise through its capability returns
+ * an error whose message includes `Unsupported`; OpenDAL never silently drops
a
+ * condition. A read with `{ size: 0n }` validates the read
+ * options and capabilities, then returns an empty buffer without accessing
+ * storage or evaluating conditions against the file.
+ *
+ * See the [conditional operation
specification](https://opendal.apache.org/docs/specifications/conditional-operations/)
+ * for the complete cross-operation contract.
+ */
export interface ReadOptions {
- /** * Set `version` for this operation.
+ /**
+ * Read the given version of the file instead of the current one.
*
- * This option can be used to retrieve the data of a specified version of
the given path.
+ * This selects which stored version the read returns; it is not a
+ * condition on the file. A version that does not exist produces
+ * an error whose message includes `NotFound`.
+ *
+ * Check `Capability.readWithVersion` before using this
+ * option.
*/
version?: string
- /** * Set `concurrent` for the operation.
+ /**
+ * Set `concurrent` for the operation.
*
- * OpenDAL by default to read file without concurrent. This is not efficient
for cases when users
- * read large chunks of data. By setting `concurrent`, opendal will reading
files concurrently
- * on support storage services.
+ * 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 give chunk size.
+ * the given chunk size. Without `chunk`, OpenDAL does not read concurrently.
*
* The value must be an integer between 0 and 4294967295.
*/
concurrent?: number
- /** * Sets the chunk size for this operation.
+ /**
+ * Set `chunk` for the operation.
*
- * OpenDAL will use services' preferred chunk size by default. Users can set
chunk based on their own needs.
+ * By default, OpenDAL reads the range with a single request instead of in
chunks. Users can set chunk
+ * based on their own needs.
+ * `0` has the same behavior as omitting it.
+ *
+ * A read with a positive `chunk` and no `size` first
+ * stats the file to learn its length.
+ * That stat carries the read's version and conditions, so each of them
+ * also needs its stat capability, such as
+ * `Capability.statWithIfModifiedSince` for
+ * `ifModifiedSince`; otherwise the read returns
+ * an error whose message includes `Unsupported`.
*/
chunk?: number
/** Each call to `read()` or `readSync()` reads a single byte range, so
`gap` has no effect. */
gap?: bigint
- /** * Sets the offset (starting position) for range read operations.
- * The read will start from this position in the file.
+ /**
+ * Read from this byte offset instead of from the start of the file.
+ *
+ * An offset at or beyond the end of the file can return an empty buffer or
+ * fail the read, depending on the service and on `chunk`. A negative value,
+ * or one above `2^64 - 1`, fails the operation.
*/
offset?: bigint
- /** * Sets the size (length) for range read operations.
- * The read will continue for this many bytes after the offset.
+ /**
+ * Read this many bytes from `offset`. Without `size`, the read continues to
+ * the end of the file.
+ *
+ * A `size` of `0n` validates the other options, then returns an empty buffer
+ * without accessing storage. A file that ends before `offset` plus `size`
+ * fails the read. A negative value, or one above `2^64 - 1`, fails the
+ * operation.
*/
size?: bigint
- /** * Sets if-match condition for this operation.
- * If file exists and its etag doesn't match, an error will be returned.
+ /**
+ * 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 produces
+ * an error whose message includes `ConditionNotMatch`; a missing file
produces
+ * an error whose message includes `NotFound`. Only concrete ETag values are
+ * portable; a wildcard such as `"*"` has no portable meaning here.
+ *
+ * The operation returns an error whose message includes `Unsupported` when
the
+ * service does not advertise `Capability.readWithIfMatch`.
*/
ifMatch?: string
- /** * Sets if-none-match condition for this operation.
- * If file exists and its etag matches, an error will be returned.
+ /**
+ * 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
+ * produces an error whose message includes `ConditionNotMatch`; a missing
file
+ * produces an error whose message includes `NotFound`. Only concrete ETag
values
+ * are portable; a wildcard such as `"*"` has no portable meaning here.
+ *
+ * The operation returns an error whose message includes `Unsupported` when
the
+ * service does not advertise
+ * `Capability.readWithIfNoneMatch`.
*/
ifNoneMatch?: string
- /** * Sets if-modified-since condition for this operation.
- * If file exists and hasn't been modified since the specified time, an
error will be returned.
- * ISO 8601 formatted date string
- *
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
+ /**
+ * 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 produces
+ * an error whose message includes `ConditionNotMatch`; a missing file
produces
+ * an error whose message includes `NotFound`.
+ *
+ * The operation returns an error whose message includes `Unsupported` when
the
+ * service does not advertise
+ * `Capability.readWithIfModifiedSince`.
+ *
+ * Pass an ISO 8601 string, such as `2024-01-01T00:00:00Z` or the result
+ * of `Date.prototype.toISOString()`. A string that does not parse fails
+ * the operation.
*/
ifModifiedSince?: string
- /** * Sets if-unmodified-since condition for this operation.
- * If file exists and has been modified since the specified time, an error
will be returned.
- * ISO 8601 formatted date string
- *
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
+ /**
+ * 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 produces
+ * an error whose message includes `ConditionNotMatch`; a missing file
produces
+ * an error whose message includes `NotFound`.
+ *
+ * The operation returns an error whose message includes `Unsupported` when
the
+ * service does not advertise
+ * `Capability.readWithIfUnmodifiedSince`.
+ *
+ * Pass an ISO 8601 string, such as `2024-01-01T00:00:00Z` or the result
+ * of `Date.prototype.toISOString()`. A string that does not parse fails
+ * the operation.
*/
ifUnmodifiedSince?: string
- /** * Specify the `content-type` header that should be sent back by the
operation.
- *
- * This option is only meaningful when used along with presign.
+ /**
+ * Request a `content-type` response header override from services that
+ * support it. `presignRead(path, expires)` takes no options, so presigned
reads cannot request one.
*/
contentType?: string
- /** * Specify the `cache-control` header that should be sent back by the
operation.
- *
- * This option is only meaningful when used along with presign.
+ /**
+ * Request a `cache-control` response header override from services that
+ * support it. `presignRead(path, expires)` takes no options, so presigned
reads cannot request one.
*/
cacheControl?: string
- /** * Specify the `content-disposition` header that should be sent back by
the operation.
- *
- * This option is only meaningful when used along with presign.
+ /**
+ * Request a `content-disposition` response header override from services
+ * that support it. `presignRead(path, expires)` takes no options, so
presigned reads cannot request one.
*/
contentDisposition?: string
}
diff --git a/bindings/nodejs/src/options.rs b/bindings/nodejs/src/options.rs
index 35fea5a62c..bd5e3b3321 100644
--- a/bindings/nodejs/src/options.rs
+++ b/bindings/nodejs/src/options.rs
@@ -25,9 +25,11 @@ use crate::validate::parse_count;
mod delete;
mod list;
+mod read;
mod stat;
pub use delete::DeleteOptions;
pub use list::ListOptions;
+pub use read::ReadOptions;
pub use stat::StatOptions;
/// Convert a JavaScript `BigInt` into a `u64` offset or size.
@@ -55,6 +57,20 @@ fn bigint_to_u64(value: &BigInt, field: &str) ->
napi::Result<u64> {
Ok(word)
}
+/// Convert the JavaScript `offset` and `size` of a read into a byte range.
+///
+/// An omitted `offset` reads from the start, and an omitted `size` reads to
+/// the end.
+fn bytes_range(offset: Option<BigInt>, size: Option<BigInt>) ->
napi::Result<BytesRange> {
+ let offset = offset
+ .map(|offset| bigint_to_u64(&offset, "offset"))
+ .transpose()?
+ .unwrap_or_default();
+ let size = size.map(|size| bigint_to_u64(&size, "size")).transpose()?;
+
+ Ok(BytesRange::new(offset, size))
+}
+
/// Parse a conditional request timestamp received from JavaScript.
///
/// Dropping an unparsable value would silently turn a conditional read or stat
@@ -68,158 +84,6 @@ fn parse_timestamp(value: &str, field: &str) ->
napi::Result<Timestamp> {
})
}
-#[napi(object)]
-#[derive(Default, Debug)]
-pub struct ReadOptions {
- /**
- * Set `version` for this operation.
- *
- * This option can be used to retrieve the data of a specified version of
the given path.
- */
- pub version: Option<String>,
-
- /**
- * Set `concurrent` for the operation.
- *
- * OpenDAL by default to read file without concurrent. This is not
efficient for cases when users
- * read large chunks of data. By setting `concurrent`, opendal will
reading files concurrently
- * on support storage services.
- *
- * By setting `concurrent`, opendal will fetch chunks concurrently with
- * the give chunk size.
- *
- * The value must be an integer between 0 and 4294967295.
- */
- pub concurrent: Option<f64>,
-
- /**
- * Sets the chunk size for this operation.
- *
- * OpenDAL will use services' preferred chunk size by default. Users can
set chunk based on their own needs.
- */
- pub chunk: Option<u32>,
-
- /// Each call to `read()` or `readSync()` reads a single byte range, so
`gap` has no effect.
- pub gap: Option<BigInt>,
-
- /**
- * Sets the offset (starting position) for range read operations.
- * The read will start from this position in the file.
- */
- pub offset: Option<BigInt>,
-
- /**
- * Sets the size (length) for range read operations.
- * The read will continue for this many bytes after the offset.
- */
- pub size: Option<BigInt>,
-
- /**
- * Sets if-match condition for this operation.
- * If file exists and its etag doesn't match, an error will be returned.
- */
- pub if_match: Option<String>,
-
- /**
- * Sets if-none-match condition for this operation.
- * If file exists and its etag matches, an error will be returned.
- */
- pub if_none_match: Option<String>,
-
- /**
- * Sets if-modified-since condition for this operation.
- * If file exists and hasn't been modified since the specified time, an
error will be returned.
- * ISO 8601 formatted date string
- *
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
- */
- pub if_modified_since: Option<String>,
-
- /**
- * Sets if-unmodified-since condition for this operation.
- * If file exists and has been modified since the specified time, an error
will be returned.
- * ISO 8601 formatted date string
- *
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
- */
- pub if_unmodified_since: Option<String>,
-
- /**
- * Specify the `content-type` header that should be sent back by the
operation.
- *
- * This option is only meaningful when used along with presign.
- */
- pub content_type: Option<String>,
-
- /**
- * Specify the `cache-control` header that should be sent back by the
operation.
- *
- * This option is only meaningful when used along with presign.
- */
- pub cache_control: Option<String>,
-
- /**
- * Specify the `content-disposition` header that should be sent back by
the operation.
- *
- * This option is only meaningful when used along with presign.
- */
- pub content_disposition: Option<String>,
-}
-
-impl ReadOptions {
- fn make_range(&self) -> napi::Result<BytesRange> {
- let offset = self
- .offset
- .as_ref()
- .map(|offset| bigint_to_u64(offset, "offset"))
- .transpose()?
- .unwrap_or_default();
- let size = self
- .size
- .as_ref()
- .map(|size| bigint_to_u64(size, "size"))
- .transpose()?;
-
- Ok(BytesRange::new(offset, size))
- }
-}
-
-impl TryFrom<ReadOptions> for opendal::options::ReadOptions {
- type Error = napi::Error;
-
- fn try_from(value: ReadOptions) -> napi::Result<Self> {
- let range = value.make_range()?;
- let if_modified_since = value
- .if_modified_since
- .map(|v| parse_timestamp(&v, "ifModifiedSince"))
- .transpose()?;
- let if_unmodified_since = value
- .if_unmodified_since
- .map(|v| parse_timestamp(&v, "ifUnmodifiedSince"))
- .transpose()?;
-
- let concurrent = value
- .concurrent
- .map(|v| parse_count(v, "concurrent", 0))
- .transpose()?
- .unwrap_or_default();
- Ok(Self {
- version: value.version,
- concurrent,
- chunk: value.chunk.map(|chunk| chunk as usize),
- gap: value.gap.map(|gap| gap.get_u64().1 as usize),
- range,
- if_match: value.if_match,
- if_none_match: value.if_none_match,
- if_modified_since,
- if_unmodified_since,
- content_length_hint: None,
- override_content_type: value.content_type,
- override_cache_control: value.cache_control,
- override_content_disposition: value.content_disposition,
- ..Default::default()
- })
- }
-}
-
#[napi(object)]
#[derive(Default)]
pub struct ReaderOptions {
diff --git a/bindings/nodejs/src/options/read.rs
b/bindings/nodejs/src/options/read.rs
new file mode 100644
index 0000000000..32d55acd1c
--- /dev/null
+++ b/bindings/nodejs/src/options/read.rs
@@ -0,0 +1,198 @@
+// 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.
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
opendal/dev/src/generate/nodejs.rs.
+
+/// Options for read operations.
+///
+/// Each condition checks the file being read, and every condition must hold
+/// for the read to proceed. Once the option and capability checks pass, a
+/// read that reaches storage fails with an error whose message includes
`NotFound` for a
+/// missing file, no matter which conditions are set. An existing file that
+/// fails a condition produces an error whose message includes
`ConditionNotMatch`, and a
+/// condition the service does not advertise through its capability returns
+/// an error whose message includes `Unsupported`; OpenDAL never silently
drops a
+/// condition. A read with `{ size: 0n }` validates the read
+/// options and capabilities, then returns an empty buffer without accessing
+/// storage or evaluating conditions against the file.
+///
+/// See the [conditional operation
specification](https://opendal.apache.org/docs/specifications/conditional-operations/)
+/// for the complete cross-operation contract.
+#[napi(object)]
+#[derive(Debug, Default)]
+pub struct ReadOptions {
+ /// Read the given version of the file instead of the current one.
+ ///
+ /// This selects which stored version the read returns; it is not a
+ /// condition on the file. A version that does not exist produces
+ /// an error whose message includes `NotFound`.
+ ///
+ /// Check `Capability.readWithVersion` before using this
+ /// option.
+ pub version: Option<String>,
+
+ /// 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.
+ ///
+ /// The value must be an integer between 0 and 4294967295.
+ pub concurrent: Option<f64>,
+
+ /// Set `chunk` for the operation.
+ ///
+ /// By default, OpenDAL reads the range with a single request instead of
in chunks. Users can set chunk
+ /// based on their own needs.
+ /// `0` has the same behavior as omitting it.
+ ///
+ /// A read with a positive `chunk` and no `size` first
+ /// stats the file to learn its length.
+ /// That stat carries the read's version and conditions, so each of them
+ /// also needs its stat capability, such as
+ /// `Capability.statWithIfModifiedSince` for
+ /// `ifModifiedSince`; otherwise the read returns
+ /// an error whose message includes `Unsupported`.
+ pub chunk: Option<u32>,
+
+ /// Each call to `read()` or `readSync()` reads a single byte range, so
`gap` has no effect.
+ pub gap: Option<napi::bindgen_prelude::BigInt>,
+
+ /// Read from this byte offset instead of from the start of the file.
+ ///
+ /// An offset at or beyond the end of the file can return an empty buffer
or
+ /// fail the read, depending on the service and on `chunk`. A negative
value,
+ /// or one above `2^64 - 1`, fails the operation.
+ pub offset: Option<napi::bindgen_prelude::BigInt>,
+
+ /// Read this many bytes from `offset`. Without `size`, the read continues
to
+ /// the end of the file.
+ ///
+ /// A `size` of `0n` validates the other options, then returns an empty
buffer
+ /// without accessing storage. A file that ends before `offset` plus `size`
+ /// fails the read. A negative value, or one above `2^64 - 1`, fails the
+ /// operation.
+ pub size: Option<napi::bindgen_prelude::BigInt>,
+
+ /// 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 produces
+ /// an error whose message includes `ConditionNotMatch`; a missing file
produces
+ /// an error whose message includes `NotFound`. Only concrete ETag values
are
+ /// portable; a wildcard such as `"*"` has no portable meaning here.
+ ///
+ /// The operation returns an error whose message includes `Unsupported`
when the
+ /// service does not advertise `Capability.readWithIfMatch`.
+ pub if_match: Option<String>,
+
+ /// 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
+ /// produces an error whose message includes `ConditionNotMatch`; a
missing file
+ /// produces an error whose message includes `NotFound`. Only concrete
ETag values
+ /// are portable; a wildcard such as `"*"` has no portable meaning here.
+ ///
+ /// The operation returns an error whose message includes `Unsupported`
when the
+ /// service does not advertise
+ /// `Capability.readWithIfNoneMatch`.
+ pub if_none_match: Option<String>,
+
+ /// 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 produces
+ /// an error whose message includes `ConditionNotMatch`; a missing file
produces
+ /// an error whose message includes `NotFound`.
+ ///
+ /// The operation returns an error whose message includes `Unsupported`
when the
+ /// service does not advertise
+ /// `Capability.readWithIfModifiedSince`.
+ ///
+ /// Pass an ISO 8601 string, such as `2024-01-01T00:00:00Z` or the result
+ /// of `Date.prototype.toISOString()`. A string that does not parse fails
+ /// the operation.
+ pub if_modified_since: Option<String>,
+
+ /// 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 produces
+ /// an error whose message includes `ConditionNotMatch`; a missing file
produces
+ /// an error whose message includes `NotFound`.
+ ///
+ /// The operation returns an error whose message includes `Unsupported`
when the
+ /// service does not advertise
+ /// `Capability.readWithIfUnmodifiedSince`.
+ ///
+ /// Pass an ISO 8601 string, such as `2024-01-01T00:00:00Z` or the result
+ /// of `Date.prototype.toISOString()`. A string that does not parse fails
+ /// the operation.
+ pub if_unmodified_since: Option<String>,
+
+ /// Request a `content-type` response header override from services that
+ /// support it. `presignRead(path, expires)` takes no options, so
presigned reads cannot request one.
+ pub content_type: Option<String>,
+
+ /// Request a `cache-control` response header override from services that
+ /// support it. `presignRead(path, expires)` takes no options, so
presigned reads cannot request one.
+ pub cache_control: Option<String>,
+
+ /// Request a `content-disposition` response header override from services
+ /// that support it. `presignRead(path, expires)` takes no options, so
presigned reads cannot request one.
+ pub content_disposition: Option<String>,
+}
+
+impl TryFrom<ReadOptions> for opendal::options::ReadOptions {
+ type Error = napi::Error;
+
+ fn try_from(value: ReadOptions) -> napi::Result<Self> {
+ Ok(Self {
+ range: super::bytes_range(value.offset, value.size)?,
+ limit: Default::default(),
+ version: value.version,
+ if_match: value.if_match,
+ if_none_match: value.if_none_match,
+ if_version_match: Default::default(),
+ if_version_not_match: Default::default(),
+ if_modified_since: value
+ .if_modified_since
+ .map(|v| super::parse_timestamp(&v, "ifModifiedSince"))
+ .transpose()?,
+ if_unmodified_since: value
+ .if_unmodified_since
+ .map(|v| super::parse_timestamp(&v, "ifUnmodifiedSince"))
+ .transpose()?,
+ content_length_hint: Default::default(),
+ concurrent: value
+ .concurrent
+ .map(|v| crate::validate::parse_count(v, "concurrent", 0))
+ .transpose()?
+ .unwrap_or_default(),
+ chunk: value.chunk.map(|v| v as usize),
+ gap: value.gap.map(|v| v.get_u64().1 as usize),
+ override_content_type: value.content_type,
+ override_cache_control: value.cache_control,
+ override_content_disposition: value.content_disposition,
+ checksum: Default::default(),
+ })
+ }
+}
diff --git a/bindings/nodejs/tests/read-options-surface.test.mjs
b/bindings/nodejs/tests/read-options-surface.test.mjs
new file mode 100644
index 0000000000..b19dbdfba2
--- /dev/null
+++ b/bindings/nodejs/tests/read-options-surface.test.mjs
@@ -0,0 +1,157 @@
+/*
+ * 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.
+ */
+
+import { readFileSync } from 'node:fs'
+import path from 'node:path'
+
+import { assert, describe, expect, test } from 'vitest'
+
+import { Operator } from '../index.mjs'
+
+const content = '0123456789abcdef'
+
+// `ReadOptions` and the read methods as `generated.d.ts` declared them before
+// `ReadOptions` was generated from core. Callers pass these options as object
+// literals or implement the interface structurally, so each member must stay
+// with its type and stay optional, and a new member must be added here on
+// purpose.
+//
+// Each member comes with a value of its type and the core option it sets.
+// When core checks a capability for that option, the capability is listed
+// too, and a service without it must reject the read naming the core option.
+// Otherwise the read must return the listed content.
+const FROZEN_MEMBERS = [
+ ['version?: string', 'v1', 'version', 'readWithVersion', content],
+ ['concurrent?: number', 4, 'concurrent', null, content],
+ ['chunk?: number', 3, 'chunk', null, content],
+ ['gap?: bigint', 1n, 'gap', null, content],
+ ['offset?: bigint', 10n, 'range', null, 'abcdef'],
+ ['size?: bigint', 4n, 'range', null, '0123'],
+ ['ifMatch?: string', '"etag"', 'if_match', 'readWithIfMatch', content],
+ ['ifNoneMatch?: string', '"etag"', 'if_none_match', 'readWithIfNoneMatch',
content],
+ ['ifModifiedSince?: string', new Date(0).toISOString(), 'if_modified_since',
'readWithIfModifiedSince', content],
+ ['ifUnmodifiedSince?: string', '2100-01-01T00:00:00Z',
'if_unmodified_since', 'readWithIfUnmodifiedSince', content],
+ ['contentType?: string', 'text/plain', 'override_content_type', null,
content],
+ ['cacheControl?: string', 'no-cache', 'override_cache_control', null,
content],
+ ['contentDisposition?: string', 'attachment',
'override_content_disposition', null, content],
+]
+
+const FROZEN_SIGNATURES = [
+ 'read(path: string, options?: ReadOptions | undefined | null):
Promise<Buffer>',
+ 'readSync(path: string, options?: ReadOptions | undefined | null): Buffer',
+ // The `ReadOptions` docs say that `presignRead` takes no options, so the
+ // response header overrides cannot reach a presigned read.
+ 'presignRead(path: string, expires: number): Promise<PresignedRequest>',
+]
+
+const READS = [
+ ['read', (op, path, options) => op.read(path, options)],
+ ['readSync', async (op, path, options) => op.readSync(path, options)],
+]
+
+function declared(kind, name) {
+ const dts = readFileSync(path.resolve(__dirname, '../generated.d.ts'),
'utf8')
+ const body = dts.match(new RegExp(`^export ${kind} ${name}
\\{\\n([\\s\\S]*?)^\\}`, 'm'))
+ assert.ok(body, `generated.d.ts declares ${kind} ${name}`)
+ return body[1]
+ .split('\n')
+ .filter((line) => /^ {2}\w/.test(line))
+ .map((line) => line.trim())
+}
+
+describe('ReadOptions keeps its historical surface', () => {
+ const op = new Operator('memory')
+ const file = 'read-options-surface'
+ op.writeSync(file, content)
+
+ test('declares exactly the frozen members', () => {
+ assert.sameMembers(
+ declared('interface', 'ReadOptions'),
+ FROZEN_MEMBERS.map(([member]) => member),
+ )
+ })
+
+ for (const signature of FROZEN_SIGNATURES) {
+ test(signature, () => {
+ assert.include(declared('declare class', 'Operator'), signature)
+ })
+ }
+
+ for (const [member, value, coreOption, capability, expected] of
FROZEN_MEMBERS) {
+ const [, field] = member.match(/^(\w+)\?: /)
+ const options = { [field]: value }
+
+ for (const [method, read] of READS) {
+ test(`${method} with ${member}`, async () => {
+ if (capability === null || op.capability()[capability]) {
+ // The read accepts a value of the declared type.
+ assert.equal((await read(op, file, options)).toString(), expected)
+ } else {
+ // The option reaches core as `coreOption`, which this service does
+ // not support.
+ const unsupported = new RegExp(
+ `^Unsupported \\(permanent\\) at read\\b.* with the arguments
${coreOption}\\.`,
+ )
+ await expect(read(op, file,
options)).rejects.toThrowError(unsupported)
+ }
+ })
+ }
+ }
+
+ for (const [method, read] of READS) {
+ test(`${method} converts each member as main did`, async () => {
+ // `offset` and `size` select one byte range together.
+ assert.equal((await read(op, file, { offset: 3n, size: 4n
})).toString(), '3456')
+ assert.equal((await read(op, file, { chunk: 0, concurrent: 0
})).toString(), content)
+ assert.equal((await read(op, file, { chunk: 4, concurrent: 2
})).toString(), content)
+ // `chunk` reaches core: only a chunked read checks an offset past the
+ // end against the file size on memory, and a zero `chunk` reads as if
+ // it were omitted.
+ assert.equal((await read(op, file, { offset: 100n })).length, 0)
+ assert.equal((await read(op, file, { offset: 100n, chunk: 0 })).length,
0)
+ await expect(read(op, file, { offset: 100n, chunk: 4
})).rejects.toThrowError(/^RangeNotSatisfied \(permanent\)/)
+ // `gap` ignores its sign and the bits above 64, as main did.
+ assert.equal((await read(op, file, { gap: -1n })).toString(), content)
+ assert.equal((await read(op, file, { gap: 1n << 64n })).toString(),
content)
+ // An empty range returns no bytes without accessing storage.
+ assert.equal((await read(op, `${file}-missing`, { size: 0n })).length, 0)
+ })
+
+ test(`${method} rejects invalid values in main's order`, async () => {
+ const invalid = {
+ offset: -1n,
+ size: 1n << 64n,
+ ifModifiedSince: 'not-a-date',
+ ifUnmodifiedSince: 'not-a-date',
+ concurrent: 1.5,
+ }
+ for (const [field, message] of [
+ ['offset', 'offset must not be negative'],
+ ['size', 'size must not be greater than 18446744073709551615'],
+ ['ifModifiedSince', 'ifModifiedSince must be an ISO 8601 timestamp'],
+ ['ifUnmodifiedSince', 'ifUnmodifiedSince must be an ISO 8601
timestamp'],
+ ['concurrent', 'concurrent must be an integer between 0 and
4294967295'],
+ ]) {
+ await expect(read(op, file, invalid)).rejects.toThrowError(message)
+ delete invalid[field]
+ }
+ assert.deepEqual(invalid, {})
+ })
+ }
+})
diff --git a/core/core/src/types/options.rs b/core/core/src/types/options.rs
index 19b06cba85..2e789079b2 100644
--- a/core/core/src/types/options.rs
+++ b/core/core/src/types/options.rs
@@ -200,11 +200,11 @@ pub struct ListOptions {
/// Options for read operations.
///
/// Each condition checks the file being read, and every condition must hold
-/// for the read to proceed. A missing file fails the read with
-/// [`crate::ErrorKind::NotFound`] no matter which conditions are set. An
-/// existing file that fails a condition returns
-/// [`crate::ErrorKind::ConditionNotMatch`], and a condition the service does
-/// not advertise through its capability returns
+/// for the read to proceed. Once the option and capability checks pass, a
+/// read that reaches storage fails with [`crate::ErrorKind::NotFound`] for a
+/// missing file, no matter which conditions are set. An existing file that
+/// fails a condition returns [`crate::ErrorKind::ConditionNotMatch`], and a
+/// condition the service does not advertise through its capability returns
/// [`crate::ErrorKind::Unsupported`]; OpenDAL never silently drops a
/// condition. A read with a zero limit or an empty range validates the read
/// options and capabilities, then returns an empty buffer without accessing
@@ -327,21 +327,30 @@ pub struct ReadOptions {
/// Set `concurrent` for the operation.
///
- /// OpenDAL by default to read file without concurrent. This is not
efficient for cases when users
- /// read large chunks of data. By setting `concurrent`, opendal will
reading files concurrently
- /// on support storage services.
+ /// 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 give chunk size.
+ /// the given chunk size. Without `chunk`, OpenDAL does not read
concurrently.
///
/// Refer to the [performance
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)
/// for more details.
pub concurrent: usize,
/// Set `chunk` for the operation.
///
- /// OpenDAL will use services' preferred chunk size by default. Users can
set chunk based on their own needs.
+ /// By default, OpenDAL reads the range with a single request instead of
in chunks. Users can set chunk
+ /// based on their own needs.
/// `Some(0)` has the same behavior as `None`.
///
+ /// A read with a positive `chunk` and an open-ended or nonempty suffix
range first
+ /// stats the file to learn its length, unless `content_length_hint` is
set.
+ /// That stat carries the read'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`].
+ ///
/// Refer to the [performance
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)
/// for more details.
pub chunk: Option<usize>,
@@ -363,17 +372,14 @@ pub struct ReadOptions {
/// for more details.
pub gap: Option<usize>,
- /// Specify the content-type header that should be sent back by the
operation.
- ///
- /// This option is only meaningful when used along with presign.
+ /// Request a `content-type` response header override from services that
+ /// support it, including for presigned read requests.
pub override_content_type: Option<String>,
- /// Specify the `cache-control` header that should be sent back by the
operation.
- ///
- /// This option is only meaningful when used along with presign.
+ /// Request a `cache-control` response header override from services that
+ /// support it, including for presigned read requests.
pub override_cache_control: Option<String>,
- /// Specify the `content-disposition` header that should be sent back by
the operation.
- ///
- /// This option is only meaningful when used along with presign.
+ /// Request a `content-disposition` response header override from services
+ /// that support it, including for presigned read requests.
pub override_content_disposition: Option<String>,
/// Request full-file checksum metadata when the service can provide it.
diff --git a/dev/src/generate/java.rs b/dev/src/generate/java.rs
index 4ebca3bd95..f6f7a33fe5 100644
--- a/dev/src/generate/java.rs
+++ b/dev/src/generate/java.rs
@@ -1663,7 +1663,10 @@ mod tests {
match class.name {
"ReadOptions" => assert_field(
field,
- &["<p>This option is only meaningful when used along
with presign."],
+ &[
+ "response header override from services that
support it",
+ "including for presigned read requests.",
+ ],
),
"StatOptions" => assert_field(
field,
diff --git a/dev/src/generate/nodejs.rs b/dev/src/generate/nodejs.rs
index 4bbaf284f1..b85f5ec17a 100644
--- a/dev/src/generate/nodejs.rs
+++ b/dev/src/generate/nodejs.rs
@@ -18,7 +18,7 @@
//! Generator for the Node.js binding.
use super::capability::{self, CapabilityField};
-use super::core_options::{self, OptionField, OptionKind, OptionsStruct};
+use super::core_options::{self, OptionKind, OptionsStruct};
use super::metadata::{self, MetadataKind};
use super::rustdoc::rewrite_code_spans;
use anyhow::{Result, bail};
@@ -178,49 +178,181 @@ struct JsOptions {
name: &'static str,
/// The module under `bindings/nodejs/src/options/`.
module: &'static str,
- /// The core fields that JS exposes, in JS order, with the core kind that
- /// their JS type was chosen for.
+ /// The core fields that JS exposes, in JS order, with their JS form.
///
/// A core field missing here is not exposed in JS, and the conversion
- /// sets it to its default. Generation fails when core changes the kind of
- /// an exposed field, so the JS type never changes silently.
- fields: &'static [(&'static str, OptionKind)],
+ /// sets it to its default. Each form carries one core kind (see
+ /// [`Js::kind`]), and generation fails when core changes the kind of an
+ /// exposed field, so the JS type never changes silently.
+ fields: &'static [(&'static str, Js)],
+ /// Exposed core fields that JS names differently, as `(core, napi)`.
+ /// Every other field keeps its core name.
+ renamed: &'static [(&'static str, &'static str)],
+ /// JS docs that replace the core doc of a member, as `(napi member, doc
+ /// lines)`, where the core doc does not hold for the JS methods. The
+ /// `offset` and `size` members of a `range` need one.
+ docs: &'static [(&'static str, &'static [&'static str])],
+ /// Node.js wording for rendered core doc text that does not hold for the
+ /// JS methods, as `(rendered text, JS text)`. Generation fails when one
+ /// matches nothing, so a reworded core doc gets reviewed again.
+ rewrites: &'static [(&'static str, &'static str)],
+}
+
+/// The JS form of an exposed core option field. Each form keeps the type and
+/// conversion that the binding used before codegen.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Js {
+ /// An `Option<String>` as a `string`.
+ String,
+ /// A `bool` as a `boolean`. An omitted value is `false`.
+ Bool,
+ /// An `Option<usize>` as a `number` read as `u32`, so an explicit `0`
+ /// reaches core as `Some(0)`.
+ U32,
+ /// A `usize` count as a `number` that `parse_count` checks. An omitted
+ /// value is `0`.
+ Count,
+ /// An `Option<usize>` as a `bigint` read with `BigInt::get_u64`, which
+ /// ignores the sign and the bits above 64.
+ LossyBigInt,
+ /// An `Option<Timestamp>` as an ISO 8601 `string` that must parse.
+ Timestamp,
+ /// A `BytesRange` as the `offset` and `size` `bigint`s, which
+ /// `bigint_to_u64` checks.
+ OffsetSize,
+}
+
+impl Js {
+ /// The core kind that this form carries.
+ const fn kind(self) -> OptionKind {
+ match self {
+ Js::String => OptionKind::OptionString,
+ Js::Bool => OptionKind::Bool,
+ Js::U32 | Js::LossyBigInt => OptionKind::OptionUsize,
+ Js::Count => OptionKind::Usize,
+ Js::Timestamp => OptionKind::OptionTimestamp,
+ Js::OffsetSize => OptionKind::BytesRange,
+ }
+ }
}
const LIST_OPTIONS: JsOptions = JsOptions {
name: "ListOptions",
module: "list",
fields: &[
- ("limit", OptionKind::OptionUsize),
- ("start_after", OptionKind::OptionString),
- ("recursive", OptionKind::Bool),
- ("versions", OptionKind::Bool),
- ("deleted", OptionKind::Bool),
+ ("limit", Js::U32),
+ ("start_after", Js::String),
+ ("recursive", Js::Bool),
+ ("versions", Js::Bool),
+ ("deleted", Js::Bool),
],
+ renamed: &[],
+ docs: &[],
+ rewrites: &[],
};
const STAT_OPTIONS: JsOptions = JsOptions {
name: "StatOptions",
module: "stat",
fields: &[
- ("version", OptionKind::OptionString),
- ("if_match", OptionKind::OptionString),
- ("if_none_match", OptionKind::OptionString),
- ("if_modified_since", OptionKind::OptionTimestamp),
- ("if_unmodified_since", OptionKind::OptionTimestamp),
- ("override_content_type", OptionKind::OptionString),
- ("override_cache_control", OptionKind::OptionString),
- ("override_content_disposition", OptionKind::OptionString),
+ ("version", Js::String),
+ ("if_match", Js::String),
+ ("if_none_match", Js::String),
+ ("if_modified_since", Js::Timestamp),
+ ("if_unmodified_since", Js::Timestamp),
+ ("override_content_type", Js::String),
+ ("override_cache_control", Js::String),
+ ("override_content_disposition", Js::String),
],
+ renamed: &[],
+ docs: &[],
+ rewrites: &[],
};
const DELETE_OPTIONS: JsOptions = JsOptions {
name: "DeleteOptions",
module: "delete",
fields: &[
- ("version", OptionKind::OptionString),
- ("recursive", OptionKind::Bool),
- ("if_match", OptionKind::OptionString),
+ ("version", Js::String),
+ ("recursive", Js::Bool),
+ ("if_match", Js::String),
+ ],
+ renamed: &[],
+ docs: &[],
+ rewrites: &[],
+};
+
+const READ_OPTIONS: JsOptions = JsOptions {
+ name: "ReadOptions",
+ module: "read",
+ fields: &[
+ ("version", Js::String),
+ ("concurrent", Js::Count),
+ ("chunk", Js::U32),
+ ("gap", Js::LossyBigInt),
+ ("range", Js::OffsetSize),
+ ("if_match", Js::String),
+ ("if_none_match", Js::String),
+ ("if_modified_since", Js::Timestamp),
+ ("if_unmodified_since", Js::Timestamp),
+ ("override_content_type", Js::String),
+ ("override_cache_control", Js::String),
+ ("override_content_disposition", Js::String),
+ ],
+ renamed: &[
+ ("override_content_type", "content_type"),
+ ("override_cache_control", "cache_control"),
+ ("override_content_disposition", "content_disposition"),
+ ],
+ // Core documents how `Reader::fetch` merges ranges, which JS does not
+ // expose, and documents `range` in Rust range syntax.
+ docs: &[
+ (
+ "gap",
+ &[
+ "Each call to `read()` or `readSync()` reads a single byte
range, so `gap` has no effect.",
+ ],
+ ),
+ (
+ "offset",
+ &[
+ "Read from this byte offset instead of from the start of the
file.",
+ "",
+ "An offset at or beyond the end of the file can return an
empty buffer or",
+ "fail the read, depending on the service and on `chunk`. A
negative value,",
+ "or one above `2^64 - 1`, fails the operation.",
+ ],
+ ),
+ (
+ "size",
+ &[
+ "Read this many bytes from `offset`. Without `size`, the read
continues to",
+ "the end of the file.",
+ "",
+ "A `size` of `0n` validates the other options, then returns an
empty buffer",
+ "without accessing storage. A file that ends before `offset`
plus `size`",
+ "fails the read. A negative value, or one above `2^64 - 1`,
fails the",
+ "operation.",
+ ],
+ ),
+ ],
+ // JS reads take an `offset` and a `size`, but no `limit`, suffix range,
+ // or `content_length_hint`, and `presignRead(path, expires)` takes no
+ // options.
+ rewrites: &[
+ (
+ "A read with a zero limit or an empty range validates",
+ "A read with `{ size: 0n }` validates",
+ ),
+ (
+ "and an open-ended or nonempty suffix range first",
+ "and no `size` first",
+ ),
+ (", unless `content_length_hint` is set.", "."),
+ (
+ ", including for presigned read requests.",
+ ". `presignRead(path, expires)` takes no options, so presigned
reads cannot request one.",
+ ),
],
};
@@ -254,7 +386,7 @@ fn generate_options(workspace_dir: &Path) -> Result<()> {
let dir = workspace_dir.join("bindings/nodejs/src/options");
fs::create_dir_all(&dir)?;
- for options in [&LIST_OPTIONS, &STAT_OPTIONS, &DELETE_OPTIONS] {
+ for options in [&LIST_OPTIONS, &STAT_OPTIONS, &DELETE_OPTIONS,
&READ_OPTIONS] {
let rendered = render_options(&parsed, options, &capabilities)?;
fs::write(
dir.join(format!("{}.rs", options.module)),
@@ -274,30 +406,62 @@ fn render_options(
bail!("core has no options struct `{struct_name}`");
};
+ let mut rewritten = vec![false; options.rewrites.len()];
+ let doc = rewrite_doc(
+ js_doc(&core.doc, options, capabilities),
+ options.rewrites,
+ &mut rewritten,
+ );
+
let mut fields = Vec::with_capacity(options.fields.len());
let mut fallible = false;
- for &(name, kind) in options.fields {
+ for &(name, form) in options.fields {
let Some(field) = core.fields.iter().find(|field| field.name == name)
else {
bail!("core {struct_name} has no field `{name}`");
};
- if field.kind != kind {
+ if field.kind != form.kind() {
bail!(
- "core {struct_name}::{name} is {:?}, but its JS type was
chosen for {kind:?}",
- field.kind
+ "core {struct_name}::{name} is {:?}, but its JS type was
chosen for {:?}",
+ field.kind,
+ form.kind()
);
}
- let js = js_type(struct_name, field)?;
+ let js = js_type(js_name(options, name), form);
fallible |= js.fallible;
- let mut doc = js_doc(&field.doc, options, capabilities);
- if !js.note.is_empty() {
- doc.push(String::new());
- doc.extend(js.note.iter().map(|line| line.to_string()));
+ let members = match form {
+ Js::OffsetSize => vec!["offset", "size"],
+ _ => vec![js_name(options, name)],
+ };
+ for member in members {
+ let mut doc = match options.docs.iter().find(|&&(js, _)| js ==
member) {
+ Some((_, doc)) => doc.iter().map(|line|
line.to_string()).collect(),
+ None if form == Js::OffsetSize => bail!(
+ "{struct_name}::{member} needs a JS doc, because core
documents \
+ `{name}` in Rust range syntax"
+ ),
+ None => rewrite_doc(
+ js_doc(&field.doc, options, capabilities),
+ options.rewrites,
+ &mut rewritten,
+ ),
+ };
+ if !js.note.is_empty() {
+ doc.push(String::new());
+ doc.extend(js.note.iter().map(|line| line.to_string()));
+ }
+ fields.push(OptionsField {
+ name: member.to_string(),
+ rs_type: js.rs_type,
+ doc,
+ });
}
- fields.push(OptionsField {
- name: field.name.clone(),
- rs_type: js.rs_type,
- doc,
- });
+ }
+
+ if let Some(i) = rewritten.iter().position(|&matched| !matched) {
+ bail!(
+ "core {struct_name} docs no longer contain `{}`; review its
Node.js rewrite",
+ options.rewrites[i].0
+ );
}
// List every core field instead of ending with `..Default::default()`, so
@@ -305,9 +469,12 @@ fn render_options(
// regenerated, and the regenerated conversion shows it as unexposed.
let mut conversions = Vec::with_capacity(core.fields.len());
for field in &core.fields {
- let exposed = options.fields.iter().any(|&(name, _)| name ==
field.name);
- let expr = if exposed {
- js_type(struct_name, field)?.expr
+ let exposed = options
+ .fields
+ .iter()
+ .find(|&&(name, ..)| name == field.name);
+ let expr = if let Some(&(name, form)) = exposed {
+ js_type(js_name(options, name), form).expr
} else {
"Default::default()".to_string()
};
@@ -321,7 +488,7 @@ fn render_options(
env.add_template("options_rs", include_str!("nodejs/options_rs.j2"))?;
Ok(env.get_template("options_rs")?.render(context! {
name => struct_name,
- doc => js_doc(&core.doc, options, capabilities),
+ doc => doc,
fields => Serde(&fields),
conversions => Serde(&conversions),
fallible => fallible,
@@ -329,6 +496,31 @@ fn render_options(
})?)
}
+/// Apply Node.js `rewrites` to rendered doc lines, and mark each rewrite that
+/// matched in `matched`.
+fn rewrite_doc(doc: Vec<String>, rewrites: &[(&str, &str)], matched: &mut
[bool]) -> Vec<String> {
+ if rewrites.is_empty() || doc.is_empty() {
+ return doc;
+ }
+ let mut text = doc.join("\n");
+ for (&(from, to), matched) in rewrites.iter().zip(matched) {
+ if text.contains(from) {
+ *matched = true;
+ text = text.replace(from, to);
+ }
+ }
+ text.split('\n').map(str::to_owned).collect()
+}
+
+/// The napi field name of an exposed core field.
+fn js_name(options: &JsOptions, core: &'static str) -> &'static str {
+ options
+ .renamed
+ .iter()
+ .find(|&&(name, _)| name == core)
+ .map_or(core, |&(_, napi)| napi)
+}
+
/// How an exposed core option field surfaces in JS.
struct JsType {
/// Rust type of the napi field.
@@ -337,33 +529,44 @@ struct JsType {
expr: String,
/// Whether `expr` can fail, which makes the conversion a `TryFrom`.
fallible: bool,
- /// Extra doc paragraph, one entry per line, for kinds whose JS form
- /// needs explaining.
+ /// Extra doc paragraph, one entry per line, for JS forms that need
+ /// explaining.
note: &'static [&'static str],
}
-/// The napi type of an exposed core option field and the expression that
-/// converts it back.
+/// The napi type of an exposed core option field in its JS form, and the
+/// expression that converts the napi field `name` back.
///
-/// These keep the types the binding used before codegen: `limit` is a
-/// `number` read as `u32`, so an explicit `0` reaches core as `Some(0)`, an
-/// omitted boolean is `false`, and a timestamp is a string that must parse.
-fn js_type(struct_name: &str, field: &OptionField) -> Result<JsType> {
- let name = &field.name;
+/// The expressions are laid out as rustfmt formats them inside the struct
+/// literal.
+fn js_type(name: &str, form: Js) -> JsType {
let infallible = |rs_type, expr| JsType {
rs_type,
expr,
fallible: false,
note: &[],
};
- Ok(match field.kind {
- OptionKind::OptionUsize => {
- infallible("Option<u32>", format!("value.{name}.map(|v| v as
usize)"))
- }
- OptionKind::OptionString => infallible("Option<String>",
format!("value.{name}")),
- OptionKind::Bool => infallible("Option<bool>",
format!("value.{name}.unwrap_or_default()")),
- // Laid out as rustfmt formats the chain inside the struct literal.
- OptionKind::OptionTimestamp => JsType {
+ match form {
+ Js::String => infallible("Option<String>", format!("value.{name}")),
+ Js::Bool => infallible("Option<bool>",
format!("value.{name}.unwrap_or_default()")),
+ Js::U32 => infallible("Option<u32>", format!("value.{name}.map(|v| v
as usize)")),
+ Js::Count => JsType {
+ rs_type: "Option<f64>",
+ expr: format!(
+ "value\n .{name}\n \
+ .map(|v| crate::validate::parse_count(v, \"{}\", 0))\n
\
+ .transpose()?\n \
+ .unwrap_or_default()",
+ heck::AsLowerCamelCase(name)
+ ),
+ fallible: true,
+ note: &["The value must be an integer between 0 and 4294967295."],
+ },
+ Js::LossyBigInt => infallible(
+ "Option<napi::bindgen_prelude::BigInt>",
+ format!("value.{name}.map(|v| v.get_u64().1 as usize)"),
+ ),
+ Js::Timestamp => JsType {
rs_type: "Option<String>",
expr: format!(
"value\n .{name}\n \
@@ -378,8 +581,13 @@ fn js_type(struct_name: &str, field: &OptionField) ->
Result<JsType> {
"the operation.",
],
},
- kind => bail!("core {struct_name}::{name} is {kind:?}, which has no JS
type yet"),
- })
+ Js::OffsetSize => JsType {
+ rs_type: "Option<napi::bindgen_prelude::BigInt>",
+ expr: "super::bytes_range(value.offset, value.size)?".to_string(),
+ fallible: true,
+ note: &[],
+ },
+ }
}
/// The core doc comment as it reads in JS. napi-rs copies it into
@@ -390,18 +598,41 @@ fn js_type(struct_name: &str, field: &OptionField) ->
Result<JsType> {
/// crate reference links keep their label.
///
/// Code spans that name a JS property use its JS name (see [`js_code_span`]).
-/// OpenDAL error kinds appear in the JS error message.
+/// OpenDAL error kinds appear in the JS error message. JS has no `Option`, so
+/// "`Some(0)` has the same behavior as `None`" reads "`0` has the same
+/// behavior as omitting it".
+///
+/// Core's paragraph that points to the performance guide is dropped, because
+/// that guide covers the Rust API only. Only the exact paragraph is dropped,
+/// so a reworded one shows up in review instead of disappearing.
fn js_doc(lines: &[String], options: &JsOptions, capabilities:
&[CapabilityField]) -> Vec<String> {
let mut doc = String::new();
- for line in lines {
- let line = rewrite_code_spans(&render_crate_reference_links(line),
|code| {
- js_code_span(code, options, capabilities)
- });
- doc.push_str(&line.replace(
- "`crate::ErrorKind::Unsupported`",
- "an error whose message includes `Unsupported`",
- ));
- doc.push('\n');
+ let mut first = true;
+ for paragraph in lines.split(|line| line.is_empty()) {
+ if paragraph.join(" ") == PERFORMANCE_GUIDE {
+ continue;
+ }
+ if !first {
+ doc.push('\n');
+ }
+ first = false;
+ for line in paragraph {
+ let line = rewrite_code_spans(&render_crate_reference_links(line),
|code| {
+ js_code_span(code, options, capabilities)
+ });
+ doc.push_str(
+ &line
+ .replace(
+ "`crate::ErrorKind::Unsupported`",
+ "an error whose message includes `Unsupported`",
+ )
+ .replace(
+ "`Some(0)` has the same behavior as `None`",
+ "`0` has the same behavior as omitting it",
+ ),
+ );
+ doc.push('\n');
+ }
}
for kind in ["NotFound", "ConditionNotMatch", "Conflict"] {
@@ -421,6 +652,12 @@ fn js_doc(lines: &[String], options: &JsOptions,
capabilities: &[CapabilityField
doc.split_terminator('\n').map(str::to_owned).collect()
}
+/// The paragraph that core options docs use to point to the Rust performance
+/// guide.
+const PERFORMANCE_GUIDE: &str = "Refer to the \
+ [performance
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)
\
+ for more details.";
+
/// Render the known specification link and keep only the label of other
/// reference-style links to crate items.
fn render_crate_reference_links(line: &str) -> String {
@@ -450,17 +687,23 @@ fn render_crate_reference_links(line: &str) -> String {
/// or `None` to keep the code span as written.
///
/// napi-rs exposes snake_case Rust names in lower camel case, so an exposed
-/// field of these options like `start_after` reads `startAfter`, and a core
+/// field of these options like `start_after` reads `startAfter`, a renamed
+/// one like the read `override_content_type` reads `contentType`, and a core
/// capability like `Capability::list_with_start_after` reads
/// `Capability.listWithStartAfter`, the getter on the JS `Capability` that
-/// `op.capability()` returns.
+/// `op.capability()` returns. A core `range` has no single JS name, so it
+/// stays as written.
fn js_code_span(
code: &str,
options: &JsOptions,
capabilities: &[CapabilityField],
) -> Option<String> {
- if options.fields.iter().any(|&(name, _)| name == code) {
- return Some(heck::AsLowerCamelCase(code).to_string());
+ if let Some(&(name, ..)) = options
+ .fields
+ .iter()
+ .find(|&&(name, form)| name == code && form != Js::OffsetSize)
+ {
+ return Some(heck::AsLowerCamelCase(js_name(options,
name)).to_string());
}
let name = code
.strip_prefix("crate::")
@@ -475,6 +718,7 @@ fn js_code_span(
#[cfg(test)]
mod tests {
use super::*;
+ use regex::Regex;
fn field(name: &str, kind: MetadataKind) -> MetadataField {
metadata_field(metadata::MetadataField {
@@ -583,9 +827,12 @@ mod tests {
doc
}
+ const ALL_OPTIONS: [&JsOptions; 4] =
+ [&LIST_OPTIONS, &STAT_OPTIONS, &DELETE_OPTIONS, &READ_OPTIONS];
+
#[test]
fn test_options_new_core_field_is_not_exposed() {
- for options in [&LIST_OPTIONS, &STAT_OPTIONS, &DELETE_OPTIONS] {
+ for options in ALL_OPTIONS {
let core = core_options(options.name);
let mut mutated = core.clone();
mutated.fields.insert(
@@ -634,6 +881,16 @@ mod tests {
"{err}"
);
+ for name in ["range", "override_content_type"] {
+ let mut missing = core_options("ReadOptions");
+ missing.fields.retain(|field| field.name != name);
+ let err = render(missing, &READ_OPTIONS).unwrap_err().to_string();
+ assert!(
+ err.contains(&format!("ReadOptions has no field `{name}`")),
+ "{err}"
+ );
+ }
+
// A kind change must fail, whether or not JS supports the new kind:
// `limit` must not change its JS type, `startAfter` must not turn
// into a boolean, `ifModifiedSince` must keep being parsed, and the
@@ -669,6 +926,40 @@ mod tests {
OptionKind::OptionString,
"DeleteOptions::recursive is OptionString",
),
+ // The read `concurrent` must stay a checked count, `chunk` and
+ // `gap` must keep their `number` and `bigint` types, `range` must
+ // keep its `offset` and `size`, and the renamed overrides must
+ // stay strings.
+ (
+ &READ_OPTIONS,
+ "concurrent",
+ OptionKind::OptionUsize,
+ "ReadOptions::concurrent is OptionUsize",
+ ),
+ (
+ &READ_OPTIONS,
+ "chunk",
+ OptionKind::Usize,
+ "ReadOptions::chunk is Usize",
+ ),
+ (
+ &READ_OPTIONS,
+ "gap",
+ OptionKind::OptionU64,
+ "ReadOptions::gap is OptionU64",
+ ),
+ (
+ &READ_OPTIONS,
+ "range",
+ OptionKind::OptionU64,
+ "ReadOptions::range is OptionU64",
+ ),
+ (
+ &READ_OPTIONS,
+ "override_cache_control",
+ OptionKind::Bool,
+ "ReadOptions::override_cache_control is Bool",
+ ),
] {
let mut changed = core_options(options.name);
let field = changed.fields.iter_mut().find(|f| f.name ==
name).unwrap();
@@ -676,6 +967,86 @@ mod tests {
let err = render(changed, options).unwrap_err().to_string();
assert!(err.contains(expected), "{err}");
}
+
+ // Core documents `range` in Rust range syntax, so its JS members
+ // cannot fall back to the core doc.
+ let undocumented = JsOptions {
+ docs: &READ_OPTIONS.docs[..2],
+ ..READ_OPTIONS
+ };
+ let err = render(core_options("ReadOptions"), &undocumented)
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("ReadOptions::size needs a JS doc"), "{err}");
+
+ // A Node.js rewrite that no longer matches core's doc fails, so the
+ // new core wording gets reviewed for JS.
+ let mut reworded = core_options("ReadOptions");
+ for line in &mut reworded.doc {
+ *line = line.replace("an empty range validates", "an empty range
checks");
+ }
+ let err = render(reworded, &READ_OPTIONS).unwrap_err().to_string();
+ assert!(
+ err.contains(
+ "ReadOptions docs no longer contain \
+ `A read with a zero limit or an empty range validates`"
+ ),
+ "{err}"
+ );
+ }
+
+ #[test]
+ fn test_read_options_docs_use_node_wording() {
+ let rendered = render(core_options("ReadOptions"),
&READ_OPTIONS).unwrap();
+ let struct_doc =
&rendered[..rendered.find("#[napi(object)]").unwrap()];
+ // An empty read in JS, and the stat that a chunked read without a
+ // `size` makes, which needs the stat capability of each condition.
+ let struct_text = struct_doc
+ .lines()
+ .filter_map(|line| line.strip_prefix("///"))
+ .map(str::trim)
+ .collect::<Vec<_>>()
+ .join(" ");
+ for expected in [
+ "Once the option and capability checks pass, a read that reaches
storage fails with \
+ an error whose message includes `NotFound` for a missing file",
+ "condition. A read with `{ size: 0n }` validates the read options
and capabilities, \
+ then returns an empty buffer without accessing storage",
+ ] {
+ assert!(struct_text.contains(expected), "{struct_text}");
+ }
+ let chunk = field_doc(&rendered, "chunk").join(" ");
+ for expected in [
+ "A read with a positive `chunk` and no `size` first stats the file
to learn its length.",
+ "such as `Capability.statWithIfModifiedSince` for
`ifModifiedSince`; otherwise the read \
+ returns an error whose message includes `Unsupported`.",
+ ] {
+ assert!(chunk.contains(expected), "{chunk}");
+ }
+ // `presignRead(path, expires)` takes no options, so the overrides
+ // apply to `read()` and `readSync()` only.
+ for member in ["content_type", "cache_control", "content_disposition"]
{
+ let doc = field_doc(&rendered, member).join(" ");
+ assert!(
+ doc.ends_with(
+ "support it. `presignRead(path, expires)` takes no
options, so presigned reads \
+ cannot request one."
+ ),
+ "{member}: {doc}"
+ );
+ }
+ let docs: String = rendered
+ .lines()
+ .filter(|line| line.trim_start().starts_with("///"))
+ .collect();
+ for rust in [
+ "presigned read requests",
+ "zero limit",
+ "suffix",
+ "content_length_hint",
+ ] {
+ assert!(!docs.contains(rust), "ReadOptions docs contain `{rust}`");
+ }
}
#[test]
@@ -729,6 +1100,31 @@ mod tests {
"if_not_changed",
][..],
),
+ (
+ &READ_OPTIONS,
+ &[
+ "version: Option<String>,",
+ "concurrent: Option<f64>,",
+ "chunk: Option<u32>,",
+ "gap: Option<napi::bindgen_prelude::BigInt>,",
+ "offset: Option<napi::bindgen_prelude::BigInt>,",
+ "size: Option<napi::bindgen_prelude::BigInt>,",
+ "if_match: Option<String>,",
+ "if_none_match: Option<String>,",
+ "if_modified_since: Option<String>,",
+ "if_unmodified_since: Option<String>,",
+ "content_type: Option<String>,",
+ "cache_control: Option<String>,",
+ "content_disposition: Option<String>,",
+ ][..],
+ &[
+ "limit",
+ "if_version_match",
+ "if_version_not_match",
+ "content_length_hint",
+ "checksum",
+ ][..],
+ ),
] {
let name = options.name;
let rendered = render(core_options(name), options).unwrap();
@@ -764,6 +1160,48 @@ mod tests {
}
}
+ #[test]
+ fn test_read_options_conversion() {
+ let rendered = render(core_options("ReadOptions"),
&READ_OPTIONS).unwrap();
+ assert!(rendered.contains("impl TryFrom<ReadOptions> for
opendal::options::ReadOptions {"));
+ // The conversion on main: `offset` and `size` must fit a `u64`,
+ // `concurrent` must be a count, `chunk` is read as `u32`, `gap` drops
+ // its sign and high bits, and the overrides keep their JS names.
+ for line in [
+ " range: super::bytes_range(value.offset,
value.size)?,\n",
+ " version: value.version,\n",
+ " if_match: value.if_match,\n",
+ " if_none_match: value.if_none_match,\n",
+ concat!(
+ " concurrent: value\n",
+ " .concurrent\n",
+ " .map(|v| crate::validate::parse_count(v,
\"concurrent\", 0))\n",
+ " .transpose()?\n",
+ " .unwrap_or_default(),\n",
+ ),
+ " chunk: value.chunk.map(|v| v as usize),\n",
+ " gap: value.gap.map(|v| v.get_u64().1 as usize),\n",
+ " override_content_type: value.content_type,\n",
+ " override_cache_control: value.cache_control,\n",
+ " override_content_disposition:
value.content_disposition,\n",
+ ] {
+ assert!(rendered.contains(line), "{line}");
+ }
+ // Main converts `offset` and `size` first, then the timestamps, then
+ // `concurrent`, so a call with several invalid values reports the
+ // same one.
+ let order: Vec<usize> = [
+ "range:",
+ "if_modified_since:",
+ "if_unmodified_since:",
+ "concurrent:",
+ ]
+ .iter()
+ .map(|field| rendered.find(&format!(" {field} ")).unwrap())
+ .collect();
+ assert!(order.is_sorted(), "{order:?}");
+ }
+
#[test]
fn test_options_conversion_parses_timestamps() {
let stat = render(core_options("StatOptions"), &STAT_OPTIONS).unwrap();
@@ -853,6 +1291,56 @@ mod tests {
js_doc(&lines, &STAT_OPTIONS, &core_capabilities()),
["Use `ifNoneMatch`, not `start_after`."]
);
+
+ // A renamed field reads its JS name, and `range`, which JS splits
+ // into `offset` and `size`, stays as written.
+ let lines = ["Set `override_content_type`, `chunk_size`, `range`, or
`gap`.".to_string()];
+ assert_eq!(
+ js_doc(&lines, &READ_OPTIONS, &core_capabilities()),
+ ["Set `contentType`, `chunk_size`, `range`, or `gap`."]
+ );
+ assert_eq!(
+ js_doc(&lines, &STAT_OPTIONS, &core_capabilities()),
+ ["Set `overrideContentType`, `chunk_size`, `range`, or `gap`."]
+ );
+ }
+
+ #[test]
+ fn test_js_doc_rewrites_rust_only_text() {
+ let lines = [
+ "First paragraph.",
+ "",
+ "Refer to the [performance
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)",
+ "for more details.",
+ "",
+ "`Some(0)` has the same behavior as `None`.",
+ "- `Some(0)` has the same behavior as `None`",
+ "Other `Some(1)` and `None` stay.",
+ "",
+ "Refer to the [performance
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)",
+ "for more details.",
+ "",
+ "Refer to the [performance
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)",
+ "for reads.",
+ ]
+ .map(String::from);
+ // A reworded paragraph stays, so a review sees it.
+ assert_eq!(
+ js_doc(&lines, &READ_OPTIONS, &core_capabilities()),
+ [
+ "First paragraph.",
+ "",
+ "`0` has the same behavior as omitting it.",
+ "- `0` has the same behavior as omitting it",
+ "Other `Some(1)` and `None` stay.",
+ "",
+ "Refer to the [performance
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)",
+ "for reads.",
+ ]
+ );
+ // Docs without such text keep every line and blank line.
+ let lines = ["", "a", "", "", "b", ""].map(String::from);
+ assert_eq!(js_doc(&lines, &READ_OPTIONS, &core_capabilities()), lines);
}
#[test]
@@ -866,7 +1354,7 @@ mod tests {
"An unrelated `crate::ErrorKind::PermissionDenied` stays.",
]
.map(String::from);
- for options in [&LIST_OPTIONS, &STAT_OPTIONS, &DELETE_OPTIONS] {
+ for options in ALL_OPTIONS {
assert_eq!(
js_doc(&lines, options, &core_capabilities()),
[
@@ -994,6 +1482,19 @@ mod tests {
("if_match", "`Capability.deleteWithIfMatch`"),
][..],
),
+ (
+ &READ_OPTIONS,
+ &[
+ ("version", "`Capability.readWithVersion`"),
+ ("if_match", "`Capability.readWithIfMatch`"),
+ ("if_none_match", "`Capability.readWithIfNoneMatch`"),
+ ("if_modified_since",
"`Capability.readWithIfModifiedSince`"),
+ (
+ "if_unmodified_since",
+ "`Capability.readWithIfUnmodifiedSince`",
+ ),
+ ][..],
+ ),
] {
let rendered = render(core_options(options.name),
options).unwrap();
for (name, capability) in expected {
@@ -1014,4 +1515,229 @@ mod tests {
}
}
}
+
+ /// Split doc lines into paragraphs, each joined into one line of words.
+ fn paragraphs<'a>(lines: impl IntoIterator<Item = &'a str>) -> Vec<String>
{
+ let mut paragraphs = vec![Vec::new()];
+ for line in lines {
+ match line.trim() {
+ "" => paragraphs.push(Vec::new()),
+ text => paragraphs.last_mut().unwrap().push(text),
+ }
+ }
+ paragraphs
+ .into_iter()
+ .filter(|words| !words.is_empty())
+ .map(|words| words.join(" "))
+ .collect()
+ }
+
+ /// A snake_case name in lower camel case, as napi-rs names JS properties.
+ fn camel(name: &str) -> String {
+ let mut parts = name.split('_');
+ let mut out = parts.next().unwrap().to_string();
+ for part in parts {
+ let mut chars = part.chars();
+ if let Some(first) = chars.next() {
+ out.extend(first.to_uppercase());
+ out.push_str(chars.as_str());
+ }
+ }
+ out
+ }
+
+ /// Core doc text as the Node.js docs must read it, one entry per
+ /// paragraph.
+ ///
+ /// Rustdoc links keep their code span or text, and the conditional
+ /// operations specification links to its website page. Code spans that
+ /// name an exposed field (`names`, as core and JS names) or a capability
+ /// use the JS name, error kinds are described by message, `Some(0)` and
+ /// `None` read as JS, and paragraphs that point to the Rust performance
+ /// guide are dropped.
+ fn expected_js_paragraphs(core_doc: &[String], names: &[(&str, String)])
-> Vec<String> {
+ let text = core_doc.join("\n");
+ let text =
Regex::new(r"\[([^\]]*)\]\[crate::docs::specs::conditional_operations\]")
+ .unwrap()
+ .replace_all(
+ &text,
+
"[$1](https://opendal.apache.org/docs/specifications/conditional-operations/)",
+ );
+ let text = Regex::new(r"\[([^\]]*)\]\[crate::[^\]]*\]")
+ .unwrap()
+ .replace_all(&text, "$1");
+ let text = Regex::new(r"\[(`[^`]*`)\](\([^)]*\))?")
+ .unwrap()
+ .replace_all(&text, "$1");
+ let text = Regex::new(r"`(?:crate::)?Capability::(\w+)`")
+ .unwrap()
+ .replace_all(&text, |c: ®ex::Captures| {
+ format!("`Capability.{}`", camel(&c[1]))
+ });
+ let text = Regex::new(r"`(\w+)`")
+ .unwrap()
+ .replace_all(&text, |c: ®ex::Captures| {
+ match names.iter().find(|(core, _)| *core == &c[1]) {
+ Some((_, js)) => format!("`{js}`"),
+ None => c[0].to_string(),
+ }
+ });
+ let text =
+
Regex::new(r"returns(\s+)`crate::ErrorKind::(NotFound|ConditionNotMatch|Conflict)`")
+ .unwrap()
+ .replace_all(&text, "produces${1}`crate::ErrorKind::$2`");
+ let text =
+
Regex::new(r"`crate::ErrorKind::(Unsupported|NotFound|ConditionNotMatch|Conflict)`")
+ .unwrap()
+ .replace_all(&text, "an error whose message includes `$1`")
+ .replace(
+ "`Some(0)` has the same behavior as `None`",
+ "`0` has the same behavior as omitting it",
+ );
+ paragraphs(text.lines())
+ .into_iter()
+ .filter(|paragraph|
!paragraph.contains("core/core/src/docs/performance"))
+ .collect()
+ }
+
+ /// Core paragraphs with the Node.js wording that replaces text which does
+ /// not hold for the JS methods of `options`.
+ fn node_wording(options: &str, paragraphs: Vec<String>) -> Vec<String> {
+ let wording: &[(&str, &str)] = match options {
+ "ReadOptions" => &[
+ (
+ "A read with a zero limit or an empty range validates",
+ "A read with `{ size: 0n }` validates",
+ ),
+ (
+ "and an open-ended or nonempty suffix range first",
+ "and no `size` first",
+ ),
+ (", unless `content_length_hint` is set.", "."),
+ (
+ ", including for presigned read requests.",
+ ". `presignRead(path, expires)` takes no options, so
presigned reads \
+ cannot request one.",
+ ),
+ ],
+ _ => &[],
+ };
+ paragraphs
+ .into_iter()
+ .map(|paragraph| {
+ wording
+ .iter()
+ .fold(paragraph, |text, (from, to)| text.replace(from, to))
+ })
+ .collect()
+ }
+
+ #[test]
+ fn test_options_docs_render_core_docs_in_full() {
+ // The JS notes that follow the core doc, as main documented them.
+ let timestamp_note = "Pass an ISO 8601 string, such as
`2024-01-01T00:00:00Z` or the \
+ result of `Date.prototype.toISOString()`. A
string that does not \
+ parse fails the operation.";
+ let count_note = "The value must be an integer between 0 and
4294967295.";
+ // Members whose core doc does not hold for JS, with their JS doc.
+ let js_only: &[(&str, &str, &[&str])] = &[
+ (
+ "ReadOptions",
+ "gap",
+ &[
+ "Each call to `read()` or `readSync()` reads a single byte
range, so `gap` \
+ has no effect.",
+ ],
+ ),
+ (
+ "ReadOptions",
+ "offset",
+ &[
+ "Read from this byte offset instead of from the start of
the file.",
+ "An offset at or beyond the end of the file can return an
empty buffer or \
+ fail the read, depending on the service and on `chunk`. A
negative value, \
+ or one above `2^64 - 1`, fails the operation.",
+ ],
+ ),
+ (
+ "ReadOptions",
+ "size",
+ &[
+ "Read this many bytes from `offset`. Without `size`, the
read continues to \
+ the end of the file.",
+ "A `size` of `0n` validates the other options, then
returns an empty buffer \
+ without accessing storage. A file that ends before
`offset` plus `size` \
+ fails the read. A negative value, or one above `2^64 -
1`, fails the \
+ operation.",
+ ],
+ ),
+ ];
+
+ for options in ALL_OPTIONS {
+ let name = options.name;
+ let core = core_options(name);
+ let rendered = render(core.clone(), options).unwrap();
+ let names: Vec<(&str, String)> = options
+ .fields
+ .iter()
+ .filter(|&&(_, form)| form != Js::OffsetSize)
+ .map(|&(field, ..)| (field, camel(js_name(options, field))))
+ .collect();
+
+ let struct_doc =
rendered[..rendered.find("#[napi(object)]").unwrap()]
+ .lines()
+ .filter_map(|line| line.strip_prefix("///"));
+ let expected = node_wording(name,
expected_js_paragraphs(&core.doc, &names));
+ assert!(!expected.is_empty(), "core `{name}` has no doc");
+ assert_eq!(paragraphs(struct_doc), expected, "doc of `{name}`");
+
+ let napi = napi_struct(&rendered);
+ let members: Vec<&str> = napi
+ .lines()
+ .filter_map(|line| line.strip_prefix(" pub "))
+ .map(|line| line.split(':').next().unwrap())
+ .collect();
+ for member in members {
+ let expected: Vec<String> = match js_only
+ .iter()
+ .find(|&&(options, js, _)| options == name && js == member)
+ {
+ Some((.., doc)) => doc.iter().map(|p|
p.to_string()).collect(),
+ None => {
+ let &(field, form) = options
+ .fields
+ .iter()
+ .find(|&&(field, ..)| js_name(options, field) ==
member)
+ .unwrap_or_else(|| panic!("`{name}::{member}` has
no core field"));
+ let doc = &core.fields.iter().find(|f| f.name ==
field).unwrap().doc;
+ let mut expected = node_wording(name,
expected_js_paragraphs(doc, &names));
+ match form {
+ Js::Timestamp =>
expected.push(timestamp_note.to_string()),
+ Js::Count => expected.push(count_note.to_string()),
+ _ => {}
+ }
+ expected
+ }
+ };
+ assert!(!expected.is_empty(), "`{name}::{member}` has no doc");
+ assert_eq!(
+ paragraphs(field_doc(&rendered, member)),
+ expected,
+ "doc of `{name}::{member}`"
+ );
+ }
+
+ for rust in [
+ "[`",
+ "](crate",
+ "][crate",
+ "Capability::",
+ "crate::ErrorKind::",
+ "Some(",
+ "performance guide",
+ ] {
+ assert!(!rendered.contains(rust), "{name} docs contain
`{rust}`");
+ }
+ }
+ }
}