diff --git a/packages/react-native/React/Fabric/RCTScheduler.mm b/packages/react-native/React/Fabric/RCTScheduler.mm index 5130b2fdcddc..13a600d2102e 100644 --- a/packages/react-native/React/Fabric/RCTScheduler.mm +++ b/packages/react-native/React/Fabric/RCTScheduler.mm @@ -24,23 +24,23 @@ class SchedulerDelegateProxy : public SchedulerDelegate { public: - SchedulerDelegateProxy(void *scheduler) : scheduler_(scheduler) {} + SchedulerDelegateProxy(RCTScheduler *scheduler) : scheduler_(scheduler) {} void schedulerDidFinishTransaction(const std::shared_ptr &mountingCoordinator) override { - RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_; + RCTScheduler *scheduler __attribute__((objc_precise_lifetime)) = scheduler_; [scheduler.delegate schedulerDidFinishTransaction:mountingCoordinator]; } void schedulerShouldRenderTransactions(const std::shared_ptr &mountingCoordinator) override { - RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_; + RCTScheduler *scheduler __attribute__((objc_precise_lifetime)) = scheduler_; [scheduler.delegate schedulerShouldRenderTransactions:mountingCoordinator]; } void schedulerShouldMergeReactRevision(SurfaceId surfaceId) override { - RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_; + RCTScheduler *scheduler __attribute__((objc_precise_lifetime)) = scheduler_; [scheduler.delegate schedulerShouldMergeReactRevision:surfaceId]; } @@ -55,14 +55,14 @@ void schedulerDidDispatchCommand( const std::string &commandName, const folly::dynamic &args) override { - RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_; + RCTScheduler *scheduler __attribute__((objc_precise_lifetime)) = scheduler_; [scheduler.delegate schedulerDidDispatchCommand:shadowView commandName:commandName args:args]; } void schedulerDidSetIsJSResponder(const ShadowView &shadowView, bool isJSResponder, bool blockNativeResponder) override { - RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_; + RCTScheduler *scheduler __attribute__((objc_precise_lifetime)) = scheduler_; [scheduler.delegate schedulerDidSetIsJSResponder:isJSResponder blockNativeResponder:blockNativeResponder forShadowView:shadowView]; @@ -70,13 +70,13 @@ void schedulerDidSetIsJSResponder(const ShadowView &shadowView, bool isJSRespond void schedulerDidSendAccessibilityEvent(const ShadowView &shadowView, const std::string &eventType) override { - RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_; + RCTScheduler *scheduler __attribute__((objc_precise_lifetime)) = scheduler_; [scheduler.delegate schedulerDidSendAccessibilityEvent:shadowView eventType:eventType]; } void schedulerShouldSynchronouslyUpdateViewOnUIThread(facebook::react::Tag tag, const folly::dynamic &props) override { - RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_; + RCTScheduler *scheduler __attribute__((objc_precise_lifetime)) = scheduler_; [scheduler.delegate schedulerDidSynchronouslyUpdateViewOnUIThread:tag props:props]; } @@ -105,7 +105,7 @@ void schedulerDidClearPendingSnapshots() override } private: - void *scheduler_; + __weak RCTScheduler *scheduler_; }; class LayoutAnimationDelegateProxy : public LayoutAnimationStatusDelegate, public RunLoopObserver::Delegate { @@ -188,7 +188,7 @@ void pause() override @implementation RCTScheduler { std::unique_ptr _scheduler; std::shared_ptr _animationDriver; - std::unique_ptr _delegateProxy; + std::shared_ptr _delegateProxy; std::shared_ptr _layoutAnimationDelegateProxy; std::unique_ptr _uiRunLoopObserver; } @@ -196,7 +196,7 @@ @implementation RCTScheduler { - (instancetype)initWithToolbox:(SchedulerToolbox)toolbox { if (self = [super init]) { - _delegateProxy = std::make_unique((__bridge void *)self); + _delegateProxy = std::make_shared(self); if (ReactNativeFeatureFlags::enableLayoutAnimationsOnIOS()) { _layoutAnimationDelegateProxy = std::make_shared((__bridge void *)self); @@ -213,8 +213,8 @@ - (instancetype)initWithToolbox:(SchedulerToolbox)toolbox toolbox.animationChoreographer = std::make_shared(); } - _scheduler = std::make_unique( - toolbox, (_animationDriver ? _animationDriver.get() : nullptr), _delegateProxy.get()); + _scheduler = + std::make_unique(toolbox, (_animationDriver ? _animationDriver.get() : nullptr), _delegateProxy); } return self; diff --git a/packages/react-native/React/Fabric/RCTSurfacePresenter.mm b/packages/react-native/React/Fabric/RCTSurfacePresenter.mm index e3f6424f53f0..d85eca703770 100644 --- a/packages/react-native/React/Fabric/RCTSurfacePresenter.mm +++ b/packages/react-native/React/Fabric/RCTSurfacePresenter.mm @@ -334,7 +334,9 @@ - (void)_stopAllSurfacesWithScheduler:(RCTScheduler *)scheduler - (void)_applicationWillTerminate { + RCTScheduler *scheduler = [self scheduler]; [self suspend]; + [scheduler stopObservingLayoutAnimations]; } #pragma mark - RCTSchedulerDelegate diff --git a/packages/react-native/React/Tests/Mounting/RCTFabricSurfaceLifecycleTests.mm b/packages/react-native/React/Tests/Mounting/RCTFabricSurfaceLifecycleTests.mm index 006453c1b6fd..cbe84555946e 100644 --- a/packages/react-native/React/Tests/Mounting/RCTFabricSurfaceLifecycleTests.mm +++ b/packages/react-native/React/Tests/Mounting/RCTFabricSurfaceLifecycleTests.mm @@ -18,6 +18,29 @@ using facebook::react::RuntimeSchedulerKey; using facebook::react::SurfaceHandler; +@interface RCTSurfacePresenter (TerminationTesting) +- (void)_applicationWillTerminate; +@end + +@interface RCTSchedulerTerminationProbe : NSObject +@property (nonatomic, weak) id delegate; +@property (nonatomic, copy) dispatch_block_t onStopObserving; +@property (nonatomic, copy) void (^onDealloc)(BOOL onMainThread); +- (void)stopObservingLayoutAnimations; +@end + +@implementation RCTSchedulerTerminationProbe +- (void)stopObservingLayoutAnimations +{ + self.onStopObserving(); +} + +- (void)dealloc +{ + self.onDealloc([NSThread isMainThread]); +} +@end + @interface RCTFabricSurfaceLifecycleTests : XCTestCase @end @@ -79,4 +102,47 @@ - (void)testStopCancelsPendingStart XCTAssertEqual(surface.surfaceHandler.getStatus(), SurfaceHandler::Status::Registered); } +- (void)testTerminationStopsObserverBeforeBackgroundSchedulerRelease +{ + XCTAssertTrue([NSThread isMainThread]); + RCTSurfacePresenter *presenter = [RCTSurfacePresenter new]; + XCTestExpectation *released = [self expectationWithDescription:@"Scheduler released by in-flight callback"]; + __block BOOL stoppedOnMain = NO; + __block BOOL releasedOnMain = YES; + __block RCTSchedulerTerminationProbe *inFlightScheduler; + __weak RCTSchedulerTerminationProbe *weakScheduler; + @autoreleasepool { + RCTSchedulerTerminationProbe *scheduler = [RCTSchedulerTerminationProbe new]; + scheduler.delegate = presenter; + scheduler.onStopObserving = ^{ + stoppedOnMain = [NSThread isMainThread]; + }; + scheduler.onDealloc = ^(BOOL onMainThread) { + releasedOnMain = onMainThread; + [released fulfill]; + }; + weakScheduler = scheduler; + inFlightScheduler = scheduler; + [presenter setValue:scheduler forKey:@"scheduler"]; + } + + @autoreleasepool { + [presenter _applicationWillTerminate]; + } + + XCTAssertNil(presenter.scheduler); + XCTAssertNotNil(weakScheduler); + XCTAssertNil(weakScheduler.delegate); + XCTAssertTrue(stoppedOnMain); + + dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + @autoreleasepool { + inFlightScheduler = nil; + } + }); + [self waitForExpectations:@[ released ] timeout:2]; + XCTAssertNil(weakScheduler); + XCTAssertFalse(releasedOnMain); +} + @end diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp index a278fb2b3400..7dda27be8ca1 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp @@ -32,11 +32,39 @@ namespace facebook::react { +struct Scheduler::DelegateState { + explicit DelegateState( + SchedulerDelegate* delegate, + std::shared_ptr owner = nullptr) + : delegate(delegate), owner(std::move(owner)) {} + + SchedulerDelegate* delegate; + std::shared_ptr owner; + std::atomic invalidated{false}; +}; + Scheduler::Scheduler( const SchedulerToolbox& schedulerToolbox, UIManagerAnimationDelegate* animationDelegate, SchedulerDelegate* delegate) - : runtimeExecutor_(schedulerToolbox.runtimeExecutor), + : Scheduler(schedulerToolbox, animationDelegate, delegate, nullptr) {} + +Scheduler::Scheduler( + const SchedulerToolbox& schedulerToolbox, + UIManagerAnimationDelegate* animationDelegate, + std::shared_ptr delegate) + : Scheduler(schedulerToolbox, animationDelegate, delegate.get(), delegate) { +} + +Scheduler::Scheduler( + const SchedulerToolbox& schedulerToolbox, + UIManagerAnimationDelegate* animationDelegate, + SchedulerDelegate* delegate, + std::shared_ptr owner) + : delegate_(delegate), + delegateState_( + std::make_shared(delegate, std::move(owner))), + runtimeExecutor_(schedulerToolbox.runtimeExecutor), contextContainer_(schedulerToolbox.contextContainer) { // Creating a container for future `EventDispatcher` instance. eventDispatcher_ = std::make_shared>(); @@ -156,7 +184,6 @@ Scheduler::Scheduler( std::weak_ptr( componentDescriptorRegistry_)); - delegate_ = delegate; commitHooks_ = schedulerToolbox.commitHooks; // Layout events (`onLayout`) are emitted as a standalone consumer of the @@ -185,6 +212,8 @@ Scheduler::Scheduler( } Scheduler::~Scheduler() { + setDelegate(nullptr); + LOG(WARNING) << "Scheduler::~Scheduler() was called (address: " << this << ")."; @@ -278,11 +307,26 @@ Scheduler::findComponentDescriptorByHandle_DO_NOT_USE_THIS_IS_BROKEN( #pragma mark - Delegate void Scheduler::setDelegate(SchedulerDelegate* delegate) { - delegate_ = delegate; + std::shared_ptr previousState; + { + std::lock_guard lock(delegateStateMutex_); + if (delegate_ == delegate) { + return; + } + previousState = std::move(delegateState_); + previousState->invalidated.store(true); + delegate_ = delegate; + delegateState_ = std::make_shared(delegate); + } } SchedulerDelegate* Scheduler::getDelegate() const { - return delegate_; + return getDelegateState()->delegate; +} + +std::shared_ptr Scheduler::getDelegateState() const { + std::lock_guard lock(delegateStateMutex_); + return delegateState_; } #pragma mark - UIManagerAnimationDelegate @@ -301,22 +345,30 @@ void Scheduler::uiManagerDidFinishTransaction( bool mountSynchronously) { TraceSection s("Scheduler::uiManagerDidFinishTransaction"); - if (delegate_ != nullptr) { + auto delegateState = getDelegateState(); + if (delegateState->delegate != nullptr) { // This is no-op on all platforms except for Android where we need to // observe each transaction to be able to mount correctly. - delegate_->schedulerDidFinishTransaction(mountingCoordinator); + delegateState->delegate->schedulerDidFinishTransaction(mountingCoordinator); if (!mountSynchronously) { auto surfaceId = mountingCoordinator->getSurfaceId(); runtimeScheduler_->scheduleRenderingUpdate( surfaceId, - [delegate = delegate_, + [delegateState, mountingCoordinator = std::move(mountingCoordinator)]() { - delegate->schedulerShouldRenderTransactions(mountingCoordinator); + if (!delegateState->invalidated.load()) { + delegateState->delegate->schedulerShouldRenderTransactions( + mountingCoordinator); + } }); } else { - delegate_->schedulerShouldRenderTransactions(mountingCoordinator); + auto currentDelegateState = getDelegateState(); + if (currentDelegateState->delegate != nullptr) { + currentDelegateState->delegate->schedulerShouldRenderTransactions( + mountingCoordinator); + } } } } @@ -333,15 +385,19 @@ void Scheduler::uiManagerDidDispatchCommand( const folly::dynamic& args) { TraceSection s( "Scheduler::uiManagerDispatchCommand", "commandName", commandName); - if (delegate_ != nullptr) { + auto delegateState = getDelegateState(); + if (delegateState->delegate != nullptr) { auto shadowView = ShadowView(*shadowNode); runtimeScheduler_->scheduleRenderingUpdate( shadowNode->getSurfaceId(), - [delegate = delegate_, + [delegateState, shadowView = std::move(shadowView), commandName, args]() { - delegate->schedulerDidDispatchCommand(shadowView, commandName, args); + if (!delegateState->invalidated.load()) { + delegateState->delegate->schedulerDidDispatchCommand( + shadowView, commandName, args); + } }); } } @@ -424,13 +480,17 @@ void Scheduler::uiManagerShouldRemoveEventListener( } void Scheduler::uiManagerDidFinishReactCommit(const ShadowTree& shadowTree) { - if (delegate_ == nullptr) { + auto delegateState = getDelegateState(); + if (delegateState->delegate == nullptr) { return; } auto surfaceId = shadowTree.getSurfaceId(); runtimeScheduler_->scheduleRenderingUpdate( - surfaceId, [surfaceId, uiManager = uiManager_, delegate = delegate_]() { + surfaceId, [surfaceId, uiManager = uiManager_, delegateState]() { + if (delegateState->invalidated.load()) { + return; + } bool promoted = false; uiManager->getShadowTreeRegistry().visit( @@ -439,7 +499,7 @@ void Scheduler::uiManagerDidFinishReactCommit(const ShadowTree& shadowTree) { }); if (promoted) { - delegate->schedulerShouldMergeReactRevision(surfaceId); + delegateState->delegate->schedulerShouldMergeReactRevision(surfaceId); } }); } diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h index 139df24d68d3..285bdb99bd31 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -44,6 +45,10 @@ class Scheduler final : public UIManagerDelegate { const SchedulerToolbox &schedulerToolbox, UIManagerAnimationDelegate *animationDelegate, SchedulerDelegate *delegate); + Scheduler( + const SchedulerToolbox &schedulerToolbox, + UIManagerAnimationDelegate *animationDelegate, + std::shared_ptr delegate); ~Scheduler() override; #pragma mark - Surface Management @@ -123,8 +128,18 @@ class Scheduler final : public UIManagerDelegate { private: friend class SurfaceHandler; + struct DelegateState; + + Scheduler( + const SchedulerToolbox &schedulerToolbox, + UIManagerAnimationDelegate *animationDelegate, + SchedulerDelegate *delegate, + std::shared_ptr owner); + std::shared_ptr getDelegateState() const; SchedulerDelegate *delegate_; + mutable std::mutex delegateStateMutex_; + std::shared_ptr delegateState_; SharedComponentDescriptorRegistry componentDescriptorRegistry_; RuntimeExecutor runtimeExecutor_; std::shared_ptr uiManager_; diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/tests/SchedulerDelegateInvalidationTest.cpp b/packages/react-native/ReactCommon/react/renderer/scheduler/tests/SchedulerDelegateInvalidationTest.cpp index 9005250d6063..e19b2b5452de 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/tests/SchedulerDelegateInvalidationTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/tests/SchedulerDelegateInvalidationTest.cpp @@ -45,6 +45,7 @@ #include #include #include +#include #include #include #include @@ -52,6 +53,7 @@ #include #include #include +#include #include #include @@ -108,7 +110,9 @@ class RecordingDelegate : public SchedulerDelegate { ++shouldRenderTransactionsCount_; } - void schedulerShouldMergeReactRevision(SurfaceId /*unused*/) override {} + void schedulerShouldMergeReactRevision(SurfaceId /*unused*/) override { + ++shouldMergeReactRevisionCount_; + } void schedulerDidRequestPreliminaryViewAllocation( const ShadowNode& /*unused*/) override {} void schedulerDidDispatchCommand( @@ -152,12 +156,16 @@ class RecordingDelegate : public SchedulerDelegate { int didDispatchCommandCount() const { return didDispatchCommandCount_; } + int shouldMergeReactRevisionCount() const { + return shouldMergeReactRevisionCount_; + } private: uint64_t aliveMagic_{kAlive}; int didFinishTransactionCount_{0}; int shouldRenderTransactionsCount_{0}; int didDispatchCommandCount_{0}; + int shouldMergeReactRevisionCount_{0}; }; // EventBeat stub. Scheduler instantiates one through the toolbox factory but @@ -208,6 +216,9 @@ class TestFeatureFlags : public ReactNativeFeatureFlagsDefaults { bool enableBridgelessArchitecture() override { return true; } + bool enableFabricCommitBranching() override { + return true; + } }; // Builds a ComponentRegistryFactory with just the descriptors needed for the @@ -234,7 +245,7 @@ ComponentRegistryFactory makeComponentRegistryFactory() { // a real Scheduler and drive uiManagerDidFinishTransaction end-to-end. class SchedulerDelegateInvalidationTest : public ::testing::Test { protected: - void setUp() { + void setUp(std::shared_ptr ownedDelegate = nullptr) { ReactNativeFeatureFlags::override(std::make_unique()); runtime_ = facebook::hermes::makeHermesRuntime( @@ -302,9 +313,15 @@ class SchedulerDelegateInvalidationTest : public ::testing::Test { std::move(ownerBox), *runtimeScheduler_); }; - delegate_ = std::make_unique(); - scheduler_ = std::make_unique( - toolbox, /*animationDelegate=*/nullptr, delegate_.get()); + if (ownedDelegate) { + delegate_ = std::move(ownedDelegate); + scheduler_ = std::make_unique( + toolbox, /*animationDelegate=*/nullptr, delegate_); + } else { + delegate_ = std::make_unique(); + scheduler_ = std::make_unique( + toolbox, /*animationDelegate=*/nullptr, delegate_.get()); + } // Register a surface with the scheduler so the teardown path mirrors // production cascade ordering (per-surface unregister BEFORE delegate @@ -326,6 +343,9 @@ class SchedulerDelegateInvalidationTest : public ::testing::Test { scheduler_->unregisterSurface(*surfaceHandler_); } surfaceHandler_.reset(); + if (scheduler_) { + scheduler_->getUIManager()->getShadowTreeRegistry().remove(11); + } scheduler_.reset(); delegate_.reset(); coordinator_.reset(); @@ -371,6 +391,29 @@ class SchedulerDelegateInvalidationTest : public ::testing::Test { executorQueue_->flush(); } + void queueReactCommit() { + auto uiManager = scheduler_->getUIManager(); + auto shadowTree = std::make_unique( + SurfaceId{11}, + LayoutConstraints{}, + LayoutContext{}, + *uiManager, + *contextContainer_); + auto* tree = shadowTree.get(); + uiManager->getShadowTreeRegistry().add(std::move(shadowTree)); + + ASSERT_EQ( + tree->commit( + [](const RootShadowNode& root) { + return std::make_shared( + root, ShadowNodeFragment{}); + }, + {.mountSynchronously = false, + .source = ShadowTreeCommitSource::React}), + ShadowTreeCommitStatus::Succeeded); + ASSERT_TRUE(tree->getCurrentReactRevision().has_value()); + } + // Schedules a JS task whose host function throws an uncaught Error. When // the task runs and the throw escapes the host-function boundary, // RuntimeScheduler routes it through the onTaskError callback installed @@ -404,7 +447,7 @@ class SchedulerDelegateInvalidationTest : public ::testing::Test { std::unique_ptr executorQueue_; std::shared_ptr runtimeScheduler_; std::shared_ptr contextContainer_; - std::unique_ptr delegate_; + std::shared_ptr delegate_; std::unique_ptr scheduler_; std::unique_ptr surfaceHandler_; std::shared_ptr coordinator_; @@ -481,44 +524,187 @@ TEST_F(SchedulerDelegateInvalidationTest, JSThrowInitiatedTeardownIsSafe) { SUCCEED(); } -// --------------------------------------------------------------------------- -// Test 3 — The window that remains open: a delegate detached with no error -// involved. -// -// handleTaskError clears pendingRenderingUpdates_ before the host error -// handler runs, so an error-driven teardown is safe (Test 2). A plain -// setDelegate swap never reaches handleTaskError, so the lambda enqueued in -// (a) still calls through the raw pointer it captured when the queue drains -// in (c). Had the host also destroyed the delegate — as an instance teardown -// does — that call would be a use-after-free. -// -// The delegate is deliberately kept alive here rather than destroyed under an -// EXPECT_DEATH. Asserting on the crash asks undefined behaviour to reliably -// terminate the process, which it does not: the death-test form of this test -// (and its two predecessors) passed on the fbcode host but flaked above 88% -// on the Android instrumentation runner, reporting "failed to die" until -// trunk auto-disabled them. Observing the stale call directly pins the same -// open window deterministically. -// --------------------------------------------------------------------------- +// The delegate remains alive so an unwanted call is a deterministic assertion +// failure rather than undefined behavior from dereferencing freed memory. TEST_F( SchedulerDelegateInvalidationTest, - DelegateDetachedWithoutError_PendingRenderingUpdateCallsStaleDelegate) { + DelegateDetachedWithoutError_SkipsPendingRenderingUpdate) { setUp(); - // (a) Enqueue a rendering-update lambda capturing delegate_ raw. scheduler_->uiManagerDidFinishTransaction( coordinator_, /*mountSynchronously=*/false); EXPECT_EQ(delegate_->shouldRenderTransactionsCount(), 0); - // (b) Host swaps the delegate out. No JS throw, so nothing clears the - // rendering-update queue. scheduler_->setDelegate(nullptr); EXPECT_EQ(scheduler_->getDelegate(), nullptr); - // (c) Drain — the lambda calls through its captured pointer even though the - // scheduler itself no longer has a delegate. runOneEventLoopTick(); - EXPECT_EQ(delegate_->shouldRenderTransactionsCount(), 1); + EXPECT_EQ(delegate_->shouldRenderTransactionsCount(), 0); +} + +TEST_F( + SchedulerDelegateInvalidationTest, + DispatchCommand_DelegateDetachedWithoutError_SkipsPendingCallback) { + setUp(); + ASSERT_NE(rootShadowNode_, nullptr); + + scheduler_->uiManagerDidDispatchCommand( + rootShadowNode_, "scrollTo", folly::dynamic::array()); + ASSERT_EQ(delegate_->didDispatchCommandCount(), 0); + + scheduler_->setDelegate(nullptr); + runOneEventLoopTick(); + + EXPECT_FALSE(jsThrowObserved_); + EXPECT_EQ(delegate_->didDispatchCommandCount(), 0); +} + +TEST_F( + SchedulerDelegateInvalidationTest, + DispatchCommand_SchedulerDestroyedWithoutError_SkipsPendingCallback) { + setUp(); + + scheduler_->uiManagerDidDispatchCommand( + rootShadowNode_, "scrollTo", folly::dynamic::array()); + scheduler_->unregisterSurface(*surfaceHandler_); + scheduler_.reset(); + + runOneEventLoopTick(); + + EXPECT_FALSE(jsThrowObserved_); + EXPECT_EQ(delegate_->didDispatchCommandCount(), 0); +} + +TEST_F( + SchedulerDelegateInvalidationTest, + DispatchCommand_DelegateReattached_DoesNotRevivePendingCallback) { + setUp(); + + scheduler_->uiManagerDidDispatchCommand( + rootShadowNode_, "scrollTo", folly::dynamic::array()); + scheduler_->setDelegate(nullptr); + scheduler_->setDelegate(delegate_.get()); + scheduler_->uiManagerDidDispatchCommand( + rootShadowNode_, "scrollTo", folly::dynamic::array()); + + runOneEventLoopTick(); + + EXPECT_EQ(delegate_->didDispatchCommandCount(), 1); +} + +TEST_F( + SchedulerDelegateInvalidationTest, + DispatchCommand_OwnedDelegate_ReleasedAfterCancelledCallbackDrains) { + setUp(std::make_shared()); + std::weak_ptr delegate = delegate_; + + scheduler_->uiManagerDidDispatchCommand( + rootShadowNode_, "scrollTo", folly::dynamic::array()); + scheduler_->unregisterSurface(*surfaceHandler_); + scheduler_.reset(); + delegate_.reset(); + + EXPECT_FALSE(delegate.expired()); + runOneEventLoopTick(); + EXPECT_TRUE(delegate.expired()); +} + +TEST_F( + SchedulerDelegateInvalidationTest, + DispatchCommand_ReentrantTeardown_KeepsOwnedDelegateAliveUntilReturn) { + class TeardownDelegate : public RecordingDelegate { + public: + explicit TeardownDelegate(bool& destroyed) : destroyed_(destroyed) {} + + ~TeardownDelegate() override { + destroyed_ = true; + } + + void schedulerDidDispatchCommand( + const ShadowView& /*shadowView*/, + const std::string& /*commandName*/, + const folly::dynamic& /*args*/) override { + onCommand(); + } + + std::function onCommand; + + private: + bool& destroyed_; + }; + + bool destroyed = false; + bool callbackRan = false; + auto delegate = std::make_shared(destroyed); + delegate->onCommand = [this, &destroyed, &callbackRan]() { + scheduler_->unregisterSurface(*surfaceHandler_); + scheduler_.reset(); + delegate_.reset(); + EXPECT_FALSE(destroyed); + callbackRan = true; + }; + setUp(delegate); + delegate.reset(); + + scheduler_->uiManagerDidDispatchCommand( + rootShadowNode_, "scrollTo", folly::dynamic::array()); + runOneEventLoopTick(); + + EXPECT_TRUE(callbackRan); + EXPECT_TRUE(destroyed); +} + +TEST_F( + SchedulerDelegateInvalidationTest, + ReactCommit_DelegateAlive_MergesPromotedRevision) { + setUp(); + queueReactCommit(); + EXPECT_EQ(delegate_->shouldMergeReactRevisionCount(), 0); + + runOneEventLoopTick(); + + EXPECT_EQ(delegate_->shouldMergeReactRevisionCount(), 1); +} + +TEST_F( + SchedulerDelegateInvalidationTest, + ReactCommit_DelegateDetached_SkipsPendingMerge) { + setUp(); + queueReactCommit(); + scheduler_->setDelegate(nullptr); + + runOneEventLoopTick(); + + EXPECT_EQ(delegate_->shouldMergeReactRevisionCount(), 0); +} + +TEST_F( + SchedulerDelegateInvalidationTest, + SynchronousTransaction_DelegateReplaced_RendersWithReplacement) { + class ReplacingDelegate : public RecordingDelegate { + public: + void schedulerDidFinishTransaction( + const std::shared_ptr< + const MountingCoordinator>& /*mountingCoordinator*/) override { + onTransaction(); + } + + std::function onTransaction; + }; + + auto original = std::make_shared(); + auto replacement = std::make_shared(); + original->onTransaction = [this, &replacement]() { + scheduler_->setDelegate(replacement.get()); + }; + setUp(original); + + scheduler_->uiManagerDidFinishTransaction( + coordinator_, /*mountSynchronously=*/true); + + EXPECT_EQ(original->shouldRenderTransactionsCount(), 0); + EXPECT_EQ(replacement->shouldRenderTransactionsCount(), 1); + scheduler_->setDelegate(nullptr); } // --------------------------------------------------------------------------- diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api index 7b33432309db..68a69c5a8bfa 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api @@ -3524,6 +3524,7 @@ class facebook::react::SafeAreaViewProps : public facebook::react::HostPlatformV class facebook::react::Scheduler : public facebook::react::UIManagerDelegate { public Scheduler(const facebook::react::SchedulerToolbox& schedulerToolbox, facebook::react::UIManagerAnimationDelegate* animationDelegate, facebook::react::SchedulerDelegate* delegate); + public Scheduler(const facebook::react::SchedulerToolbox& schedulerToolbox, facebook::react::UIManagerAnimationDelegate* animationDelegate, std::shared_ptr delegate); public facebook::react::SchedulerDelegate* getDelegate() const; public std::shared_ptr getContextContainer() const; public std::shared_ptr getUIManager() const; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api index aeaed7df09a0..7a69fec5952d 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -5698,6 +5698,7 @@ class facebook::react::SafeAreaViewProps : public facebook::react::HostPlatformV class facebook::react::Scheduler : public facebook::react::UIManagerDelegate { public Scheduler(const facebook::react::SchedulerToolbox& schedulerToolbox, facebook::react::UIManagerAnimationDelegate* animationDelegate, facebook::react::SchedulerDelegate* delegate); + public Scheduler(const facebook::react::SchedulerToolbox& schedulerToolbox, facebook::react::UIManagerAnimationDelegate* animationDelegate, std::shared_ptr delegate); public facebook::react::SchedulerDelegate* getDelegate() const; public std::shared_ptr getContextContainer() const; public std::shared_ptr getUIManager() const; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api index 4c05ab7f6cec..892bf59981b2 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api @@ -2117,6 +2117,7 @@ class facebook::react::RuntimeSchedulerResizeObserverDelegate { class facebook::react::Scheduler : public facebook::react::UIManagerDelegate { public Scheduler(const facebook::react::SchedulerToolbox& schedulerToolbox, facebook::react::UIManagerAnimationDelegate* animationDelegate, facebook::react::SchedulerDelegate* delegate); + public Scheduler(const facebook::react::SchedulerToolbox& schedulerToolbox, facebook::react::UIManagerAnimationDelegate* animationDelegate, std::shared_ptr delegate); public facebook::react::SchedulerDelegate* getDelegate() const; public std::shared_ptr getContextContainer() const; public std::shared_ptr getUIManager() const;