Skip to content
Closed
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
2 changes: 2 additions & 0 deletions src/jsc/bindings/headers.h

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

56 changes: 53 additions & 3 deletions src/jsc/bindings/node/NodeTimers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ namespace Bun {

using namespace JSC;

JSC_DEFINE_HOST_FUNCTION(functionSetTimeout,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
static JSC::EncodedJSValue setTimeoutImpl(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame, bool fakeable)
{
auto& vm = JSC::getVM(globalObject);
JSC::JSValue job = callFrame->argument(0);
Expand Down Expand Up @@ -63,11 +62,25 @@ JSC_DEFINE_HOST_FUNCTION(functionSetTimeout,
}
#endif

if (fakeable) {
RELEASE_AND_RETURN(scope, Bun__Timer__setFakeTimeout(globalObject, JSC::JSValue::encode(job), JSC::JSValue::encode(arguments), JSValue::encode(num)));
}
RELEASE_AND_RETURN(scope, Bun__Timer__setTimeout(globalObject, JSC::JSValue::encode(job), JSC::JSValue::encode(arguments), JSValue::encode(num)));
}

JSC_DEFINE_HOST_FUNCTION(functionSetInterval,
JSC_DEFINE_HOST_FUNCTION(functionSetTimeout,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
return setTimeoutImpl(globalObject, callFrame, false);
}

JSC_DEFINE_HOST_FUNCTION(functionFakeSetTimeout,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
return setTimeoutImpl(globalObject, callFrame, true);
}

static JSC::EncodedJSValue setIntervalImpl(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame, bool fakeable)
{
auto& vm = JSC::getVM(globalObject);
JSC::JSValue job = callFrame->argument(0);
Expand Down Expand Up @@ -120,9 +133,24 @@ JSC_DEFINE_HOST_FUNCTION(functionSetInterval,
}
#endif

if (fakeable) {
RELEASE_AND_RETURN(scope, Bun__Timer__setFakeInterval(globalObject, JSC::JSValue::encode(job), JSC::JSValue::encode(arguments), JSValue::encode(num)));
}
RELEASE_AND_RETURN(scope, Bun__Timer__setInterval(globalObject, JSC::JSValue::encode(job), JSC::JSValue::encode(arguments), JSValue::encode(num)));
}

JSC_DEFINE_HOST_FUNCTION(functionSetInterval,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
return setIntervalImpl(globalObject, callFrame, false);
}

JSC_DEFINE_HOST_FUNCTION(functionFakeSetInterval,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
return setIntervalImpl(globalObject, callFrame, true);
}

// https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate
JSC_DEFINE_HOST_FUNCTION(functionSetImmediate,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
Expand Down Expand Up @@ -278,11 +306,33 @@ JSValue createSetTimeoutFunction(VM& vm, JSObject* globalObject)
return createTimerFunction(vm, globalObject, "setTimeout"_s, functionSetTimeout, setTimeoutPromisifyCustomGetter);
}

JSValue createFakeSetTimeoutFunction(VM& vm, JSObject* globalObject)
{
return createTimerFunction(vm, globalObject, "setTimeout"_s, functionFakeSetTimeout, setTimeoutPromisifyCustomGetter);
}

JSValue createSetIntervalFunction(VM& vm, JSObject* globalObject)
{
return createTimerFunction(vm, globalObject, "setInterval"_s, functionSetInterval, setIntervalPromisifyCustomGetter);
}

JSValue createFakeSetIntervalFunction(VM& vm, JSObject* globalObject)
{
return createTimerFunction(vm, globalObject, "setInterval"_s, functionFakeSetInterval, setIntervalPromisifyCustomGetter);
}

extern "C" EncodedJSValue JSMock__createFakeSetTimeoutFunction(JSGlobalObject* lexicalGlobalObject)
{
auto& vm = getVM(lexicalGlobalObject);
return JSValue::encode(createFakeSetTimeoutFunction(vm, defaultGlobalObject(lexicalGlobalObject)));
}

extern "C" EncodedJSValue JSMock__createFakeSetIntervalFunction(JSGlobalObject* lexicalGlobalObject)
{
auto& vm = getVM(lexicalGlobalObject);
return JSValue::encode(createFakeSetIntervalFunction(vm, defaultGlobalObject(lexicalGlobalObject)));
}

JSValue createSetImmediateFunction(VM& vm, JSObject* globalObject)
{
return createTimerFunction(vm, globalObject, "setImmediate"_s, functionSetImmediate, setImmediatePromisifyCustomGetter);
Expand Down
4 changes: 4 additions & 0 deletions src/jsc/bindings/node/NodeTimers.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
namespace Bun {

JSC_DECLARE_HOST_FUNCTION(functionSetTimeout);
JSC_DECLARE_HOST_FUNCTION(functionFakeSetTimeout);
JSC_DECLARE_HOST_FUNCTION(functionSetInterval);
JSC_DECLARE_HOST_FUNCTION(functionFakeSetInterval);
JSC_DECLARE_HOST_FUNCTION(functionSetImmediate);
JSC_DECLARE_HOST_FUNCTION(functionClearTimeout);
JSC_DECLARE_HOST_FUNCTION(functionClearInterval);
Expand All @@ -15,7 +17,9 @@ JSC_DECLARE_HOST_FUNCTION(functionClearImmediate);
// setInterval / setImmediate with Node's `[util.promisify.custom]` accessor,
// which resolves to the node:timers/promises implementation on first read.
JSC::JSValue createSetTimeoutFunction(JSC::VM&, JSC::JSObject* globalObject);
JSC::JSValue createFakeSetTimeoutFunction(JSC::VM&, JSC::JSObject* globalObject);
JSC::JSValue createSetIntervalFunction(JSC::VM&, JSC::JSObject* globalObject);
JSC::JSValue createFakeSetIntervalFunction(JSC::VM&, JSC::JSObject* globalObject);
JSC::JSValue createSetImmediateFunction(JSC::VM&, JSC::JSObject* globalObject);

} // namespace Bun
68 changes: 50 additions & 18 deletions src/runtime/test_runner/timers/FakeTimers.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use bun_core::Timespec;
use bun_jsc::bindgen::{JsHeap, JsLocal, JsScope};
use bun_jsc::{JSFunction, JSGlobalObject, JSHostFn, JSValue, JsResult};
use bun_jsc::{JSFunction, JSGlobalObject, JSHostFn, JSValue, JsResult, Strong};
use crate::api::cron::CronJob;
use crate::generated_bindgen::fake_timers::{
Bun__FakeTimers__advanceTimersByTime, Bun__FakeTimers__advanceTimersToNextTimer,
Expand All @@ -18,6 +18,8 @@ use crate::timer::{
unsafe extern "C" {
safe fn JSMock__setOverridenDateNow(global: &JSGlobalObject, value: f64);
safe fn JSMock__getCurrentUnixTimeMs() -> f64;
safe fn JSMock__createFakeSetTimeoutFunction(global: &JSGlobalObject) -> JSValue;
safe fn JSMock__createFakeSetIntervalFunction(global: &JSGlobalObject) -> JSValue;
}

#[derive(Default)]
Expand All @@ -26,6 +28,8 @@ pub(crate) struct FakeTimers {
now: Option<Timespec>,
/// `Date.now()` minus `now.ms()`.
date_now_offset: f64,
original_set_timeout: Option<Strong>,
original_set_interval: Option<Strong>,
/// Depth of [`FakeTimers::fire`] calls on the stack; each covers the callback and its microtask drain.
firing: u32,
/// The sorted fake timers. TimerHeap is not optimal here because we need these operations:
Expand Down Expand Up @@ -154,11 +158,28 @@ impl FakeTimers {
if self.is_active() && self.firing > 0 { 1 } else { 0 }
}

fn activate(&mut self, js_now: f64, global: &JSGlobalObject) {
fn activate(&mut self, js_now: f64, global: &JSGlobalObject) -> JsResult<()> {
let global_this = global.to_js_value();
if self.original_set_timeout.is_none() {
let original = global_this
.get(global, "setTimeout")?
.ok_or_else(|| global.throw(format_args!("globalThis.setTimeout is not available")))?;
self.original_set_timeout = Some(Strong::create(original, global));
}
if self.original_set_interval.is_none() {
let original = global_this
.get(global, "setInterval")?
.ok_or_else(|| global.throw(format_args!("globalThis.setInterval is not available")))?;
self.original_set_interval = Some(Strong::create(original, global));
}
global_this.put(global, b"setTimeout", JSMock__createFakeSetTimeoutFunction(global));
global_this.put(global, b"setInterval", JSMock__createFakeSetIntervalFunction(global));
self.set_now(global, &Timespec::EPOCH, Some(js_now));
Ok(())
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

fn deactivate(&mut self, global: &JSGlobalObject) -> ClearedTimers {
self.restore_timer_functions(global);
let cleared = self.clear();
self.clear_now(global);
cleared
Expand All @@ -170,9 +191,20 @@ impl FakeTimers {
/// JS has stopped) can walk the still-populated fake heap and release
/// `TimeoutObject` pins and discard `AbortSignalTimeout` timers.
pub(crate) fn reset_for_isolation(&mut self, global: &JSGlobalObject) {
self.restore_timer_functions(global);
self.clear_now(global);
}

fn restore_timer_functions(&mut self, global: &JSGlobalObject) {
let global_this = global.to_js_value();
if let Some(original) = self.original_set_timeout.take() {
global_this.put(global, b"setTimeout", original.get());
}
if let Some(original) = self.original_set_interval.take() {
global_this.put(global, b"setInterval", original.get());
}
}

/// Pop every fake timer. Popping only unlinks the nodes; the owners that
/// need to hear about it are returned for the caller to release.
fn clear(&mut self) -> ClearedTimers {
Expand Down Expand Up @@ -360,33 +392,33 @@ pub(crate) fn use_fake_timers(
js_now = now;
}

// Set setTimeout.clock = true to signal that fake timers are enabled.
// This is used by testing-library/react to detect if jest.advanceTimersByTime should be called.
// This can run user code and throw, so do it before turning on the fake clock.
set_fake_timer_marker(global, true)?;

// SAFETY: `timer::All` is per-thread, and `activate` doesn't re-enter it.
unsafe { (*timer_all()).fake_timers.activate(js_now, global) };
unsafe { (*timer_all()).fake_timers.activate(js_now, global)? };

// Mark the installed fake function, rather than the real setTimeout that
// activate() just replaced. If defining the marker fails, roll back the
// activation so useFakeTimers() cannot leave the clock partially enabled.
if let Err(error) = set_fake_timer_marker(global, true) {
let cleared = unsafe { (*timer_all()).fake_timers.deactivate(global) };
cleared.release(global.bun_vm_ptr());
return Err(error);
}

Ok(bun_jsc::cpp::JSMock__toThisStrict(
global,
this_value.to_js(),
))
Ok(bun_jsc::cpp::JSMock__toThisStrict(global, this_value.to_js()))
}

pub(crate) fn use_real_timers(cx: &mut JsScope<'_>, this_value: JsLocal<'_>) -> JsResult<JSValue> {
let global = cx.global();
// Remove the marker from the fake function before restoring the real one.
let marker_result = set_fake_timer_marker(global, false);
// SAFETY: per-thread `timer::All`; the borrow ends before `release`.
let cleared = unsafe { (*timer_all()).fake_timers.deactivate(global) };
cleared.release(global.bun_vm_ptr());

// Remove the setTimeout.clock marker when switching back to real timers.
set_fake_timer_marker(global, false)?;
// Complete teardown even if removing the marker ran a throwing accessor.
marker_result?;

Ok(bun_jsc::cpp::JSMock__toThisStrict(
global,
this_value.to_js(),
))
Ok(bun_jsc::cpp::JSMock__toThisStrict(global, this_value.to_js()))
}

pub(crate) fn advance_timers_to_next_timer(
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/timer/ImmediateObject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ impl ImmediateObject {
callback: JSValue,
arguments: JSValue,
) -> JSValue {
Self::init_with(cx, id, Kind::SetImmediate, 0, callback, arguments)
Self::init_with(cx, id, Kind::SetImmediate, 0, callback, arguments, false)
}

/// Thin forwarder to
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/timer/TimeoutObject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ impl TimeoutObject {
interval: u32,
callback: JSValue,
arguments: JSValue,
fakeable: bool,
) -> JSValue {
Self::init_with(cx, id, kind, interval, callback, arguments)
Self::init_with(cx, id, kind, interval, callback, arguments, fakeable)
}

pub(crate) fn refresh(
Expand Down
55 changes: 53 additions & 2 deletions src/runtime/timer/Timer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ impl All {
countdown_int,
wrapped_promise,
JSValue::UNDEFINED,
true,
))
}

Expand All @@ -219,6 +220,7 @@ impl All {
callback: JSValue,
arguments: JSValue,
countdown: JSValue,
fakeable: bool,
) -> JsResult<JSValue> {
bun_jsc::mark_binding!();
debug_assert!(!callback.is_empty() && !arguments.is_empty() && !countdown.is_empty());
Expand All @@ -239,6 +241,7 @@ impl All {
countdown_int,
wrapped_callback,
arguments,
fakeable,
))
}

Expand All @@ -247,6 +250,7 @@ impl All {
callback: JSValue,
arguments: JSValue,
countdown: JSValue,
fakeable: bool,
) -> JsResult<JSValue> {
bun_jsc::mark_binding!();
debug_assert!(!callback.is_empty() && !arguments.is_empty() && !countdown.is_empty());
Expand All @@ -267,6 +271,7 @@ impl All {
countdown_int,
wrapped_callback,
arguments,
fakeable,
))
}

Expand Down Expand Up @@ -528,7 +533,30 @@ pub(crate) fn set_timeout_export(
countdown: JSValue,
) -> JsResult<JSValue> {
let context = global.bun_vm().context_of_caller();
All::set_timeout(&global.js_thread(context), callback, arguments, countdown)
All::set_timeout(
&global.js_thread(context),
callback,
arguments,
countdown,
false,
)
}

// HOST_EXPORT(Bun__Timer__setFakeTimeout, c)
pub(crate) fn set_fake_timeout_export(
global: &JSGlobalObject,
callback: JSValue,
arguments: JSValue,
countdown: JSValue,
) -> JsResult<JSValue> {
let context = global.bun_vm().context_of_caller();
All::set_timeout(
&global.js_thread(context),
callback,
arguments,
countdown,
true,
)
}

// HOST_EXPORT(Bun__Timer__setInterval, c)
Expand All @@ -539,7 +567,30 @@ pub(crate) fn set_interval_export(
countdown: JSValue,
) -> JsResult<JSValue> {
let context = global.bun_vm().context_of_caller();
All::set_interval(&global.js_thread(context), callback, arguments, countdown)
All::set_interval(
&global.js_thread(context),
callback,
arguments,
countdown,
false,
)
}

// HOST_EXPORT(Bun__Timer__setFakeInterval, c)
pub(crate) fn set_fake_interval_export(
global: &JSGlobalObject,
callback: JSValue,
arguments: JSValue,
countdown: JSValue,
) -> JsResult<JSValue> {
let context = global.bun_vm().context_of_caller();
All::set_interval(
&global.js_thread(context),
callback,
arguments,
countdown,
true,
)
}

// HOST_EXPORT(Bun__Timer__clearImmediate, c)
Expand Down
Loading
Loading