This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/fix-nodejs-concurrent-limit-and-timestamp-options in repository https://gitbox.apache.org/repos/asf/opendal.git
commit 37bd6d0eb2a4fc299a6cb5b615c7c9f4ca50ce1a Author: Xuanwo <[email protected]> AuthorDate: Mon Nov 23 10:21:13 2026 +0100 fix(bindings/nodejs): reject invalid permits and conditional timestamps `ConcurrentLimitLayer` cast `permits` and `httpPermits` to `usize` without checking them. Zero permits built a semaphore that never hands out a permit, so every operation on the layer hung forever, and a negative value wrapped to `usize::MAX` and silently disabled the limit. Validate both values in the constructor and in the setter, so an invalid count fails eagerly with `InvalidArg` instead of hanging or weakening the limit. `StatOptions`, `ReadOptions`, and `ReaderOptions` parsed `ifModifiedSince` and `ifUnmodifiedSince` with `.ok()`, which dropped every unparsable timestamp and ran the operation unconditionally. Report a parse failure as `InvalidArg`, and convert `StatOptions` with `TryFrom` so `stat` and `statSync` surface it. The TypeScript signatures are unchanged; keeping the parsed counts as `usize` in `ConcurrentLimitLayer` only moves validation from `build()` to the constructor and the setter. --- bindings/nodejs/generated.d.ts | 8 +++++ bindings/nodejs/src/layer.rs | 51 ++++++++++++++++++++++------- bindings/nodejs/src/lib.rs | 10 ++++-- bindings/nodejs/src/options.rs | 41 +++++++++++++++++------ bindings/nodejs/tests/layer.test.mjs | 34 ++++++++++++++++++- bindings/nodejs/tests/options.test.mjs | 60 ++++++++++++++++++++++++++++++++++ 6 files changed, 180 insertions(+), 24 deletions(-) diff --git a/bindings/nodejs/generated.d.ts b/bindings/nodejs/generated.d.ts index 9bad0bbff6..2e9fa9690f 100644 --- a/bindings/nodejs/generated.d.ts +++ b/bindings/nodejs/generated.d.ts @@ -257,6 +257,10 @@ export declare class ConcurrentLimitLayer { * # Arguments * * * `permits` - The maximum number of concurrent operations allowed. + * + * # Errors + * + * Returns an error if `permits` is not greater than 0. */ constructor(permits: number) /** @@ -267,6 +271,10 @@ export declare class ConcurrentLimitLayer { * # Arguments * * * `v` - The maximum number of concurrent HTTP requests allowed. + * + * # Errors + * + * Returns an error if `v` is not greater than 0. */ set httpPermits(v: number) /** diff --git a/bindings/nodejs/src/layer.rs b/bindings/nodejs/src/layer.rs index b131a20fa4..caf411253f 100644 --- a/bindings/nodejs/src/layer.rs +++ b/bindings/nodejs/src/layer.rs @@ -189,6 +189,27 @@ impl NodeLayer for opendal::layers::ConcurrentLimitLayer { } } +/// Validate a permit count received from JavaScript. +/// +/// Zero permits block every operation forever, and negative values wrap to +/// `usize::MAX` and silently disable the limit, so only positive counts that +/// fit in `usize` are accepted. +fn parse_permits(value: i64, field: &str) -> Result<usize> { + if value <= 0 { + return Err(Error::new( + Status::InvalidArg, + format!("{field} must be greater than 0"), + )); + } + + usize::try_from(value).map_err(|_| { + Error::new( + Status::InvalidArg, + format!("{field} must not be greater than {}", usize::MAX), + ) + }) +} + /// Concurrent limit layer /// /// Add concurrent request limit. @@ -219,8 +240,8 @@ impl NodeLayer for opendal::layers::ConcurrentLimitLayer { /// ``` #[napi] pub struct ConcurrentLimitLayer { - permits: i64, - http_permits: Option<i64>, + permits: usize, + http_permits: Option<usize>, } #[napi] @@ -232,12 +253,16 @@ impl ConcurrentLimitLayer { /// # Arguments /// /// * `permits` - The maximum number of concurrent operations allowed. + /// + /// # Errors + /// + /// Returns an error if `permits` is not greater than 0. #[napi(constructor)] - pub fn new(permits: i64) -> Self { - Self { - permits, + pub fn new(permits: i64) -> Result<Self> { + Ok(Self { + permits: parse_permits(permits, "permits")?, http_permits: None, - } + }) } /// Set a concurrent limit for HTTP requests. @@ -247,9 +272,14 @@ impl ConcurrentLimitLayer { /// # Arguments /// /// * `v` - The maximum number of concurrent HTTP requests allowed. + /// + /// # Errors + /// + /// Returns an error if `v` is not greater than 0. #[napi(setter)] - pub fn http_permits(&mut self, v: i64) { - self.http_permits = Some(v); + pub fn http_permits(&mut self, v: i64) -> Result<()> { + self.http_permits = Some(parse_permits(v, "httpPermits")?); + Ok(()) } /// Build the layer. @@ -257,11 +287,10 @@ impl ConcurrentLimitLayer { /// Returns an `External<Layer>` that can be used with `Operator.layer()`. #[napi] pub fn build(&self) -> External<Layer> { - let permits = self.permits; - let mut l = opendal::layers::ConcurrentLimitLayer::new(permits as usize); + let mut l = opendal::layers::ConcurrentLimitLayer::new(self.permits); if let Some(http_permits) = self.http_permits { - l = l.with_http_concurrent_limit(http_permits as usize); + l = l.with_http_concurrent_limit(http_permits); } External::new(Layer { inner: Box::new(l) }) diff --git a/bindings/nodejs/src/lib.rs b/bindings/nodejs/src/lib.rs index 351351d608..84cec53cf0 100644 --- a/bindings/nodejs/src/lib.rs +++ b/bindings/nodejs/src/lib.rs @@ -127,7 +127,10 @@ impl Operator { path: String, options: Option<options::StatOptions>, ) -> Result<Metadata> { - let options = options.map_or_else(StatOptions::default, StatOptions::from); + let options = match options { + Some(options) => StatOptions::try_from(options)?, + None => StatOptions::default(), + }; let meta = self .async_op .stat_options(&path, options) @@ -152,7 +155,10 @@ impl Operator { path: String, options: Option<options::StatOptions>, ) -> Result<Metadata> { - let options = options.map_or_else(StatOptions::default, StatOptions::from); + let options = match options { + Some(options) => StatOptions::try_from(options)?, + None => StatOptions::default(), + }; let meta = self .blocking_op .stat_options(&path, options) diff --git a/bindings/nodejs/src/options.rs b/bindings/nodejs/src/options.rs index 6e2fedbe0a..8094dfcc16 100644 --- a/bindings/nodejs/src/options.rs +++ b/bindings/nodejs/src/options.rs @@ -58,6 +58,19 @@ fn bigint_to_usize(value: &BigInt, field: &str) -> napi::Result<usize> { }) } +/// Parse a conditional request timestamp received from JavaScript. +/// +/// Dropping an unparsable value would silently turn a conditional read or stat +/// into an unconditional one, so an invalid timestamp is reported instead. +fn parse_timestamp(value: &str, field: &str) -> napi::Result<Timestamp> { + value.parse::<Timestamp>().map_err(|_| { + napi::Error::new( + Status::InvalidArg, + format!("{field} must be an ISO 8601 timestamp, for example 2024-01-01T00:00:00Z"), + ) + }) +} + #[napi(object)] #[derive(Debug)] pub struct StatOptions { @@ -114,16 +127,20 @@ pub struct StatOptions { pub override_content_disposition: Option<String>, } -impl From<StatOptions> for opendal::options::StatOptions { - fn from(value: StatOptions) -> Self { +impl TryFrom<StatOptions> for opendal::options::StatOptions { + type Error = napi::Error; + + fn try_from(value: StatOptions) -> napi::Result<Self> { let if_modified_since = value .if_modified_since - .and_then(|v| v.parse::<Timestamp>().ok()); + .map(|v| parse_timestamp(&v, "ifModifiedSince")) + .transpose()?; let if_unmodified_since = value .if_unmodified_since - .and_then(|v| v.parse::<Timestamp>().ok()); + .map(|v| parse_timestamp(&v, "ifUnmodifiedSince")) + .transpose()?; - Self { + Ok(Self { if_modified_since, if_unmodified_since, version: value.version, @@ -133,7 +150,7 @@ impl From<StatOptions> for opendal::options::StatOptions { override_cache_control: value.override_cache_control, override_content_disposition: value.override_content_disposition, ..Default::default() - } + }) } } @@ -267,10 +284,12 @@ impl TryFrom<ReadOptions> for opendal::options::ReadOptions { let range = value.make_range()?; let if_modified_since = value .if_modified_since - .and_then(|v| v.parse::<Timestamp>().ok()); + .map(|v| parse_timestamp(&v, "ifModifiedSince")) + .transpose()?; let if_unmodified_since = value .if_unmodified_since - .and_then(|v| v.parse::<Timestamp>().ok()); + .map(|v| parse_timestamp(&v, "ifUnmodifiedSince")) + .transpose()?; let gap = value .gap @@ -391,10 +410,12 @@ impl TryFrom<ReaderOptions> for opendal::options::ReaderOptions { fn try_from(value: ReaderOptions) -> napi::Result<Self> { let if_modified_since = value .if_modified_since - .and_then(|v| v.parse::<Timestamp>().ok()); + .map(|v| parse_timestamp(&v, "ifModifiedSince")) + .transpose()?; let if_unmodified_since = value .if_unmodified_since - .and_then(|v| v.parse::<Timestamp>().ok()); + .map(|v| parse_timestamp(&v, "ifUnmodifiedSince")) + .transpose()?; let gap = value .gap .as_ref() diff --git a/bindings/nodejs/tests/layer.test.mjs b/bindings/nodejs/tests/layer.test.mjs index e85362557f..175fabf789 100644 --- a/bindings/nodejs/tests/layer.test.mjs +++ b/bindings/nodejs/tests/layer.test.mjs @@ -19,7 +19,7 @@ import { assert, test } from 'vitest' -import { ThrottleLayer } from '../index.mjs' +import { ConcurrentLimitLayer, ThrottleLayer } from '../index.mjs' function assertInvalidArgument(createLayer, field) { let error @@ -52,3 +52,35 @@ test('ThrottleLayer accepts positive bandwidth and burst', () => { const layer = new ThrottleLayer(1024, 2048) assert.ok(layer.build()) }) + +// A zero-permit semaphore never hands out a permit, so every operation hangs +// forever, and a negative permit count wraps to usize::MAX and disables the +// limit instead of failing. +const invalidPermits = [0, -1] + +for (const permits of invalidPermits) { + test(`ConcurrentLimitLayer rejects ${permits} permits`, () => { + assertInvalidArgument(() => new ConcurrentLimitLayer(permits), 'permits') + }) + + test(`ConcurrentLimitLayer rejects ${permits} httpPermits`, () => { + const layer = new ConcurrentLimitLayer(1024) + assertInvalidArgument(() => { + layer.httpPermits = permits + }, 'httpPermits') + }) +} + +test('ConcurrentLimitLayer accepts positive permits', () => { + const layer = new ConcurrentLimitLayer(1024) + layer.httpPermits = 512 + assert.ok(layer.build()) +}) + +test('ConcurrentLimitLayer stays usable after a rejected httpPermits', () => { + const layer = new ConcurrentLimitLayer(1024) + assert.throws(() => { + layer.httpPermits = 0 + }) + assert.ok(layer.build()) +}) diff --git a/bindings/nodejs/tests/options.test.mjs b/bindings/nodejs/tests/options.test.mjs index ddc8dce6e9..fa15c0ba27 100644 --- a/bindings/nodejs/tests/options.test.mjs +++ b/bindings/nodejs/tests/options.test.mjs @@ -131,3 +131,63 @@ describe('bigint options', () => { }) }) }) + +// An unparsable timestamp used to be dropped, so the conditional read, stat, +// or reader silently ran unconditionally instead of reporting the mistake. +const invalidTimestamps = ['not-a-date', new Date(0).toUTCString()] + +// Return the error a promise rejects with, or undefined when it resolves. +async function settle(promise) { + try { + await promise + return undefined + } catch (err) { + return err + } +} + +describe('conditional timestamps', () => { + const op = new Operator('memory') + + beforeEach(async () => { + await op.write(path, content) + }) + + for (const field of ['ifModifiedSince', 'ifUnmodifiedSince']) { + for (const value of invalidTimestamps) { + it(`read rejects an invalid ${field} (${value})`, async () => { + await expect(op.read(path, { [field]: value })).rejects.toThrowError(`${field} must be an ISO 8601`) + }) + + it(`readSync rejects an invalid ${field} (${value})`, () => { + expect(() => op.readSync(path, { [field]: value })).toThrowError(`${field} must be an ISO 8601`) + }) + + it(`reader rejects an invalid ${field} (${value})`, async () => { + await expect(op.reader(path, { [field]: value })).rejects.toThrowError(`${field} must be an ISO 8601`) + }) + + it(`readerSync rejects an invalid ${field} (${value})`, () => { + expect(() => op.readerSync(path, { [field]: value })).toThrowError(`${field} must be an ISO 8601`) + }) + + it(`stat rejects an invalid ${field} (${value})`, async () => { + await expect(op.stat(path, { [field]: value })).rejects.toThrowError(`${field} must be an ISO 8601`) + }) + + it(`statSync rejects an invalid ${field} (${value})`, () => { + expect(() => op.statSync(path, { [field]: value })).toThrowError(`${field} must be an ISO 8601`) + }) + } + } + + it('accepts an ISO 8601 timestamp', async () => { + // The memory service does not support conditional reads and stats, so the + // option must reach the service instead of being rejected as malformed. + const readError = await settle(op.read(path, { ifModifiedSince: '2024-01-01T00:00:00Z' })) + expect(String(readError?.message ?? '')).not.toMatch('must be an ISO 8601') + + const statError = await settle(op.stat(path, { ifUnmodifiedSince: '2024-01-01T00:00:00Z' })) + expect(String(statError?.message ?? '')).not.toMatch('must be an ISO 8601') + }) +})
