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 99f65c51f9 fix(bindings/nodejs): avoid stale Reader borrows after 
worker termination (#9258)
99f65c51f9 is described below

commit 99f65c51f9e73f0b16510ebf7ba67e76c8ff6c91
Author: Chitral Verma <[email protected]>
AuthorDate: Sat Nov 28 21:41:58 2026 +0530

    fix(bindings/nodejs): avoid stale Reader borrows after worker termination 
(#9258)
    
    Reader.read and Reader.readChunk were napi-rs `async fn(&self)` methods.
    napi-rs keeps the `&self` borrow in a process-global map keyed by the
    native object's address until the promise settles, but Node frees the
    Reader when its worker terminates. A later `&mut self` call on an object
    allocated at the reused address then failed with "The same native value
    cannot be borrowed mutably while another borrow is active", and the
    pending future kept a dangling reference.
    
    Pending reads now own an Arc of the reader instead of borrowing the
    Reader, and a per-environment shutdown signal cancels them when their
    Node.js environment shuts down, so terminating a worker still releases
    the pending request.
    
    Closes #9255
    
    Signed-off-by: Chitral Verma <[email protected]>
---
 bindings/nodejs/src/lib.rs                   | 114 ++++++++++++++++++++-------
 bindings/nodejs/tests/suites/async.suite.mjs |  55 +++++++++++++
 2 files changed, 142 insertions(+), 27 deletions(-)

diff --git a/bindings/nodejs/src/lib.rs b/bindings/nodejs/src/lib.rs
index afc0966d2a..5f8410010d 100644
--- a/bindings/nodejs/src/lib.rs
+++ b/bindings/nodejs/src/lib.rs
@@ -18,16 +18,21 @@
 #[macro_use]
 extern crate napi_derive;
 
+use std::cell::RefCell;
 use std::collections::HashMap;
 use std::fmt::Display;
 use std::io::Read;
+use std::pin::pin;
+use std::sync::Arc;
 
 use futures::TryStreamExt;
+use futures::future;
 use napi::bindgen_prelude::*;
 use opendal::options::{
     DeleteOptions, ListOptions, ReadOptions, ReaderOptions, StatOptions, 
WriteOptions,
 };
 use tokio::sync::Mutex;
+use tokio::sync::watch;
 
 use crate::layer::Layer;
 use crate::metadata::Metadata;
@@ -284,7 +289,7 @@ impl Operator {
             .await
             .map_err(format_napi_error)?;
         Ok(Reader {
-            inner: Mutex::new(inner),
+            inner: Arc::new(Mutex::new(inner)),
         })
     }
 
@@ -939,7 +944,9 @@ impl BlockingReader {
 /// manner.
 #[napi]
 pub struct Reader {
-    inner: Mutex<opendal::FuturesAsyncReader>,
+    // Node can free this object while a read is pending, for example when its
+    // worker terminates. Pending reads own a clone instead of borrowing 
`self`.
+    inner: Arc<Mutex<opendal::FuturesAsyncReader>>,
 }
 
 #[napi]
@@ -948,18 +955,22 @@ impl Reader {
     ///
     /// Wait for the promise to settle before accessing the buffer again.
     #[napi(ts_return_type = "Promise<bigint>")]
-    pub async fn read(
+    pub fn read<'env>(
         &self,
+        env: &'env Env,
         #[napi(ts_arg_type = "Buffer")] buf: ReadTarget,
-    ) -> Result<ReadIntoBuffer> {
-        let chunk = self
-            .inner
-            .lock()
-            .await
-            .read_buffer(buf.requested_len)
-            .await
-            .map_err(format_napi_error)?;
-        Ok(ReadIntoBuffer { target: buf, chunk })
+    ) -> Result<PromiseRaw<'env, ReadIntoBuffer>> {
+        let inner = self.inner.clone();
+        let env_shutdown = subscribe_env_shutdown(env)?;
+        env.spawn_future(until_env_shutdown(env_shutdown, async move {
+            let chunk = inner
+                .lock()
+                .await
+                .read_buffer(buf.requested_len)
+                .await
+                .map_err(format_napi_error)?;
+            Ok(ReadIntoBuffer { target: buf, chunk })
+        }))
     }
 
     /// Read up to `maxBytes` bytes from the same cursor as `read`.
@@ -967,23 +978,72 @@ impl Reader {
     /// `maxBytes` must be an integer between 1 and 4294967295. The promise
     /// resolves to a writable Buffer, or `null` at the end of the input.
     #[napi(ts_return_type = "Promise<Buffer | null>")]
-    pub async fn read_chunk(&self, max_bytes: f64) -> 
Result<Option<ReadChunk>> {
-        // N-API's uint32 conversion truncates and wraps JavaScript numbers.
-        if !(1.0..=f64::from(u32::MAX)).contains(&max_bytes) || 
max_bytes.fract() != 0.0 {
-            return Err(Error::new(
-                Status::InvalidArg,
-                "maxBytes must be an integer between 1 and 4294967295",
-            ));
+    pub fn read_chunk<'env>(
+        &self,
+        env: &'env Env,
+        max_bytes: f64,
+    ) -> Result<PromiseRaw<'env, Option<ReadChunk>>> {
+        let inner = self.inner.clone();
+        let env_shutdown = subscribe_env_shutdown(env)?;
+        env.spawn_future(until_env_shutdown(env_shutdown, async move {
+            // N-API's uint32 conversion truncates and wraps JavaScript 
numbers.
+            if !(1.0..=f64::from(u32::MAX)).contains(&max_bytes) || 
max_bytes.fract() != 0.0 {
+                return Err(Error::new(
+                    Status::InvalidArg,
+                    "maxBytes must be an integer between 1 and 4294967295",
+                ));
+            }
+
+            let chunk = inner
+                .lock()
+                .await
+                .read_buffer(max_bytes as usize)
+                .await
+                .map_err(format_napi_error)?;
+            Ok((!chunk.is_empty()).then_some(ReadChunk(chunk)))
+        }))
+    }
+}
+
+thread_local! {
+    // Keyed by `napi_env` because an embedder such as Electron can run several
+    // Node.js environments on one thread. Each environment's cleanup hook 
drops
+    // its sender when that environment shuts down.
+    static ENV_SHUTDOWN: RefCell<HashMap<usize, watch::Sender<()>>> = 
RefCell::new(HashMap::new());
+}
+
+/// Subscribes to the shutdown of the calling Node.js environment.
+fn subscribe_env_shutdown(env: &Env) -> Result<watch::Receiver<()>> {
+    let key = env.raw() as usize;
+    ENV_SHUTDOWN.with_borrow_mut(|senders| {
+        if let Some(sender) = senders.get(&key) {
+            return Ok(sender.subscribe());
         }
+        env.add_env_cleanup_hook(key, |key| {
+            let _ = ENV_SHUTDOWN.try_with(|senders| 
senders.borrow_mut().remove(&key));
+        })?;
+        let (sender, receiver) = watch::channel(());
+        senders.insert(key, sender);
+        Ok(receiver)
+    })
+}
 
-        let chunk = self
-            .inner
-            .lock()
-            .await
-            .read_buffer(max_bytes as usize)
-            .await
-            .map_err(format_napi_error)?;
-        Ok((!chunk.is_empty()).then_some(ReadChunk(chunk)))
+/// Cancels `fut` when the Node.js environment that started it shuts down.
+///
+/// Without this, a read pending when its worker terminates would keep its
+/// reader, and the reader's open request, alive.
+async fn until_env_shutdown<T>(
+    mut env_shutdown: watch::Receiver<()>,
+    fut: impl Future<Output = Result<T>>,
+) -> Result<T> {
+    let fut = pin!(fut);
+    let shutdown = pin!(env_shutdown.changed());
+    match future::select(fut, shutdown).await {
+        future::Either::Left((result, _)) => result,
+        future::Either::Right(_) => Err(Error::new(
+            Status::Cancelled,
+            "Node.js environment shut down before the read completed",
+        )),
     }
 }
 
diff --git a/bindings/nodejs/tests/suites/async.suite.mjs 
b/bindings/nodejs/tests/suites/async.suite.mjs
index 558500bee6..ebd10fd883 100644
--- a/bindings/nodejs/tests/suites/async.suite.mjs
+++ b/bindings/nodejs/tests/suites/async.suite.mjs
@@ -518,6 +518,61 @@ export function run(op) {
       10000,
     )
 
+    test('reads pending in a terminated worker leave no borrow on other 
threads', async () => {
+      const memory = new Operator('memory')
+      memory.writeSync('object', 'hello')
+      const server = createServer()
+      server.listen(0, '127.0.0.1')
+      onTestFinished(() => {
+        server.closeAllConnections()
+        server.close()
+      })
+      await once(server, 'listening')
+      let requests = 0
+      const requested = new Promise((resolve) => {
+        server.on('request', () => {
+          if (++requests === 8) resolve()
+        })
+      })
+      const worker = new Worker(
+        `
+          const { workerData } = require('node:worker_threads')
+          import(workerData.entry).then(async ({ Operator }) => {
+            const op = new Operator('http', { endpoint: workerData.endpoint })
+            for (let i = 0; i < 8; i++) {
+              const reader = await op.reader('object')
+              reader.read(Buffer.alloc(16))
+              reader.readChunk(16)
+            }
+          })
+        `,
+        {
+          eval: true,
+          workerData: {
+            entry: new URL('../../index.mjs', import.meta.url).href,
+            endpoint: `http://127.0.0.1:${server.address().port}`,
+          },
+        },
+      )
+      onTestFinished(() => worker.terminate())
+
+      await Promise.race([
+        requested,
+        once(worker, 'exit').then(([code]) => {
+          throw new Error(`Worker exited before starting its GETs (${code})`)
+        }),
+      ])
+      expect(await worker.terminate()).toBe(1)
+
+      // Terminating the worker frees its Readers, and this thread can reuse 
their addresses.
+      const readers = []
+      for (let i = 0; i < 1000; i++) {
+        const reader = memory.readerSync('object')
+        readers.push(reader)
+        expect(reader.read(Buffer.alloc(5))).toBe(5n)
+      }
+    })
+
     test.runIf(op.capability().read && op.capability().write)('write with 
behavior', async () => {
       let c = Buffer.from('hello world')
       const filename = `random_file_${randomUUID()}`

Reply via email to