Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 54 additions & 20 deletions packages/react-native/React/Fabric/RCTScheduler.mm
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#import <react/featureflags/ReactNativeFeatureFlags.h>
#import <react/renderer/animations/LayoutAnimationDriver.h>
#import <react/renderer/componentregistry/ComponentDescriptorFactory.h>
#import <react/renderer/runtimescheduler/RuntimeScheduler.h>
#import <react/renderer/scheduler/Scheduler.h>
#import <react/renderer/scheduler/SchedulerDelegate.h>
#import <react/utils/RunLoopObserver.h>
Expand All @@ -24,24 +25,29 @@

class SchedulerDelegateProxy : public SchedulerDelegate {
public:
SchedulerDelegateProxy(void *scheduler) : scheduler_(scheduler) {}
id<RCTSchedulerDelegate> getDelegate() const
{
return delegate_;
}

void setDelegate(id<RCTSchedulerDelegate> delegate)
{
delegate_ = delegate;
}

void schedulerDidFinishTransaction(const std::shared_ptr<const MountingCoordinator> &mountingCoordinator) override
{
RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_;
[scheduler.delegate schedulerDidFinishTransaction:mountingCoordinator];
[delegate_ schedulerDidFinishTransaction:mountingCoordinator];
}

void schedulerShouldRenderTransactions(const std::shared_ptr<const MountingCoordinator> &mountingCoordinator) override
{
RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_;
[scheduler.delegate schedulerShouldRenderTransactions:mountingCoordinator];
[delegate_ schedulerShouldRenderTransactions:mountingCoordinator];
}

void schedulerShouldMergeReactRevision(SurfaceId surfaceId) override
{
RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_;
[scheduler.delegate schedulerShouldMergeReactRevision:surfaceId];
[delegate_ schedulerShouldMergeReactRevision:surfaceId];
}

void schedulerDidRequestPreliminaryViewAllocation(const ShadowNode &shadowNode) override
Expand All @@ -55,29 +61,25 @@ void schedulerDidDispatchCommand(
const std::string &commandName,
const folly::dynamic &args) override
{
RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_;
[scheduler.delegate schedulerDidDispatchCommand:shadowView commandName:commandName args:args];
[delegate_ schedulerDidDispatchCommand:shadowView commandName:commandName args:args];
}

void schedulerDidSetIsJSResponder(const ShadowView &shadowView, bool isJSResponder, bool blockNativeResponder)
override
{
RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_;
[scheduler.delegate schedulerDidSetIsJSResponder:isJSResponder
blockNativeResponder:blockNativeResponder
forShadowView:shadowView];
[delegate_ schedulerDidSetIsJSResponder:isJSResponder
blockNativeResponder:blockNativeResponder
forShadowView:shadowView];
}

void schedulerDidSendAccessibilityEvent(const ShadowView &shadowView, const std::string &eventType) override
{
RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_;
[scheduler.delegate schedulerDidSendAccessibilityEvent:shadowView eventType:eventType];
[delegate_ schedulerDidSendAccessibilityEvent:shadowView eventType:eventType];
}

void schedulerShouldSynchronouslyUpdateViewOnUIThread(facebook::react::Tag tag, const folly::dynamic &props) override
{
RCTScheduler *scheduler = (__bridge RCTScheduler *)scheduler_;
[scheduler.delegate schedulerDidSynchronouslyUpdateViewOnUIThread:tag props:props];
[delegate_ schedulerDidSynchronouslyUpdateViewOnUIThread:tag props:props];
}

void schedulerDidUpdateShadowTree(const std::unordered_map<Tag, folly::dynamic> &tagToProps) override
Expand Down Expand Up @@ -105,7 +107,7 @@ void schedulerDidClearPendingSnapshots() override
}

private:
void *scheduler_;
__weak id<RCTSchedulerDelegate> delegate_;
};

