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 8de9d5d5ab feat(bindings/nodejs): generate WriteOptions from core
(#9383)
8de9d5d5ab is described below
commit 8de9d5d5ab89928ed5813e48469d6742c36deee1
Author: Chitral Verma <[email protected]>
AuthorDate: Sun Nov 29 22:57:24 2026 +0530
feat(bindings/nodejs): generate WriteOptions from core (#9383)
* feat(bindings/nodejs): generate WriteOptions from core
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/nodejs): generate WriteOptions from core
Name the one-shot write methods in the core concurrent doc, scope the
Node.js 0n wording to chunk, and allow only the two cacheControl web
links in the generated docs.
Signed-off-by: Chitral Verma <[email protected]>
* fixup! feat(bindings/nodejs): generate WriteOptions from core
Say that the service writer receives one buffer and may split it, that
a check against the stored file fails while writing or closing, that
each chunk reaches the service writer as one write, and that a later
stat returns user metadata.
Signed-off-by: Chitral Verma <[email protected]>
* docs: clarify concurrency when chunk is omitted
---------
Signed-off-by: Chitral Verma <[email protected]>
Co-authored-by: Xuanwo <[email protected]>
---
bindings/nodejs/generated.d.ts | 241 ++++++++++--
bindings/nodejs/src/options.rs | 110 +-----
bindings/nodejs/src/options/write.rs | 301 +++++++++++++++
.../nodejs/tests/write-options-surface.test.mjs | 209 ++++++++++
core/core/src/types/options.rs | 31 +-
dev/src/generate/core_options.rs | 80 +++-
dev/src/generate/nodejs.rs | 426 ++++++++++++++++++++-
7 files changed, 1233 insertions(+), 165 deletions(-)
diff --git a/bindings/nodejs/generated.d.ts b/bindings/nodejs/generated.d.ts
index c933d5efe0..267ec164eb 100644
--- a/bindings/nodejs/generated.d.ts
+++ b/bindings/nodejs/generated.d.ts
@@ -1727,73 +1727,239 @@ export interface StatOptions {
overrideContentDisposition?: string
}
+/**
+ * Options for write operations.
+ *
+ * Each condition checks the file currently stored at the write path, and
+ * the service evaluates it atomically with the write's visible commit:
+ *
+ * - A false condition fails the write with
+ * an error whose message includes `ConditionNotMatch` and leaves the
previously
+ * visible file unchanged. `writer()` and `writerSync()` do not access
storage, so depending on
+ * the service, a check against the stored file fails the returned
+ * writer's `write()` or `close()`.
+ * - A condition the service does not advertise through its capability fails
+ * the write with an error whose message includes `Unsupported`; OpenDAL never
+ * silently drops a condition. A service that cannot preserve a
+ * combination of conditions also returns `Unsupported`.
+ * - A service-side conflict unrelated to these conditions surfaces as
+ * an error whose message includes `Conflict`.
+ *
+ * See the [conditional operation
specification](https://opendal.apache.org/docs/specifications/conditional-operations/)
+ * for the complete cross-operation contract.
+ */
export interface WriteOptions {
/**
- * Append bytes into a path.
+ * Sets append mode for this operation.
*
- * ### Notes
+ * ### Capability
*
- * - It always appends content to the end of the file.
- * - It will create file if the path does not exist.
+ * Check `Capability.writeCanAppend` before using this option.
+ *
+ * ### Behavior
+ *
+ * - By default, write operations overwrite existing files
+ * - When append is set to true:
+ * - New data will be appended to the end of existing file
+ * - If file doesn't exist, it will be created
+ * - If not supported, will return an error
+ *
+ * This operation allows adding data to existing files instead of
overwriting them.
*/
append?: boolean
/**
- * Set the chunk of op.
+ * Sets chunk size for buffered writes.
+ *
+ * ### Capability
+ *
+ * Check `Capability.writeMultiMinSize` and `Capability.writeMultiMaxSize`
for size limits.
+ *
+ * ### Behavior
+ *
+ * - By default, OpenDAL buffers data until it reaches the service's
+ * `Capability.writeMultiMinSize` and then writes everything
+ * buffered at once; a service without that minimum receives each write
+ * as it arrives
+ * - `0n` has the same behavior as omitting it
+ * - When chunk size is set:
+ * - Data will be buffered until reaching chunk size
+ * - Each chunk reaches the service writer as one write; a service may
+ * add requests, such as the ones that start and complete an S3
+ * multipart upload
+ * - Last chunk may be smaller than chunk size
+ * - Important considerations:
+ * - Some services require minimum chunk sizes, so OpenDAL raises a chunk
+ * size below `Capability.writeMultiMinSize` to that minimum
+ * and lowers one above `Capability.writeMultiMaxSize` to
+ * that maximum
+ * - Smaller chunks increase API calls and costs
+ * - Larger chunks increase memory usage, but improve performance and
reduce costs
+ *
+ * ### Performance Impact
+ *
+ * Setting appropriate chunk size can:
+ * - Reduce number of API calls
+ * - Improve overall throughput
+ * - Lower operation costs
+ * - Better utilize network bandwidth
+ */
+ chunk?: bigint
+ /**
+ * Sets `Content-Type` header for this write operation.
+ *
+ * ## Capability
+ *
+ * Check `Capability.writeWithContentType` before using this feature.
*
- * If chunk is set, the data will be chunked by the underlying writer.
+ * ### Behavior
*
- * ## NOTE
+ * - If supported, sets Content-Type as system metadata on the target file
+ * - The value should follow MIME type format (e.g. "text/plain",
"image/jpeg")
+ * - If not supported, the value will be ignored
*
- * A service could have their own minimum chunk size while perform write
- * operations like multipart uploads. So the chunk size may be larger than
- * the given buffer size.
+ * This operation allows specifying the media type of the content being
written.
*/
- chunk?: bigint
- /** Set the
[Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type)
of op. */
contentType?: string
- /** Set the
[Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition)
of op. */
+ /**
+ * Sets Content-Disposition header for this write request.
+ *
+ * ### Capability
+ *
+ * Check `Capability.writeWithContentDisposition` before using this feature.
+ *
+ * ### Behavior
+ *
+ * - If supported, sets Content-Disposition as system metadata on the target
file
+ * - The value should follow HTTP Content-Disposition header format
+ * - Common values include:
+ * - `inline` - Content displayed within browser
+ * - `attachment` - Content downloaded as file
+ * - `attachment; filename="example.jpg"` - Downloaded with specified
filename
+ * - If not supported, the value will be ignored
+ *
+ * This operation allows controlling how the content should be displayed or
downloaded.
+ */
contentDisposition?: string
- /** Set the
[Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
of op. */
+ /**
+ * Sets Cache-Control header for this write operation.
+ *
+ * ### Capability
+ *
+ * Check `Capability.writeWithCacheControl` before using this feature.
+ *
+ * ### Behavior
+ *
+ * - If supported, sets Cache-Control as system metadata on the target file
+ * - The value should follow HTTP Cache-Control header format
+ * - If not supported, the value will be ignored
+ *
+ * This operation allows controlling caching behavior for the written
content.
+ *
+ * ### Use Cases
+ *
+ * - Setting browser cache duration
+ * - Configuring CDN behavior
+ * - Optimizing content delivery
+ * - Managing cache invalidation
+ *
+ * ### References
+ *
+ * - [MDN
Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
+ * - [RFC 7234 Section 5.2](https://tools.ietf.org/html/rfc7234#section-5.2)
+ */
cacheControl?: string
- /** Set the [Content-Encoding]
https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Encoding
of op. */
+ /**
+ * Sets Content-Encoding header for this write request.
+ *
+ * ### Capability
+ *
+ * Check `Capability.writeWithContentEncoding` before using this feature.
+ *
+ * ### Behavior
+ *
+ * - If supported, sets Content-Encoding as system metadata on the target
file
+ * - The value should follow HTTP Content-Encoding header format
+ * - Common values include:
+ * - `gzip` - Content encoded using gzip compression
+ * - `deflate` - Content encoded using deflate compression
+ * - `br` - Content encoded using Brotli compression
+ * - `identity` - No encoding applied (default value)
+ * - If not supported, the value will be ignored
+ *
+ * This operation allows specifying the encoding applied to the content
being written.
+ */
contentEncoding?: string
/**
- * Sets user metadata of op.
+ * Sets user metadata for this write request.
+ *
+ * ### Capability
*
- * If chunk is set, the user metadata will be attached to the object during
write.
+ * Check `Capability.writeWithUserMetadata` before using this feature.
*
- * ## NOTE
+ * ### Behavior
*
+ * - If supported, the user metadata will be attached to the object during
write
+ * - Accepts key-value pairs where both key and value are strings
+ * - Some services, such as `s3`, return keys in lowercase
* - Services may have limitations for user metadata, for example:
* - Key length is typically limited (e.g., 1024 bytes)
* - Value length is typically limited (e.g., 4096 bytes)
* - Total metadata size might be limited
* - Some characters might be forbidden in keys
+ * - If not supported, the metadata will be ignored
+ *
+ * User metadata provides a way to attach custom metadata to objects during
write operations.
+ * A later `stat()` or `statSync()` returns this metadata as `userMetadata`
+ * when the service exposes user metadata.
*/
userMetadata?: Record<string, string>
/**
- * Sets if-match condition of op.
+ * Write only when the file at the write path has this exact ETag.
*
- * This operation provides conditional write functionality based on ETag
matching,
- * helping prevent unintended overwrites in concurrent scenarios.
+ * The condition succeeds when the file exists and its ETag equals this
+ * value. A file with a different ETag, or a missing file, fails the
+ * write with an error whose message includes `ConditionNotMatch`. 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.writeWithIfMatch`.
*/
ifMatch?: string
/**
- * Sets if-none-match condition of op.
+ * Write only when the file at the write path does not have this ETag.
+ *
+ * With a concrete ETag value, the condition succeeds when the file has
+ * a different ETag or does not exist; the write then replaces or
+ * creates the file. A file whose ETag equals this value fails the write
+ * with an error whose message includes `ConditionNotMatch`. Only concrete
ETag
+ * values are portable; a wildcard such as `"*"` has no portable meaning
+ * here.
*
- * This operation provides conditional write functionality based on ETag
non-matching,
- * useful for preventing overwriting existing resources or ensuring unique
writes.
+ * The operation returns an error whose message includes `Unsupported` when
the
+ * service does not advertise
+ * `Capability.writeWithIfNoneMatch`. Some services, such
+ * as `s3`, support `ifNotExists` but not `ifNoneMatch`; use
+ * `ifNotExists` when you only need to guard against
+ * an existing file.
*/
ifNoneMatch?: string
/**
- * Sets if_not_exists condition of op.
+ * Write only when no file exists at the write path.
*
- * This operation provides a way to ensure write operations only create new
resources
- * without overwriting existing ones, useful for implementing "create if not
exists" logic.
+ * The condition succeeds when the path is empty, so the write creates
+ * the file. An existing file fails the write with
+ * an error whose message includes `ConditionNotMatch`.
+ *
+ * The operation returns an error whose message includes `Unsupported` when
the
+ * service does not advertise
+ * `Capability.writeWithIfNotExists`.
*/
ifNotExists?: boolean
/**
- * Sets concurrent of op.
+ * Sets concurrent write operations for this writer.
+ *
+ * ## Behavior
*
* - By default, OpenDAL writes files sequentially
* - When concurrent is set:
@@ -1801,6 +1967,25 @@ export interface WriteOptions {
* - Write operations return immediately without waiting if tasks space
are available
* - Close operation ensures all writes complete in order
* - Memory usage increases with concurrency level
+ * - If not supported, falls back to sequential writes
+ *
+ * `write()` and `writeSync()` without `chunk` pass their content to the
+ * service writer as one write. A service that splits the buffer
+ * internally, such as `fs` with `direct_io` on Linux, can write the
+ * parts concurrently.
+ *
+ * This feature significantly improves performance when:
+ * - Writing large files
+ * - Network latency is high
+ * - Storage service supports concurrent uploads like multipart uploads
+ *
+ * ## Performance Impact
+ *
+ * Setting appropriate concurrency can:
+ * - Increase write throughput
+ * - Reduce total write time
+ * - Better utilize available bandwidth
+ * - Trade memory for performance
*
* The value must be an integer between 0 and 4294967295.
*/
diff --git a/bindings/nodejs/src/options.rs b/bindings/nodejs/src/options.rs
index ddf2000698..19238945df 100644
--- a/bindings/nodejs/src/options.rs
+++ b/bindings/nodejs/src/options.rs
@@ -19,20 +19,19 @@ use napi::Status;
use napi::bindgen_prelude::BigInt;
use opendal::BytesRange;
use opendal::raw::Timestamp;
-use std::collections::HashMap;
-
-use crate::validate::parse_count;
mod delete;
mod list;
mod read;
mod reader;
mod stat;
+mod write;
pub use delete::DeleteOptions;
pub use list::ListOptions;
pub use read::ReadOptions;
pub use reader::ReaderOptions;
pub use stat::StatOptions;
+pub use write::WriteOptions;
/// Convert a JavaScript `BigInt` into a `u64` offset or size.
///
@@ -86,111 +85,6 @@ fn parse_timestamp(value: &str, field: &str) ->
napi::Result<Timestamp> {
})
}
-#[napi(object)]
-#[derive(Default, Debug)]
-pub struct WriteOptions {
- /// Append bytes into a path.
- ///
- /// ### Notes
- ///
- /// - It always appends content to the end of the file.
- /// - It will create file if the path does not exist.
- pub append: Option<bool>,
-
- /// Set the chunk of op.
- ///
- /// If chunk is set, the data will be chunked by the underlying writer.
- ///
- /// ## NOTE
- ///
- /// A service could have their own minimum chunk size while perform write
- /// operations like multipart uploads. So the chunk size may be larger than
- /// the given buffer size.
- pub chunk: Option<BigInt>,
-
- /// Set the
[Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type)
of op.
- pub content_type: Option<String>,
-
- /// Set the
[Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition)
of op.
- pub content_disposition: Option<String>,
-
- /// Set the
[Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
of op.
- pub cache_control: Option<String>,
-
- /// Set the [Content-Encoding]
https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Encoding
of op.
- pub content_encoding: Option<String>,
-
- /// Sets user metadata of op.
- ///
- /// If chunk is set, the user metadata will be attached to the object
during write.
- ///
- /// ## NOTE
- ///
- /// - Services may have limitations for user metadata, for example:
- /// - Key length is typically limited (e.g., 1024 bytes)
- /// - Value length is typically limited (e.g., 4096 bytes)
- /// - Total metadata size might be limited
- /// - Some characters might be forbidden in keys
- pub user_metadata: Option<HashMap<String, String>>,
-
- /// Sets if-match condition of op.
- ///
- /// This operation provides conditional write functionality based on ETag
matching,
- /// helping prevent unintended overwrites in concurrent scenarios.
- pub if_match: Option<String>,
-
- /// Sets if-none-match condition of op.
- ///
- /// This operation provides conditional write functionality based on ETag
non-matching,
- /// useful for preventing overwriting existing resources or ensuring
unique writes.
- pub if_none_match: Option<String>,
-
- /// Sets if_not_exists condition of op.
- ///
- /// This operation provides a way to ensure write operations only create
new resources
- /// without overwriting existing ones, useful for implementing "create if
not exists" logic.
- pub if_not_exists: Option<bool>,
-
- /// Sets concurrent of op.
- ///
- /// - By default, OpenDAL writes files sequentially
- /// - When concurrent is set:
- /// - Multiple write operations can execute in parallel
- /// - Write operations return immediately without waiting if tasks space
are available
- /// - Close operation ensures all writes complete in order
- /// - Memory usage increases with concurrency level
- ///
- /// The value must be an integer between 0 and 4294967295.
- pub concurrent: Option<f64>,
-}
-
-impl TryFrom<WriteOptions> for opendal::options::WriteOptions {
- type Error = napi::Error;
-
- fn try_from(value: WriteOptions) -> napi::Result<Self> {
- let concurrent = value
- .concurrent
- .map(|v| parse_count(v, "concurrent", 0))
- .transpose()?
- .unwrap_or_default();
-
- Ok(Self {
- append: value.append.unwrap_or_default(),
- chunk: value.chunk.map(|chunk| chunk.get_u64().1 as usize),
- content_type: value.content_type,
- content_disposition: value.content_disposition,
- cache_control: value.cache_control,
- content_encoding: value.content_encoding,
- user_metadata: value.user_metadata,
- if_match: value.if_match,
- if_none_match: value.if_none_match,
- if_not_exists: value.if_not_exists.unwrap_or_default(),
- concurrent,
- ..Default::default()
- })
- }
-}
-
#[cfg(test)]
mod tests {
use super::ListOptions;
diff --git a/bindings/nodejs/src/options/write.rs
b/bindings/nodejs/src/options/write.rs
new file mode 100644
index 0000000000..4225d814c9
--- /dev/null
+++ b/bindings/nodejs/src/options/write.rs
@@ -0,0 +1,301 @@
+// 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 write operations.
+///
+/// Each condition checks the file currently stored at the write path, and
+/// the service evaluates it atomically with the write's visible commit:
+///
+/// - A false condition fails the write with
+/// an error whose message includes `ConditionNotMatch` and leaves the
previously
+/// visible file unchanged. `writer()` and `writerSync()` do not access
storage, so depending on
+/// the service, a check against the stored file fails the returned
+/// writer's `write()` or `close()`.
+/// - A condition the service does not advertise through its capability fails
+/// the write with an error whose message includes `Unsupported`; OpenDAL never
+/// silently drops a condition. A service that cannot preserve a
+/// combination of conditions also returns `Unsupported`.
+/// - A service-side conflict unrelated to these conditions surfaces as
+/// an error whose message includes `Conflict`.
+///
+/// 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 WriteOptions {
+ /// Sets append mode for this operation.
+ ///
+ /// ### Capability
+ ///
+ /// Check `Capability.writeCanAppend` before using this option.
+ ///
+ /// ### Behavior
+ ///
+ /// - By default, write operations overwrite existing files
+ /// - When append is set to true:
+ /// - New data will be appended to the end of existing file
+ /// - If file doesn't exist, it will be created
+ /// - If not supported, will return an error
+ ///
+ /// This operation allows adding data to existing files instead of
overwriting them.
+ pub append: Option<bool>,
+
+ /// Sets chunk size for buffered writes.
+ ///
+ /// ### Capability
+ ///
+ /// Check `Capability.writeMultiMinSize` and
`Capability.writeMultiMaxSize` for size limits.
+ ///
+ /// ### Behavior
+ ///
+ /// - By default, OpenDAL buffers data until it reaches the service's
+ /// `Capability.writeMultiMinSize` and then writes everything
+ /// buffered at once; a service without that minimum receives each write
+ /// as it arrives
+ /// - `0n` has the same behavior as omitting it
+ /// - When chunk size is set:
+ /// - Data will be buffered until reaching chunk size
+ /// - Each chunk reaches the service writer as one write; a service may
+ /// add requests, such as the ones that start and complete an S3
+ /// multipart upload
+ /// - Last chunk may be smaller than chunk size
+ /// - Important considerations:
+ /// - Some services require minimum chunk sizes, so OpenDAL raises a
chunk
+ /// size below `Capability.writeMultiMinSize` to that minimum
+ /// and lowers one above `Capability.writeMultiMaxSize` to
+ /// that maximum
+ /// - Smaller chunks increase API calls and costs
+ /// - Larger chunks increase memory usage, but improve performance and
reduce costs
+ ///
+ /// ### Performance Impact
+ ///
+ /// Setting appropriate chunk size can:
+ /// - Reduce number of API calls
+ /// - Improve overall throughput
+ /// - Lower operation costs
+ /// - Better utilize network bandwidth
+ pub chunk: Option<napi::bindgen_prelude::BigInt>,
+
+ /// Sets `Content-Type` header for this write operation.
+ ///
+ /// ## Capability
+ ///
+ /// Check `Capability.writeWithContentType` before using this feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, sets Content-Type as system metadata on the target file
+ /// - The value should follow MIME type format (e.g. "text/plain",
"image/jpeg")
+ /// - If not supported, the value will be ignored
+ ///
+ /// This operation allows specifying the media type of the content being
written.
+ pub content_type: Option<String>,
+
+ /// Sets Content-Disposition header for this write request.
+ ///
+ /// ### Capability
+ ///
+ /// Check `Capability.writeWithContentDisposition` before using this
feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, sets Content-Disposition as system metadata on the
target file
+ /// - The value should follow HTTP Content-Disposition header format
+ /// - Common values include:
+ /// - `inline` - Content displayed within browser
+ /// - `attachment` - Content downloaded as file
+ /// - `attachment; filename="example.jpg"` - Downloaded with specified
filename
+ /// - If not supported, the value will be ignored
+ ///
+ /// This operation allows controlling how the content should be displayed
or downloaded.
+ pub content_disposition: Option<String>,
+
+ /// Sets Cache-Control header for this write operation.
+ ///
+ /// ### Capability
+ ///
+ /// Check `Capability.writeWithCacheControl` before using this feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, sets Cache-Control as system metadata on the target
file
+ /// - The value should follow HTTP Cache-Control header format
+ /// - If not supported, the value will be ignored
+ ///
+ /// This operation allows controlling caching behavior for the written
content.
+ ///
+ /// ### Use Cases
+ ///
+ /// - Setting browser cache duration
+ /// - Configuring CDN behavior
+ /// - Optimizing content delivery
+ /// - Managing cache invalidation
+ ///
+ /// ### References
+ ///
+ /// - [MDN
Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
+ /// - [RFC 7234 Section
5.2](https://tools.ietf.org/html/rfc7234#section-5.2)
+ pub cache_control: Option<String>,
+
+ /// Sets Content-Encoding header for this write request.
+ ///
+ /// ### Capability
+ ///
+ /// Check `Capability.writeWithContentEncoding` before using this feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, sets Content-Encoding as system metadata on the target
file
+ /// - The value should follow HTTP Content-Encoding header format
+ /// - Common values include:
+ /// - `gzip` - Content encoded using gzip compression
+ /// - `deflate` - Content encoded using deflate compression
+ /// - `br` - Content encoded using Brotli compression
+ /// - `identity` - No encoding applied (default value)
+ /// - If not supported, the value will be ignored
+ ///
+ /// This operation allows specifying the encoding applied to the content
being written.
+ pub content_encoding: Option<String>,
+
+ /// Sets user metadata for this write request.
+ ///
+ /// ### Capability
+ ///
+ /// Check `Capability.writeWithUserMetadata` before using this feature.
+ ///
+ /// ### Behavior
+ ///
+ /// - If supported, the user metadata will be attached to the object
during write
+ /// - Accepts key-value pairs where both key and value are strings
+ /// - Some services, such as `s3`, return keys in lowercase
+ /// - Services may have limitations for user metadata, for example:
+ /// - Key length is typically limited (e.g., 1024 bytes)
+ /// - Value length is typically limited (e.g., 4096 bytes)
+ /// - Total metadata size might be limited
+ /// - Some characters might be forbidden in keys
+ /// - If not supported, the metadata will be ignored
+ ///
+ /// User metadata provides a way to attach custom metadata to objects
during write operations.
+ /// A later `stat()` or `statSync()` returns this metadata as
`userMetadata`
+ /// when the service exposes user metadata.
+ pub user_metadata: Option<std::collections::HashMap<String, String>>,
+
+ /// Write only when the file at the write path has this exact ETag.
+ ///
+ /// The condition succeeds when the file exists and its ETag equals this
+ /// value. A file with a different ETag, or a missing file, fails the
+ /// write with an error whose message includes `ConditionNotMatch`. 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.writeWithIfMatch`.
+ pub if_match: Option<String>,
+
+ /// Write only when the file at the write path does not have this ETag.
+ ///
+ /// With a concrete ETag value, the condition succeeds when the file has
+ /// a different ETag or does not exist; the write then replaces or
+ /// creates the file. A file whose ETag equals this value fails the write
+ /// with an error whose message includes `ConditionNotMatch`. 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.writeWithIfNoneMatch`. Some services, such
+ /// as `s3`, support `ifNotExists` but not `ifNoneMatch`; use
+ /// `ifNotExists` when you only need to guard against
+ /// an existing file.
+ pub if_none_match: Option<String>,
+
+ /// Write only when no file exists at the write path.
+ ///
+ /// The condition succeeds when the path is empty, so the write creates
+ /// the file. An existing file fails the write with
+ /// an error whose message includes `ConditionNotMatch`.
+ ///
+ /// The operation returns an error whose message includes `Unsupported`
when the
+ /// service does not advertise
+ /// `Capability.writeWithIfNotExists`.
+ pub if_not_exists: Option<bool>,
+
+ /// Sets concurrent write operations for this writer.
+ ///
+ /// ## Behavior
+ ///
+ /// - By default, OpenDAL writes files sequentially
+ /// - When concurrent is set:
+ /// - Multiple write operations can execute in parallel
+ /// - Write operations return immediately without waiting if tasks space
are available
+ /// - Close operation ensures all writes complete in order
+ /// - Memory usage increases with concurrency level
+ /// - If not supported, falls back to sequential writes
+ ///
+ /// `write()` and `writeSync()` without `chunk` pass their content to the
+ /// service writer as one write. A service that splits the buffer
+ /// internally, such as `fs` with `direct_io` on Linux, can write the
+ /// parts concurrently.
+ ///
+ /// This feature significantly improves performance when:
+ /// - Writing large files
+ /// - Network latency is high
+ /// - Storage service supports concurrent uploads like multipart uploads
+ ///
+ /// ## Performance Impact
+ ///
+ /// Setting appropriate concurrency can:
+ /// - Increase write throughput
+ /// - Reduce total write time
+ /// - Better utilize available bandwidth
+ /// - Trade memory for performance
+ ///
+ /// The value must be an integer between 0 and 4294967295.
+ pub concurrent: Option<f64>,
+}
+
+impl TryFrom<WriteOptions> for opendal::options::WriteOptions {
+ type Error = napi::Error;
+
+ fn try_from(value: WriteOptions) -> napi::Result<Self> {
+ Ok(Self {
+ append: value.append.unwrap_or_default(),
+ cache_control: value.cache_control,
+ content_type: value.content_type,
+ content_disposition: value.content_disposition,
+ content_encoding: value.content_encoding,
+ content_language: Default::default(),
+ user_metadata: value.user_metadata,
+ expires: Default::default(),
+ if_match: value.if_match,
+ if_none_match: value.if_none_match,
+ if_version_match: Default::default(),
+ if_version_not_match: Default::default(),
+ if_not_exists: value.if_not_exists.unwrap_or_default(),
+ if_not_changed: Default::default(),
+ concurrent: value
+ .concurrent
+ .map(|v| crate::validate::parse_count(v, "concurrent", 0))
+ .transpose()?
+ .unwrap_or_default(),
+ chunk: value.chunk.map(|v| v.get_u64().1 as usize),
+ ..Default::default()
+ })
+ }
+}
diff --git a/bindings/nodejs/tests/write-options-surface.test.mjs
b/bindings/nodejs/tests/write-options-surface.test.mjs
new file mode 100644
index 0000000000..6e5020368f
--- /dev/null
+++ b/bindings/nodejs/tests/write-options-surface.test.mjs
@@ -0,0 +1,209 @@
+/*
+ * 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'
+
+// `WriteOptions` and the write methods as `generated.d.ts` declared them
+// before `WriteOptions` 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 write naming the core
+// option. Otherwise the write must store the content.
+const FROZEN_MEMBERS = [
+ ['append?: boolean', true, 'append', 'writeCanAppend'],
+ ['chunk?: bigint', 3n, 'chunk', null],
+ ['contentType?: string', 'text/plain', 'content_type', null],
+ ['contentDisposition?: string', 'attachment', 'content_disposition', null],
+ ['cacheControl?: string', 'no-store', 'cache_control', null],
+ ['contentEncoding?: string', 'identity', 'content_encoding', null],
+ ['userMetadata?: Record<string, string>', { key: 'value' }, 'user_metadata',
null],
+ ['ifMatch?: string', '"etag"', 'if_match', 'writeWithIfMatch'],
+ ['ifNoneMatch?: string', '"etag"', 'if_none_match', 'writeWithIfNoneMatch'],
+ ['ifNotExists?: boolean', true, 'if_not_exists', 'writeWithIfNotExists'],
+ ['concurrent?: number', 4, 'concurrent', null],
+]
+
+const FROZEN_SIGNATURES = [
+ 'write(path: string, content: Buffer | string, options?: WriteOptions |
undefined | null): Promise<Metadata>',
+ 'writeSync(path: string, content: Buffer | string, options?: WriteOptions |
undefined | null): Metadata',
+ 'writer(path: string, options?: WriteOptions | undefined | null):
Promise<Writer>',
+ 'writerSync(path: string, options?: WriteOptions | undefined | null):
BlockingWriter',
+]
+
+// Each entry point writes `data` in one call and, for a writer, closes it.
+const WRITERS = [
+ ['write', async (op, path, data, options) => op.write(path, data, options)],
+ ['writeSync', async (op, path, data, options) => op.writeSync(path, data,
options)],
+ [
+ 'writer',
+ async (op, path, data, options) => {
+ const writer = await op.writer(path, options)
+ await writer.write(data)
+ await writer.close()
+ },
+ ],
+ [
+ 'writerSync',
+ async (op, path, data, options) => {
+ const writer = op.writerSync(path, options)
+ writer.write(data)
+ writer.close()
+ },
+ ],
+]
+
+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('WriteOptions keeps its historical surface', () => {
+ const op = new Operator('memory')
+ let n = 0
+ const fresh = () => `write-options-surface-${++n}`
+
+ test('declares exactly the frozen members', () => {
+ assert.sameMembers(
+ declared('interface', 'WriteOptions'),
+ 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] of FROZEN_MEMBERS) {
+ const [, field] = member.match(/^(\w+)\?: /)
+ const options = { [field]: value }
+
+ for (const [method, write] of WRITERS) {
+ test(`${method} with ${member}`, async () => {
+ const path = fresh()
+ if (capability === null || op.capability()[capability]) {
+ // The write accepts a value of the declared type.
+ await write(op, path, content, options)
+ assert.equal((await op.read(path)).toString(), content)
+ } else {
+ // The option reaches core as `coreOption`, which this service does
+ // not support.
+ const unsupported = new RegExp(
+ `^Unsupported \\(permanent\\) at write\\b.* with the arguments
${coreOption}\\.`,
+ )
+ await expect(write(op, path, content,
options)).rejects.toThrowError(unsupported)
+ await expect(op.read(path)).rejects.toThrowError(/^NotFound /)
+ }
+ })
+ }
+ }
+
+ for (const [method, write] of WRITERS) {
+ test(`${method} stores the metadata options under their core names`, async
() => {
+ const path = fresh()
+ const userMetadata = { MixedCase: 'v1', lower: 'v2' }
+ await write(op, path, content, {
+ contentType: 'text/x-probe',
+ contentDisposition: 'attachment; filename="probe.txt"',
+ cacheControl: 'max-age=60',
+ contentEncoding: 'identity',
+ userMetadata,
+ })
+ // `stat` and `statSync` return what the write stored.
+ for (const metadata of [await op.stat(path), op.statSync(path)]) {
+ assert.equal(metadata.contentType, 'text/x-probe')
+ assert.equal(metadata.contentDisposition, 'attachment;
filename="probe.txt"')
+ assert.equal(metadata.cacheControl, 'max-age=60')
+ assert.equal(metadata.contentEncoding, 'identity')
+ assert.deepEqual(metadata.userMetadata, userMetadata)
+ }
+ })
+
+ test(`${method} converts ifNotExists, chunk, and concurrent as main did`,
async () => {
+ // `ifNotExists` reaches core: it keeps an existing file, and an omitted
+ // or `false` value overwrites it.
+ const path = fresh()
+ await op.write(path, 'old')
+ await expect(write(op, path, content, { ifNotExists: true
})).rejects.toThrowError(
+ /^ConditionNotMatch \(permanent\) at write\b/,
+ )
+ assert.equal((await op.read(path)).toString(), 'old')
+ await write(op, path, content, { ifNotExists: false, append: false })
+ assert.equal((await op.read(path)).toString(), content)
+ // `chunk` ignores its sign and the bits above 64, and a zero `chunk` or
+ // `concurrent` writes as if it were omitted. Which `chunk` and
+ // `concurrent` reach core is not observable on memory; the generator
+ // test `test_write_options_conversion` pins their conversion.
+ for (const options of [
+ { chunk: 0n, concurrent: 0 },
+ { chunk: -1n },
+ { chunk: 1n << 64n },
+ { chunk: 4n, concurrent: 2 },
+ ]) {
+ const path = fresh()
+ await write(op, path, content, options)
+ assert.equal((await op.read(path)).toString(), content)
+ }
+ })
+
+ test(`${method} rejects an invalid concurrent as main did`, async () => {
+ for (const concurrent of [1.5, -1, 2 ** 32]) {
+ await expect(write(op, fresh(), content, { concurrent
})).rejects.toThrowError(
+ 'concurrent must be an integer between 0 and 4294967295',
+ )
+ }
+ })
+ }
+
+ test('writer and writerSync check options without accessing storage', async
() => {
+ // An unsupported condition fails when the writer is created.
+ const unsupported = /^Unsupported \(permanent\) at write\b.* with the
arguments if_match\./
+ await expect(op.writer(fresh(), { ifMatch: '"etag"'
})).rejects.toThrowError(unsupported)
+ expect(() => op.writerSync(fresh(), { ifMatch: '"etag"'
})).toThrowError(unsupported)
+
+ // A false condition surfaces from the returned writer. Memory reports it
+ // when closing.
+ const path = fresh()
+ await op.write(path, 'old')
+ const writer = await op.writer(path, { ifNotExists: true })
+ await writer.write(content)
+ await expect(writer.close()).rejects.toThrowError(/^ConditionNotMatch
\(permanent\) at write\b/)
+ const blockingWriter = op.writerSync(path, { ifNotExists: true })
+ blockingWriter.write(content)
+ expect(() => blockingWriter.close()).toThrowError(/^ConditionNotMatch
\(permanent\) at write\b/)
+ assert.equal((await op.read(path)).toString(), 'old')
+ })
+})
diff --git a/core/core/src/types/options.rs b/core/core/src/types/options.rs
index 9ac3acf260..7cb16ba1e5 100644
--- a/core/core/src/types/options.rs
+++ b/core/core/src/types/options.rs
@@ -682,8 +682,11 @@ pub struct StatOptions {
///
/// - A false condition fails the write with
/// [`crate::ErrorKind::ConditionNotMatch`] and leaves the previously
-/// visible file unchanged. Depending on the service, the error may surface
-/// when the write starts, while writing, or when closing the writer.
+/// visible file unchanged. Creating a writer does not access storage, so
+/// depending on the service, a check against the stored file fails while
+/// writing or when closing the writer. Combining `if_not_changed` with a
+/// conflicting `if_match` or `if_version_match` fails before the writer
+/// exists, without accessing storage.
/// - A condition the service does not advertise through its capability fails
/// the write with [`crate::ErrorKind::Unsupported`]; OpenDAL never
/// silently drops a condition. A service that cannot preserve a
@@ -806,7 +809,7 @@ pub struct WriteOptions {
///
/// - If supported, the user metadata will be attached to the object
during write
/// - Accepts key-value pairs where both key and value are strings
- /// - Keys are case-insensitive in most services
+ /// - Some services, such as `s3`, return keys in lowercase
/// - Services may have limitations for user metadata, for example:
/// - Key length is typically limited (e.g., 1024 bytes)
/// - Value length is typically limited (e.g., 4096 bytes)
@@ -815,7 +818,8 @@ pub struct WriteOptions {
/// - If not supported, the metadata will be ignored
///
/// User metadata provides a way to attach custom metadata to objects
during write operations.
- /// This metadata can be retrieved later when reading the object.
+ /// A later stat returns this metadata when the service exposes user
metadata.
+ /// [`crate::Reader::metadata`] may omit it, for example on `fs`.
pub user_metadata: Option<HashMap<String, String>>,
/// Sets how long the new file lives after the write commits.
@@ -948,6 +952,11 @@ pub struct WriteOptions {
/// - Memory usage increases with concurrency level
/// - If not supported, falls back to sequential writes
///
+ /// [`crate::Operator::write_with`] and [`crate::Operator::write_options`]
+ /// without `chunk` pass the whole buffer to the service writer as one
+ /// write. A service that splits the buffer internally, such as `fs` with
+ /// `direct_io` on Linux, can write the parts concurrently.
+ ///
/// This feature significantly improves performance when:
/// - Writing large files
/// - Network latency is high
@@ -969,14 +978,22 @@ pub struct WriteOptions {
///
/// ### Behavior
///
- /// - By default, OpenDAL sets optimal chunk size based on service
capabilities
+ /// - By default, OpenDAL buffers data until it reaches the service's
+ /// [`crate::Capability::write_multi_min_size`] and then writes
everything
+ /// buffered at once; a service without that minimum receives each write
+ /// as it arrives
/// - `Some(0)` has the same behavior as `None`
/// - When chunk size is set:
/// - Data will be buffered until reaching chunk size
- /// - One API call will be made per chunk
+ /// - Each chunk reaches the service writer as one write; a service may
+ /// add requests, such as the ones that start and complete an S3
+ /// multipart upload
/// - Last chunk may be smaller than chunk size
/// - Important considerations:
- /// - Some services require minimum chunk sizes (e.g. S3's
EntityTooSmall error)
+ /// - Some services require minimum chunk sizes, so OpenDAL raises a
chunk
+ /// size below [`crate::Capability::write_multi_min_size`] to that
minimum
+ /// and lowers one above [`crate::Capability::write_multi_max_size`] to
+ /// that maximum
/// - Smaller chunks increase API calls and costs
/// - Larger chunks increase memory usage, but improve performance and
reduce costs
///
diff --git a/dev/src/generate/core_options.rs b/dev/src/generate/core_options.rs
index a1efea9c7c..4604056799 100644
--- a/dev/src/generate/core_options.rs
+++ b/dev/src/generate/core_options.rs
@@ -26,9 +26,10 @@ use anyhow::{Context, Result, bail};
use serde::Serialize;
use std::fs;
use std::path::Path;
-use syn::{GenericArgument, Item, ItemStruct, PathArguments, Type, TypePath,
Visibility};
-
-use super::options::doc_lines;
+use syn::{
+ Expr, ExprLit, GenericArgument, Item, ItemStruct, Lit, Meta,
PathArguments, Type, TypePath,
+ Visibility,
+};
/// The shape of one option field.
///
@@ -67,7 +68,7 @@ pub struct OptionField {
pub name: String,
/// The shape of the field type.
pub kind: OptionKind,
- /// Doc comment of the field, one entry per line.
+ /// Doc comment of the field, one entry per line (see [`doc_lines`]).
pub doc: Vec<String>,
}
@@ -76,7 +77,7 @@ pub struct OptionField {
pub struct OptionsStruct {
/// The struct name, e.g. `ReadOptions`.
pub name: String,
- /// Doc comment of the struct, one entry per line.
+ /// Doc comment of the struct, one entry per line (see [`doc_lines`]).
pub doc: Vec<String>,
/// The fields in declaration order.
pub fields: Vec<OptionField>,
@@ -144,6 +145,38 @@ fn parse_struct(struct_: &ItemStruct) ->
Result<OptionsStruct> {
})
}
+/// Collect a doc comment as trimmed lines, except that a nested list item
+/// keeps its indentation, so a binding can render core's nested lists.
+///
+/// Rustdoc reads `/// - item` as ` - item`; the first space belongs to the
+/// comment marker. Other lines, including the continuation lines of a list
+/// item, lose their indentation, which Markdown reads the same way.
+fn doc_lines(attrs: &[syn::Attribute]) -> Vec<String> {
+ attrs
+ .iter()
+ .filter(|attr| attr.path().is_ident("doc"))
+ .filter_map(|attr| {
+ let Meta::NameValue(meta) = &attr.meta else {
+ return None;
+ };
+ let Expr::Lit(ExprLit {
+ lit: Lit::Str(s), ..
+ }) = &meta.value
+ else {
+ return None;
+ };
+ let line = s.value();
+ let text = line.trim();
+ let indent = line.len() - line.trim_start().len();
+ if indent > 1 && (text.starts_with("- ") || text.starts_with("*
")) {
+ Some(format!("{}{text}", " ".repeat(indent - 1)))
+ } else {
+ Some(text.to_string())
+ }
+ })
+ .collect()
+}
+
fn classify(ty: &Type) -> Option<OptionKind> {
let segment = last_segment(ty)?;
match segment.ident.to_string().as_str() {
@@ -219,6 +252,43 @@ mod tests {
assert!(!write.fields[0].doc.is_empty());
}
+ #[test]
+ fn test_doc_lines_keep_nested_list_items() {
+ let struct_: ItemStruct = syn::parse_quote! {
+ /// Struct doc.
+ ///
+ /// - Top item
+ /// continues here.
+ /// - Nested item
+ /// continues here.
+ /// * Deeper item
+ /// Indented prose.
+ pub struct FakeOptions {
+ /// - Field item
+ /// - Nested field item
+ pub flag: bool,
+ }
+ };
+ let parsed = parse_struct(&struct_).unwrap();
+ assert_eq!(
+ parsed.doc,
+ [
+ "Struct doc.",
+ "",
+ "- Top item",
+ "continues here.",
+ " - Nested item",
+ "continues here.",
+ " * Deeper item",
+ "Indented prose.",
+ ]
+ );
+ assert_eq!(
+ parsed.fields[0].doc,
+ ["- Field item", " - Nested field item"]
+ );
+ }
+
#[test]
fn test_unmirrored_fields() {
let path =
crate::workspace_dir().join("core/core/src/types/options.rs");
diff --git a/dev/src/generate/nodejs.rs b/dev/src/generate/nodejs.rs
index 709c966f00..a7b4289aa9 100644
--- a/dev/src/generate/nodejs.rs
+++ b/dev/src/generate/nodejs.rs
@@ -220,6 +220,8 @@ enum Js {
LossyBigInt,
/// An `Option<Timestamp>` as an ISO 8601 `string` that must parse.
Timestamp,
+ /// An `Option<HashMap<String, String>>` as a `Record<string, string>`.
+ StringMap,
/// A `BytesRange` as the `offset` and `size` `bigint`s, which
/// `bigint_to_u64` checks.
OffsetSize,
@@ -234,6 +236,7 @@ impl Js {
Js::U32 | Js::LossyBigInt => OptionKind::OptionUsize,
Js::Count | Js::U32OrZero => OptionKind::Usize,
Js::Timestamp => OptionKind::OptionTimestamp,
+ Js::StringMap => OptionKind::OptionStringMap,
Js::OffsetSize => OptionKind::BytesRange,
}
}
@@ -425,6 +428,73 @@ const READER_OPTIONS: JsOptions = JsOptions {
],
};
+const WRITE_OPTIONS: JsOptions = JsOptions {
+ name: "WriteOptions",
+ module: "write",
+ fields: &[
+ ("append", Js::Bool),
+ ("chunk", Js::LossyBigInt),
+ ("content_type", Js::String),
+ ("content_disposition", Js::String),
+ ("cache_control", Js::String),
+ ("content_encoding", Js::String),
+ ("user_metadata", Js::StringMap),
+ ("if_match", Js::String),
+ ("if_none_match", Js::String),
+ ("if_not_exists", Js::Bool),
+ ("concurrent", Js::Count),
+ ],
+ renamed: &[],
+ docs: &[],
+ // JS writes go through `write()`, `writeSync()`, and the writers that
+ // `writer()` and `writerSync()` return. JS has no `if_not_changed` and no
+ // reader metadata, and the write `chunk` is a `bigint`.
+ rewrites: &[
+ (
+ concat!(
+ "Creating a writer does not access storage, so\n",
+ "depending on the service, a check against the stored file
fails while\n",
+ "writing or when closing the writer. Combining
`if_not_changed` with a\n",
+ "conflicting `ifMatch` or `if_version_match` fails before the
writer\n",
+ "exists, without accessing storage.",
+ ),
+ concat!(
+ "`writer()` and `writerSync()` do not access storage, so
depending on\n",
+ "the service, a check against the stored file fails the
returned\n",
+ "writer's `write()` or `close()`.",
+ ),
+ ),
+ (
+ concat!(
+ "A later stat returns this metadata when the service exposes
user metadata.\n",
+ "`crate::Reader::metadata` may omit it, for example on `fs`.",
+ ),
+ concat!(
+ "A later `stat()` or `statSync()` returns this metadata as
`userMetadata`\n",
+ "when the service exposes user metadata.",
+ ),
+ ),
+ (
+ concat!(
+ "`crate::Operator::write_with` and
`crate::Operator::write_options`\n",
+ "without `chunk` pass the whole buffer to the service writer
as one\n",
+ "write. A service that splits the buffer internally, such as
`fs` with\n",
+ "`direct_io` on Linux, can write the parts concurrently.",
+ ),
+ concat!(
+ "`write()` and `writeSync()` without `chunk` pass their
content to the\n",
+ "service writer as one write. A service that splits the
buffer\n",
+ "internally, such as `fs` with `direct_io` on Linux, can write
the\n",
+ "parts concurrently.",
+ ),
+ ),
+ (
+ "`0` has the same behavior as omitting it\n- When chunk size is
set:",
+ "`0n` has the same behavior as omitting it\n- When chunk size is
set:",
+ ),
+ ],
+};
+
/// Render model for one field of a napi options object.
#[derive(Serialize)]
struct OptionsField {
@@ -461,6 +531,7 @@ fn generate_options(workspace_dir: &Path) -> Result<()> {
&DELETE_OPTIONS,
&READ_OPTIONS,
&READER_OPTIONS,
+ &WRITE_OPTIONS,
] {
let rendered = render_options(&parsed, options, &capabilities)?;
fs::write(
@@ -660,6 +731,10 @@ fn js_type(name: &str, form: Js) -> JsType {
"the operation.",
],
},
+ Js::StringMap => infallible(
+ "Option<std::collections::HashMap<String, String>>",
+ format!("value.{name}"),
+ ),
Js::OffsetSize => JsType {
rs_type: "Option<napi::bindgen_prelude::BigInt>",
expr: "super::bytes_range(value.offset, value.size)?".to_string(),
@@ -766,21 +841,25 @@ 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`, 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. A core `range` has no single JS name, so it
-/// stays as written.
+/// field of these options like `start_after` or `ListOptions::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. 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> {
+ let field = code
+ .strip_prefix(options.name)
+ .and_then(|field| field.strip_prefix("::"))
+ .unwrap_or(code);
if let Some(&(name, ..)) = options
.fields
.iter()
- .find(|&&(name, form)| name == code && form != Js::OffsetSize)
+ .find(|&&(name, form)| name == field && form != Js::OffsetSize)
{
return Some(heck::AsLowerCamelCase(js_name(options,
name)).to_string());
}
@@ -906,12 +985,13 @@ mod tests {
doc
}
- const ALL_OPTIONS: [&JsOptions; 5] = [
+ const ALL_OPTIONS: [&JsOptions; 6] = [
&LIST_OPTIONS,
&STAT_OPTIONS,
&DELETE_OPTIONS,
&READ_OPTIONS,
&READER_OPTIONS,
+ &WRITE_OPTIONS,
];
#[test]
@@ -983,6 +1063,16 @@ mod tests {
"{err}"
);
+ for name in ["user_metadata", "if_not_exists"] {
+ let mut missing = core_options("WriteOptions");
+ missing.fields.retain(|field| field.name != name);
+ let err = render(missing, &WRITE_OPTIONS).unwrap_err().to_string();
+ assert!(
+ err.contains(&format!("WriteOptions 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
@@ -1084,6 +1174,38 @@ mod tests {
OptionKind::OptionString,
"ReaderOptions::if_unmodified_since is OptionString",
),
+ // The write `chunk` must stay a `bigint`, `concurrent` a checked
+ // count, `userMetadata` a string record, and the flags booleans.
+ (
+ &WRITE_OPTIONS,
+ "chunk",
+ OptionKind::OptionU64,
+ "WriteOptions::chunk is OptionU64",
+ ),
+ (
+ &WRITE_OPTIONS,
+ "concurrent",
+ OptionKind::OptionUsize,
+ "WriteOptions::concurrent is OptionUsize",
+ ),
+ (
+ &WRITE_OPTIONS,
+ "user_metadata",
+ OptionKind::OptionString,
+ "WriteOptions::user_metadata is OptionString",
+ ),
+ (
+ &WRITE_OPTIONS,
+ "if_not_exists",
+ OptionKind::OptionString,
+ "WriteOptions::if_not_exists is OptionString",
+ ),
+ (
+ &WRITE_OPTIONS,
+ "content_encoding",
+ OptionKind::OptionStringMap,
+ "WriteOptions::content_encoding is OptionStringMap",
+ ),
] {
let mut changed = core_options(options.name);
let field = changed.fields.iter_mut().find(|f| f.name ==
name).unwrap();
@@ -1139,6 +1261,46 @@ mod tests {
"{err}"
);
+ let mut reworded = core_options("WriteOptions");
+ let user_metadata = reworded
+ .fields
+ .iter_mut()
+ .find(|f| f.name == "user_metadata")
+ .unwrap();
+ for line in &mut user_metadata.doc {
+ *line = line.replace("A later stat returns", "A later lookup
returns");
+ }
+ let err = render(reworded, &WRITE_OPTIONS).unwrap_err().to_string();
+ assert!(
+ err.contains(
+ "WriteOptions docs no longer contain `A later stat returns
this metadata when \
+ the service exposes user metadata."
+ ),
+ "{err}"
+ );
+
+ // The write `chunk` is a `bigint`, but `concurrent` is a `number`, so
+ // only `chunk` reads `0n`.
+ let mut other = core_options("WriteOptions");
+ let concurrent = other
+ .fields
+ .iter_mut()
+ .find(|f| f.name == "concurrent")
+ .unwrap();
+ concurrent
+ .doc
+ .push("- `Some(0)` has the same behavior as `None`".to_string());
+ let rendered = render(other, &WRITE_OPTIONS).unwrap();
+ let concurrent = field_doc(&rendered, "concurrent");
+ assert!(
+ concurrent.contains(&"- `0` has the same behavior as omitting it"),
+ "{concurrent:?}"
+ );
+ assert!(
+ field_doc(&rendered, "chunk").contains(&"- `0n` has the same
behavior as omitting it"),
+ "{rendered}"
+ );
+
// A rewrite only changes the text it was written for, so the same
// words in another member's doc stay as core wrote them.
let mut other = core_options("ReaderOptions");
@@ -1213,6 +1375,104 @@ mod tests {
}
}
+ #[test]
+ fn test_write_options_docs_use_node_wording() {
+ let rendered = render(core_options("WriteOptions"),
&WRITE_OPTIONS).unwrap();
+ let struct_text = rendered[..rendered.find("#[napi(object)]").unwrap()]
+ .lines()
+ .filter_map(|line| line.strip_prefix("///"))
+ .map(str::trim)
+ .collect::<Vec<_>>()
+ .join(" ");
+ // A writer checks the options and capabilities when it is created,
+ // and a check against the stored file fails its `write()` or
+ // `close()`. JS has no `if_not_changed`.
+ assert!(
+ struct_text.contains(
+ "leaves the previously visible file unchanged. `writer()` and
`writerSync()` do \
+ not access storage, so depending on the service, a check
against the stored \
+ file fails the returned writer's `write()` or `close()`."
+ ),
+ "{struct_text}"
+ );
+ // JS readers return no metadata.
+ let user_metadata = field_doc(&rendered, "user_metadata").join(" ");
+ assert!(
+ user_metadata.ends_with(
+ "A later `stat()` or `statSync()` returns this metadata as
`userMetadata` when \
+ the service exposes user metadata."
+ ),
+ "{user_metadata}"
+ );
+ // A one-shot JS write without `chunk` reaches the service writer as
+ // one write. The service can split it internally for concurrent
writes.
+ let concurrent = field_doc(&rendered, "concurrent").join(" ");
+ assert!(
+ concurrent.contains(
+ "`write()` and `writeSync()` without `chunk` pass their
content to the service \
+ writer as one write. A service that splits the buffer
internally, such as \
+ `fs` with `direct_io` on Linux, can write the parts
concurrently."
+ ),
+ "{concurrent}"
+ );
+ // The write `chunk` is a `bigint`.
+ let chunk = field_doc(&rendered, "chunk").join(" ");
+ assert!(
+ chunk.contains("- `0n` has the same behavior as omitting it -"),
+ "{chunk}"
+ );
+ // Core links `if_not_exists` as a field of `WriteOptions`.
+ let if_none_match = field_doc(&rendered, "if_none_match").join(" ");
+ assert!(
+ if_none_match.contains(
+ "support `ifNotExists` but not `ifNoneMatch`; use
`ifNotExists` when you only"
+ ),
+ "{if_none_match}"
+ );
+ let docs: String = rendered
+ .lines()
+ .filter(|line| line.trim_start().starts_with("///"))
+ .collect();
+ for rust in [
+ "Creating a writer",
+ "if_not_changed",
+ "Reader::metadata",
+ "A later stat",
+ "crate::Operator",
+ "`0` has",
+ "WriteOptions::",
+ "if_not_exists",
+ ] {
+ assert!(!docs.contains(rust), "WriteOptions docs contain
`{rust}`");
+ }
+ }
+
+ #[test]
+ fn test_write_options_docs_keep_nested_lists() {
+ // Core nests list items under `When concurrent is set:` and others;
+ // napi-rs keeps the indentation in `generated.d.ts`.
+ let rendered = render(core_options("WriteOptions"),
&WRITE_OPTIONS).unwrap();
+ for expected in [
+ concat!(
+ " /// - When append is set to true:\n",
+ " /// - New data will be appended to the end of existing
file\n",
+ " /// - If file doesn't exist, it will be created\n",
+ " /// - If not supported, will return an error\n",
+ ),
+ concat!(
+ " /// - When concurrent is set:\n",
+ " /// - Multiple write operations can execute in
parallel\n",
+ ),
+ concat!(
+ " /// - When chunk size is set:\n",
+ " /// - Data will be buffered until reaching chunk
size\n",
+ ),
+ " /// - Important considerations:\n /// - Some services
require minimum chunk sizes,",
+ ] {
+ assert!(rendered.contains(expected), "missing `{expected}`");
+ }
+ }
+
#[test]
fn test_read_options_docs_use_node_wording() {
let rendered = render(core_options("ReadOptions"),
&READ_OPTIONS).unwrap();
@@ -1363,6 +1623,29 @@ mod tests {
"checksum",
][..],
),
+ (
+ &WRITE_OPTIONS,
+ &[
+ "append: Option<bool>,",
+ "chunk: Option<napi::bindgen_prelude::BigInt>,",
+ "content_type: Option<String>,",
+ "content_disposition: Option<String>,",
+ "cache_control: Option<String>,",
+ "content_encoding: Option<String>,",
+ "user_metadata: Option<std::collections::HashMap<String,
String>>,",
+ "if_match: Option<String>,",
+ "if_none_match: Option<String>,",
+ "if_not_exists: Option<bool>,",
+ "concurrent: Option<f64>,",
+ ][..],
+ &[
+ "content_language",
+ "expires",
+ "if_version_match",
+ "if_version_not_match",
+ "if_not_changed",
+ ][..],
+ ),
] {
let name = options.name;
let rendered = render(core_options(name), options).unwrap();
@@ -1487,6 +1770,40 @@ mod tests {
assert!(order.is_sorted(), "{order:?}");
}
+ #[test]
+ fn test_write_options_conversion() {
+ let rendered = render(core_options("WriteOptions"),
&WRITE_OPTIONS).unwrap();
+ assert!(
+ rendered.contains("impl TryFrom<WriteOptions> for
opendal::options::WriteOptions {")
+ );
+ // The conversion on main: strings and user metadata pass through,
+ // omitted flags are `false`, `concurrent` must be a count, `chunk`
+ // drops its sign and high bits, and `checksum` keeps its default.
+ for line in [
+ " append: value.append.unwrap_or_default(),\n",
+ " cache_control: value.cache_control,\n",
+ " content_type: value.content_type,\n",
+ " content_disposition: value.content_disposition,\n",
+ " content_encoding: value.content_encoding,\n",
+ " user_metadata: value.user_metadata,\n",
+ " if_match: value.if_match,\n",
+ " if_none_match: value.if_none_match,\n",
+ " if_not_exists:
value.if_not_exists.unwrap_or_default(),\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.get_u64().1 as
usize),\n",
+ " ..Default::default()\n })\n",
+ ] {
+ assert!(rendered.contains(line), "{line}");
+ }
+ assert!(!rendered.contains("checksum"));
+ }
+
#[test]
fn test_options_conversion_parses_timestamps() {
let stat = render(core_options("StatOptions"), &STAT_OPTIONS).unwrap();
@@ -1588,6 +1905,17 @@ mod tests {
js_doc(&lines, &STAT_OPTIONS, &core_capabilities()),
["Set `overrideContentType`, `chunk_size`, `range`, or `gap`."]
);
+
+ // A field written with its struct's name reads its JS name, while a
+ // field of another struct or an unknown one stays as written.
+ let lines = [
+ "Use `WriteOptions::if_not_exists`, `ReadOptions::chunk`, or
`WriteOptions::glob`."
+ .to_string(),
+ ];
+ assert_eq!(
+ js_doc(&lines, &WRITE_OPTIONS, &core_capabilities()),
+ ["Use `ifNotExists`, `ReadOptions::chunk`, or
`WriteOptions::glob`."]
+ );
}
#[test]
@@ -1744,6 +2072,11 @@ mod tests {
#[test]
fn test_options_docs_use_js_capability_names() {
let specification_link = "[conditional operation
specification](https://opendal.apache.org/docs/specifications/conditional-operations/)";
+ // The web references that core gives `cacheControl` stay as written.
+ let web_links = [
+ "[MDN
Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)",
+ "[RFC 7234 Section
5.2](https://tools.ietf.org/html/rfc7234#section-5.2)",
+ ];
// Core links each version or condition option to the capability that
// it requires.
for (options, expected) in [
@@ -1794,6 +2127,25 @@ mod tests {
("chunk", "`Capability.statWithIfModifiedSince`"),
][..],
),
+ (
+ &WRITE_OPTIONS,
+ &[
+ ("append", "`Capability.writeCanAppend`"),
+ ("chunk", "`Capability.writeMultiMinSize`"),
+ ("chunk", "`Capability.writeMultiMaxSize`"),
+ ("content_type", "`Capability.writeWithContentType`"),
+ (
+ "content_disposition",
+ "`Capability.writeWithContentDisposition`",
+ ),
+ ("cache_control", "`Capability.writeWithCacheControl`"),
+ ("content_encoding",
"`Capability.writeWithContentEncoding`"),
+ ("user_metadata", "`Capability.writeWithUserMetadata`"),
+ ("if_match", "`Capability.writeWithIfMatch`"),
+ ("if_none_match", "`Capability.writeWithIfNoneMatch`"),
+ ("if_not_exists", "`Capability.writeWithIfNotExists`"),
+ ][..],
+ ),
] {
let rendered = render(core_options(options.name),
options).unwrap();
for (name, capability) in expected {
@@ -1801,16 +2153,19 @@ mod tests {
assert!(doc.contains(capability), "{name}: {doc}");
}
assert!(rendered.contains(&format!("/// See the
{specification_link}\n")));
- // Rust capability paths and rustdoc link syntax stay out of the
generated docs.
+ // Rust capability paths and rustdoc link syntax stay out of the
+ // generated docs.
for line in rendered
.lines()
.filter(|l| l.trim_start().starts_with("///"))
{
assert!(!line.contains("Capability::"), "{line}");
- assert!(
- !line.replace(specification_link, "").contains('['),
- "{line}"
- );
+ let line = web_links
+ .iter()
+ .fold(line.replace(specification_link, ""), |line, link| {
+ line.replace(link, "")
+ });
+ assert!(!line.contains('['), "{line}");
}
}
}
@@ -1854,7 +2209,11 @@ mod tests {
/// 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> {
+ fn expected_js_paragraphs(
+ struct_name: &str,
+ 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()
@@ -1873,7 +2232,7 @@ mod tests {
.replace_all(&text, |c: ®ex::Captures| {
format!("`Capability.{}`", camel(&c[1]))
});
- let text = Regex::new(r"`(\w+)`")
+ let text = Regex::new(&format!(r"`(?:{struct_name}::)?(\w+)`"))
.unwrap()
.replace_all(&text, |c: ®ex::Captures| {
match names.iter().find(|(core, _)| *core == &c[1]) {
@@ -1946,6 +2305,38 @@ mod tests {
"`ifModifiedSince`; otherwise creating the reader fails
with",
),
],
+ "WriteOptions" => &[
+ (
+ "Creating a writer does not access storage, so depending
on the service, a \
+ check against the stored file fails while writing or when
closing the \
+ writer. Combining `if_not_changed` with a conflicting
`ifMatch` or \
+ `if_version_match` fails before the writer exists,
without accessing \
+ storage.",
+ "`writer()` and `writerSync()` do not access storage, so
depending on the \
+ service, a check against the stored file fails the
returned writer's \
+ `write()` or `close()`.",
+ ),
+ (
+ "A later stat returns this metadata when the service
exposes user metadata. \
+ `crate::Reader::metadata` may omit it, for example on
`fs`.",
+ "A later `stat()` or `statSync()` returns this metadata as
`userMetadata` \
+ when the service exposes user metadata.",
+ ),
+ (
+ "`crate::Operator::write_with` and
`crate::Operator::write_options` without \
+ `chunk` pass the whole buffer to the service writer as
one write. A \
+ service that splits the buffer internally, such as `fs`
with `direct_io` \
+ on Linux, can write the parts concurrently.",
+ "`write()` and `writeSync()` without `chunk` pass their
content to the \
+ service writer as one write. A service that splits the
buffer \
+ internally, such as `fs` with `direct_io` on Linux, can
write the \
+ parts concurrently.",
+ ),
+ (
+ "`0` has the same behavior as omitting it - When chunk
size is set:",
+ "`0n` has the same behavior as omitting it - When chunk
size is set:",
+ ),
+ ],
_ => &[],
};
paragraphs
@@ -2021,7 +2412,7 @@ mod tests {
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));
+ let expected = node_wording(name, expected_js_paragraphs(name,
&core.doc, &names));
assert!(!expected.is_empty(), "core `{name}` has no doc");
assert_eq!(paragraphs(struct_doc), expected, "doc of `{name}`");
@@ -2044,7 +2435,8 @@ mod tests {
.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));
+ let mut expected =
+ node_wording(name, expected_js_paragraphs(name,
doc, &names));
match form {
Js::Timestamp =>
expected.push(timestamp_note.to_string()),
Js::Count => expected.push(count_note.to_string()),