Files
react-native/ReactCommon/react/renderer/mounting/MountingCoordinator.cpp
T
Joshua Gross 1e4d8d902d Core/Differ: detect and optimize reparenting
Summary:
# Summary

In previous diffs earlier in 2020, we made changes to detect and optimize reordering of views when the order of views changed underneath the same parent.

However, until now we have ignored reparenting and there's evidence of issues because of that. Because Fabric flattens views more aggressively, reparenting is also marginally more likely to happen.

This diff introduces a very general Reparenting detection. It will work with view flattening/unflattening, as well as tree grafting - subtrees moved to entirely different parts of the tree, not just a single
parent disappearing or reappearing because of flattening/unflattening.

There is also another consideration: previously, we were generating strictly too many Create+Delete operations that were redundant and could cause consistency issues, crashes, or bugs on platforms that do not handle that gracefully -
especially since the ordering of the Create+Delete is not guaranteed (a reparented view could be created "first" and then the differ could later issue a "delete" for the same view).

Intuition behind how it works: we know the cases where we can detect reparenting: it's when nodes are *not* matched up with another node from the other tree, and we're either trying to delete an entire subtree, or create an entire subtree. For perf reasons, we generate whatever set of operations comes first (say, we generate all the Delete and Remove instructions) and take note in the `ReparentingMetadata` data-structure that Delete and/or Remove have been performed for each tag (if ordering is different, we do the same for Create+Insert if those come first). Then if we later detect a corresponding subtree creation/deletion, we don't generate those mutations and we mark the previous mutations for deletion. This incurs some map lookup cost, but this is only wasteful for commits where a large tree is deleted and a large tree is created, without reparenting.

We may be able to improve perf further for certain edge-cases in the future.

# Why can't we solve this in JS?

Two things:

1. We certainly can avoid reparenting situations in JS, but it's trickier than before because of Fabric's view flattening logic - product engineers would have to think much harder about how to prevent reparenting in the general case.
2. In the case of specific views like BottomSheet that may crash if they're reparented, the solution is to make sure that the BottomSheet and the first child of the BottomSheet is never memoized, so that lifecycle functions and render are called more often; and that in every render, the BottomSheet manually clones its child, so that when the Views are recreated, the child of the BottomSheet has a tag and is an entirely different instance. This is certainly possible to do but feels like an onerous requirement for product teams, and it could be challenging to track down every specific BottomSheet that is memoized and/or hoist them higher in the view hierarchy so they're not reparented as often.

Reviewed By: shergin

Differential Revision: D23123575

fbshipit-source-id: 2fa7e1f026f87b6f0c60cad469a3ba85cdc234de
2020-08-15 19:20:33 -07:00

185 lines
5.4 KiB
C++

