Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
32 changes: 24 additions & 8 deletions src/bundler/ParseTask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,12 @@ mod EventLoop {
#[derive(bun_core::EnumTag)]
#[enum_tag(existing = ContentsOrFdTag)]
pub enum ContentsOrFd {
Fd { dir: Fd, file: Fd },
Fd {
dir: Fd,
file: Fd,
/// Opened by this task's read (not the resolver cache); the bundle thread closes it if the watcher does not adopt it.
owns_file: bool,
},
// The `'static` is ownership-erased: contents may be arena-owned,
// plugin-owned, or truly static (runtime source). The producer keeps the
// backing allocation alive for the duration of the bundle pass.
Expand Down Expand Up @@ -160,13 +165,16 @@ impl ResultValue {
pub(crate) struct WatcherData {
pub(crate) fd: Fd,
pub(crate) dir_fd: Fd,
/// See `ContentsOrFd::Fd::owns_file`.
pub(crate) owns_fd: bool,
}

impl WatcherData {
/// When no files to watch, this encoding is used.
pub(crate) const NONE: WatcherData = WatcherData {
fd: Fd::INVALID,
dir_fd: Fd::INVALID,
owns_fd: false,
};
}

Expand Down Expand Up @@ -261,6 +269,7 @@ impl ParseTask {
contents_or_fd: ContentsOrFd::Fd {
dir: resolve_result.dirname_fd,
file: resolve_result.file_fd,
owns_file: false,
},
side_effects: resolve_result.primary_side_effects_data,
// D042: resolver-side and bundler-side `jsx::Pragma` are the SAME
Expand Down Expand Up @@ -1445,7 +1454,7 @@ pub mod parse_worker {
_loader: Loader,
) -> core::result::Result<CacheEntry, AnyError> {
match &task.contents_or_fd {
ContentsOrFd::Fd { dir, file } => 'brk: {
ContentsOrFd::Fd { dir, file, .. } => 'brk: {
let contents_dir = *dir;
let contents_file = *file;
let _trace = perf::trace("Bundler.readFile");
Expand Down Expand Up @@ -1503,6 +1512,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`
Expand Down Expand Up @@ -2359,20 +2370,20 @@ pub mod parse_worker {
// there); closing it leaves a stale fd for the next in-process build.
let opened_own_fd =
matches!(task.contents_or_fd, ContentsOrFd::Fd { file, .. } if !file.is_valid());
let will_close_file_descriptor = opened_own_fd
&& entry.fd.is_valid()
&& entry.fd.stdio_tag().is_none()
&& worker_ctx.bun_watcher.is_none();
if will_close_file_descriptor {
let owns_fd = opened_own_fd && entry.fd.is_valid() && entry.fd.stdio_tag().is_none();
if owns_fd && worker_ctx.bun_watcher.is_none() {
let _ = entry.close_fd();
task.contents_or_fd = ContentsOrFd::Fd {
file: Fd::INVALID,
dir: Fd::INVALID,
owns_file: false,
};
} else if matches!(task.contents_or_fd, ContentsOrFd::Fd { .. }) {
// With a watcher, `on_parse_task_complete` hands the fd to the watcher or closes it.
task.contents_or_fd = ContentsOrFd::Fd {
file: entry.fd,
dir: Fd::INVALID,
owns_file: owns_fd,
};
}
*step = Step::Parse;
Expand Down Expand Up @@ -2862,9 +2873,14 @@ pub mod parse_worker {
// doesn't derive `Copy`, so move it out (task is consumed here).
external: core::mem::take(&mut this.external_free_function),
watcher_data: match this.contents_or_fd {
ContentsOrFd::Fd { file, dir } => WatcherData {
ContentsOrFd::Fd {
file,
dir,
owns_file,
} => WatcherData {
fd: file,
dir_fd: dir,
owns_fd: owns_file,
},
ContentsOrFd::Contents(_) => WatcherData::NONE,
},
Expand Down
87 changes: 56 additions & 31 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,8 +222,10 @@ 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`. `add_file` is driven
// from the bundle thread (`thread_lock`-asserted); parse workers reach
// the watcher only through `watch_file_before_read`, and `Watcher`
// serializes both with its own mutex.
Comment thread
robobun marked this conversation as resolved.
Resolved
self.bun_watcher.map(|mut p| unsafe { p.as_mut() })
}

Expand Down Expand Up @@ -5019,6 +5021,7 @@ pub mod bv2_impl {
contents_or_fd: parse_task::ContentsOrFd::Fd {
dir: bun_sys::Fd::INVALID,
file: bun_sys::Fd::INVALID,
owns_file: false,
},
side_effects: bun_ast::SideEffects::HasSideEffects,
jsx: this
Expand Down Expand Up @@ -5468,6 +5471,22 @@ pub mod bv2_impl {
}
}

/// Watch `path` before a parse worker reads it, so a save that lands
/// while the file is parsed still raises an event.
/// `on_parse_task_complete` adds the watch only after the parse.
Comment thread
robobun marked this conversation as resolved.
Resolved
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);
}

Comment thread
robobun marked this conversation as resolved.
Resolved
/// 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,
Expand Down Expand Up @@ -7237,35 +7256,41 @@ pub mod bv2_impl {
}
}

// To minimize contention, watchers are appended on the bundle thread.
if this.bun_watcher.is_some() {
if parse_result.watcher_data.fd != bun_sys::Fd::INVALID {
let source_index = parse_result.value.source_index();
// borrowck — read the source path before
// `should_add_watcher(&self)` so the column borrow is released.
let source_path = this.graph.input_files.items_source()[source_index as usize]
.path
.text;
if this.should_add_watcher(source_path) {
let fd = parse_result.watcher_data.fd;
let dir_fd = parse_result.watcher_data.dir_fd;
let hash = bun_wyhash::hash(source_path) as u32;
let bun_watcher = this.bun_watcher_mut().unwrap();
// The watcher keeps the path past this bundle; borrow it
// only when it is interned for the process lifetime
// (`dupe_alloc` leaves other paths in the bundle arena).
let _ = if Fs::as_interned_path(source_path).is_some() {
bun_watcher.add_file::<{ cfg!(windows) }>(
fd,
source_path,
hash,
dir_fd,
None,
)
} else {
bun_watcher.add_file::<true>(fd, source_path, hash, dir_fd, None)
};
}
// The parse worker watched the file before it read it
// (`watch_file_before_read`); this settles who owns the descriptor
// it read through.
Comment thread
robobun marked this conversation as resolved.
Resolved
let watcher_data = &parse_result.watcher_data;
if this.bun_watcher.is_some() && watcher_data.fd.is_valid() {
let source_index = parse_result.value.source_index();
// Read the source path before `should_add_watcher(&self)` so the column borrow is released.
let source_path = this.graph.input_files.items_source()[source_index as usize]
.path
.text;
// A descriptor the resolver cache owns stays with it.
let adopted = watcher_data.owns_fd && this.should_add_watcher(source_path) && {
let fd = watcher_data.fd;
let dir_fd = watcher_data.dir_fd;
let hash = bun_wyhash::hash(source_path) as u32;
let bun_watcher = this.bun_watcher_mut().unwrap();
// The watcher keeps the path past this bundle; borrow it
// only when it is interned for the process lifetime
// (`dupe_alloc` leaves other paths in the bundle arena).
Comment thread
robobun marked this conversation as resolved.
Resolved
let added = if Fs::as_interned_path(source_path).is_some() {
bun_watcher.add_file::<{ cfg!(windows) }>(
fd,
source_path,
hash,
dir_fd,
None,
)
} else {
bun_watcher.add_file::<true>(fd, source_path, hash, dir_fd, None)
};
matches!(added, Ok(bun_watcher::FdOwnership::Watcher))
};
// Nothing else closes the fd this parse opened.
if !adopted && watcher_data.owns_fd {
let _ = bun_sys::close(watcher_data.fd);
}
}

Expand Down
15 changes: 15 additions & 0 deletions src/jsc/RuntimeTranspilerStore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -873,6 +873,21 @@ impl TranspilerJob {
let is_watcher_enabled =
import_watcher.is_some_and(|iw| !matches!(&*iw, ImportWatcher::None));

// Watch before the read: a save that lands while this module is
// parsed must still raise an event.
Comment thread
robobun marked this conversation as resolved.
Resolved
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::<false, false>(parse_options, None)
else {
Expand Down
9 changes: 9 additions & 0 deletions src/jsc/hot_reloader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<const COPY_FILE_PATH: bool>(
&mut self,
Expand Down
29 changes: 29 additions & 0 deletions src/runtime/jsc_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2668,6 +2668,10 @@ fn transpile_source_code_inner(
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.
Expand Down Expand Up @@ -3495,6 +3499,31 @@ fn transpile_source_code_inner(
}
}

/// Watch `path` before the parse reads it (same filter as
/// [`maybe_watch_file`]), so a save that lands while the module is parsed
/// still raises an event.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[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::<bun_jsc::ImportWatcher>() };
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.
Expand Down
Loading
Loading