diff --git a/src/bundler/ParseTask.rs b/src/bundler/ParseTask.rs index 1c20cf221d97..b98207443dc4 100644 --- a/src/bundler/ParseTask.rs +++ b/src/bundler/ParseTask.rs @@ -1523,6 +1523,8 @@ pub mod parse_worker { } } + ctx.watch_file_before_read(file_path); + // Always read into the worker arena: it is pinned for the // entire bundle pass (freed only via `pool.deinit()` inside // `deinit_without_freeing_arena`, after `process_files_to_copy` diff --git a/src/bundler/bundle_v2.rs b/src/bundler/bundle_v2.rs index eb72b4d389c5..caf46828569f 100644 --- a/src/bundler/bundle_v2.rs +++ b/src/bundler/bundle_v2.rs @@ -225,8 +225,8 @@ impl<'a> BundleV2<'a> { // SAFETY: BACKREF — heap-owned by hot_reloader / DevServer (set via // `install_bun_watcher`), live for the process under `--watch`. The // watcher storage is disjoint from `self`; `&mut self` excludes any - // other safe projection from this `BundleV2`, and `add_file` is only - // ever driven from the single bundle thread (`thread_lock`-asserted). + // other safe projection from this `BundleV2`, and this projection is + // only used on the single bundle thread (`thread_lock`-asserted). self.bun_watcher.map(|mut p| unsafe { p.as_mut() }) } @@ -5899,6 +5899,20 @@ pub mod bv2_impl { } } + /// See `Watcher::add_file_before_read`. Runs on parse worker threads. + pub(crate) fn watch_file_before_read(&self, path: &Fs::Path) { + let Some(mut bun_watcher) = self.bun_watcher else { + return; + }; + if !self.should_add_watcher_plugin(path.namespace, path.text) { + return; + } + // SAFETY: BACKREF — see `bun_watcher_mut`. This runs on parse + // worker threads; `Watcher` serializes watchlist writes with its + // own mutex, as it does for the runtime transpiler's workers. + let _ = unsafe { bun_watcher.as_mut() }.add_file_before_read(path.text); + } + /// Dev Server uses this instead to run a subset of the transpiler, and to run it asynchronously. pub fn start_from_bake_dev_server( &mut self, @@ -7719,7 +7733,7 @@ pub mod bv2_impl { } } - // To minimize contention, watchers are appended on the bundle thread. + // The parse worker already watches the file (`watch_file_before_read`); settle who owns the read fd. if this.bun_watcher.is_some() { if parse_result.watcher_data.fd != bun_sys::Fd::INVALID { let source_index = parse_result.value.source_index(); diff --git a/src/jsc/RuntimeTranspilerStore.rs b/src/jsc/RuntimeTranspilerStore.rs index 149537ecd89f..69de71bc9417 100644 --- a/src/jsc/RuntimeTranspilerStore.rs +++ b/src/jsc/RuntimeTranspilerStore.rs @@ -898,6 +898,20 @@ impl TranspilerJob { let is_watcher_enabled = import_watcher.is_some_and(|iw| !matches!(&*iw, ImportWatcher::None)); + // Watch before the read, so a save during the parse still raises an event. + if is_watcher_enabled + && !is_node_override + && bun_paths::is_absolute(path.text) + && !strings::contains(path.text, b"node_modules") + { + if let Some(iw) = import_watcher { + // SAFETY: BACKREF — process-lifetime watcher; no other + // `&ImportWatcher` is live here, and the add is thread-safe + // via watcher mutex. + let _ = unsafe { iw.assume_mut() }.add_file_before_read(path.text); + } + } + let Some(mut parse_result) = transpiler .parse_maybe_return_file_only_allow_shared_buffer::(parse_options, None) else { diff --git a/src/jsc/hot_reloader.rs b/src/jsc/hot_reloader.rs index 83c086196842..7bd3fef26d2a 100644 --- a/src/jsc/hot_reloader.rs +++ b/src/jsc/hot_reloader.rs @@ -62,6 +62,15 @@ impl ImportWatcher { } } + /// See [`Watcher::add_file_before_read`]. + #[inline] + pub fn add_file_before_read(&mut self, file_path: &[u8]) -> bool { + match self { + ImportWatcher::Hot(w) | ImportWatcher::Watch(w) => w.add_file_before_read(file_path), + ImportWatcher::None => false, + } + } + #[inline] pub fn add_file( &mut self, diff --git a/src/runtime/jsc_hooks.rs b/src/runtime/jsc_hooks.rs index 4a9da411e5f9..446d9f222201 100644 --- a/src/runtime/jsc_hooks.rs +++ b/src/runtime/jsc_hooks.rs @@ -2649,6 +2649,10 @@ fn transpile_source_code_of_any_provenance( replace_exports: Default::default(), }; + if !disable_transpilying && virtual_source.is_none() { + maybe_watch_file_before_read(jsc_vm, is_node_override, path); + } + // Both the file-only and transpiled arms hit the same // `parse_maybe_return_file_only_allow_shared_buffer` body, so // dispatch at runtime via the const-generic bool. @@ -3479,6 +3483,29 @@ fn transpile_source_code_of_any_provenance( } } +/// [`maybe_watch_file`]'s filter, before the parse reads `path`. See `Watcher::add_file_before_read`. +#[inline] +fn maybe_watch_file_before_read( + jsc_vm: *mut VirtualMachine, + is_node_override: bool, + path: &Fs::Path, +) { + // SAFETY: per fn contract — `jsc_vm` is the live per-thread VM. + if !unsafe { &*jsc_vm }.is_watcher_enabled() { + return; + } + if is_node_override + || !bun_paths::is_absolute(path.text) + || bun_core::strings::contains(path.text, b"node_modules") + { + return; + } + // SAFETY: `bun_watcher` is the `*mut ImportWatcher` set when + // `is_watcher_enabled()`; cast recovers the concrete type. + let watcher = unsafe { &mut *(*jsc_vm).bun_watcher.cast::() }; + let _ = watcher.add_file_before_read(path.text); +} + /// Register the just-opened file /// with the dev-server watcher (if enabled, absolute, and not in /// `node_modules`). Factored out of the two call sites. diff --git a/src/watcher/Watcher.rs b/src/watcher/Watcher.rs index 9e8f65f480cb..4327721d7fe5 100644 --- a/src/watcher/Watcher.rs +++ b/src/watcher/Watcher.rs @@ -306,7 +306,9 @@ impl Watcher { if close_descriptors && me.running.load() { let fds = me.watchlist.items_fd(); for &fd in fds { - let _ = bun_sys::close(fd); + if fd.is_valid() { + let _ = bun_sys::close(fd); + } } } true @@ -379,7 +381,9 @@ impl Watcher { if close_descriptors { let fds = self.watchlist.items_fd(); for &fd in fds { - let _ = bun_sys::close(fd); + if fd.is_valid() { + let _ = bun_sys::close(fd); + } } } false @@ -877,6 +881,18 @@ impl Watcher { } } + /// Watch `file_path` before its caller reads it. The `add_file` after the parse then only settles who owns the read fd. + pub fn add_file_before_read(&mut self, file_path: &[u8]) -> bool { + // The `add_file` after the read prints the out-of-root warning, once. + #[cfg(windows)] + if bun_paths::resolve_path::is_parent_or_equal(self.top_level_dir(), file_path) + == bun_paths::resolve_path::ParentEqual::Unrelated + { + return false; + } + self.add_file_by_path_slow(file_path) + } + pub fn add_file( &mut self, fd: Fd, @@ -896,8 +912,9 @@ impl Watcher { // directory-event recovery sees a valid fd. A valid stored fd // is never replaced: the watchlist owns it until eviction, // and the old overwrite leaked it. + // An fd to a file that a rename has since replaced would pin the inode inotify waits on. let fds = self.watchlist.items_fd_mut(); - if !fds[index as usize].is_valid() { + if !fds[index as usize].is_valid() && Self::is_file_at_path(fd, file_path) { fds[index as usize] = fd; ownership = FdOwnership::Watcher; } @@ -917,6 +934,30 @@ impl Watcher { r } + /// Whether `fd` is still the file that `file_path` names. + #[cfg(not(windows))] + fn is_file_at_path(fd: Fd, file_path: &[u8]) -> bool { + let mut buf = bun_paths::path_buffer_pool::get(); + if file_path.len() >= buf.len() { + return false; + } + buf[..file_path.len()].copy_from_slice(file_path); + buf[file_path.len()] = 0; + let path = ZStr::from_buf(&buf[..], file_path.len()); + match (sys::fstat(fd), sys::stat(path)) { + (Ok(opened), Ok(named)) => { + opened.st_ino == named.st_ino && opened.st_dev == named.st_dev + } + _ => false, + } + } + + /// Windows never stores the descriptor of an existing entry. + #[cfg(windows)] + fn is_file_at_path(_: Fd, _: &[u8]) -> bool { + true + } + pub fn index_of(&self, hash: HashType) -> Option { for (i, other) in self.watchlist.items_hash().iter().enumerate() { if hash == *other { diff --git a/test/cli/watch/watch.test.ts b/test/cli/watch/watch.test.ts index bc2982d84f66..7f1c86bed532 100644 --- a/test/cli/watch/watch.test.ts +++ b/test/cli/watch/watch.test.ts @@ -1,6 +1,6 @@ import type { Subprocess } from "bun"; import { spawn } from "bun"; -import { afterEach, expect, it } from "bun:test"; +import { afterEach, describe, expect, it } from "bun:test"; import { bunEnv, bunExe, isBroken, isLinux, isMacOS, isWindows, tempDir, tmpdirSync } from "harness"; import { copyFileSync, @@ -758,3 +758,104 @@ it.skipIf(!isLinux)("watcher opens the watched directory and files with O_CLOEXE "/main.ts": [O_CLOEXEC], }); }); + +// A save can land after a module was read and before its parse is done. The +// watcher has to watch the file by then. If it does not, the save raises no +// event and the stale module stays loaded until the next save. The fixture +// puts the save in that window itself: `mod.js` calls a macro, a macro runs +// while its caller is parsed, and this one saves `mod.js`. It then holds the +// parse until the watcher has handled the save (BUN_WATCHER_TRACE), so a +// watch that is added after the parse is always too late. +describe("a save that lands while the module is parsed is picked up", () => { + // `save(how, from)` changes "value = " in `mod.js` to the next number, + // once. "write" saves in place with one write(2), so the file is never + // partial. "rename" writes a second file and renames it over `mod.js`. + // The trace names `mod.js` as a watched file, or as a name in its directory. + const files = (how: "write" | "rename", from: number) => ({ + "save.js": ` +import { closeSync, openSync, readFileSync, renameSync, writeFileSync, writeSync } from "node:fs"; +import { join } from "node:path"; +const trace = () => readFileSync(process.env.BUN_WATCHER_TRACE, "utf8"); +export function save(how, from) { + const path = join(import.meta.dir, "mod.js"); + const text = readFileSync(path, "utf8"); + const at = text.indexOf("value = " + from); + if (at === -1) return "kept"; + const before = trace().length; + if (how === "rename") { + const next = join(import.meta.dir, "next.js"); + writeFileSync(next, text.replace("value = " + from, "value = " + (from + 1))); + renameSync(next, path); + } else { + const fd = openSync(path, "r+"); + writeSync(fd, String(from + 1), at + "value = ".length); + closeSync(fd); + } + for (;;) { + const handled = trace().slice(before); + if (handled.includes('mod.js":') || handled.includes('"mod.js"')) return "saved"; + } +} +`, + "mod.js": `import { save } from "./save.js" with { type: "macro" }; +export const value = 0; +export const macro = save("${how}", ${from}); +`, + "entry.js": `import { value, macro } from "./mod.js"; +console.log("value " + value + " " + macro); +setInterval(() => {}, 1000); +`, + "entry-require.js": `const { value, macro } = require("./mod.js"); +console.log("value " + value + " " + macro); +setInterval(() => {}, 1000); +`, + // Saves `mod.js` once itself, after the first load. + "entry-saves.js": `import { value, macro } from "./mod.js"; +import { save } from "./save.js"; +console.log("value " + value + " " + macro); +save("write", 0); +setInterval(() => {}, 1000); +`, + "entry.test.js": `import { test } from "bun:test"; +import { value, macro } from "./mod.js"; +test("logs", () => console.log("value " + value + " " + macro)); +`, + }); + + // A lost save leaves the child on the module it parsed, and `waitFor` never + // returns. + async function expectOutput(cmd: string[], how: "write" | "rename", from: number, needle: string) { + using dir = tempDir("watch-save-during-parse", files(how, from)); + // Not in the watched directory: a trace line must not raise an event. + using traceDir = tempDir("watch-save-during-parse-trace", {}); + watchee = spawn({ + cmd: [bunExe(), ...cmd], + cwd: String(dir), + env: { ...bunEnv, BUN_WATCHER_TRACE: join(String(traceDir), "trace.log") }, + stdout: "pipe", + // `bun test` reports on stderr, in the format of the report of this file. + stderr: cmd[0] === "test" ? "ignore" : "inherit", + stdin: "ignore", + }); + const { waitFor, release } = stdoutWaiter(watchee); + await waitFor(needle); + release(); + watchee.kill("SIGKILL"); + await watchee.exited; + } + + it("--watch, import", () => expectOutput(["--watch", "entry.js"], "write", 0, "value 1 kept")); + it("--watch, require", () => expectOutput(["--watch", "entry-require.js"], "write", 0, "value 1 kept")); + it("--hot, import", () => expectOutput(["--hot", "entry.js"], "write", 0, "value 1 kept")); + // Windows refuses to rename over a file that is open for the parse. + it.skipIf(isWindows)("--hot, saved with a rename", () => + expectOutput(["--hot", "entry.js"], "rename", 0, "value 1 kept"), + ); + // On Linux a save in place takes the file off the watchlist until the reload + // reads it again. Here the macro saves while that reload parses the file. + it("--hot, during the reload of an earlier save", () => + expectOutput(["--hot", "entry-saves.js"], "write", 1, "value 2 kept")); + it("bun test --watch", () => expectOutput(["test", "--watch", "./entry.test.js"], "write", 0, "value 1 kept")); + // Without --outdir the bundle goes to stdout, once per build. + it("bun build --watch", () => expectOutput(["build", "--watch", "entry.js"], "write", 0, "var value = 1;")); +});