From b439ef7c3f99f2ad446a011be46ae886a5a71320 Mon Sep 17 00:00:00 2001 From: Janic Duplessis Date: Mon, 21 Sep 2026 02:10:25 -0700 Subject: [PATCH] Process synchronous event beats in the frame that requested them (#58530) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: `EventEmitter::experimental_flushSync` only *requests* an event beat; the beat is processed at the next `EventBeat::induce`. On iOS the run loop observer that induces the beat runs before Core Animation's commit observer, so a request made from `layoutSubviews` — inside CA's commit cycle — is only processed one frame later. Anything that reports layout-driven state to JS synchronously (`VirtualView` mode changes, and safe area insets in the PRs that build on this) renders a frame late in exactly the cases that matter. `AppleEventBeat` now also schedules an induce in the **display phase of the current commit cycle**. Core Animation runs a commit as layout → display → commit, so a zero-sized layer marked as needing display during layout gets its `display` call after the whole layout pass and before the transaction is committed. That layer needs to live in the tree being committed, so the beat has to know which tree that is — and the emitter tells it: - `experimental_flushSync` carries the **tag of the emitting view** through `EventDispatcher` and `EventQueue` to `EventBeat::requestSynchronous(Tag)`, with `kNoTag` (https://github.com/react/react-native/issues/58531) meaning no view attribution; a no-argument overload keeps unattributed requesters and the existing tests unchanged. The emitter reads the tag from its `ShadowNodeFamily` at flush time; `kNoTag` if the family is already gone. - `AppleEventBeat` resolves the tag to the layer of the view's **window** through a resolver injected by `RCTSurfacePresenter` (`findComponentViewWithTag:` on the mounting registry — nullable, non-creating, main thread) and attaches its flusher layer there. The requesting view's window is by definition the root of the layer tree whose layout emitted the request, so the flusher is guaranteed a display phase in the current commit cycle — including for content UIKit mounts in a window of its own, like a full screen modal or LogBox. Requests within one cycle coalesce into a single induce. One related fix in `EventBeat` itself: a synchronous request is no longer stranded behind an already-scheduled asynchronous beat (it would silently lose its this-frame guarantee, and the leftover flag would make an unrelated later beat blocking). `AppleEventBeat.cpp` becomes `.mm` for the Objective-C. **Risk:** this changes when queued events are flushed on iOS for every `experimental_flushSync` caller — today `VirtualView`, and safe area insets with the PRs on top. The worst case is a beat processed a frame *earlier* than before, inside a Core Animation commit; the run loop observer path is untouched and still catches anything the display phase misses (an emitter with no tag, an unmounted view, a request off the main thread). Android ignores the tag. Revert is self-contained. ## Design Q&A: **What happens when two views in different windows update at once?** Each requesting window gets its own dirty flusher layer (the map is keyed by host layer), and the first `display` to fire induces the beat, which drains the whole event queue — every window's updates mount before that commit presents. The remaining flushers hit the `isEventBeatRequested_` guard and no-op, so it is one beat total, not one per window. If windows ever commit in separate transactions, each request still resolves within its own window's cycle, since its layer sits in the tree that emitted it. Only requesting windows carry a dirty layer. **Can the tag point at the wrong view — after an unmount, or a recycled view?** No. The tag comes from the emitter's `ShadowNodeFamily`, and a family keeps one tag for its whole life, across clones and state updates; if the family is already gone the flush carries `kNoTag` and skips the resolver. What changes over a view's life — its window — is read live: the tag resolves to a view at flush time and `view.window.layer` is looked up then, so a view that moved between windows targets its current tree. A view mid-unmount or recycled resolves to nil (the registry erases the entry and recycled views get tag `0`) and degrades to run-loop-observer timing. The tag only ever influences *where the induce is scheduled*, never what is delivered or to whom, so the blast radius of any staleness is one frame of timing, not correctness. **Does `VirtualView` need changes to benefit?** No — its sync mode-change flush goes through its own emitter, so the tag attribution is automatic. The case this improves is a mode change emitted during Core Animation layout (a resize pulling a virtualized item into view): on `main` that renders one frame late; here the induce lands in the display phase of the VirtualView's own window, including inside a full screen modal. ## Changelog: [INTERNAL] - Process synchronous event beats in the frame that requested them on iOS, scheduling the induce on the requesting view's window Pull Request resolved: https://github.com/react/react-native/pull/58530 Test Plan: New unit tests in `EventBeatTest.cpp` cover the beat semantics: a synchronous request during an already-scheduled asynchronous beat, coalescing, and induce ordering. They drive the protected `induce` through a subclass standing in for the platform. On device, with the safe area insets prop from the PRs above merged on top: an RNTester example renders a loud marker (yellow background) while a view observes the safe area but has not received an inset event yet, so any presented marker frame means the dispatch was not synchronous. The full apply → landscape → portrait sequence **inside a full screen modal** on an iPhone 17 Pro simulator, decomposed with ffmpeg into 982 frames and every frame scanned for the marker color — **zero marker frames**, and mid-rotation frames already carry the incoming orientation's insets, so the padding animates with the rotation. Scoped honestly: the first inset event after setting the prop is processed at the call site, so the marker primarily proves no regression; the same-frame path for layout-driven changes rests on the by-construction argument above plus the rotation frames. https://github.com/user-attachments/assets/0f2db837-c9c0-4457-96c2-847b7aecf10e `yarn fantom .../ViewSafeAreaInsets-itest.js` passes 4/4 with the prop merged on top. C++ API snapshots regenerated (`scripts/cxx-api/parser`, Doxygen 1.16.1): the deltas are the `requestSynchronous` overload pair, `EventEmitter::getTag`, the resolver type, and the `AppleEventBeat` constructor and destructor. --- **Stack** — split out of https://github.com/react/react-native/issues/57967, which stays open as the prototype and design discussion. GitHub will not take a fork branch as a pull request base, so each of these targets `main` and its diff contains the ones below it until they merge. Each PR is one commit on top of the previous one. This is the bottom of the stack, so its diff is already just this change. 👉 1. https://github.com/react/react-native/issues/58530 — Process synchronous event beats in the frame that requested them 2. https://github.com/react/react-native/issues/58109 — Add an `experimental_onSafeAreaInsetsChange` view prop 3. https://github.com/react/react-native/issues/58110 — Report the window safe area insets through Dimensions 4. https://github.com/react/react-native/issues/58112 — Render the internal SafeAreaView from the safe area insets prop 5. https://github.com/react/react-native/issues/58113 — Remove the native SafeAreaView and the deprecated public export An earlier variant that targeted the surface's root view instead of the view's window was closed in https://github.com/react/react-native/issues/58528; its review thread carries the analysis behind the window-based resolution. https://github.com/react/react-native/issues/58108 was the per-window predecessor this supersedes. Reviewed By: javache Differential Revision: D120200496 Pulled By: Abbondanzo fbshipit-source-id: b06ecb30935837abd6561f54674afef0cdf215a8 --- .../React/Fabric/AppleEventBeat.cpp | 31 --- .../React/Fabric/AppleEventBeat.h | 38 +++- .../React/Fabric/AppleEventBeat.mm | 127 ++++++++++++ .../React/Fabric/RCTSurfacePresenter.mm | 12 +- .../react/renderer/core/EventBeat.cpp | 13 +- .../react/renderer/core/EventBeat.h | 12 +- .../react/renderer/core/EventDispatcher.cpp | 4 +- .../react/renderer/core/EventDispatcher.h | 3 +- .../react/renderer/core/EventEmitter.cpp | 9 + .../react/renderer/core/EventEmitter.h | 8 +- .../react/renderer/core/EventQueue.cpp | 4 +- .../react/renderer/core/EventQueue.h | 3 +- .../runtimescheduler/tests/EventBeatTest.cpp | 185 ++++++++++++++++++ .../api-snapshots/ReactAndroidDebugCxx.api | 3 +- .../api-snapshots/ReactAndroidNewarchCxx.api | 3 +- .../api-snapshots/ReactAndroidReleaseCxx.api | 3 +- .../api-snapshots/ReactAppleDebugCxx.api | 13 +- .../api-snapshots/ReactAppleNewarchCxx.api | 13 +- .../api-snapshots/ReactAppleReleaseCxx.api | 13 +- .../api-snapshots/ReactCommonDebugCxx.api | 3 +- .../api-snapshots/ReactCommonNewarchCxx.api | 3 +- .../api-snapshots/ReactCommonReleaseCxx.api | 3 +- 22 files changed, 450 insertions(+), 56 deletions(-) delete mode 100644 packages/react-native/React/Fabric/AppleEventBeat.cpp create mode 100644 packages/react-native/React/Fabric/AppleEventBeat.mm create mode 100644 packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/EventBeatTest.cpp diff --git a/packages/react-native/React/Fabric/AppleEventBeat.cpp b/packages/react-native/React/Fabric/AppleEventBeat.cpp deleted file mode 100644 index 4a3d533a0cd..00000000000 --- a/packages/react-native/React/Fabric/AppleEventBeat.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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 "AppleEventBeat.h" - -#include - -namespace facebook::react { - -AppleEventBeat::AppleEventBeat( - std::shared_ptr ownerBox, - std::unique_ptr uiRunLoopObserver, - RuntimeScheduler& runtimeScheduler) - : EventBeat(std::move(ownerBox), runtimeScheduler), - uiRunLoopObserver_(std::move(uiRunLoopObserver)) { - uiRunLoopObserver_->setDelegate(this); - uiRunLoopObserver_->enable(); -} - -void AppleEventBeat::activityDidChange( - const RunLoopObserver::Delegate* delegate, - RunLoopObserver::Activity /*activity*/) const noexcept { - react_native_assert(delegate == this); - induce(); -} - -} // namespace facebook::react diff --git a/packages/react-native/React/Fabric/AppleEventBeat.h b/packages/react-native/React/Fabric/AppleEventBeat.h index 256e0f0983a..71ea0a112dc 100644 --- a/packages/react-native/React/Fabric/AppleEventBeat.h +++ b/packages/react-native/React/Fabric/AppleEventBeat.h @@ -7,10 +7,18 @@ #pragma once +#include +#include +#include + +#import + #include #include #include +@class RCTEventBeatFlusherLayer; + namespace facebook::react { class RuntimeScheduler; @@ -19,13 +27,38 @@ class RuntimeScheduler; * Event beat associated with JavaScript runtime. * The beat is called on `RuntimeExecutor`'s thread induced by the UI thread * event loop. + * + * A synchronous request made while Core Animation is laying out the current + * frame (the run loop observer that induces the beat has already run at that + * point) is additionally induced from the display phase of the same commit + * cycle, so that its effects are mounted before the frame is presented. The + * induce is scheduled on the layer of the requesting view's window — the root + * of the tree Core Animation is laying out when the request is made from + * layout. */ class AppleEventBeat : public EventBeat, public RunLoopObserver::Delegate { public: + /* + * Resolves the layer of the window containing the view with the given tag. + * Called on the main thread; returns nil when the view is not mounted or + * not attached to a window. + */ + using WindowLayerResolver = std::function; + AppleEventBeat( std::shared_ptr ownerBox, std::unique_ptr uiRunLoopObserver, - RuntimeScheduler &RuntimeScheduler); + RuntimeScheduler &RuntimeScheduler, + WindowLayerResolver windowLayerResolver); + AppleEventBeat(const AppleEventBeat &) = delete; + AppleEventBeat &operator=(const AppleEventBeat &) = delete; + AppleEventBeat(AppleEventBeat &&) = delete; + AppleEventBeat &operator=(AppleEventBeat &&) = delete; + + ~AppleEventBeat() override; + + using EventBeat::requestSynchronous; + void requestSynchronous(Tag tag) const override; #pragma mark - RunLoopObserver::Delegate @@ -34,6 +67,9 @@ class AppleEventBeat : public EventBeat, public RunLoopObserver::Delegate { private: std::unique_ptr uiRunLoopObserver_; + WindowLayerResolver windowLayerResolver_; + NSMapTable *layers_; + void (^onDisplay_)(void); }; } // namespace facebook::react diff --git a/packages/react-native/React/Fabric/AppleEventBeat.mm b/packages/react-native/React/Fabric/AppleEventBeat.mm new file mode 100644 index 00000000000..66f93729aee --- /dev/null +++ b/packages/react-native/React/Fabric/AppleEventBeat.mm @@ -0,0 +1,127 @@ +/* + * 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 "AppleEventBeat.h" + +#import +#import + +#include + +/* + * A zero-sized layer whose only purpose is to run a callback during the + * display phase of a Core Animation commit. Core Animation processes a commit + * as layout → display → (repeat until stable) → commit, so a layer marked as + * needing display during the layout phase has its `display` called after the + * whole layout pass but before the transaction is committed. + */ +@interface RCTEventBeatFlusherLayer : CALayer +- (instancetype)initWithOnDisplay:(void (^)(void))onDisplay; +@end + +@implementation RCTEventBeatFlusherLayer { + void (^_onDisplay)(void); +} + +- (instancetype)initWithOnDisplay:(void (^)(void))onDisplay +{ + self = [super init]; + if (self != nil) { + _onDisplay = [onDisplay copy]; + self.frame = CGRectZero; + } + return self; +} + +- (void)display +{ + _onDisplay(); +} + +// The layer is not a visual element; never participate in animations. +- (id)actionForKey:(NSString *)event +{ + return nil; +} + +@end + +namespace facebook::react { + +AppleEventBeat::AppleEventBeat( + std::shared_ptr ownerBox, + std::unique_ptr uiRunLoopObserver, + RuntimeScheduler &runtimeScheduler, + WindowLayerResolver windowLayerResolver) + : EventBeat(std::move(ownerBox), runtimeScheduler), + uiRunLoopObserver_(std::move(uiRunLoopObserver)), + windowLayerResolver_(std::move(windowLayerResolver)), + layers_([NSMapTable weakToStrongObjectsMapTable]) +{ + std::weak_ptr weakOwner = ownerBox_->owner; + onDisplay_ = ^{ + // The owner (indirectly) retains the event beat; if it is gone, so is + // the beat this induces. + auto owner = weakOwner.lock(); + if (!owner) { + return; + } + this->induce(); + }; + + uiRunLoopObserver_->setDelegate(this); + uiRunLoopObserver_->enable(); +} + +AppleEventBeat::~AppleEventBeat() +{ + // The beat can be destroyed on any thread; layer mutations belong on the + // main thread. The block only retains the layers, and a display happening + // before it executes is made safe by the owner check above. + NSMapTable *layers = layers_; + RCTExecuteOnMainQueue(^{ + NSEnumerator *enumerator = layers.objectEnumerator; + RCTEventBeatFlusherLayer *layer = enumerator.nextObject; + while (layer != nil) { + [layer removeFromSuperlayer]; + layer = enumerator.nextObject; + } + }); +} + +void AppleEventBeat::requestSynchronous(Tag tag) const +{ + EventBeat::requestSynchronous(tag); + + if (tag == kNoTag || !RCTIsMainQueue()) { + return; + } + CALayer *hostLayer = windowLayerResolver_ ? windowLayerResolver_(tag) : nil; + if (hostLayer == nil) { + return; + } + RCTEventBeatFlusherLayer *layer = [layers_ objectForKey:hostLayer]; + if (layer == nil) { + layer = [[RCTEventBeatFlusherLayer alloc] initWithOnDisplay:onDisplay_]; + [layers_ setObject:layer forKey:hostLayer]; + } + if (layer.superlayer != hostLayer) { + [layer removeFromSuperlayer]; + [hostLayer addSublayer:layer]; + } + [layer setNeedsDisplay]; +} + +void AppleEventBeat::activityDidChange( + const RunLoopObserver::Delegate *delegate, + RunLoopObserver::Activity /*activity*/) const noexcept +{ + react_native_assert(delegate == this); + induce(); +} + +} // namespace facebook::react diff --git a/packages/react-native/React/Fabric/RCTSurfacePresenter.mm b/packages/react-native/React/Fabric/RCTSurfacePresenter.mm index 0e4bbe37646..cda782d1d5f 100644 --- a/packages/react-native/React/Fabric/RCTSurfacePresenter.mm +++ b/packages/react-native/React/Fabric/RCTSurfacePresenter.mm @@ -292,11 +292,17 @@ class ReactRevisionMergeRunLoopObserverDelegate final : public RunLoopObserver:: toolbox.runtimeExecutor = runtimeExecutor; toolbox.bridgelessBindingsExecutor = _bridgelessBindingsExecutor; - toolbox.eventBeatFactory = - [runtimeScheduler](std::shared_ptr ownerBox) -> std::unique_ptr { + __weak RCTMountingManager *weakMountingManager = _mountingManager; + toolbox.eventBeatFactory = [runtimeScheduler, weakMountingManager]( + std::shared_ptr ownerBox) -> std::unique_ptr { auto runLoopObserver = std::make_unique(RunLoopObserver::Activity::BeforeWaiting, ownerBox->owner); - return std::make_unique(std::move(ownerBox), std::move(runLoopObserver), *runtimeScheduler); + auto windowLayerResolver = [weakMountingManager](Tag tag) -> CALayer * { + RCTMountingManager *mountingManager = weakMountingManager; + return [mountingManager.componentViewRegistry findComponentViewWithTag:tag].window.layer; + }; + return std::make_unique( + std::move(ownerBox), std::move(runLoopObserver), *runtimeScheduler, std::move(windowLayerResolver)); }; RCTScheduler *scheduler = [[RCTScheduler alloc] initWithToolbox:toolbox]; diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventBeat.cpp b/packages/react-native/ReactCommon/react/renderer/core/EventBeat.cpp index cdb05f4719f..e8cf9ffdda2 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventBeat.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/EventBeat.cpp @@ -26,6 +26,10 @@ void EventBeat::request() const { } void EventBeat::requestSynchronous() const { + requestSynchronous(kNoTag); +} + +void EventBeat::requestSynchronous(Tag /*tag*/) const { react_native_assert( beatCallback_ && "Unexpected state: EventBeat::setBeatCallback was not called before EventBeat::requestSynchronous."); @@ -53,7 +57,14 @@ void EventBeat::induce() const { isEventBeatRequested_ = false; if (isBeatCallbackScheduled_) { - return; + // An asynchronous beat is already scheduled but has not run yet. A + // synchronous request must not be stranded behind it (it would silently + // lose its this-frame guarantee, and the leftover flag would make an + // unrelated later beat blocking), so it proceeds and processes the queue + // now; the already scheduled beat will simply find an empty queue. + if (!isSynchronousRequested_) { + return; + } } isBeatCallbackScheduled_ = true; diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventBeat.h b/packages/react-native/ReactCommon/react/renderer/core/EventBeat.h index 6f25d5f45c6..561a72472cd 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventBeat.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventBeat.h @@ -9,6 +9,7 @@ #include +#include #include #include #include @@ -110,8 +111,17 @@ class EventBeat { * thread────────────────────┴─────────────────────────┴▶ * Both JS and UI thread are * blocked. + * + * `tag` is the view the request originates from, or `kNoTag` when unknown. + * Platform implementations use it to schedule an induce where that view + * renders, and fall back to their ordinary beat timing without it. */ - virtual void requestSynchronous() const; + virtual void requestSynchronous(Tag tag) const; + + /* + * Convenience for requesters with no view attribution. + */ + void requestSynchronous() const; /* * The callback will be executed once a consumer (for example EventQueue) diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.cpp b/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.cpp index 5fa5e6821a5..70f9c63ee77 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.cpp @@ -37,8 +37,8 @@ void EventDispatcher::dispatchEvent(RawEvent&& rawEvent) const { eventQueue_.enqueueEvent(std::move(rawEvent)); } -void EventDispatcher::experimental_flushSync() const { - eventQueue_.experimental_flushSync(); +void EventDispatcher::experimental_flushSync(Tag tag) const { + eventQueue_.experimental_flushSync(tag); } void EventDispatcher::dispatchStateUpdate( diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.h b/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.h index 5aaa48364f9..12d651c4239 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventDispatcher.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -46,7 +47,7 @@ class EventDispatcher { /* * Experimental API exposed to support EventEmitter::experimental_flushSync. */ - void experimental_flushSync() const; + void experimental_flushSync(Tag tag) const; /* * Dispatches a raw event with asynchronous batched priority. Before the diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.cpp b/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.cpp index 2d6ac50e373..ee4f386d614 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.cpp @@ -7,6 +7,8 @@ #include "EventEmitter.h" +#include + #include #include #include @@ -234,6 +236,13 @@ void EventEmitter::setShadowNodeFamily( shadowNodeFamily_ = std::move(shadowNodeFamily); } +Tag EventEmitter::getTag() const { + if (auto family = shadowNodeFamily_.lock()) { + return family->getTag(); + } + return kNoTag; +} + const SharedEventTarget& EventEmitter::getEventTarget() const { return eventTarget_; } diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h b/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h index 8863d9a6f4f..f1313960d7d 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventEmitter.h @@ -77,7 +77,7 @@ class EventEmitter { } syncFunc(); - eventDispatcher->experimental_flushSync(); + eventDispatcher->experimental_flushSync(getTag()); } /* @@ -133,6 +133,12 @@ class EventEmitter { private: friend class UIManagerBinding; + /* + * The tag of the view this emitter belongs to, or `kNoTag` once its family + * is gone. + */ + Tag getTag() const; + SharedEventTarget eventTarget_; std::weak_ptr shadowNodeFamily_; diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventQueue.cpp b/packages/react-native/ReactCommon/react/renderer/core/EventQueue.cpp index 6e99fd71bb7..27b4ee16df9 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventQueue.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/EventQueue.cpp @@ -86,8 +86,8 @@ void EventQueue::onEnqueue() const { eventBeat_->request(); } -void EventQueue::experimental_flushSync() const { - eventBeat_->requestSynchronous(); +void EventQueue::experimental_flushSync(Tag tag) const { + eventBeat_->requestSynchronous(tag); } void EventQueue::onBeat(jsi::Runtime& runtime) const { diff --git a/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h b/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h index 93fc8119e72..d67875ac5fd 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h +++ b/packages/react-native/ReactCommon/react/renderer/core/EventQueue.h @@ -9,6 +9,7 @@ #include +#include #include #include #include @@ -63,7 +64,7 @@ class EventQueue { /* * Experimental API exposed to support EventEmitter::experimental_flushSync. */ - void experimental_flushSync() const; + void experimental_flushSync(Tag tag) const; protected: /* diff --git a/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/EventBeatTest.cpp b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/EventBeatTest.cpp new file mode 100644 index 00000000000..d64d41f1328 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/runtimescheduler/tests/EventBeatTest.cpp @@ -0,0 +1,185 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include +#include + +#include "StubQueue.h" + +namespace facebook::react { + +class EventBeatTestFeatureFlags : public ReactNativeFeatureFlagsDefaults { + public: + bool enableBridgelessArchitecture() override { + return true; + } +}; + +/* + * `induce` is protected: production code induces from platform beat + * subclasses. The tests drive it directly, standing in for the platform. + */ +class TestEventBeat : public EventBeat { + public: + using EventBeat::EventBeat; + using EventBeat::induce; +}; + +class EventBeatTest : public testing::Test { + protected: + void SetUp() override { + ReactNativeFeatureFlags::dangerouslyReset(); + ReactNativeFeatureFlags::override( + std::make_unique()); + + runtime_ = facebook::hermes::makeHermesRuntime( + ::hermes::vm::RuntimeConfig::Builder().build()); + stubQueue_ = std::make_unique(); + + RuntimeExecutor runtimeExecutor = + [this]( + std::function&& callback) { + stubQueue_->runOnQueue([this, callback = std::move(callback)]() { + callback(*runtime_); + }); + }; + + runtimeScheduler_ = std::make_unique(runtimeExecutor); + + ownerBox_ = std::make_shared(); + owner_ = std::make_shared(0); + ownerBox_->owner = owner_; + eventBeat_ = std::make_unique(ownerBox_, *runtimeScheduler_); + } + + void TearDown() override { + ReactNativeFeatureFlags::dangerouslyReset(); + } + + std::unique_ptr runtime_; + std::unique_ptr stubQueue_; + std::unique_ptr runtimeScheduler_; + std::shared_ptr ownerBox_; + std::shared_ptr owner_; + std::unique_ptr eventBeat_; +}; + +TEST_F(EventBeatTest, induceWithoutRequestIsNoop) { + int beatCount = 0; + eventBeat_->setBeatCallback( + [&beatCount](jsi::Runtime& /*runtime*/) { beatCount++; }); + + eventBeat_->induce(); + + EXPECT_EQ(beatCount, 0); + EXPECT_EQ(stubQueue_->size(), 0); +} + +TEST_F(EventBeatTest, synchronousRequestIsProcessedAtInduce) { + int beatCount = 0; + eventBeat_->setBeatCallback( + [&beatCount](jsi::Runtime& /*runtime*/) { beatCount++; }); + + eventBeat_->requestSynchronous(); + EXPECT_EQ(beatCount, 0); + + // Platform implementations induce the beat at a point where the effects of + // synchronous events can still make the current frame (the display phase on + // Apple, before the draw on Android). The beat callback runs synchronously + // before `induce` returns, with both threads blocked. + std::thread driver([this]() { + stubQueue_->waitForTask(); + stubQueue_->tick(); + }); + eventBeat_->induce(); + driver.join(); + + EXPECT_EQ(beatCount, 1); + + // The request was consumed: another induce does nothing. + eventBeat_->induce(); + EXPECT_EQ(beatCount, 1); + EXPECT_EQ(stubQueue_->size(), 0); +} + +TEST_F(EventBeatTest, requestMadeDuringBeatIsProcessedByASubsequentInduce) { + int beatCount = 0; + eventBeat_->setBeatCallback([&](jsi::Runtime& /*runtime*/) { + beatCount++; + if (beatCount == 1) { + // A synchronous request made from within the beat (e.g. an event whose + // handler causes another synchronous event). Platform implementations + // defer the induce for it (the display phase flusher on Apple, the next + // pre-draw on Android) rather than inducing from within the beat. + eventBeat_->requestSynchronous(); + } + }); + + eventBeat_->requestSynchronous(); + std::thread driver([this]() { + stubQueue_->waitForTask(); + stubQueue_->tick(); + }); + eventBeat_->induce(); + driver.join(); + + EXPECT_EQ(beatCount, 1); + + // The request made during the beat is not lost: the next induce processes + // it. + std::thread driver2([this]() { + stubQueue_->waitForTask(); + stubQueue_->tick(); + }); + eventBeat_->induce(); + driver2.join(); + + EXPECT_EQ(beatCount, 2); +} + +TEST_F(EventBeatTest, synchronousRequestIsNotStrandedBehindScheduledBeat) { + int beatCount = 0; + eventBeat_->setBeatCallback( + [&beatCount](jsi::Runtime& /*runtime*/) { beatCount++; }); + + // An asynchronous beat is scheduled but has not run yet. + eventBeat_->request(); + eventBeat_->induce(); + EXPECT_EQ(beatCount, 0); + + // A synchronous request arriving now must still be processed by its induce + // instead of being silently deferred behind the scheduled beat. + eventBeat_->requestSynchronous(); + std::thread inducer([this]() { eventBeat_->induce(); }); + + // Wait until the synchronous access request joins the already-queued work + // item, so that the tick order below is deterministic. + stubQueue_->waitForTasks(2); + + // The scheduled beat's work item yields to the pending synchronous access + // without executing. + stubQueue_->tick(); + EXPECT_EQ(beatCount, 0); + + // The synchronous access processes the beat within its induce. + stubQueue_->tick(); + inducer.join(); + EXPECT_EQ(beatCount, 1); + + // The beat that yielded resumes afterwards; it was not lost. + stubQueue_->tick(); + EXPECT_EQ(beatCount, 2); + EXPECT_EQ(stubQueue_->size(), 0); +} + +} // namespace facebook::react diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api index c28b679c658..ddbcc025df4 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api @@ -2235,8 +2235,9 @@ class facebook::react::EventBeat { public using BeatCallback = std::function; public using Factory = std::function(std::shared_ptr ownerBox)>; public virtual void request() const; - public virtual void requestSynchronous() const; + public virtual void requestSynchronous(facebook::react::Tag tag) const; public virtual ~EventBeat() = default; + public void requestSynchronous() const; public void setBeatCallback(facebook::react::EventBeat::BeatCallback beatCallback); } diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api index b5a1b0466f1..27faa45129f 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api @@ -2218,8 +2218,9 @@ class facebook::react::EventBeat { public using BeatCallback = std::function; public using Factory = std::function(std::shared_ptr ownerBox)>; public virtual void request() const; - public virtual void requestSynchronous() const; + public virtual void requestSynchronous(facebook::react::Tag tag) const; public virtual ~EventBeat() = default; + public void requestSynchronous() const; public void setBeatCallback(facebook::react::EventBeat::BeatCallback beatCallback); } diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api index 4909bc99e6e..100ffa70ba5 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api @@ -2233,8 +2233,9 @@ class facebook::react::EventBeat { public using BeatCallback = std::function; public using Factory = std::function(std::shared_ptr ownerBox)>; public virtual void request() const; - public virtual void requestSynchronous() const; + public virtual void requestSynchronous(facebook::react::Tag tag) const; public virtual ~EventBeat() = default; + public void requestSynchronous() const; public void setBeatCallback(facebook::react::EventBeat::BeatCallback beatCallback); } diff --git a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api index 97701240061..c15e97984e0 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api @@ -4233,8 +4233,16 @@ class facebook::react::AppRegistryBinding { } class facebook::react::AppleEventBeat : public facebook::react::EventBeat, public facebook::react::RunLoopObserver::Delegate { - public AppleEventBeat(std::shared_ptr ownerBox, std::unique_ptr uiRunLoopObserver, facebook::react::RuntimeScheduler& RuntimeScheduler); + public AppleEventBeat(const facebook::react::AppleEventBeat&) = delete; + public AppleEventBeat(facebook::react::AppleEventBeat&&) = delete; + public AppleEventBeat(std::shared_ptr ownerBox, std::unique_ptr uiRunLoopObserver, facebook::react::RuntimeScheduler& RuntimeScheduler, facebook::react::AppleEventBeat::WindowLayerResolver windowLayerResolver); + public facebook::react::AppleEventBeat& operator=(const facebook::react::AppleEventBeat&) = delete; + public facebook::react::AppleEventBeat& operator=(facebook::react::AppleEventBeat&&) = delete; + public using WindowLayerResolver = std::function; public virtual void activityDidChange(const facebook::react::RunLoopObserver::Delegate* delegate, facebook::react::RunLoopObserver::Activity activity) const noexcept override; + public virtual void requestSynchronous(facebook::react::Tag tag) const override; + public void requestSynchronous() const; + public ~AppleEventBeat() override; } class facebook::react::AsyncArrayBuffer { @@ -4747,8 +4755,9 @@ class facebook::react::EventBeat { public using BeatCallback = std::function; public using Factory = std::function(std::shared_ptr ownerBox)>; public virtual void request() const; - public virtual void requestSynchronous() const; + public virtual void requestSynchronous(facebook::react::Tag tag) const; public virtual ~EventBeat() = default; + public void requestSynchronous() const; public void setBeatCallback(facebook::react::EventBeat::BeatCallback beatCallback); } diff --git a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api index 26b4fef4c1e..548568e0645 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api @@ -4220,8 +4220,16 @@ class facebook::react::AppRegistryBinding { } class facebook::react::AppleEventBeat : public facebook::react::EventBeat, public facebook::react::RunLoopObserver::Delegate { - public AppleEventBeat(std::shared_ptr ownerBox, std::unique_ptr uiRunLoopObserver, facebook::react::RuntimeScheduler& RuntimeScheduler); + public AppleEventBeat(const facebook::react::AppleEventBeat&) = delete; + public AppleEventBeat(facebook::react::AppleEventBeat&&) = delete; + public AppleEventBeat(std::shared_ptr ownerBox, std::unique_ptr uiRunLoopObserver, facebook::react::RuntimeScheduler& RuntimeScheduler, facebook::react::AppleEventBeat::WindowLayerResolver windowLayerResolver); + public facebook::react::AppleEventBeat& operator=(const facebook::react::AppleEventBeat&) = delete; + public facebook::react::AppleEventBeat& operator=(facebook::react::AppleEventBeat&&) = delete; + public using WindowLayerResolver = std::function; public virtual void activityDidChange(const facebook::react::RunLoopObserver::Delegate* delegate, facebook::react::RunLoopObserver::Activity activity) const noexcept override; + public virtual void requestSynchronous(facebook::react::Tag tag) const override; + public void requestSynchronous() const; + public ~AppleEventBeat() override; } class facebook::react::AsyncArrayBuffer { @@ -4723,8 +4731,9 @@ class facebook::react::EventBeat { public using BeatCallback = std::function; public using Factory = std::function(std::shared_ptr ownerBox)>; public virtual void request() const; - public virtual void requestSynchronous() const; + public virtual void requestSynchronous(facebook::react::Tag tag) const; public virtual ~EventBeat() = default; + public void requestSynchronous() const; public void setBeatCallback(facebook::react::EventBeat::BeatCallback beatCallback); } diff --git a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api index c9b332d6b53..3f4cda1ab15 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api @@ -4231,8 +4231,16 @@ class facebook::react::AppRegistryBinding { } class facebook::react::AppleEventBeat : public facebook::react::EventBeat, public facebook::react::RunLoopObserver::Delegate { - public AppleEventBeat(std::shared_ptr ownerBox, std::unique_ptr uiRunLoopObserver, facebook::react::RuntimeScheduler& RuntimeScheduler); + public AppleEventBeat(const facebook::react::AppleEventBeat&) = delete; + public AppleEventBeat(facebook::react::AppleEventBeat&&) = delete; + public AppleEventBeat(std::shared_ptr ownerBox, std::unique_ptr uiRunLoopObserver, facebook::react::RuntimeScheduler& RuntimeScheduler, facebook::react::AppleEventBeat::WindowLayerResolver windowLayerResolver); + public facebook::react::AppleEventBeat& operator=(const facebook::react::AppleEventBeat&) = delete; + public facebook::react::AppleEventBeat& operator=(facebook::react::AppleEventBeat&&) = delete; + public using WindowLayerResolver = std::function; public virtual void activityDidChange(const facebook::react::RunLoopObserver::Delegate* delegate, facebook::react::RunLoopObserver::Activity activity) const noexcept override; + public virtual void requestSynchronous(facebook::react::Tag tag) const override; + public void requestSynchronous() const; + public ~AppleEventBeat() override; } class facebook::react::AsyncArrayBuffer { @@ -4745,8 +4753,9 @@ class facebook::react::EventBeat { public using BeatCallback = std::function; public using Factory = std::function(std::shared_ptr ownerBox)>; public virtual void request() const; - public virtual void requestSynchronous() const; + public virtual void requestSynchronous(facebook::react::Tag tag) const; public virtual ~EventBeat() = default; + public void requestSynchronous() const; public void setBeatCallback(facebook::react::EventBeat::BeatCallback beatCallback); } diff --git a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api index b9dd6c56882..da20c08e826 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api @@ -1477,8 +1477,9 @@ class facebook::react::EventBeat { public using BeatCallback = std::function; public using Factory = std::function(std::shared_ptr ownerBox)>; public virtual void request() const; - public virtual void requestSynchronous() const; + public virtual void requestSynchronous(facebook::react::Tag tag) const; public virtual ~EventBeat() = default; + public void requestSynchronous() const; public void setBeatCallback(facebook::react::EventBeat::BeatCallback beatCallback); } diff --git a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api index 10385325431..5fde082a114 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api @@ -1461,8 +1461,9 @@ class facebook::react::EventBeat { public using BeatCallback = std::function; public using Factory = std::function(std::shared_ptr ownerBox)>; public virtual void request() const; - public virtual void requestSynchronous() const; + public virtual void requestSynchronous(facebook::react::Tag tag) const; public virtual ~EventBeat() = default; + public void requestSynchronous() const; public void setBeatCallback(facebook::react::EventBeat::BeatCallback beatCallback); } diff --git a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api index 03199a6de00..dc936960516 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api @@ -1475,8 +1475,9 @@ class facebook::react::EventBeat { public using BeatCallback = std::function; public using Factory = std::function(std::shared_ptr ownerBox)>; public virtual void request() const; - public virtual void requestSynchronous() const; + public virtual void requestSynchronous(facebook::react::Tag tag) const; public virtual ~EventBeat() = default; + public void requestSynchronous() const; public void setBeatCallback(facebook::react::EventBeat::BeatCallback beatCallback); }