Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 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
11 changes: 9 additions & 2 deletions src/bundler/entry_points.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,11 @@ pub struct ServerEntryPoint {
// auto-generated `Drop`, so no explicit impl is needed.

impl ServerEntryPoint {
/// `generation` orders the loads under `--hot`: one that finishes after a newer one does not apply its server config.
pub fn generate(
entry: &mut ServerEntryPoint,
is_hot_reload_enabled: bool,
generation: u32,
path_to_use: &[u8],
) -> crate::Result<()> {
// Use the global arena so this buffer's lifetime is decoupled
Expand All @@ -54,14 +56,19 @@ impl ServerEntryPoint {
"// @bun\n\
import * as start from '{}';\n\
var hmrSymbol = Symbol(\"BunServerHMR\");\n\
var newestGeneration = Symbol.for(\"BunServerHMR.newestGeneration\");\n\
var entryNamespace = start;\n\
function isServerConfig(def) {{\n\
\x20 return def && def !== globalThis && (typeof def.fetch === 'function' || def.app != undefined) && typeof def.stop !== 'function';\n\
}}\n\
function isNewestGeneration() {{\n\
\x20 return !(globalThis[newestGeneration] > {generation});\n\
}}\n\
if (isNewestGeneration()) globalThis[newestGeneration] = {generation};\n\
Comment thread
robobun marked this conversation as resolved.
Resolved
if (typeof entryNamespace?.then === 'function') {{\n\
\x20 entryNamespace = entryNamespace.then((entryNamespace) => {{\n\
\x20 var def = entryNamespace?.default;\n\
\x20 if (isServerConfig(def)) {{\n\
\x20 if (isNewestGeneration() && isServerConfig(def)) {{\n\
\x20 var server = globalThis[hmrSymbol];\n\
\x20 if (server) {{\n\
\x20 server.reload(def);\n\
Expand All @@ -72,7 +79,7 @@ impl ServerEntryPoint {
\x20 }}\n\
\x20 }}\n\
\x20 }}, reportError);\n\
}} else if (isServerConfig(entryNamespace?.default)) {{\n\
}} else if (isNewestGeneration() && isServerConfig(entryNamespace?.default)) {{\n\
\x20 var server = globalThis[hmrSymbol];\n\
\x20 if (server) {{\n\
\x20 server.reload(entryNamespace.default);\n\
Expand Down
15 changes: 12 additions & 3 deletions src/jsc/RuntimeTranspilerStore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ impl RuntimeTranspilerStore {
(*job).promise.deinit();
(*job).module_loader.deinit();
(*job).reset_for_pool();
(*(*job).vm).module_fetches.settled((*job).fetch_generation);
self.store.put(job);
}
}
Expand Down Expand Up @@ -375,6 +376,7 @@ impl RuntimeTranspilerStore {
poll_ref: KeepAlive::default(),
resolved_source,
generation_number: self.generation_number.load(Ordering::SeqCst),
fetch_generation: 0,
parse_error: None,
work_task: WorkPoolTask {
node: Default::default(),
Expand Down Expand Up @@ -432,6 +434,8 @@ pub struct TranspilerJob {
pub global_this: BackRef<JSGlobalObject>,
pub(crate) poll_ref: KeepAlive,
pub(crate) generation_number: u32,
/// From `GenerationFetches::started`, for `settled`.
pub(crate) fetch_generation: u32,
pub(crate) log: bun_ast::Log,
pub(crate) parse_error: Option<crate::CrateError>,
/// Moved out by `run_from_js_thread`; dropped with the slot otherwise.
Expand Down Expand Up @@ -528,6 +532,7 @@ impl TranspilerJob {

fn run_from_js_thread(&mut self) -> JsResult<()> {
let vm = self.vm;
let fetch_generation = self.fetch_generation;
let promise = self.promise.swap();
let module_loader = self.module_loader.swap();
// Copy the BackRef out (it is `Copy`) so the borrow of `*self` ends
Expand Down Expand Up @@ -560,8 +565,9 @@ impl TranspilerJob {
(*vm)
.transpiler_store
.store
.put(std::ptr::from_mut::<TranspilerJob>(self))
};
.put(std::ptr::from_mut::<TranspilerJob>(self));
(*vm).module_fetches.settled(fetch_generation);
}

AsyncModule::fulfill(
&global_this,
Expand All @@ -580,7 +586,10 @@ impl TranspilerJob {
// `bun_runtime::init`).
self.poll_ref.ref_(get_vm_ctx(AllocatorType::Js));
// SAFETY: JS thread; the VM owns the store this slot lives in.
self.ticket = Some(unsafe { (*self.vm).ticket() });
unsafe {
self.fetch_generation = (*self.vm).module_fetches.started();
self.ticket = Some((*self.vm).ticket());
}
WorkPool::schedule(&raw mut self.work_task);
}

Expand Down
70 changes: 61 additions & 9 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,36 @@ pub struct EntryPointResult {
pub evaluated_as_cjs: bool,
}

/// Unsettled module fetches (transpile jobs, plugin `onLoad` promises) that one `--hot` generation started.
#[derive(Default)]
pub(crate) struct GenerationFetches {
generation: u32,
in_flight: u32,
}

impl GenerationFetches {
fn of(generation: u32) -> Self {
Self {
generation,
in_flight: 0,
}
}

/// Returns the generation to pass to [`settled`](Self::settled).
pub(crate) fn started(&mut self) -> u32 {
self.in_flight += 1;
self.generation
}

/// A fetch that an earlier generation started is not in this count.
pub(crate) fn settled(&mut self, generation: u32) {
if generation == self.generation {
debug_assert!(self.in_flight > 0);
self.in_flight = self.in_flight.saturating_sub(1);
}
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}

/// Downstream-compat alias: lib.rs previously exposed `virtual_machine::InitOptions`.
/// Carries the cross-tier subset of `Options` that [`init`] and
/// `RuntimeHooks::init_runtime_state` need. `transform_options`/`debugger`
Expand Down Expand Up @@ -296,6 +326,7 @@ pub struct VirtualMachine {
pub pending_internal_promise_is_protected: bool,
pub pending_internal_promise_reported_at: u32,
pub(crate) hot_reload_deferred: bool,
pub(crate) module_fetches: GenerationFetches,
pub entry_point_result: EntryPointResult,

pub on_unhandled_rejection: OnUnhandledRejection,
Expand Down Expand Up @@ -753,6 +784,17 @@ impl ExitHandler {
vm.entry_evaluation_started = true;
}

/// A plugin's `onLoad` returned a promise. Its reactions call [`Bun__VM__moduleFetchSettled`].
#[unsafe(no_mangle)]
pub(crate) extern "C" fn Bun__VM__moduleFetchStarted(vm: &mut VirtualMachine) -> u32 {
vm.module_fetches.started()
}

#[unsafe(no_mangle)]
pub(crate) extern "C" fn Bun__VM__moduleFetchSettled(vm: &mut VirtualMachine, generation: u32) {
vm.module_fetches.settled(generation);
}

/// Only a worker's start waits on this (`wait_for_worker_entry_evaluation`);
/// any other VM answers `true` so the hook's registry probe never runs there.
#[unsafe(no_mangle)]
Expand Down Expand Up @@ -3554,6 +3596,7 @@ impl VirtualMachine {
break;
}
self.event_loop_mut().tick();
self.retry_deferred_hot_reload();
let Some(p) = self.pending_internal_promise else {
break;
};
Expand Down Expand Up @@ -4432,7 +4475,7 @@ impl VirtualMachine {
(self.on_unhandled_rejection)(self, global_object, reason);
}

/// After a hot reload, surfaces the entry-point promise's rejection (if any) and re-arms the watcher.
/// Per watch-mode tick: reports the entry promise's rejection, retries a deferred reload, re-arms the watcher.
pub fn report_exception_in_hot_reloaded_module_if_needed(&mut self) {
let promise = match self.pending_internal_promise {
Some(p) => p,
Expand All @@ -4443,10 +4486,7 @@ impl VirtualMachine {
};
// SAFETY: `promise` is a live JSC heap cell tracked by the VM.
match crate::JSPromise::status_ptr(promise) {
crate::js_promise::Status::Pending => {
self.add_main_to_watcher_if_needed();
return;
}
crate::js_promise::Status::Pending => {}
crate::js_promise::Status::Rejected => {
if self.pending_internal_promise_reported_at != self.hot_reload_counter {
self.pending_internal_promise_reported_at = self.hot_reload_counter;
Expand All @@ -4465,10 +4505,15 @@ impl VirtualMachine {
crate::js_promise::Status::Fulfilled => {}
}

self.retry_deferred_hot_reload();
self.add_main_to_watcher_if_needed();
}

/// Runs a reload [`reload`] deferred; it defers itself again while the entry load is still in flight.
fn retry_deferred_hot_reload(&mut self) {
if self.hot_reload_deferred {
self.reload(None);
}
self.add_main_to_watcher_if_needed();
}
Comment thread
robobun marked this conversation as resolved.
Resolved

/// Adds the main entry point to the file watcher when watch mode is enabled.
Expand Down Expand Up @@ -4527,7 +4572,7 @@ impl VirtualMachine {
}
}

/// Performs a hot reload: re-evaluates the entry point once any pending entry-point load settles.
/// Re-evaluates the entry point, or defers to [`retry_deferred_hot_reload`] while its load is in flight.
pub(crate) fn reload(&mut self, _: Option<&mut crate::hot_reloader::HotReloadTask>) {
if self.hot_reload == HotReload::Watch {
// Watch reload replaces the process: never defer on a pending
Expand All @@ -4549,8 +4594,14 @@ impl VirtualMachine {
// SAFETY: `p` is a live JSC heap cell tracked by the VM.
match crate::JSPromise::status_ptr(p) {
crate::js_promise::Status::Pending => {
self.hot_reload_deferred = true;
return;
// Replaced only when parked on a top-level await: no load in flight (two would share the registry), no body running under this tick.
let parked = self.module_fetches.in_flight == 0
&& !self.global().vm().is_entered()
&& crate::cpp::Bun__entryRootIsAwaiting(self.global());
Comment thread
robobun marked this conversation as resolved.
Resolved
if !parked {
self.hot_reload_deferred = true;
return;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
}
crate::js_promise::Status::Rejected => {
if self.pending_internal_promise_reported_at != self.hot_reload_counter {
Expand Down Expand Up @@ -4583,6 +4634,7 @@ impl VirtualMachine {
// the JSC module loader registry.
self.global().reload().expect("Failed to reload");
self.hot_reload_counter += 1;
self.module_fetches = GenerationFetches::of(self.hot_reload_counter);
if self.pending_internal_promise_is_protected {
if let Some(p) = self.pending_internal_promise {
JSValue::from_cell(p).unprotect();
Expand Down
5 changes: 5 additions & 0 deletions src/jsc/bindings/ModuleLoader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ using namespace Zig;
using namespace WebCore;

extern "C" BunLoaderType Bun__getDefaultLoader(JSC::JSGlobalObject*, const BunString* specifier);
extern "C" uint32_t Bun__VM__moduleFetchStarted(void* bunVM);
extern "C" void Bun__VM__moduleFetchSettled(void* bunVM, uint32_t generation);

static JSC::JSPromise* rejectedInternalPromise(JSC::JSGlobalObject* globalObject, JSC::JSValue value)
{
Expand Down Expand Up @@ -453,6 +455,7 @@ static JSValue handleVirtualModuleResult(
ASSERT(!arguments.hasOverflowed());
JSC::profiledCall(globalObject, ProfilingReason::Microtask, performPromiseThenFunction, callData, jsUndefined(), arguments);
RETURN_IF_EXCEPTION(scope, {});
pendingModule->fetchGeneration = Bun__VM__moduleFetchStarted(globalObject->bunVM());
return internalPromise;
}
default: {
Expand Down Expand Up @@ -1272,6 +1275,7 @@ BUN_DEFINE_HOST_FUNCTION(jsFunctionOnLoadObjectResultResolve, (JSC::JSGlobalObje
ErrorableResolvedSource res;
JSC::JSValue objectResult = callFrame->argument(0);
PendingVirtualModuleResult* pendingModule = uncheckedDowncast<PendingVirtualModuleResult>(callFrame->argument(1));
Bun__VM__moduleFetchSettled(static_cast<Zig::GlobalObject*>(globalObject)->bunVM(), pendingModule->fetchGeneration);
JSC::JSValue specifierString = pendingModule->internalField(0).get();
JSC::JSValue referrerString = pendingModule->internalField(1).get();
pendingModule->internalField(0).set(vm, pendingModule, JSC::jsUndefined());
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -1308,6 +1312,7 @@ BUN_DEFINE_HOST_FUNCTION(jsFunctionOnLoadObjectResultReject, (JSC::JSGlobalObjec
auto& vm = JSC::getVM(globalObject);
JSC::JSValue reason = callFrame->argument(0);
PendingVirtualModuleResult* pendingModule = uncheckedDowncast<PendingVirtualModuleResult>(callFrame->argument(1));
Bun__VM__moduleFetchSettled(static_cast<Zig::GlobalObject*>(globalObject)->bunVM(), pendingModule->fetchGeneration);
pendingModule->internalField(0).set(vm, pendingModule, JSC::jsUndefined());
pendingModule->internalField(1).set(vm, pendingModule, JSC::jsUndefined());
JSC::JSPromise* promise = pendingModule->internalPromise();
Expand Down
2 changes: 2 additions & 0 deletions src/jsc/bindings/ModuleLoader.h
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ class PendingVirtualModuleResult : public JSC::JSInternalFieldObjectImpl<3> {
void finishCreation(JSC::VM&, const WTF::String& specifier, const WTF::String& referrer);

bool wasModuleMock = false;
// From Bun__VM__moduleFetchStarted, for Bun__VM__moduleFetchSettled.
uint32_t fetchGeneration = 0;
};

// `graph`: the Bun.ModuleGraph whose loader is fetching, or null. A CommonJS file
Expand Down
33 changes: 20 additions & 13 deletions src/jsc/bindings/ZigGlobalObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4320,24 +4320,31 @@ extern "C" bool Bun__VM__entryEvaluationStarted(void*);
extern "C" BunString Bun__VM__entryRootKey(void*);
extern "C" void Bun__VM__noteEntryEvaluationStarted(void*);

// A module body is about to run. That means "the entry's graph is linked and executing" only if it is
// part of the entry root's own evaluation — the root's record is Evaluating (or beyond) from the moment
// linkAndEvaluateModule() enters it, and its dependencies run inside that (post-order). A module that
// evaluates before then is some other root: a preload's un-awaited import() finishing while the entry is
// still fetching.
static void noteModuleEvaluation(Zig::GlobalObject* globalObject, JSModuleLoader* moduleLoader)
// Evaluating: the entry's graph is linked and its bodies are on the stack. EvaluatingAsync: only a top-level await is left.
static bool entryRootReached(Zig::GlobalObject* globalObject, JSModuleLoader* moduleLoader, JSC::CyclicModuleRecord::Status status)
{
void* bunVM = globalObject->bunVM();
if (Bun__VM__entryEvaluationStarted(bunVM))
return;
BunString rootKey = Bun__VM__entryRootKey(bunVM);
BunString rootKey = Bun__VM__entryRootKey(globalObject->bunVM());
auto* entry = moduleLoader->registryEntry(JSC::Identifier::fromString(globalObject->vm(), rootKey.toWTFString(BunString::ZeroCopy)));
if (!entry)
return;
return false;
auto* cyclic = dynamicDowncast<JSC::CyclicModuleRecord>(entry->record());
if (!cyclic || cyclic->status() < JSC::CyclicModuleRecord::Status::Evaluating)
return cyclic && cyclic->status() >= status;
}

// Asked by a --hot reload that finds the entry promise still pending (VirtualMachine::reload).
extern "C" [[ZIG_EXPORT(nothrow)]] bool Bun__entryRootIsAwaiting(Zig::GlobalObject* globalObject)
{
return entryRootReached(globalObject, globalObject->moduleLoader(), JSC::CyclicModuleRecord::Status::EvaluatingAsync);
}

// A body running before the root is Evaluating belongs to another root (a preload's un-awaited import()).
static void noteModuleEvaluation(Zig::GlobalObject* globalObject, JSModuleLoader* moduleLoader)
{
void* bunVM = globalObject->bunVM();
if (Bun__VM__entryEvaluationStarted(bunVM))
return;
Bun__VM__noteEntryEvaluationStarted(bunVM);
if (entryRootReached(globalObject, moduleLoader, JSC::CyclicModuleRecord::Status::Evaluating))
Bun__VM__noteEntryEvaluationStarted(bunVM);
}

JSC::JSValue GlobalObject::moduleLoaderEvaluate(JSGlobalObject* lexicalGlobalObject,
Expand Down
5 changes: 3 additions & 2 deletions src/runtime/jsc_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -647,14 +647,15 @@ unsafe fn deinit_runtime_state(_vm: *mut VirtualMachine, state: OpaqueRuntimeSta
/// `ServerEntryPoint.generate(watch, entry_path)` — produces the synthetic
/// `bun:main` wrapper. Returns `false` on error (the error is already logged
/// into `vm.log` by `generate`).
fn generate_entry_point(_vm: &VirtualMachine, watch: bool, entry_path: &[u8]) -> bool {
fn generate_entry_point(vm: &VirtualMachine, watch: bool, entry_path: &[u8]) -> bool {
let state = runtime_state();
if state.is_null() {
return false;
}
// SAFETY: `state` is the live per-thread `RuntimeState` (boxed in
// `init_runtime_state`); no other `&mut` to `entry_point` is held here.
ServerEntryPoint::generate(unsafe { &mut (*state).entry_point }, watch, entry_path).is_ok()
let entry_point = unsafe { &mut (*state).entry_point };
ServerEntryPoint::generate(entry_point, watch, vm.hot_reload_counter, entry_path).is_ok()
}

/// `loadPreloads()` — runs `--preload` scripts. Returns the first rejected
Expand Down
Loading
Loading