/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "MountingCoordinator.h"
#ifdef RN_SHADOW_TREE_INTROSPECTION
#include <glog/logging.h>
#include <sstream>
#endif
#include <condition_variable>
#include <react/renderer/mounting/ShadowViewMutation.h>
namespace facebook {
namespace react {
MountingCoordinator::MountingCoordinator(
ShadowTreeRevision baseRevision,
std::weak_ptr<MountingOverrideDelegate const> delegate,
bool enableReparentingDetection)
: surfaceId_(baseRevision.getRootShadowNode().getSurfaceId()),
baseRevision_(baseRevision),
mountingOverrideDelegate_(delegate),
telemetryController_(*this),
enableReparentingDetection_(enableReparentingDetection) {
#ifdef RN_SHADOW_TREE_INTROSPECTION
stubViewTree_ = stubViewTreeFromShadowNode(baseRevision_.getRootShadowNode());
#endif
}
SurfaceId MountingCoordinator::getSurfaceId() const {
return surfaceId_;
}
void MountingCoordinator::push(ShadowTreeRevision &&revision) const {
{
std::lock_guard<std::mutex> lock(mutex_);
assert(
!lastRevision_.has_value() ||
revision.getNumber() != lastRevision_->getNumber());
if (!lastRevision_.has_value() ||
lastRevision_->getNumber() < revision.getNumber()) {
lastRevision_ = std::move(revision);
}
}
signal_.notify_all();
}
void MountingCoordinator::revoke() const {
std::lock_guard<std::mutex> lock(mutex_);
// We have two goals here.
// 1. We need to stop retaining `ShadowNode`s to not prolong their lifetime
// to prevent them from overliving `ComponentDescriptor`s.
// 2. A possible call to `pullTransaction()` should return empty optional.
baseRevision_.rootShadowNode_.reset();
lastRevision_.reset();
}
bool MountingCoordinator::waitForTransaction(
std::chrono::duration<double> timeout) const {
std::unique_lock<std::mutex> lock(mutex_);
return signal_.wait_for(
lock, timeout, [this]() { return lastRevision_.has_value(); });
}
void MountingCoordinator::updateBaseRevision(
ShadowTreeRevision const &baseRevision) const {
baseRevision_ = std::move(baseRevision);
}
void MountingCoordinator::resetLatestRevision() const {
lastRevision_.reset();
}
#ifdef RN_SHADOW_TREE_INTROSPECTION
void MountingCoordinator::validateTransactionAgainstStubViewTree(
ShadowViewMutationList const &mutations,
bool assertEquality) const {
std::string line;
std::stringstream ssMutations(getDebugDescription(mutations, {}));
while (std::getline(ssMutations, line, '\n')) {
LOG(ERROR) << "Mutations:" << line;
}
stubViewTree_.mutate(mutations);
auto stubViewTree =
stubViewTreeFromShadowNode(lastRevision_->getRootShadowNode());
std::stringstream ssOldTree(
baseRevision_.getRootShadowNode().getDebugDescription());
while (std::getline(ssOldTree, line, '\n')) {
LOG(ERROR) << "Old tree:" << line;
}
std::stringstream ssNewTree(
lastRevision_->getRootShadowNode().getDebugDescription());
while (std::getline(ssNewTree, line, '\n')) {
LOG(ERROR) << "New tree:" << line;
}
if (assertEquality) {
assert(stubViewTree_ == stubViewTree);
}
}
#endif
better::optional<MountingTransaction> MountingCoordinator::pullTransaction()
const {
std::lock_guard<std::mutex> lock(mutex_);
auto mountingOverrideDelegate = mountingOverrideDelegate_.lock();
bool shouldOverridePullTransaction = mountingOverrideDelegate &&
mountingOverrideDelegate->shouldOverridePullTransaction();
if (!shouldOverridePullTransaction && !lastRevision_.has_value()) {
return {};
}
number_++;
ShadowViewMutation::List diffMutations{};
auto telemetry =
(lastRevision_.hasValue() ? lastRevision_->getTelemetry()
: MountingTelemetry{});
if (!lastRevision_.hasValue()) {
telemetry.willLayout();
telemetry.didLayout();
telemetry.willCommit();
telemetry.didCommit();
}
telemetry.willDiff();
if (lastRevision_.hasValue()) {
diffMutations = calculateShadowViewMutations(
baseRevision_.getRootShadowNode(),
lastRevision_->getRootShadowNode(),
enableReparentingDetection_);
}
telemetry.didDiff();
better::optional<MountingTransaction> transaction{};
// The override delegate can provide custom mounting instructions,
// even if there's no `lastRevision_`. Consider cases of animation frames
// in between React tree updates.
if (shouldOverridePullTransaction) {
transaction = mountingOverrideDelegate->pullTransaction(
surfaceId_, number_, telemetry, std::move(diffMutations));
} else if (lastRevision_.hasValue()) {
transaction = MountingTransaction{
surfaceId_, number_, std::move(diffMutations), telemetry};
}
if (lastRevision_.hasValue()) {
#ifdef RN_SHADOW_TREE_INTROSPECTION
// Only validate non-animated transactions - it's garbage to validate
// animated transactions, since the stub view tree likely won't match
// the committed tree during an animation.
this->validateTransactionAgainstStubViewTree(
transaction->getMutations(), !shouldOverridePullTransaction);
#endif
baseRevision_ = std::move(*lastRevision_);
lastRevision_.reset();
}
return transaction;
}
TelemetryController const &MountingCoordinator::getTelemetryController() const {
return telemetryController_;
}
} // namespace react
} // namespace facebook