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 291ec40408 feat(bindings/nodejs): expose WriteOptions expires and
content_language from core (#9417)
291ec40408 is described below
commit 291ec40408e3f4c26bf45f1029d0939bf66f1506
Author: Chitral Verma <[email protected]>
AuthorDate: Mon Nov 30 10:02:57 2026 +0530
feat(bindings/nodejs): expose WriteOptions expires and content_language
from core (#9417)
* feat(bindings/nodejs): expose WriteOptions expires and content_language
from core
Signed-off-by: Chitral Verma <[email protected]>
* test(bindings/nodejs): keep one contentLanguage test and widen the
expires margin
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
bindings/nodejs/generated.d.ts | 24 +++++++
bindings/nodejs/src/options/write.rs | 29 +++++++-
bindings/nodejs/src/validate.rs | 7 +-
.../tests/suites/asyncWriteOptions.suite.mjs | 12 ++++
.../nodejs/tests/suites/syncWriteOptions.suite.mjs | 12 ++++
.../nodejs/tests/write-options-surface.test.mjs | 21 ++++--
dev/src/generate/nodejs.rs | 77 ++++++++++++++++++----
7 files changed, 159 insertions(+), 23 deletions(-)
diff --git a/bindings/nodejs/generated.d.ts b/bindings/nodejs/generated.d.ts
index f04eba6e67..5eb5fbaf5d 100644
--- a/bindings/nodejs/generated.d.ts
+++ b/bindings/nodejs/generated.d.ts
@@ -2021,4 +2021,28 @@ export interface WriteOptions {
* The value must be an integer between 0 and 4294967295.
*/
concurrent?: number
+ /**
+ * Sets Content-Language system metadata on the object being written.
+ *
+ * Use a language tag or a comma-separated list of tags, such as `fr-CA, en`.
+ * Check `Capability.writeWithContentLanguage` for support. A
+ * subsequent `stat()` or `statSync()` can retrieve the stored value as
+ * `contentLanguage`.
+ * Services without support may ignore this option.
+ */
+ contentLanguage?: string
+ /**
+ * Sets how long the new file lives after the write commits.
+ *
+ * A supplied duration overrides the service's default TTL. When unset,
+ * the service uses its usual expiration policy. Services round positive
+ * durations up to their supported precision.
+ *
+ * Returns an error whose message includes `Unsupported` when the service
does not
+ * advertise `Capability.writeWithExpires`. A duration that
+ * the service cannot represent produces an error whose message includes
`ConfigInvalid`.
+ *
+ * The unit is seconds. The value must be an integer between 1 and
4294967295.
+ */
+ expires?: number
}
diff --git a/bindings/nodejs/src/options/write.rs
b/bindings/nodejs/src/options/write.rs
index 773158179d..c54edaa8d6 100644
--- a/bindings/nodejs/src/options/write.rs
+++ b/bindings/nodejs/src/options/write.rs
@@ -269,6 +269,28 @@ pub struct WriteOptions {
///
/// The value must be an integer between 0 and 4294967295.
pub concurrent: Option<f64>,
+
+ /// Sets Content-Language system metadata on the object being written.
+ ///
+ /// Use a language tag or a comma-separated list of tags, such as `fr-CA,
en`.
+ /// Check `Capability.writeWithContentLanguage` for support. A
+ /// subsequent `stat()` or `statSync()` can retrieve the stored value as
+ /// `contentLanguage`.
+ /// Services without support may ignore this option.
+ pub content_language: Option<String>,
+
+ /// Sets how long the new file lives after the write commits.
+ ///
+ /// A supplied duration overrides the service's default TTL. When unset,
+ /// the service uses its usual expiration policy. Services round positive
+ /// durations up to their supported precision.
+ ///
+ /// Returns an error whose message includes `Unsupported` when the service
does not
+ /// advertise `Capability.writeWithExpires`. A duration that
+ /// the service cannot represent produces an error whose message includes
`ConfigInvalid`.
+ ///
+ /// The unit is seconds. The value must be an integer between 1 and
4294967295.
+ pub expires: Option<f64>,
}
impl TryFrom<WriteOptions> for opendal::options::WriteOptions {
@@ -281,9 +303,12 @@ impl TryFrom<WriteOptions> for
opendal::options::WriteOptions {
content_type: value.content_type,
content_disposition: value.content_disposition,
content_encoding: value.content_encoding,
- content_language: Default::default(),
+ content_language: value.content_language,
user_metadata: value.user_metadata,
- expires: Default::default(),
+ expires: value
+ .expires
+ .map(crate::validate::parse_expires_secs)
+ .transpose()?,
if_match: value.if_match,
if_none_match: value.if_none_match,
if_version_match: Default::default(),
diff --git a/bindings/nodejs/src/validate.rs b/bindings/nodejs/src/validate.rs
index e01d8a67f3..834acaa854 100644
--- a/bindings/nodejs/src/validate.rs
+++ b/bindings/nodejs/src/validate.rs
@@ -39,11 +39,12 @@ pub(crate) fn parse_count(value: f64, field: &str, min:
u32) -> Result<usize> {
Ok(value as usize)
}
-/// Parse the `expires` argument of a presign call, which is given in seconds.
+/// Parse an `expires` value in seconds, as the presign methods and
+/// `WriteOptions.expires` take it.
///
/// The value must be a whole number of seconds between 1 and 4294967295.
-/// N-API used to wrap a negative value into a request that stays valid for
-/// more than a century, so an invalid expiry is reported instead.
+/// N-API wraps a negative value into an expiry of more than a century, so
+/// an invalid expiry is reported instead.
pub(crate) fn parse_expires_secs(value: f64) -> Result<Duration> {
let seconds = parse_count(value, "expires", 1)?;
Ok(Duration::from_secs(seconds as u64))
diff --git a/bindings/nodejs/tests/suites/asyncWriteOptions.suite.mjs
b/bindings/nodejs/tests/suites/asyncWriteOptions.suite.mjs
index 730e536ccd..ed6bb1075e 100644
--- a/bindings/nodejs/tests/suites/asyncWriteOptions.suite.mjs
+++ b/bindings/nodejs/tests/suites/asyncWriteOptions.suite.mjs
@@ -18,6 +18,7 @@
*/
import { randomUUID } from 'node:crypto'
+import { setTimeout } from 'node:timers/promises'
import { test, describe, expect, assert } from 'vitest'
import { EntryMode, Metadata } from '../../index.mjs'
@@ -144,6 +145,17 @@ export function run(op) {
await op.delete(filename)
})
+ test.runIf(capability.writeWithExpires)('write with expires', async () => {
+ const filename = `random_file_${randomUUID()}`
+
+ // `expires` is in seconds, so the file outlives 500 ms and expires
+ // within a few seconds.
+ await op.write(filename, generateBytes(), { expires: 3 })
+ await setTimeout(500)
+ expect(await op.exists(filename)).toBe(true)
+ await expect.poll(() => op.exists(filename), { timeout: 5000, interval:
100 }).toBe(false)
+ })
+
test.runIf(capability.writeWithIfMatch)('write with if match', async () =>
{
const filenameA = `random_file_${randomUUID()}`
const filenameB = `random_file_${randomUUID()}`
diff --git a/bindings/nodejs/tests/suites/syncWriteOptions.suite.mjs
b/bindings/nodejs/tests/suites/syncWriteOptions.suite.mjs
index f777ac55aa..7c4448f8be 100644
--- a/bindings/nodejs/tests/suites/syncWriteOptions.suite.mjs
+++ b/bindings/nodejs/tests/suites/syncWriteOptions.suite.mjs
@@ -18,6 +18,7 @@
*/
import { randomUUID } from 'node:crypto'
+import { setTimeout } from 'node:timers/promises'
import { test, describe, expect, assert } from 'vitest'
import { EntryMode, Metadata } from '../../index.mjs'
@@ -144,6 +145,17 @@ export function run(op) {
op.deleteSync(filename)
})
+ test.runIf(capability.writeWithExpires)('write with expires', async () => {
+ const filename = `random_file_${randomUUID()}`
+
+ // `expires` is in seconds, so the file outlives 500 ms and expires
+ // within a few seconds.
+ op.writeSync(filename, generateBytes(), { expires: 3 })
+ await setTimeout(500)
+ expect(op.existsSync(filename)).toBe(true)
+ await expect.poll(() => op.existsSync(filename), { timeout: 5000,
interval: 100 }).toBe(false)
+ })
+
test.runIf(capability.writeWithIfMatch)('write with if match', () => {
const filenameA = `random_file_${randomUUID()}`
const filenameB = `random_file_${randomUUID()}`
diff --git a/bindings/nodejs/tests/write-options-surface.test.mjs
b/bindings/nodejs/tests/write-options-surface.test.mjs
index 6e5020368f..95cda56ef8 100644
--- a/bindings/nodejs/tests/write-options-surface.test.mjs
+++ b/bindings/nodejs/tests/write-options-surface.test.mjs
@@ -26,11 +26,10 @@ 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.
+// `WriteOptions` and the write methods as `generated.d.ts` declares them.
+// 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
@@ -48,6 +47,8 @@ const FROZEN_MEMBERS = [
['ifNoneMatch?: string', '"etag"', 'if_none_match', 'writeWithIfNoneMatch'],
['ifNotExists?: boolean', true, 'if_not_exists', 'writeWithIfNotExists'],
['concurrent?: number', 4, 'concurrent', null],
+ ['contentLanguage?: string', 'fr-CA, en', 'content_language', null],
+ ['expires?: number', 60, 'expires', 'writeWithExpires'],
]
const FROZEN_SIGNATURES = [
@@ -140,6 +141,7 @@ describe('WriteOptions keeps its historical surface', () =>
{
contentDisposition: 'attachment; filename="probe.txt"',
cacheControl: 'max-age=60',
contentEncoding: 'identity',
+ contentLanguage: 'fr-CA, en',
userMetadata,
})
// `stat` and `statSync` return what the write stored.
@@ -148,6 +150,7 @@ describe('WriteOptions keeps its historical surface', () =>
{
assert.equal(metadata.contentDisposition, 'attachment;
filename="probe.txt"')
assert.equal(metadata.cacheControl, 'max-age=60')
assert.equal(metadata.contentEncoding, 'identity')
+ assert.equal(metadata.contentLanguage, 'fr-CA, en')
assert.deepEqual(metadata.userMetadata, userMetadata)
}
})
@@ -186,6 +189,14 @@ describe('WriteOptions keeps its historical surface', ()
=> {
)
}
})
+
+ test(`${method} rejects an invalid expires as presign does`, async () => {
+ for (const expires of [0, 1.5, -1, 2 ** 32]) {
+ await expect(write(op, fresh(), content, { expires
})).rejects.toThrowError(
+ 'expires must be an integer between 1 and 4294967295',
+ )
+ }
+ })
}
test('writer and writerSync check options without accessing storage', async
() => {
diff --git a/dev/src/generate/nodejs.rs b/dev/src/generate/nodejs.rs
index 17ace3090c..d33818b3ea 100644
--- a/dev/src/generate/nodejs.rs
+++ b/dev/src/generate/nodejs.rs
@@ -222,6 +222,9 @@ enum Js {
Timestamp,
/// An `Option<HashMap<String, String>>` as a `Record<string, string>`.
StringMap,
+ /// An `Option<Duration>` as a `number` of seconds that
+ /// `parse_expires_secs` checks, like the `expires` of the presign methods.
+ Seconds,
/// A `BytesRange` as the `offset` and `size` `bigint`s, which
/// `bigint_to_u64` checks.
OffsetSize,
@@ -237,6 +240,7 @@ impl Js {
Js::Count | Js::U32OrZero => OptionKind::Usize,
Js::Timestamp => OptionKind::OptionTimestamp,
Js::StringMap => OptionKind::OptionStringMap,
+ Js::Seconds => OptionKind::OptionDuration,
Js::OffsetSize => OptionKind::BytesRange,
}
}
@@ -451,12 +455,15 @@ const WRITE_OPTIONS: JsOptions = JsOptions {
("if_none_match", Js::String),
("if_not_exists", Js::Bool),
("concurrent", Js::Count),
+ ("content_language", Js::String),
+ ("expires", Js::Seconds),
],
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`.
+ // reader metadata, the write `chunk` is a `bigint`, and a zero `expires`
+ // fails in the binding before core sees it.
rewrites: &[
(
concat!(
@@ -500,6 +507,14 @@ const WRITE_OPTIONS: JsOptions = JsOptions {
"`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:",
),
+ (
+ "A\nsubsequent stat can retrieve the stored value with
`Metadata::content_language`.",
+ "A\nsubsequent `stat()` or `statSync()` can retrieve the stored
value as\n`contentLanguage`.",
+ ),
+ (
+ "A zero or\nunrepresentable duration produces",
+ "A duration that\nthe service cannot represent produces",
+ ),
],
};
@@ -743,6 +758,16 @@ fn js_type(name: &str, form: Js) -> JsType {
"Option<std::collections::HashMap<String, String>>",
format!("value.{name}"),
),
+ Js::Seconds => JsType {
+ rs_type: "Option<f64>",
+ expr: format!(
+ "value\n .{name}\n \
+ .map(crate::validate::parse_expires_secs)\n \
+ .transpose()?"
+ ),
+ fallible: true,
+ note: &["The unit is seconds. The value must be an integer between
1 and 4294967295."],
+ },
Js::OffsetSize => JsType {
rs_type: "Option<napi::bindgen_prelude::BigInt>",
expr: "super::bytes_range(value.offset, value.size)?".to_string(),
@@ -1215,6 +1240,13 @@ mod tests {
OptionKind::OptionStringMap,
"WriteOptions::content_encoding is OptionStringMap",
),
+ // `expires` must stay a duration in seconds.
+ (
+ &WRITE_OPTIONS,
+ "expires",
+ OptionKind::OptionU64,
+ "WriteOptions::expires is OptionU64",
+ ),
] {
let mut changed = core_options(options.name);
let field = changed.fields.iter_mut().find(|f| f.name ==
name).unwrap();
@@ -1556,8 +1588,8 @@ mod tests {
#[test]
fn test_options_keep_existing_js_fields() {
- // The members and order of each struct in `generated.d.ts` on main,
- // and the core fields that JS does not expose.
+ // The members and order of each struct in `generated.d.ts`, and the
+ // core fields that JS does not expose.
for (options, expected, unexposed) in [
(
&STAT_OPTIONS,
@@ -1646,14 +1678,10 @@ mod tests {
"if_none_match: Option<String>,",
"if_not_exists: Option<bool>,",
"concurrent: Option<f64>,",
+ "content_language: Option<String>,",
+ "expires: Option<f64>,",
][..],
- &[
- "content_language",
- "expires",
- "if_version_match",
- "if_version_not_match",
- "if_not_changed",
- ][..],
+ &["if_version_match", "if_version_not_match",
"if_not_changed"][..],
),
] {
let name = options.name;
@@ -1785,11 +1813,19 @@ mod tests {
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.
+ // Strings and user metadata pass through, omitted flags are `false`,
+ // `concurrent` must be a count, `chunk` drops its sign and high bits,
+ // `expires` is checked as presign checks it, and `checksum` keeps its
+ // default.
for line in [
" append: value.append.unwrap_or_default(),\n",
+ " content_language: value.content_language,\n",
+ concat!(
+ " expires: value\n",
+ " .expires\n",
+ " .map(crate::validate::parse_expires_secs)\n",
+ " .transpose()?,\n",
+ ),
" cache_control: value.cache_control,\n",
" content_type: value.content_type,\n",
" content_disposition: value.content_disposition,\n",
@@ -2155,6 +2191,8 @@ mod tests {
("if_match", "`Capability.writeWithIfMatch`"),
("if_none_match", "`Capability.writeWithIfNoneMatch`"),
("if_not_exists", "`Capability.writeWithIfNotExists`"),
+ ("content_language",
"`Capability.writeWithContentLanguage`"),
+ ("expires", "`Capability.writeWithExpires`"),
][..],
),
] {
@@ -2354,6 +2392,16 @@ mod tests {
"`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:",
),
+ (
+ "A subsequent stat can retrieve the stored value with \
+ `Metadata::content_language`.",
+ "A subsequent `stat()` or `statSync()` can retrieve the
stored value as \
+ `contentLanguage`.",
+ ),
+ (
+ "A zero or unrepresentable duration produces",
+ "A duration that the service cannot represent produces",
+ ),
],
_ => &[],
};
@@ -2374,6 +2422,8 @@ mod tests {
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.";
+ let seconds_note =
+ "The unit is seconds. The value must be an integer between 1 and
4294967295.";
// Members whose core doc does not hold for JS, with their JS doc.
let js_only: &[(&str, &str, &[&str])] = &[
(
@@ -2458,6 +2508,7 @@ mod tests {
match form {
Js::Timestamp =>
expected.push(timestamp_note.to_string()),
Js::Count => expected.push(count_note.to_string()),
+ Js::Seconds =>
expected.push(seconds_note.to_string()),
_ => {}
}
expected