diff --git a/docs/runtime/cron.mdx b/docs/runtime/cron.mdx index 4f16bab4c486..23056a1ef0e7 100644 --- a/docs/runtime/cron.mdx +++ b/docs/runtime/cron.mdx @@ -204,7 +204,7 @@ job.ref(); // keep the process alive (default) ### Fake timers -In-process cron honors `jest.useFakeTimers()`. `setSystemTime()`, `advanceTimersByTime()`, and `runAllTimers()` control when it fires, so you can test scheduled callbacks without waiting on the real clock. +In-process cron honors `jest.useFakeTimers()`. `setSystemTime()`, `advanceTimersByTime()`, and `runOnlyPendingTimers()` control when it fires, so you can test scheduled callbacks without waiting on the real clock. Because a cron job re-arms itself after every fire, `jest.runAllTimers()` will hit the `timerLimit` cap (default 100000) and throw; use `advanceTimersByTime()` or `runOnlyPendingTimers()` instead. --- diff --git a/packages/bun-types/test.d.ts b/packages/bun-types/test.d.ts index 38a6b3928b74..a324663e9c5b 100644 --- a/packages/bun-types/test.d.ts +++ b/packages/bun-types/test.d.ts @@ -94,7 +94,14 @@ declare module "bun:test" { function fn any>(func?: T): Mock; function setSystemTime(now?: number | Date): void; function setTimeout(milliseconds: number): void; - function useFakeTimers(options?: { now?: number | Date }): typeof vi; + function useFakeTimers(options?: { + now?: number | Date; + /** + * Maximum number of timers `runAllTimers()` will run before throwing an + * "assuming an infinite loop" error. Defaults to 100000. + */ + timerLimit?: number; + }): typeof vi; function useRealTimers(): typeof vi; function advanceTimersByTime(milliseconds: number): typeof vi; function advanceTimersToNextTimer(): typeof vi; diff --git a/src/runtime/test_runner/timers/FakeTimers.rs b/src/runtime/test_runner/timers/FakeTimers.rs index 2b3f0b29b0cd..68840397db54 100644 --- a/src/runtime/test_runner/timers/FakeTimers.rs +++ b/src/runtime/test_runner/timers/FakeTimers.rs @@ -19,6 +19,10 @@ unsafe extern "C" { #[derive(Default)] pub struct FakeTimers { active: bool, + /// Jest's `timerLimit`: maximum recursive timers `runAllTimers()` will drain + /// before throwing. Set by `useFakeTimers({ timerLimit })`; defaults to + /// `DEFAULT_TIMER_LIMIT` on every activation. + timer_limit: u32, /// The sorted fake timers. TimerHeap is not optimal here because we need these operations: /// - peek/takeFirst (provided by TimerHeap) /// - peekLast (cannot be implemented efficiently with TimerHeap) @@ -26,6 +30,8 @@ pub struct FakeTimers { pub timers: TimerHeap, } +const DEFAULT_TIMER_LIMIT: u32 = 100_000; + // `date_now_offset` is stored as `AtomicU64` (f64 bits) so the static is `Sync` // without `static mut`. pub struct CurrentTime { @@ -119,8 +125,9 @@ impl FakeTimers { self.active } - fn activate(&mut self, js_now: f64, global: &JSGlobalObject) { + fn activate(&mut self, js_now: f64, timer_limit: u32, global: &JSGlobalObject) { self.active = true; + self.timer_limit = timer_limit; CURRENT_TIME.set(global, &Timespec::EPOCH, Some(js_now)); } @@ -222,8 +229,24 @@ impl FakeTimers { Self::execute_until(global, until); } - fn execute_all_timers(global: &JSGlobalObject) { - while Self::execute_next(global) {} + fn execute_all_timers(global: &JSGlobalObject) -> JsResult<()> { + // Jest caps runAllTimers() so a self-re-arming timer (setInterval, + // Bun.cron) can't spin the drain loop forever. + let all = timer_all(); + // SAFETY: per-thread `timer::All`, live for the VM lifetime. + let limit = unsafe { (*all).fake_timers.timer_limit }; + for _ in 0..limit { + if !Self::execute_next(global) { + return Ok(()); + } + } + // SAFETY: as above; borrow ends at this statement. + if unsafe { (*all).fake_timers.timers.peek() }.is_none() { + return Ok(()); + } + Err(global.throw(format_args!( + "Aborting after running {limit} timers, assuming an infinite loop!" + ))) } } @@ -268,6 +291,7 @@ fn set_fake_timer_marker(global: &JSGlobalObject, enabled: bool) { fn use_fake_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { // SAFETY: FFI call into C++ JSMock let mut js_now = JSMock__getCurrentUnixTimeMs(); + let mut timer_limit = DEFAULT_TIMER_LIMIT; // Check if options object was provided let args = frame.arguments_as_array::<1>(); @@ -289,10 +313,24 @@ fn use_fake_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult u32::MAX as f64 || n.trunc() != n { + return Err(global.throw_invalid_arguments(format_args!( + "'timerLimit' must be a positive integer" + ))); + } + timer_limit = n as u32; + } } // SAFETY: per-thread `timer::All`; `activate` does not re-enter `All`. - unsafe { (*timer_all()).fake_timers.activate(js_now, global) }; + unsafe { (*timer_all()).fake_timers.activate(js_now, timer_limit, global) }; // 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. @@ -373,7 +411,7 @@ fn run_only_pending_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResu fn run_all_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { error_unless_fake_timers(global)?; - FakeTimers::execute_all_timers(global); + FakeTimers::execute_all_timers(global)?; Ok(frame.this()) } diff --git a/test/js/bun/test/fake-timers/fake-timers.test.ts b/test/js/bun/test/fake-timers/fake-timers.test.ts index 40ae5b1daae3..f163f026db26 100644 --- a/test/js/bun/test/fake-timers/fake-timers.test.ts +++ b/test/js/bun/test/fake-timers/fake-timers.test.ts @@ -1,3 +1,4 @@ +import { bunEnv, bunExe } from "harness"; import { afterEach, describe, expect, test, vi } from "vitest"; afterEach(() => vi.useRealTimers()); @@ -161,6 +162,86 @@ describe("runAllTimers", () => { vi.runAllTimers(); expect(order.takeOrderMessages()).toEqual(["9", "10", "14", "20"]); }); + + // Without the iteration cap these spin at 100% CPU forever, so run each in a + // subprocess with a spawn-side timeout as the fail-before guard. + async function runAllTimersFixture(options: string, setup: string) { + const src = ` + const { jest } = require("bun:test"); + jest.useFakeTimers(${options}); + let fires = 0; + ${setup} + try { + jest.runAllTimers(); + console.log(JSON.stringify({ threw: false, fires })); + } catch (e) { + console.log(JSON.stringify({ threw: true, message: String(e.message), fires })); + } + stop(); + jest.useRealTimers(); + `; + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", src], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + timeout: 10_000, + killSignal: "SIGKILL", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout, stderr, exitCode, signalCode: proc.signalCode }; + } + + test.concurrent.each([ + ["setInterval", `const id = setInterval(() => fires++, 10); const stop = () => clearInterval(id);`], + [ + "recursive setTimeout", + `const tick = () => { fires++; setTimeout(tick, 10); }; setTimeout(tick, 10); const stop = () => {};`, + ], + ["Bun.cron", `const job = Bun.cron("* * * * *", () => fires++); const stop = () => job.stop();`], + ])("aborts with an error when %s re-arms forever", async (_name, setup) => { + const { stdout, stderr, exitCode, signalCode } = await runAllTimersFixture("{ timerLimit: 50 }", setup); + expect({ stdout, signalCode, stderr }).toEqual({ + stdout: + JSON.stringify({ + threw: true, + message: "Aborting after running 50 timers, assuming an infinite loop!", + fires: 50, + }) + "\n", + signalCode: null, + stderr: expect.not.stringContaining("error:"), + }); + expect(exitCode).toBe(0); + }); + + test.concurrent.each([ + ["below", 5], + ["at", 50], + ])("does not abort when the chain terminates %s the limit", async (_where, n) => { + const setup = ` + let remaining = ${n}; + const tick = () => { fires++; if (--remaining > 0) setTimeout(tick, 10); }; + setTimeout(tick, 10); + const stop = () => {}; + `; + const { stdout, stderr, exitCode, signalCode } = await runAllTimersFixture("{ timerLimit: 50 }", setup); + expect({ stdout, signalCode, stderr }).toEqual({ + stdout: JSON.stringify({ threw: false, fires: n }) + "\n", + signalCode: null, + stderr: expect.not.stringContaining("error:"), + }); + expect(exitCode).toBe(0); + }); + + test("timerLimit validation", () => { + for (const bad of [0, -1, 1.5, NaN, Infinity, "ten", {}]) { + expect(() => vi.useFakeTimers({ timerLimit: bad as any })).toThrow("'timerLimit' must be a positive integer"); + } + expect(() => vi.useFakeTimers({ timerLimit: undefined })).not.toThrow(); + vi.useRealTimers(); + expect(() => vi.useFakeTimers({ timerLimit: 1 })).not.toThrow(); + vi.useRealTimers(); + }); }); describe("getTimerCount", () => { test("returns correct count of pending timers", () => {