Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crates/node_binding/napi-binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -470,8 +470,8 @@ export declare class NativeWatcher {
* # Safety
*
* This function is unsafe because it uses `&mut self` to call the watcher asynchronously.
* It's important to ensure that the watcher is not used in any other places before this function is finished.
* You must ensure that the watcher not call watch, close or pause in the same time, otherwise it may lead to undefined behavior.
* `watch` and `close` are serialized internally, but calling `pause` while this function is

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so calling pause while watching still can cause panic | abort issue?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this api's semantic is not same as js version

* in flight is still undefined behavior.
*/
close(): Promise<void>
pause(): void
Expand Down
2 changes: 1 addition & 1 deletion crates/rspack_binding_api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
simd-json = { workspace = true }
swc_core = { workspace = true, default-features = false, features = ["ecma_transforms_react"] }
tokio = { workspace = true, features = ["rt", "rt-multi-thread", "macros", "test-util", "tracing", "parking_lot"] }
tokio = { workspace = true, features = ["rt", "rt-multi-thread", "macros", "sync", "test-util", "tracing", "parking_lot"] }
ustr = { workspace = true }

[package.metadata.cargo-shear]
Expand Down
25 changes: 21 additions & 4 deletions crates/rspack_binding_api/src/native_watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::{
boxed::Box,
panic::AssertUnwindSafe,
path::{Path, PathBuf},
sync::Arc,
time::{Duration, SystemTime, UNIX_EPOCH},
};

Expand Down Expand Up @@ -59,6 +60,8 @@ pub struct NativeWatchUndelayedEvent {
pub struct NativeWatcher {
watcher: FsWatcher,
closed: bool,
watch_task: Option<tokio::task::JoinHandle<()>>,
watcher_lock: Arc<tokio::sync::Mutex<()>>,
}

fn timestamp_to_system_time(millis: u64) -> SystemTime {
Expand All @@ -81,6 +84,8 @@ impl NativeWatcher {
Self {
watcher,
closed: false,
watch_task: None,
watcher_lock: Arc::new(tokio::sync::Mutex::new(())),
}
}

Expand Down Expand Up @@ -110,8 +115,15 @@ impl NativeWatcher {

let start_time = start_time.get_u64().1;

if let Some(prev) = self.watch_task.take() {
prev.abort();
}

let watcher_lock = Arc::clone(&self.watcher_lock);
let mut watch_task = None;
reference.share_with(env, |native_watcher| {
rspack_napi::runtime::spawn(async move {
watch_task = Some(rspack_napi::runtime::spawn_handle(async move {
let _guard = watcher_lock.lock_owned().await;
native_watcher
.watcher
.watch(
Expand All @@ -123,9 +135,10 @@ impl NativeWatcher {
Box::new(js_event_handler_undelayed),
)
.await
});
}));
Ok(())
})?;
self.watch_task = watch_task;

Ok(())
}
Expand All @@ -148,8 +161,8 @@ impl NativeWatcher {
/// # Safety
///
/// This function is unsafe because it uses `&mut self` to call the watcher asynchronously.
/// It's important to ensure that the watcher is not used in any other places before this function is finished.
/// You must ensure that the watcher not call watch, close or pause in the same time, otherwise it may lead to undefined behavior.
/// `watch` and `close` are serialized internally, but calling `pause` while this function is
/// in flight is still undefined behavior.
pub unsafe fn close<'env>(
&mut self,
env: &'env Env,
Expand All @@ -160,6 +173,10 @@ impl NativeWatcher {
let shared_reference = reference.share_with(Env::from_raw(env.raw()), |native_watcher| {
rspack_napi::runtime::spawn(async move {
let result = AssertUnwindSafe(async {
if let Some(task) = native_watcher.watch_task.take() {
task.abort();
}
let _guard = Arc::clone(&native_watcher.watcher_lock).lock_owned().await;
native_watcher
.watcher
.close()
Expand Down
8 changes: 8 additions & 0 deletions crates/rspack_napi/src/runtime.rs

@hardfist hardfist Jul 14, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why need spawn_handle here and what does spawn_handle mean here?

Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ where
std::mem::drop(spawn_inner(future));
}

pub fn spawn_handle<F>(future: F) -> tokio::task::JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
spawn_inner(future)
}

pub fn block_on<F: Future>(future: F) -> F::Output {
with_runtime(|runtime| runtime.block_on(future))
}
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

59 changes: 59 additions & 0 deletions tests/rspack-test/NativeWatcherLifecycle.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const binding = require("@rspack/binding");

const ITERATIONS = 30;
const WATCHES_PER_ITERATION = 5;
const FILE_COUNT = 400;

let dir;
let files;
let dirs;

const startWatch = watcher => {
watcher.watch(
[files, []],
[dirs, []],
[[], []],
BigInt(Date.now()),
() => {},
() => {}
);
};

describe("NativeWatcher lifecycle", () => {
beforeAll(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), "rspack-native-watcher-"));
files = [];
dirs = [dir];
for (let i = 0; i < FILE_COUNT; i++) {
const sub = path.join(dir, `sub${i % 20}`);
fs.mkdirSync(sub, { recursive: true });
const file = path.join(sub, `f${i}.js`);
fs.writeFileSync(file, `module.exports = ${i};`);
files.push(file);
if (!dirs.includes(sub)) {
dirs.push(sub);
}
}
});

afterAll(() => {
fs.rmSync(dir, { recursive: true, force: true });
});

it("does not crash when watch and close race on the same watcher", async () => {
for (let i = 0; i < ITERATIONS; i++) {
const watcher = new binding.NativeWatcher({ aggregateTimeout: 1 });

for (let j = 0; j < WATCHES_PER_ITERATION; j++) {
startWatch(watcher);
}

await watcher.close();

expect(() => startWatch(watcher)).toThrow(/has been closed/);
}
});
});
1 change: 1 addition & 0 deletions tests/rspack-test/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"@module-federation/runtime-tools": "2.7.0",
"@prefresh/core": "1.5.10",
"@prefresh/utils": "1.2.1",
"@rspack/binding": "workspace:*",
"@rspack/binding-testing": "workspace:*",
"@rspack/cli": "workspace:*",
"@rspack/core": "workspace:*",
Expand Down
Loading