mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Add deterministic timer mock to Fantom (#57274)
Summary: Pull Request resolved: https://github.com/react/react-native/pull/57274 Fantom could not deterministically fire delayed JS timers: the timer registry it used scheduled timers on a real background thread with real wall-clock delays, so `setTimeout(fn, 100)`/`setInterval` callbacks never fired within a synchronous test. This adds a mockable timer registry and a public Fantom API to control it from JS, similar to `installHighResTimeStampMock`. - New `Fantom.installTimerMock()` returns a controller with `advanceTimersByTime(ms)`, `runAllTimers()`, `getPendingTimerCount()`, and `uninstall()` (jest fake-timer style). While installed, `setTimeout`/`setInterval` callbacks only fire when the virtual clock is advanced. - New deterministic `FantomTimerRegistry` (no background thread) keyed off a virtual clock, injected via a new optional `platformTimerRegistryFactory` seam on `ReactInstanceConfig` (the default registry is unchanged for all other consumers). - `PlatformTimerRegistry` gains a virtual `setTimerManager` (default no-op) so the registry can be wired polymorphically. - Control flows from JS through new `NativeFantom` methods, the same way the high-res timestamp mock works. Default (non-mock) behavior is preserved: zero-delay `setTimeout` still fires on the next work loop, and existing tests are unaffected. Changelog: [Internal] Reviewed By: christophpurrer Differential Revision: D109017304 fbshipit-source-id: 8afe6fb2a39f470ae293038f6592c46535442dc2
This commit is contained in:
1 parent
ad2cf4d1d7
commit
2d491c0c75
26 files changed
+730
-7
No files matched your search
@@ -8,9 +8,12 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
class TimerManager;
|
||||
|
||||
/**
|
||||
* This interface is implemented by each platform.
|
||||
* Responsibility: Call into some platform API to register/schedule, or delete
|
||||
@@ -27,6 +30,13 @@ class PlatformTimerRegistry {
|
||||
virtual ~PlatformTimerRegistry() noexcept = default;
|
||||
|
||||
virtual void quit() {}
|
||||
|
||||
/**
|
||||
* Provides the owning TimerManager so the registry can fire due timers via
|
||||
* TimerManager::callTimer. The default is a no-op for platforms that wire the
|
||||
* TimerManager through other means.
|
||||
*/
|
||||
virtual void setTimerManager(std::weak_ptr<TimerManager> /*timerManager*/) {}
|
||||
};
|
||||
|
||||
using TimerManagerDelegate = PlatformTimerRegistry;
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ class ObjCTimerRegistry : public facebook::react::PlatformTimerRegistry {
|
||||
void createTimer(uint32_t timerID, double delayMS) override;
|
||||
void deleteTimer(uint32_t timerID) override;
|
||||
void createRecurringTimer(uint32_t timerID, double delayMS) override;
|
||||
void setTimerManager(std::weak_ptr<facebook::react::TimerManager> timerManager);
|
||||
void setTimerManager(std::weak_ptr<facebook::react::TimerManager> timerManager) override;
|
||||
RCTTiming *_Null_unspecified timing;
|
||||
|
||||
private:
|
||||
|
||||
@@ -31,7 +31,7 @@ class PlatformTimerRegistryImpl : public PlatformTimerRegistry {
|
||||
|
||||
void createRecurringTimer(uint32_t timerID, double delayMs) override;
|
||||
|
||||
void setTimerManager(std::weak_ptr<TimerManager> timerManager);
|
||||
void setTimerManager(std::weak_ptr<TimerManager> timerManager) override;
|
||||
|
||||
void quit() override;
|
||||
|
||||
|
||||
@@ -114,7 +114,12 @@ ReactHost::~ReactHost() noexcept {
|
||||
|
||||
void ReactHost::createReactInstance() {
|
||||
// Set up timers
|
||||
auto platformTimers = std::make_unique<PlatformTimerRegistryImpl>();
|
||||
std::unique_ptr<PlatformTimerRegistry> platformTimers;
|
||||
if (reactInstanceConfig_.platformTimerRegistryFactory) {
|
||||
platformTimers = reactInstanceConfig_.platformTimerRegistryFactory();
|
||||
} else {
|
||||
platformTimers = std::make_unique<PlatformTimerRegistryImpl>();
|
||||
}
|
||||
auto* platformTimersPtr = platformTimers.get();
|
||||
auto timerManager = std::make_shared<TimerManager>(std::move(platformTimers));
|
||||
platformTimersPtr->setTimerManager(timerManager);
|
||||
|
||||
@@ -8,10 +8,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <react/debug/flags.h>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
class PlatformTimerRegistry;
|
||||
|
||||
struct ReactInstanceConfig {
|
||||
std::string appId;
|
||||
std::string deviceName;
|
||||
@@ -24,6 +28,12 @@ struct ReactInstanceConfig {
|
||||
#endif
|
||||
std::string devServerHost{"localhost"};
|
||||
uint32_t devServerPort{8081};
|
||||
|
||||
// Optional factory used to create the PlatformTimerRegistry for the instance.
|
||||
// When unset, a default thread-based PlatformTimerRegistryImpl is used. This
|
||||
// is a seam for tests (e.g. Fantom) to inject a deterministic, mockable timer
|
||||
// registry.
|
||||
std::function<std::unique_ptr<PlatformTimerRegistry>()> platformTimerRegistryFactory{nullptr};
|
||||
};
|
||||
|
||||
} // namespace facebook::react
|
||||
@@ -124,6 +124,10 @@ interface Spec extends TurboModule {
|
||||
): () => ?number;
|
||||
saveJSMemoryHeapSnapshot: (filePath: string) => void;
|
||||
forceHighResTimeStamp: (timeStamp: ?number) => void;
|
||||
setTimerMockEnabled: (enabled: boolean) => void;
|
||||
advanceTimers: (deltaMs: number) => void;
|
||||
runAllTimers: () => void;
|
||||
getPendingTimerCount: () => number;
|
||||
startJSSamplingProfiler: () => void;
|
||||
stopJSSamplingProfilerAndSaveToFile: (filePath: string) => void;
|
||||
setImageResponse(uri: string, imageResponse: ImageResponse): void;
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict-local
|
||||
* @format
|
||||
*/
|
||||
|
||||
import type {TimerMock} from '@react-native/fantom';
|
||||
|
||||
import * as Fantom from '@react-native/fantom';
|
||||
|
||||
import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
|
||||
|
||||
let timers: TimerMock;
|
||||
|
||||
beforeEach(() => {
|
||||
timers = Fantom.installTimerMock();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
timers.uninstall();
|
||||
});
|
||||
|
||||
describe('setTimeout', () => {
|
||||
it('does not fire before the delay elapses', () => {
|
||||
const callback = jest.fn();
|
||||
setTimeout(callback, 100);
|
||||
|
||||
timers.advanceTimersByTime(99);
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it('fires once after the delay elapses', () => {
|
||||
const callback = jest.fn();
|
||||
setTimeout(callback, 100);
|
||||
|
||||
timers.advanceTimersByTime(100);
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not fire again after firing once', () => {
|
||||
const callback = jest.fn();
|
||||
setTimeout(callback, 100);
|
||||
|
||||
timers.advanceTimersByTime(1000);
|
||||
timers.advanceTimersByTime(1000);
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('passes additional arguments to the callback', () => {
|
||||
const callback = jest.fn();
|
||||
setTimeout(callback, 100, 'a', 'b');
|
||||
|
||||
timers.advanceTimersByTime(100);
|
||||
|
||||
expect(callback).toHaveBeenCalledWith('a', 'b');
|
||||
});
|
||||
|
||||
it('fires multiple timers in order of their due time', () => {
|
||||
const calls: Array<string> = [];
|
||||
setTimeout(() => calls.push('second'), 200);
|
||||
setTimeout(() => calls.push('first'), 100);
|
||||
|
||||
timers.advanceTimersByTime(200);
|
||||
|
||||
expect(calls).toEqual(['first', 'second']);
|
||||
});
|
||||
|
||||
it('runs timers scheduled by other timers on the next advance', () => {
|
||||
const callback = jest.fn();
|
||||
setTimeout(() => {
|
||||
setTimeout(callback, 100);
|
||||
}, 100);
|
||||
|
||||
timers.advanceTimersByTime(100);
|
||||
expect(callback).toHaveBeenCalledTimes(0);
|
||||
|
||||
timers.advanceTimersByTime(100);
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clearTimeout', () => {
|
||||
it('prevents a pending timer from firing', () => {
|
||||
const callback = jest.fn();
|
||||
const id = setTimeout(callback, 100);
|
||||
|
||||
clearTimeout(id);
|
||||
timers.advanceTimersByTime(1000);
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setInterval', () => {
|
||||
it('fires once per interval', () => {
|
||||
const callback = jest.fn();
|
||||
const id = setInterval(callback, 100);
|
||||
|
||||
timers.advanceTimersByTime(350);
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(3);
|
||||
|
||||
clearInterval(id);
|
||||
});
|
||||
|
||||
it('keeps firing across multiple advances until cleared', () => {
|
||||
const callback = jest.fn();
|
||||
const id = setInterval(callback, 100);
|
||||
|
||||
timers.advanceTimersByTime(100);
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
|
||||
timers.advanceTimersByTime(200);
|
||||
expect(callback).toHaveBeenCalledTimes(3);
|
||||
|
||||
clearInterval(id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clearInterval', () => {
|
||||
it('stops a recurring timer from firing again', () => {
|
||||
const callback = jest.fn();
|
||||
const id = setInterval(callback, 100);
|
||||
|
||||
timers.advanceTimersByTime(100);
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
|
||||
clearInterval(id);
|
||||
timers.advanceTimersByTime(1000);
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -463,6 +463,32 @@ Fantom.scrollTo(scrollViewElement, {
|
||||
expect(scrollViewElement.scrollTop).toBe(1);
|
||||
```
|
||||
|
||||
#### How can I test logic that relies on timers (`setTimeout`/`setInterval`)?
|
||||
|
||||
Install a deterministic timer mock with `Fantom.installTimerMock()`. While
|
||||
installed, `setTimeout`/`setInterval` callbacks do not fire on their own; you
|
||||
advance a virtual clock to fire them, similar to `jest.useFakeTimers()`:
|
||||
|
||||
```javascript
|
||||
const timers = Fantom.installTimerMock();
|
||||
|
||||
const callback = jest.fn();
|
||||
setTimeout(callback, 100);
|
||||
|
||||
timers.advanceTimersByTime(50);
|
||||
expect(callback).toHaveBeenCalledTimes(0);
|
||||
|
||||
timers.advanceTimersByTime(50);
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
|
||||
timers.uninstall();
|
||||
```
|
||||
|
||||
`advanceTimersByTime`/`runAllTimers` run the work loop internally, so callbacks
|
||||
have executed by the time they return. Use `getPendingTimerCount()` to inspect
|
||||
how many timers are still scheduled, and `uninstall()` (typically in
|
||||
`afterEach`) to restore the default behavior.
|
||||
|
||||
#### What can be tested with Fantom?
|
||||
|
||||
Fantom was designed to make it possible to test integration between React and
|
||||
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict-local
|
||||
* @format
|
||||
*/
|
||||
|
||||
import {runWorkLoop} from './index';
|
||||
import NativeFantom from 'react-native/src/private/testing/fantom/specs/NativeFantom';
|
||||
|
||||
/**
|
||||
* Controls the deterministic timer mock for `setTimeout`/`setInterval`.
|
||||
*/
|
||||
export interface TimerMock {
|
||||
// Advances the virtual clock by `deltaMs`, firing every timer that becomes
|
||||
// due (in order), then runs the work loop so the callbacks execute.
|
||||
advanceTimersByTime(deltaMs: number): void;
|
||||
// Fires all pending timers (bounded to avoid infinite loops), then runs the
|
||||
// work loop so the callbacks execute.
|
||||
runAllTimers(): void;
|
||||
// Returns the number of currently pending (scheduled but not yet fired)
|
||||
// timers.
|
||||
getPendingTimerCount(): number;
|
||||
uninstall(): void;
|
||||
}
|
||||
|
||||
let activeMock: ?TimerMock;
|
||||
|
||||
/**
|
||||
* Installs a deterministic timer mock. While installed, `setTimeout` and
|
||||
* `setInterval` callbacks do not fire on their own; they only fire when the
|
||||
* virtual clock is advanced via `advanceTimersByTime` or drained via
|
||||
* `runAllTimers`. This is the timer equivalent of `installHighResTimeStampMock`.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* let timers;
|
||||
*
|
||||
* afterEach(() => {
|
||||
* timers?.uninstall();
|
||||
* timers = null;
|
||||
* });
|
||||
*
|
||||
* it('fires after the delay elapses', () => {
|
||||
* timers = Fantom.installTimerMock();
|
||||
* const callback = jest.fn();
|
||||
*
|
||||
* setTimeout(callback, 100);
|
||||
* timers.advanceTimersByTime(50);
|
||||
* expect(callback).toHaveBeenCalledTimes(0);
|
||||
*
|
||||
* timers.advanceTimersByTime(50);
|
||||
* expect(callback).toHaveBeenCalledTimes(1);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function installTimerMock(): TimerMock {
|
||||
if (activeMock != null) {
|
||||
throw new Error(
|
||||
'Cannot install timer mock because there is another mock installed already. Reuse the same mock or uninstall the previous one first.',
|
||||
);
|
||||
}
|
||||
|
||||
NativeFantom.setTimerMockEnabled(true);
|
||||
|
||||
const mock: TimerMock = {
|
||||
advanceTimersByTime: deltaMs => {
|
||||
NativeFantom.advanceTimers(deltaMs);
|
||||
runWorkLoop();
|
||||
},
|
||||
runAllTimers: () => {
|
||||
NativeFantom.runAllTimers();
|
||||
runWorkLoop();
|
||||
},
|
||||
getPendingTimerCount: () => NativeFantom.getPendingTimerCount(),
|
||||
uninstall: () => {
|
||||
if (activeMock === mock) {
|
||||
NativeFantom.setTimerMockEnabled(false);
|
||||
activeMock = null;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
activeMock = mock;
|
||||
|
||||
return mock;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @fantom_mode dev
|
||||
* @flow strict-local
|
||||
* @format
|
||||
*/
|
||||
|
||||
import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
|
||||
|
||||
import type {TimerMock} from '../TimerMock';
|
||||
|
||||
import * as Fantom from '@react-native/fantom';
|
||||
|
||||
const pendingMocks: Set<TimerMock> = new Set();
|
||||
|
||||
function installTimerMock(): TimerMock {
|
||||
const mock = Fantom.installTimerMock();
|
||||
pendingMocks.add(mock);
|
||||
return mock;
|
||||
}
|
||||
|
||||
describe('Fantom timer mocks', () => {
|
||||
afterEach(() => {
|
||||
for (const mock of pendingMocks) {
|
||||
mock.uninstall();
|
||||
}
|
||||
pendingMocks.clear();
|
||||
});
|
||||
|
||||
it('tracks the number of pending timers', () => {
|
||||
const timers = installTimerMock();
|
||||
|
||||
expect(timers.getPendingTimerCount()).toBe(0);
|
||||
|
||||
setTimeout(() => {}, 100);
|
||||
const cleared = setTimeout(() => {}, 100);
|
||||
|
||||
expect(timers.getPendingTimerCount()).toBe(2);
|
||||
|
||||
clearTimeout(cleared);
|
||||
|
||||
expect(timers.getPendingTimerCount()).toBe(1);
|
||||
|
||||
timers.advanceTimersByTime(100);
|
||||
|
||||
expect(timers.getPendingTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('only fires timers that are due when advancing the clock', () => {
|
||||
const timers = installTimerMock();
|
||||
const callback = jest.fn();
|
||||
|
||||
setTimeout(callback, 100);
|
||||
|
||||
timers.advanceTimersByTime(50);
|
||||
expect(callback).toHaveBeenCalledTimes(0);
|
||||
expect(timers.getPendingTimerCount()).toBe(1);
|
||||
|
||||
timers.advanceTimersByTime(50);
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
expect(timers.getPendingTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('fires all pending timers with runAllTimers regardless of delay', () => {
|
||||
const timers = installTimerMock();
|
||||
const first = jest.fn();
|
||||
const second = jest.fn();
|
||||
|
||||
setTimeout(first, 100);
|
||||
setTimeout(second, 5000);
|
||||
|
||||
timers.runAllTimers();
|
||||
|
||||
expect(first).toHaveBeenCalledTimes(1);
|
||||
expect(second).toHaveBeenCalledTimes(1);
|
||||
expect(timers.getPendingTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('throws an error when installing multiple mocks at the same time', () => {
|
||||
installTimerMock();
|
||||
expect(() => installTimerMock()).toThrow(
|
||||
'Cannot install timer mock because there is another mock installed already. Reuse the same mock or uninstall the previous one first.',
|
||||
);
|
||||
});
|
||||
|
||||
it('does nothing when uninstalling multiple times', () => {
|
||||
const mock = installTimerMock();
|
||||
|
||||
mock.uninstall();
|
||||
mock.uninstall();
|
||||
mock.uninstall();
|
||||
|
||||
// A fresh mock can be installed again afterwards.
|
||||
const next = installTimerMock();
|
||||
const callback = jest.fn();
|
||||
setTimeout(callback, 100);
|
||||
next.advanceTimersByTime(100);
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not uninstall other mocks', () => {
|
||||
const initialMock = installTimerMock();
|
||||
initialMock.uninstall();
|
||||
|
||||
const currentMock = installTimerMock();
|
||||
|
||||
// Uninstalling the already-uninstalled mock must not affect the current one.
|
||||
initialMock.uninstall();
|
||||
|
||||
const callback = jest.fn();
|
||||
setTimeout(callback, 100);
|
||||
currentMock.advanceTimersByTime(100);
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
+1
@@ -731,6 +731,7 @@ export function takeJSMemoryHeapSnapshot(): void {
|
||||
}
|
||||
|
||||
export * from './HighResTimeStampMock';
|
||||
export * from './TimerMock';
|
||||
|
||||
function runLogBoxCheck() {
|
||||
if (isLogBoxCheckEnabled && LogBox.isInstalled()) {
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/*
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
#include "FantomTimerRegistry.h"
|
||||
|
||||
#include <react/runtime/TimerManager.h>
|
||||
#include <algorithm>
|
||||
#include <optional>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
namespace {
|
||||
// Safety bound to avoid spinning forever on self-rescheduling or zero-interval
|
||||
// recurring timers (mirrors jest fake-timer safeguards).
|
||||
constexpr uint32_t kMaxTimerFires = 100000;
|
||||
} // namespace
|
||||
|
||||
void FantomTimerRegistry::createTimer(uint32_t timerId, double delayMs) {
|
||||
scheduleTimer(timerId, delayMs, /* isRecurring */ false);
|
||||
}
|
||||
|
||||
void FantomTimerRegistry::createRecurringTimer(
|
||||
uint32_t timerId,
|
||||
double delayMs) {
|
||||
scheduleTimer(timerId, delayMs, /* isRecurring */ true);
|
||||
}
|
||||
|
||||
void FantomTimerRegistry::scheduleTimer(
|
||||
uint32_t timerId,
|
||||
double delayMs,
|
||||
bool isRecurring) {
|
||||
double effectiveDelayMs = std::max(delayMs, 0.0);
|
||||
|
||||
// In the default (non-mock) mode, preserve the behavior observable in
|
||||
// synchronous Fantom tests: a zero/negative-delay one-shot timer is
|
||||
// dispatched immediately (it fires on the next work loop). Everything else
|
||||
// stays pending until the mock clock is advanced.
|
||||
if (!mockEnabled_ && !isRecurring && effectiveDelayMs == 0.0) {
|
||||
fireTimer(timerId);
|
||||
return;
|
||||
}
|
||||
|
||||
timers_[timerId] = Timer{
|
||||
.timerId = timerId,
|
||||
.dueTimeMs = nowMs_ + effectiveDelayMs,
|
||||
.intervalMs = effectiveDelayMs,
|
||||
.isRecurring = isRecurring};
|
||||
}
|
||||
|
||||
void FantomTimerRegistry::deleteTimer(uint32_t timerId) {
|
||||
timers_.erase(timerId);
|
||||
}
|
||||
|
||||
void FantomTimerRegistry::quit() {
|
||||
timers_.clear();
|
||||
}
|
||||
|
||||
void FantomTimerRegistry::setTimerManager(
|
||||
std::weak_ptr<TimerManager> timerManager) {
|
||||
timerManager_ = std::move(timerManager);
|
||||
}
|
||||
|
||||
void FantomTimerRegistry::setMockEnabled(bool enabled) {
|
||||
mockEnabled_ = enabled;
|
||||
}
|
||||
|
||||
bool FantomTimerRegistry::isMockEnabled() const noexcept {
|
||||
return mockEnabled_;
|
||||
}
|
||||
|
||||
uint32_t FantomTimerRegistry::getPendingTimerCount() const noexcept {
|
||||
return static_cast<uint32_t>(timers_.size());
|
||||
}
|
||||
|
||||
void FantomTimerRegistry::fireTimer(uint32_t timerId) {
|
||||
if (auto timerManager = timerManager_.lock()) {
|
||||
timerManager->callTimer(static_cast<TimerHandle>(timerId));
|
||||
}
|
||||
}
|
||||
|
||||
void FantomTimerRegistry::advanceTimersByTime(double deltaMs) {
|
||||
double targetMs = nowMs_ + std::max(deltaMs, 0.0);
|
||||
|
||||
for (uint32_t fires = 0; fires < kMaxTimerFires; ++fires) {
|
||||
// Find the earliest timer due at or before the target time, breaking ties
|
||||
// by timer id (insertion order / FIFO per the timer index).
|
||||
std::optional<uint32_t> nextId;
|
||||
double nextDueMs = 0.0;
|
||||
for (const auto& [id, timer] : timers_) {
|
||||
if (timer.dueTimeMs <= targetMs) {
|
||||
if (!nextId.has_value() || timer.dueTimeMs < nextDueMs ||
|
||||
(timer.dueTimeMs == nextDueMs && id < *nextId)) {
|
||||
nextId = id;
|
||||
nextDueMs = timer.dueTimeMs;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!nextId.has_value()) {
|
||||
break;
|
||||
}
|
||||
|
||||
auto it = timers_.find(*nextId);
|
||||
Timer timer = it->second;
|
||||
|
||||
// Advance virtual time to this timer's due time before firing.
|
||||
nowMs_ = timer.dueTimeMs;
|
||||
|
||||
if (timer.isRecurring) {
|
||||
it->second.dueTimeMs = timer.dueTimeMs + timer.intervalMs;
|
||||
} else {
|
||||
timers_.erase(it);
|
||||
}
|
||||
|
||||
fireTimer(timer.timerId);
|
||||
}
|
||||
|
||||
nowMs_ = targetMs;
|
||||
}
|
||||
|
||||
void FantomTimerRegistry::runAllTimers() {
|
||||
for (uint32_t fires = 0; fires < kMaxTimerFires && !timers_.empty();
|
||||
++fires) {
|
||||
// Fire the earliest pending timer (by due time, then id).
|
||||
uint32_t nextId = 0;
|
||||
double nextDueMs = 0.0;
|
||||
bool found = false;
|
||||
for (const auto& [id, timer] : timers_) {
|
||||
if (!found || timer.dueTimeMs < nextDueMs ||
|
||||
(timer.dueTimeMs == nextDueMs && id < nextId)) {
|
||||
nextId = id;
|
||||
nextDueMs = timer.dueTimeMs;
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
|
||||
auto it = timers_.find(nextId);
|
||||
Timer timer = it->second;
|
||||
nowMs_ = timer.dueTimeMs;
|
||||
|
||||
if (timer.isRecurring) {
|
||||
it->second.dueTimeMs = timer.dueTimeMs + timer.intervalMs;
|
||||
} else {
|
||||
timers_.erase(it);
|
||||
}
|
||||
|
||||
fireTimer(timer.timerId);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace facebook::react
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <react/runtime/PlatformTimerRegistry.h>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
/**
|
||||
* A deterministic PlatformTimerRegistry for Fantom.
|
||||
*
|
||||
* Unlike the production registry, this implementation does not schedule timers
|
||||
* on a real background thread. Instead it keeps a virtual clock that is only
|
||||
* advanced from JS (through the public Fantom API -> NativeFantom), so that
|
||||
* `setTimeout`/`setInterval` callbacks fire deterministically.
|
||||
*
|
||||
* Two modes:
|
||||
* - Mock disabled (default): preserves the behavior observable in synchronous
|
||||
* Fantom tests today. Zero/negative-delay one-shot timers are dispatched
|
||||
* immediately (they fire on the next work loop); positive-delay and
|
||||
* recurring timers stay pending and never fire on their own.
|
||||
* - Mock enabled (via `setMockEnabled(true)`): all timers stay pending and
|
||||
* only fire when JS advances the virtual clock via `advanceTimersByTime` or
|
||||
* drains them via `runAllTimers` (jest fake-timer semantics).
|
||||
*
|
||||
* Firing a timer calls `TimerManager::callTimer`, which enqueues the JS
|
||||
* callback on the RuntimeScheduler; the caller is expected to run the work loop
|
||||
* afterwards to execute the callbacks.
|
||||
*
|
||||
* All methods are expected to be called on the JS thread (Fantom is
|
||||
* single-threaded), so no locking is required.
|
||||
*/
|
||||
class FantomTimerRegistry : public PlatformTimerRegistry {
|
||||
public:
|
||||
FantomTimerRegistry() noexcept = default;
|
||||
FantomTimerRegistry(const FantomTimerRegistry &) = delete;
|
||||
FantomTimerRegistry(FantomTimerRegistry &&) = delete;
|
||||
FantomTimerRegistry &operator=(const FantomTimerRegistry &) = delete;
|
||||
FantomTimerRegistry &operator=(FantomTimerRegistry &&) = delete;
|
||||
~FantomTimerRegistry() noexcept override = default;
|
||||
|
||||
// PlatformTimerRegistry
|
||||
void createTimer(uint32_t timerId, double delayMs) override;
|
||||
void deleteTimer(uint32_t timerId) override;
|
||||
void createRecurringTimer(uint32_t timerId, double delayMs) override;
|
||||
void quit() override;
|
||||
void setTimerManager(std::weak_ptr<TimerManager> timerManager) override;
|
||||
|
||||
// Control API (driven from JS via NativeFantom).
|
||||
void setMockEnabled(bool enabled);
|
||||
bool isMockEnabled() const noexcept;
|
||||
|
||||
// Advances the virtual clock by `deltaMs`, firing every timer that becomes
|
||||
// due (in due-time order), re-arming recurring timers along the way.
|
||||
void advanceTimersByTime(double deltaMs);
|
||||
|
||||
// Fires all currently pending timers until none remain (bounded to avoid
|
||||
// infinite loops with self-rescheduling/recurring timers).
|
||||
void runAllTimers();
|
||||
|
||||
uint32_t getPendingTimerCount() const noexcept;
|
||||
|
||||
private:
|
||||
struct Timer {
|
||||
uint32_t timerId{0};
|
||||
double dueTimeMs{0.0};
|
||||
double intervalMs{0.0};
|
||||
bool isRecurring{false};
|
||||
};
|
||||
|
||||
void scheduleTimer(uint32_t timerId, double delayMs, bool isRecurring);
|
||||
void fireTimer(uint32_t timerId);
|
||||
|
||||
std::weak_ptr<TimerManager> timerManager_;
|
||||
std::unordered_map<uint32_t, Timer> timers_;
|
||||
double nowMs_{0.0};
|
||||
bool mockEnabled_{false};
|
||||
};
|
||||
|
||||
} // namespace facebook::react
|
||||
@@ -61,6 +61,24 @@ void NativeFantom::produceFramesForDuration(
|
||||
appDelegate_.produceFramesForDuration(milliseconds);
|
||||
}
|
||||
|
||||
void NativeFantom::setTimerMockEnabled(
|
||||
jsi::Runtime& /*runtime*/,
|
||||
bool enabled) {
|
||||
appDelegate_.setTimerMockEnabled(enabled);
|
||||
}
|
||||
|
||||
void NativeFantom::advanceTimers(jsi::Runtime& /*runtime*/, double deltaMs) {
|
||||
appDelegate_.advanceTimers(deltaMs);
|
||||
}
|
||||
|
||||
void NativeFantom::runAllTimers(jsi::Runtime& /*runtime*/) {
|
||||
appDelegate_.runAllTimers();
|
||||
}
|
||||
|
||||
double NativeFantom::getPendingTimerCount(jsi::Runtime& /*runtime*/) {
|
||||
return static_cast<double>(appDelegate_.getPendingTimerCount());
|
||||
}
|
||||
|
||||
void NativeFantom::flushMessageQueue(jsi::Runtime& /*runtime*/) {
|
||||
appDelegate_.flushMessageQueue();
|
||||
}
|
||||
|
||||
@@ -130,6 +130,11 @@ class NativeFantom : public NativeFantomCxxSpec<NativeFantom> {
|
||||
|
||||
void forceHighResTimeStamp(jsi::Runtime &runtime, std::optional<HighResTimeStamp> now);
|
||||
|
||||
void setTimerMockEnabled(jsi::Runtime &runtime, bool enabled);
|
||||
void advanceTimers(jsi::Runtime &runtime, double deltaMs);
|
||||
void runAllTimers(jsi::Runtime &runtime);
|
||||
double getPendingTimerCount(jsi::Runtime &runtime);
|
||||
|
||||
void startJSSamplingProfiler(jsi::Runtime &runtime);
|
||||
|
||||
void stopJSSamplingProfilerAndSaveToFile(jsi::Runtime &runtime, const std::string &filePath);
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
#include "TesterAppDelegate.h"
|
||||
|
||||
#include "FantomTimerRegistry.h"
|
||||
#include "NativeFantom.h"
|
||||
#include "platform/TesterTurboModuleProvider.h"
|
||||
#include "stubs/StubClock.h"
|
||||
@@ -122,8 +123,15 @@ TesterAppDelegate::TesterAppDelegate(
|
||||
|
||||
animationChoreographer_ = std::make_shared<TesterAnimationChoreographer>();
|
||||
|
||||
ReactInstanceConfig reactInstanceConfigWithTimers = reactInstanceConfig;
|
||||
reactInstanceConfigWithTimers.platformTimerRegistryFactory = [this]() {
|
||||
auto registry = std::make_unique<FantomTimerRegistry>();
|
||||
timerRegistry_ = registry.get();
|
||||
return registry;
|
||||
};
|
||||
|
||||
reactHost_ = std::make_unique<ReactHost>(
|
||||
reactInstanceConfig,
|
||||
reactInstanceConfigWithTimers,
|
||||
mountingManager_,
|
||||
runLoopObserverManager_,
|
||||
std::move(contextContainer),
|
||||
@@ -261,6 +269,28 @@ void TesterAppDelegate::produceFramesForDuration(double milliseconds) {
|
||||
}
|
||||
}
|
||||
|
||||
void TesterAppDelegate::setTimerMockEnabled(bool enabled) {
|
||||
if (timerRegistry_ != nullptr) {
|
||||
timerRegistry_->setMockEnabled(enabled);
|
||||
}
|
||||
}
|
||||
|
||||
void TesterAppDelegate::advanceTimers(double deltaMs) {
|
||||
if (timerRegistry_ != nullptr) {
|
||||
timerRegistry_->advanceTimersByTime(deltaMs);
|
||||
}
|
||||
}
|
||||
|
||||
void TesterAppDelegate::runAllTimers() {
|
||||
if (timerRegistry_ != nullptr) {
|
||||
timerRegistry_->runAllTimers();
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t TesterAppDelegate::getPendingTimerCount() {
|
||||
return timerRegistry_ != nullptr ? timerRegistry_->getPendingTimerCount() : 0;
|
||||
}
|
||||
|
||||
void TesterAppDelegate::runUITick() {
|
||||
if (ReactNativeFeatureFlags::useSharedAnimatedBackend()) {
|
||||
auto milliseconds = std::chrono::duration_cast<AnimationTimestamp>(
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
#include <react/renderer/core/ReactPrimitives.h>
|
||||
#include <react/runtime/ReactInstanceConfig.h>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -22,6 +23,7 @@ class Runtime;
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
class FantomTimerRegistry;
|
||||
class ReactHost;
|
||||
class StubQueue;
|
||||
class RunLoopObserverManager;
|
||||
@@ -58,6 +60,12 @@ class TesterAppDelegate {
|
||||
|
||||
void produceFramesForDuration(double milliseconds);
|
||||
|
||||
// Deterministic timer control (driven from JS via NativeFantom).
|
||||
void setTimerMockEnabled(bool enabled);
|
||||
void advanceTimers(double deltaMs);
|
||||
void runAllTimers();
|
||||
uint32_t getPendingTimerCount();
|
||||
|
||||
void flushMessageQueue();
|
||||
|
||||
bool hasPendingTasksInMessageQueue();
|
||||
@@ -79,6 +87,10 @@ class TesterAppDelegate {
|
||||
void runUITick();
|
||||
|
||||
std::function<void()> onAnimationRender_{nullptr};
|
||||
|
||||
// Owned by the TimerManager (inside the ReactInstance); this is a non-owning
|
||||
// pointer used to drive the deterministic timer mock from JS.
|
||||
FantomTimerRegistry *timerRegistry_{nullptr};
|
||||
};
|
||||
|
||||
} // namespace facebook::react
|
||||
@@ -4095,6 +4095,7 @@ class facebook::react::PlatformTimerRegistry {
|
||||
public virtual void createTimer(uint32_t timerID, double delayMS) = 0;
|
||||
public virtual void deleteTimer(uint32_t timerID) = 0;
|
||||
public virtual void quit();
|
||||
public virtual void setTimerManager(std::weak_ptr<facebook::react::TimerManager>);
|
||||
public virtual ~PlatformTimerRegistry() noexcept = default;
|
||||
}
|
||||
|
||||
|
||||
@@ -3949,6 +3949,7 @@ class facebook::react::PlatformTimerRegistry {
|
||||
public virtual void createTimer(uint32_t timerID, double delayMS) = 0;
|
||||
public virtual void deleteTimer(uint32_t timerID) = 0;
|
||||
public virtual void quit();
|
||||
public virtual void setTimerManager(std::weak_ptr<facebook::react::TimerManager>);
|
||||
public virtual ~PlatformTimerRegistry() noexcept = default;
|
||||
}
|
||||
|
||||
|
||||
@@ -4092,6 +4092,7 @@ class facebook::react::PlatformTimerRegistry {
|
||||
public virtual void createTimer(uint32_t timerID, double delayMS) = 0;
|
||||
public virtual void deleteTimer(uint32_t timerID) = 0;
|
||||
public virtual void quit();
|
||||
public virtual void setTimerManager(std::weak_ptr<facebook::react::TimerManager>);
|
||||
public virtual ~PlatformTimerRegistry() noexcept = default;
|
||||
}
|
||||
|
||||
|
||||
@@ -319,7 +319,7 @@ class ObjCTimerRegistry : public facebook::react::PlatformTimerRegistry {
|
||||
public virtual void createRecurringTimer(uint32_t timerID, double delayMS) override;
|
||||
public virtual void createTimer(uint32_t timerID, double delayMS) override;
|
||||
public virtual void deleteTimer(uint32_t timerID) override;
|
||||
public void setTimerManager(std::weak_ptr<facebook::react::TimerManager> timerManager);
|
||||
public virtual void setTimerManager(std::weak_ptr<facebook::react::TimerManager> timerManager) override;
|
||||
}
|
||||
|
||||
class RCTComponentViewClassDescriptor {
|
||||
@@ -6282,6 +6282,7 @@ class facebook::react::PlatformTimerRegistry {
|
||||
public virtual void createTimer(uint32_t timerID, double delayMS) = 0;
|
||||
public virtual void deleteTimer(uint32_t timerID) = 0;
|
||||
public virtual void quit();
|
||||
public virtual void setTimerManager(std::weak_ptr<facebook::react::TimerManager>);
|
||||
public virtual ~PlatformTimerRegistry() noexcept = default;
|
||||
}
|
||||
|
||||
|
||||
@@ -319,7 +319,7 @@ class ObjCTimerRegistry : public facebook::react::PlatformTimerRegistry {
|
||||
public virtual void createRecurringTimer(uint32_t timerID, double delayMS) override;
|
||||
public virtual void createTimer(uint32_t timerID, double delayMS) override;
|
||||
public virtual void deleteTimer(uint32_t timerID) override;
|
||||
public void setTimerManager(std::weak_ptr<facebook::react::TimerManager> timerManager);
|
||||
public virtual void setTimerManager(std::weak_ptr<facebook::react::TimerManager> timerManager) override;
|
||||
}
|
||||
|
||||
class RCTComponentViewClassDescriptor {
|
||||
@@ -6164,6 +6164,7 @@ class facebook::react::PlatformTimerRegistry {
|
||||
public virtual void createTimer(uint32_t timerID, double delayMS) = 0;
|
||||
public virtual void deleteTimer(uint32_t timerID) = 0;
|
||||
public virtual void quit();
|
||||
public virtual void setTimerManager(std::weak_ptr<facebook::react::TimerManager>);
|
||||
public virtual ~PlatformTimerRegistry() noexcept = default;
|
||||
}
|
||||
|
||||
|
||||
@@ -319,7 +319,7 @@ class ObjCTimerRegistry : public facebook::react::PlatformTimerRegistry {
|
||||
public virtual void createRecurringTimer(uint32_t timerID, double delayMS) override;
|
||||
public virtual void createTimer(uint32_t timerID, double delayMS) override;
|
||||
public virtual void deleteTimer(uint32_t timerID) override;
|
||||
public void setTimerManager(std::weak_ptr<facebook::react::TimerManager> timerManager);
|
||||
public virtual void setTimerManager(std::weak_ptr<facebook::react::TimerManager> timerManager) override;
|
||||
}
|
||||
|
||||
class RCTComponentViewClassDescriptor {
|
||||
@@ -6279,6 +6279,7 @@ class facebook::react::PlatformTimerRegistry {
|
||||
public virtual void createTimer(uint32_t timerID, double delayMS) = 0;
|
||||
public virtual void deleteTimer(uint32_t timerID) = 0;
|
||||
public virtual void quit();
|
||||
public virtual void setTimerManager(std::weak_ptr<facebook::react::TimerManager>);
|
||||
public virtual ~PlatformTimerRegistry() noexcept = default;
|
||||
}
|
||||
|
||||
|
||||
@@ -2700,6 +2700,7 @@ class facebook::react::PlatformTimerRegistry {
|
||||
public virtual void createTimer(uint32_t timerID, double delayMS) = 0;
|
||||
public virtual void deleteTimer(uint32_t timerID) = 0;
|
||||
public virtual void quit();
|
||||
public virtual void setTimerManager(std::weak_ptr<facebook::react::TimerManager>);
|
||||
public virtual ~PlatformTimerRegistry() noexcept = default;
|
||||
}
|
||||
|
||||
|
||||
@@ -2594,6 +2594,7 @@ class facebook::react::PlatformTimerRegistry {
|
||||
public virtual void createTimer(uint32_t timerID, double delayMS) = 0;
|
||||
public virtual void deleteTimer(uint32_t timerID) = 0;
|
||||
public virtual void quit();
|
||||
public virtual void setTimerManager(std::weak_ptr<facebook::react::TimerManager>);
|
||||
public virtual ~PlatformTimerRegistry() noexcept = default;
|
||||
}
|
||||
|
||||
|
||||
@@ -2697,6 +2697,7 @@ class facebook::react::PlatformTimerRegistry {
|
||||
public virtual void createTimer(uint32_t timerID, double delayMS) = 0;
|
||||
public virtual void deleteTimer(uint32_t timerID) = 0;
|
||||
public virtual void quit();
|
||||
public virtual void setTimerManager(std::weak_ptr<facebook::react::TimerManager>);
|
||||
public virtual ~PlatformTimerRegistry() noexcept = default;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user