class LayoutAnimationDelegateProxy : public LayoutAnimationStatusDelegate, public RunLoopObserver::Delegate {
Expand Down Expand Up @@ -188,15 +190,21 @@ void pause() override
@implementation RCTScheduler {
std::unique_ptr<Scheduler> _scheduler;
std::shared_ptr<LayoutAnimationDriver> _animationDriver;
std::unique_ptr<SchedulerDelegateProxy> _delegateProxy;
std::shared_ptr<SchedulerDelegateProxy> _delegateProxy;
std::weak_ptr<RuntimeScheduler> _runtimeScheduler;
std::shared_ptr<LayoutAnimationDelegateProxy> _layoutAnimationDelegateProxy;
std::unique_ptr<const PlatformRunLoopObserver> _uiRunLoopObserver;
}

- (instancetype)initWithToolbox:(SchedulerToolbox)toolbox
{
if (self = [super init]) {
_delegateProxy = std::make_unique<SchedulerDelegateProxy>((__bridge void *)self);
_delegateProxy = std::make_shared<SchedulerDelegateProxy>();

auto runtimeScheduler = toolbox.contextContainer->find<std::weak_ptr<RuntimeScheduler>>(RuntimeSchedulerKey);
if (runtimeScheduler.has_value()) {
_runtimeScheduler = runtimeScheduler.value();
}

if (ReactNativeFeatureFlags::enableLayoutAnimationsOnIOS()) {
_layoutAnimationDelegateProxy = std::make_shared<LayoutAnimationDelegateProxy>((__bridge void *)self);
Expand All @@ -220,6 +228,16 @@ - (instancetype)initWithToolbox:(SchedulerToolbox)toolbox
return self;
}

- (id<RCTSchedulerDelegate>)delegate
{
return _delegateProxy->getDelegate();
}

- (void)setDelegate:(id<RCTSchedulerDelegate>)delegate
{
_delegateProxy->setDelegate(delegate);
}

- (void)animationTick
{
_scheduler->animationTick();
Expand All @@ -237,6 +255,22 @@ - (void)dealloc
}

_scheduler->setDelegate(nullptr);
_delegateProxy->setDelegate(nil);

// The JS thread may still hold rendering updates that call the proxy. Each one runs at the end of the event loop
// tick that queued it, or of the next tick if it was queued outside one, and a task error discards them together
// with this task. So the proxy is released in a task scheduled from a task: by then every update that captured it
// has run or been discarded.
if (auto runtimeScheduler = _runtimeScheduler.lock()) {
runtimeScheduler->scheduleTask(
SchedulerPriority::ImmediatePriority,
[weakRuntimeScheduler = _runtimeScheduler, delegateProxy = _delegateProxy](facebook::jsi::Runtime &) {
if (auto runtimeScheduler = weakRuntimeScheduler.lock()) {
runtimeScheduler->scheduleTask(
SchedulerPriority::ImmediatePriority, [delegateProxy](facebook::jsi::Runtime &) {});
}
});
}
}

- (void)registerSurface:(const facebook::react::SurfaceHandler &)surfaceHandler
Expand Down
219 changes: 219 additions & 0 deletions packages/react-native/React/Tests/Fabric/RCTSchedulerTests.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
/*
* 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.
*/

#import <XCTest/XCTest.h>

#import <React/RCTScheduler.h>
#import <hermes/hermes.h>
#import <react/featureflags/ReactNativeFeatureFlags.h>
#import <react/featureflags/ReactNativeFeatureFlagsDefaults.h>
#import <react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h>
#import <react/renderer/components/view/ViewComponentDescriptor.h>
#import <react/renderer/core/EventBeat.h>
#import <react/renderer/core/PropsParserContext.h>
#import <react/renderer/runtimescheduler/RuntimeScheduler.h>
#import <react/renderer/scheduler/SchedulerToolbox.h>
#import <react/renderer/uimanager/UIManager.h>
#import <react/utils/ContextContainer.h>

#include <functional>
#include <memory>
#include <queue>

using namespace facebook::react;
using facebook::jsi::Runtime;

namespace {

class TestFeatureFlags : public ReactNativeFeatureFlagsDefaults {
public:
// Selects RuntimeScheduler_Modern, which defers rendering updates to the end of the event loop tick.
bool enableBridgelessArchitecture() override
{
return true;
}
};

class StubEventBeat : public EventBeat {
public:
StubEventBeat(std::shared_ptr<OwnerBox> ownerBox, RuntimeScheduler &runtimeScheduler)
: EventBeat(std::move(ownerBox), runtimeScheduler)
{
}
};

constexpr SurfaceId kSurfaceId = 1;

} // namespace

@interface RCTSchedulerDelegateRecorder : NSObject <RCTSchedulerDelegate>
@property (nonatomic, assign) NSUInteger dispatchedCommandCount;
@end

@implementation RCTSchedulerDelegateRecorder

- (void)schedulerDidFinishTransaction:(std::shared_ptr<const MountingCoordinator>)mountingCoordinator
{
}

- (void)schedulerShouldRenderTransactions:(std::shared_ptr<const MountingCoordinator>)mountingCoordinator
{
}

- (void)schedulerShouldMergeReactRevision:(SurfaceId)surfaceId
{
}

- (void)schedulerDidDispatchCommand:(const ShadowView &)shadowView
commandName:(const std::string &)commandName
args:(const folly::dynamic &)args
{
self.dispatchedCommandCount++;
}

- (void)schedulerDidSendAccessibilityEvent:(const ShadowView &)shadowView eventType:(const std::string &)eventType
{
}

- (void)schedulerDidSetIsJSResponder:(BOOL)isJSResponder
blockNativeResponder:(BOOL)blockNativeResponder
forShadowView:(const ShadowView &)shadowView
{
}

- (void)schedulerDidSynchronouslyUpdateViewOnUIThread:(Tag)reactTag props:(folly::dynamic)props
{
}

@end

@interface RCTSchedulerTests : XCTestCase
@end

@implementation RCTSchedulerTests {
std::unique_ptr<facebook::hermes::HermesRuntime> _runtime;
// Work sent to the JS thread. Tests drain it on the main thread, so every step is ordered explicitly.
std::shared_ptr<std::queue<std::function<void()>>> _jsQueue;
std::shared_ptr<RuntimeScheduler> _runtimeScheduler;
std::shared_ptr<ContextContainer> _contextContainer;
std::unique_ptr<ViewComponentDescriptor> _viewComponentDescriptor;
std::shared_ptr<const ShadowNode> _shadowNode;
}

- (void)setUp
{
[super setUp];

ReactNativeFeatureFlags::dangerouslyReset();
ReactNativeFeatureFlags::override(std::make_unique<TestFeatureFlags>());

_runtime =
facebook::hermes::makeHermesRuntime(::hermes::vm::RuntimeConfig::Builder().withMicrotaskQueue(true).build());
_jsQueue = std::make_shared<std::queue<std::function<void()>>>();

RuntimeExecutor runtimeExecutor = [jsQueue = _jsQueue,
runtime = _runtime.get()](std::function<void(Runtime &)> &&callback) {
jsQueue->push([runtime, callback = std::move(callback)]() { callback(*runtime); });
};
_runtimeScheduler = std::make_shared<RuntimeScheduler>(runtimeExecutor);

_contextContainer = std::make_shared<ContextContainer>();
_contextContainer->insert(RuntimeSchedulerKey, std::weak_ptr<RuntimeScheduler>(_runtimeScheduler));

_viewComponentDescriptor = std::make_unique<ViewComponentDescriptor>(
ComponentDescriptorParameters{.eventDispatcher = {}, .contextContainer = _contextContainer, .flavor = nullptr});
PropsParserContext parserContext{kSurfaceId, *_contextContainer};
auto props = _viewComponentDescriptor->cloneProps(parserContext, nullptr, RawProps{});
auto family = _viewComponentDescriptor->createFamily({.tag = 2, .surfaceId = kSurfaceId, .instanceHandle = nullptr});
_shadowNode = _viewComponentDescriptor->createShadowNode(ShadowNodeFragment{.props = props}, family);
}

- (void)tearDown
{
_shadowNode.reset();
_viewComponentDescriptor.reset();
_runtimeScheduler.reset();
_contextContainer.reset();
_jsQueue.reset();
_runtime.reset();
ReactNativeFeatureFlags::dangerouslyReset();

[super tearDown];
}

- (RCTScheduler *)createScheduler
{
SchedulerToolbox toolbox{};
toolbox.contextContainer = _contextContainer;
toolbox.runtimeExecutor = [jsQueue = _jsQueue, runtime = _runtime.get()](std::function<void(Runtime &)> &&callback) {
jsQueue->push([runtime, callback = std::move(callback)]() { callback(*runtime); });
};
toolbox.componentRegistryFactory = [](const EventDispatcher::Weak &eventDispatcher,
const std::shared_ptr<const ContextContainer> &contextContainer) {
ComponentDescriptorProviderRegistry providerRegistry{};
providerRegistry.add(concreteComponentDescriptorProvider<ViewComponentDescriptor>());
return providerRegistry.createComponentDescriptorRegistry(
{.eventDispatcher = eventDispatcher, .contextContainer = contextContainer, .flavor = nullptr});
};
auto runtimeScheduler = _runtimeScheduler;
toolbox.eventBeatFactory = [runtimeScheduler](std::shared_ptr<EventBeat::OwnerBox> ownerBox) {
return std::make_unique<StubEventBeat>(std::move(ownerBox), *runtimeScheduler);
};

return [[RCTScheduler alloc] initWithToolbox:toolbox];
}

// Goes through the same path as a JS `UIManager.dispatchCommand` call, which queues a rendering update.
- (void)dispatchCommandWithScheduler:(RCTScheduler *)scheduler
{
scheduler.uiManager->getDelegate()->uiManagerDidDispatchCommand(_shadowNode, "scrollTo", folly::dynamic::array());
}

- (void)drainJSQueue
{
while (!_jsQueue->empty()) {
auto work = std::move(_jsQueue->front());
_jsQueue->pop();
work();
}
}

- (void)testQueuedCommandReachesDelegateAtEndOfTick
{
RCTSchedulerDelegateRecorder *delegate = [RCTSchedulerDelegateRecorder new];
RCTScheduler *scheduler = [self createScheduler];
scheduler.delegate = delegate;
XCTAssertEqual(scheduler.delegate, delegate);

[self dispatchCommandWithScheduler:scheduler];
XCTAssertEqual(delegate.dispatchedCommandCount, 0u);

_runtimeScheduler->scheduleWork([](Runtime &) {});
[self drainJSQueue];
XCTAssertEqual(delegate.dispatchedCommandCount, 1u);
}

- (void)testQueuedCommandIsDroppedAfterSchedulerIsReleased
{
RCTSchedulerDelegateRecorder *delegate = [RCTSchedulerDelegateRecorder new];
__weak RCTScheduler *weakScheduler;
@autoreleasepool {
RCTScheduler *scheduler = [self createScheduler];
scheduler.delegate = delegate;
weakScheduler = scheduler;
[self dispatchCommandWithScheduler:scheduler];
}

// Released off the JS thread while a rendering update that captured its delegate proxy is still queued, as when
// the app terminates. The next tick runs that update, which must reach neither the delegate nor freed memory.
XCTAssertNil(weakScheduler);
_runtimeScheduler->scheduleWork([](Runtime &) {});
[self drainJSQueue];
XCTAssertEqual(delegate.dispatchedCommandCount, 0u);
}

@end
Loading