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 c59c86fbe1 fix(bindings/nodejs): serialize Writer and Lister async 
calls (#8752)
c59c86fbe1 is described below

commit c59c86fbe13a79c9b4c639ec605acc56b4d4ad23
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 07:36:31 2026 +0800

    fix(bindings/nodejs): serialize Writer and Lister async calls (#8752)
---
 bindings/nodejs/generated.d.ts               | 17 +++-------
 bindings/nodejs/src/lib.rs                   | 49 ++++++++++++++--------------
 bindings/nodejs/tests/suites/async.suite.mjs | 40 +++++++++++++++++++++++
 3 files changed, 69 insertions(+), 37 deletions(-)

diff --git a/bindings/nodejs/generated.d.ts b/bindings/nodejs/generated.d.ts
index 973a933a78..df7d9dd9c8 100644
--- a/bindings/nodejs/generated.d.ts
+++ b/bindings/nodejs/generated.d.ts
@@ -298,12 +298,9 @@ export declare class Layer {
  */
 export declare class Lister {
   /**
-   * # Safety
-   *
-   * > &mut self in async napi methods should be marked as unsafe
+   * Return the next entry, or `null` when the lister is exhausted.
    *
-   * napi will make sure the function is safe, and we didn't do unsafe
-   * things internally.
+   * Concurrent calls are serialized, so each entry is returned exactly once.
    */
   next(): Promise<Entry | null>
 }
@@ -1071,12 +1068,10 @@ export declare class TimeoutLayer {
  */
 export declare class Writer {
   /**
-   * # Safety
-   *
-   * > &mut self in async napi methods should be marked as unsafe
-   *
    * Write bytes into this writer.
    *
+   * Concurrent calls are serialized in the order they acquire the lock.
+   *
    * ### Example
    * ```javascript
    * const writer = await op.writer("path/to/file");
@@ -1086,10 +1081,6 @@ export declare class Writer {
    */
   write(content: Buffer | string): Promise<void>
   /**
-   * # Safety
-   *
-   * > &mut self in async napi methods should be marked as unsafe
-   *
    * Close this writer.
    *
    * ### Example
diff --git a/bindings/nodejs/src/lib.rs b/bindings/nodejs/src/lib.rs
index 0ec2d59bcb..030c818e58 100644
--- a/bindings/nodejs/src/lib.rs
+++ b/bindings/nodejs/src/lib.rs
@@ -363,7 +363,9 @@ impl Operator {
             .writer_options(&path, options.into())
             .await
             .map_err(format_napi_error)?;
-        Ok(Writer(writer))
+        Ok(Writer {
+            inner: Mutex::new(writer),
+        })
     }
 
     /// Write multiple bytes into a path synchronously.
@@ -718,7 +720,9 @@ impl Operator {
             .await
             .map_err(format_napi_error)?;
 
-        Ok(Lister(l))
+        Ok(Lister {
+            inner: Mutex::new(l),
+        })
     }
 
     /// Create a lister to list entries at given path synchronously.
@@ -1162,16 +1166,16 @@ impl BlockingWriter {
 /// Writer is designed to write data into a given path in an asynchronous
 /// manner.
 #[napi]
-pub struct Writer(opendal::Writer);
+pub struct Writer {
+    inner: Mutex<opendal::Writer>,
+}
 
 #[napi]
 impl Writer {
-    /// # Safety
-    ///
-    /// > &mut self in async napi methods should be marked as unsafe
-    ///
     /// Write bytes into this writer.
     ///
+    /// Concurrent calls are serialized in the order they acquire the lock.
+    ///
     /// ### Example
     /// ```javascript
     /// const writer = await op.writer("path/to/file");
@@ -1179,18 +1183,15 @@ impl Writer {
     /// await writer.close();
     /// ```
     #[napi]
-    pub async unsafe fn write(&mut self, content: Either<Buffer, String>) -> 
Result<()> {
+    pub async fn write(&self, content: Either<Buffer, String>) -> Result<()> {
         let c = match content {
             Either::A(buf) => buf.as_ref().to_owned(),
             Either::B(s) => s.into_bytes(),
         };
-        self.0.write(c).await.map_err(format_napi_error)
+        let mut inner = self.inner.lock().await;
+        inner.write(c).await.map_err(format_napi_error)
     }
 
-    /// # Safety
-    ///
-    /// > &mut self in async napi methods should be marked as unsafe
-    ///
     /// Close this writer.
     ///
     /// ### Example
@@ -1200,28 +1201,28 @@ impl Writer {
     /// await writer.close();
     /// ```
     #[napi]
-    pub async unsafe fn close(&mut self) -> Result<()> {
-        self.0.close().await.map(|_| ()).map_err(format_napi_error)
+    pub async fn close(&self) -> Result<()> {
+        let mut inner = self.inner.lock().await;
+        inner.close().await.map(|_| ()).map_err(format_napi_error)
     }
 }
 
 /// Lister is designed to list entries at a given path in an asynchronous
 /// manner.
 #[napi]
-pub struct Lister(opendal::Lister);
+pub struct Lister {
+    inner: Mutex<opendal::Lister>,
+}
 
 #[napi]
 impl Lister {
-    /// # Safety
-    ///
-    /// > &mut self in async napi methods should be marked as unsafe
+    /// Return the next entry, or `null` when the lister is exhausted.
     ///
-    /// napi will make sure the function is safe, and we didn't do unsafe
-    /// things internally.
+    /// Concurrent calls are serialized, so each entry is returned exactly 
once.
     #[napi]
-    pub async unsafe fn next(&mut self) -> Result<Option<Entry>> {
-        Ok(self
-            .0
+    pub async fn next(&self) -> Result<Option<Entry>> {
+        let mut inner = self.inner.lock().await;
+        Ok(inner
             .try_next()
             .await
             .map_err(format_napi_error)?
diff --git a/bindings/nodejs/tests/suites/async.suite.mjs 
b/bindings/nodejs/tests/suites/async.suite.mjs
index 06bb80a799..1cbb2c4ebc 100644
--- a/bindings/nodejs/tests/suites/async.suite.mjs
+++ b/bindings/nodejs/tests/suites/async.suite.mjs
@@ -130,6 +130,46 @@ export function run(op) {
       expect(await reader.readChunk(1)).toBeNull()
     })
 
+    test('overlapping writer writes are serialized without losing data', async 
() => {
+      const memory = new Operator('memory')
+      const filename = `writer_concurrency_${randomUUID()}`
+      const chunks = Array.from({ length: 64 }, (_, i) =>
+        Buffer.from(`chunk-${i.toString().padStart(4, 
'0')}-${'x'.repeat(64)}`),
+      )
+      const writer = await memory.writer(filename)
+
+      await Promise.all(chunks.map((chunk) => writer.write(chunk)))
+      await writer.close()
+
+      const written = await memory.read(filename)
+      expect(written.length).toBe(chunks.length * chunks[0].length)
+      const actual = Array.from({ length: chunks.length }, (_, i) =>
+        written.subarray(i * chunks[0].length, (i + 1) * 
chunks[0].length).toString(),
+      )
+      expect(actual.sort()).toEqual(chunks.map((chunk) => 
chunk.toString()).sort())
+
+      await memory.delete(filename)
+    })
+
+    test('overlapping lister next calls return every entry exactly once', 
async () => {
+      const memory = new Operator('memory')
+      const dirname = `lister_concurrency_${randomUUID()}/`
+      await memory.createDir(dirname)
+
+      const names = Array.from({ length: 64 }, (_, i) => 
`file-${i.toString().padStart(4, '0')}`)
+      for (const name of names) {
+        await memory.write(`${dirname}${name}`, 'content')
+      }
+
+      const lister = await memory.lister(dirname)
+      const results = await Promise.all(Array.from({ length: names.length + 4 
}, () => lister.next()))
+      const paths = results.filter((entry) => entry !== null).map((entry) => 
entry.path())
+      expect(paths.sort()).toEqual([dirname, ...names.map((name) => 
`${dirname}${name}`)].sort())
+      expect(results.filter((entry) => entry === null)).toHaveLength(3)
+
+      await memory.removeAll(dirname)
+    })
+
     test('read stream pauses at the high water mark and emits a short tail', 
async () => {
       const memory = new Operator('memory')
       await memory.write('object', Buffer.from('abcdefghijk'))

Reply via email to