Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,9 @@ void ResizeObserverManager::shadowTreeDidCommit(

#pragma mark - RuntimeSchedulerResizeObserverDelegate

void ResizeObserverManager::runResizeObservations(jsi::Runtime& runtime) {
void ResizeObserverManager::runResizeObservations(
jsi::Runtime& runtime,
const CallbackInvoker& invokeCallback) {
TraceSection s{"ResizeObserverManager::runResizeObservations"};

// The broadcast below runs JS, which may commit synchronously and re-enter
Expand Down Expand Up @@ -288,8 +290,8 @@ void ResizeObserverManager::runResizeObservations(jsi::Runtime& runtime) {
break;
}

auto shallowest =
broadcastActiveResizeObservations(runtime, gathered.activeObservations);
auto shallowest = broadcastActiveResizeObservations(
runtime, gathered.activeObservations, invokeCallback);
if (!shallowest.has_value()) {
break;
}
Expand All @@ -299,7 +301,7 @@ void ResizeObserverManager::runResizeObservations(jsi::Runtime& runtime) {

// https://w3c.github.io/csswg-drafts/resize-observer/#deliver-resize-loop-error
if (hasSkippedObservations) {
notifyResizeObservers(runtime, true);
invokeCallback([&]() { notifyResizeObservers(runtime, true); });
}
}

Expand Down Expand Up @@ -425,7 +427,8 @@ ResizeObserverManager::gatherActiveResizeObservations(size_t depth) {

std::optional<size_t> ResizeObserverManager::broadcastActiveResizeObservations(
jsi::Runtime& runtime,
std::vector<ActiveObservation>& active) {
std::vector<ActiveObservation>& active,
const CallbackInvoker& invokeCallback) {
TraceSection s{"ResizeObserverManager::broadcastActiveResizeObservations"};

if (active.empty() || notifyResizeObserversFunction_ == nullptr) {
Expand All @@ -445,41 +448,61 @@ std::optional<size_t> ResizeObserverManager::broadcastActiveResizeObservations(
});

std::optional<size_t> shallowestDepth;
{
std::unique_lock lock(pendingEntriesMutex_);
pendingEntries_.reserve(pendingEntries_.size() + active.size());
for (auto& observation : active) {
observation.observer->markAsReported(observation.result);
shallowestDepth = shallowestDepth.has_value()
? std::min(shallowestDepth.value(), observation.result.targetDepth)
: observation.result.targetDepth;
pendingEntries_.push_back(std::move(*observation.result.entry));
}
std::vector<ResizeObserverEntry> entries;
// Instance handles are weak; root their JS identities across checkpoints.
std::vector<jsi::Value> targetInstanceHandles;
entries.reserve(active.size());
targetInstanceHandles.reserve(active.size());
for (auto& observation : active) {
targetInstanceHandles.push_back(
observation.result.entry->shadowNodeFamily->getInstanceHandle(runtime));
observation.observer->markAsReported(observation.result);
shallowestDepth = shallowestDepth.has_value()
? std::min(shallowestDepth.value(), observation.result.targetDepth)
: observation.result.targetDepth;
entries.push_back(std::move(*observation.result.entry));
}

if (!notifyResizeObservers(runtime, false)) {
return std::nullopt;
// Snapshot every entry before invoking JS, which can remove any observer.
active.clear();
auto entry = entries.begin();
while (entry != entries.end() && notifyResizeObserversFunction_ != nullptr) {
const auto observerId = entry->resizeObserverId;
{
std::unique_lock lock(pendingEntriesMutex_);
do {
pendingEntries_.push_back(std::move(*entry));
++entry;
} while (entry != entries.end() && entry->resizeObserverId == observerId);
}

invokeCallback([&]() { notifyResizeObservers(runtime, false); });
}

return shallowestDepth;
}

bool ResizeObserverManager::notifyResizeObservers(
void ResizeObserverManager::notifyResizeObservers(
jsi::Runtime& runtime,
bool hasResizeLoopError) {
// Copy the callable: the notification runs JS, and a callback may
// `disconnect()` the last observer, which clears the member while we are
// still executing it.
auto notifyResizeObserversFunction = notifyResizeObserversFunction_;
if (notifyResizeObserversFunction == nullptr) {
return false;
return;
}

// No lock may be held here. JS pulls the entries with `takeRecords` and the
// callbacks it then invokes can re-enter `observe`/`unobserve`/`disconnect`,
// or commit synchronously (which re-enters the commit hook on this thread).
notifyResizeObserversFunction(runtime, hasResizeLoopError);
return true;
try {
notifyResizeObserversFunction(runtime, hasResizeLoopError);
} catch (...) {
std::unique_lock lock(pendingEntriesMutex_);
pendingEntries_.clear();
throw;
}
}

} // namespace facebook::react
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class ResizeObserverManager final : public UIManagerCommitHook, public RuntimeSc

#pragma mark - RuntimeSchedulerResizeObserverDelegate

void runResizeObservations(jsi::Runtime &runtime) override;
void runResizeObservations(jsi::Runtime &runtime, const CallbackInvoker &invokeCallback) override;

#pragma mark - UIManagerCommitHook

Expand Down Expand Up @@ -140,10 +140,11 @@ class ResizeObserverManager final : public UIManagerCommitHook, public RuntimeSc
// was delivered.
std::optional<size_t> broadcastActiveResizeObservations(
jsi::Runtime &runtime,
std::vector<ActiveObservation> &active);
std::vector<ActiveObservation> &active,
const CallbackInvoker &invokeCallback);

// Calls into JS. Returns false if there is nothing connected to notify.
bool notifyResizeObservers(jsi::Runtime &runtime, bool hasResizeLoopError);
// Calls into JS.
void notifyResizeObservers(jsi::Runtime &runtime, bool hasResizeLoopError);
};

} // namespace facebook::react
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,19 @@
#include <react/cxxstableapi/FrameworksGuard.h>

#include <jsi/jsi.h>
#include <functional>

namespace facebook::react {

class RuntimeSchedulerResizeObserverDelegate {
public:
using CallbackInvoker = std::function<void(const std::function<void()> &)>;

virtual ~RuntimeSchedulerResizeObserverDelegate() = default;

virtual void runResizeObservations(jsi::Runtime &runtime) = 0;
// Invocations are synchronous and include callback cleanup. Do not retain
// the invoker or use it before the previous author callback has returned.
virtual void runResizeObservations(jsi::Runtime &runtime, const CallbackInvoker &invokeCallback) = 0;
};

} // namespace facebook::react
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ int64_t durationToMilliseconds(HighResDuration duration) {
return duration.toNanoseconds() / static_cast<int64_t>(1e6);
}

[[noreturn]] void rethrowMicrotaskError(
jsi::Runtime& /*unused*/,
jsi::JSError& error) {
throw error;
}

} // namespace

#pragma mark - Public
Expand Down Expand Up @@ -334,7 +340,10 @@ void RuntimeScheduler_Modern::runEventLoopTick(
executeTask(runtime, task, didUserCallbackTimeout);

// "Perform a microtask checkpoint" step.
performMicrotaskCheckpoint(runtime);
performMicrotaskCheckpoint(
runtime, [this](jsi::Runtime& runtime, jsi::JSError& error) {
handleTaskError(runtime, error);
});

auto taskEndTime = now_();
markYieldingOpportunity(taskEndTime);
Expand Down Expand Up @@ -369,20 +378,22 @@ void RuntimeScheduler_Modern::updateRendering(
// The delegate runs the spec's depth-bounded gather/broadcast loop
// internally; this call site stays a single invocation per tick.
if (resizeObserverDelegate_ != nullptr) {
// This delivers the observations to JS synchronously, so it is outside the
// error boundary of `executeTask`. Report the error without going through
// `handleTaskError`: we are already inside the "update the rendering" step,
// so clearing the queues here would drop the pending rendering updates this
// step is about to drain, and a throwing observer callback would abort the
// remaining steps below.
// Uncaught errors must unwind the observer pass before fatal handling can
// tear down delegates referenced by pending rendering callbacks.
try {
resizeObserverDelegate_->runResizeObservations(runtime);
resizeObserverDelegate_->runResizeObservations(
runtime, [&](const std::function<void()>& callback) {
callback();
performMicrotaskCheckpoint(runtime, rethrowMicrotaskError);
});
} catch (jsi::JSError& error) {
onTaskError_(runtime, error);
handleTaskError(runtime, error);
return;
} catch (std::exception& ex) {
jsi::JSError error(
runtime, std::string("Non-JS exception: ") + ex.what());
onTaskError_(runtime, error);
handleTaskError(runtime, error);
return;
}
}

Expand Down Expand Up @@ -441,7 +452,8 @@ void RuntimeScheduler_Modern::executeTask(
* Iterates on \c drainMicrotasks until it completes or hits the retries bound.
*/
void RuntimeScheduler_Modern::performMicrotaskCheckpoint(
jsi::Runtime& runtime) {
jsi::Runtime& runtime,
const RuntimeSchedulerTaskErrorHandler& onMicrotaskError) {
if (performingMicrotaskCheckpoint_) {
return;
}
Expand All @@ -465,11 +477,11 @@ void RuntimeScheduler_Modern::performMicrotaskCheckpoint(
break;
}
} catch (jsi::JSError& error) {
handleTaskError(runtime, error);
onMicrotaskError(runtime, error);
} catch (std::exception& ex) {
jsi::JSError error(
runtime, std::string("Non-JS exception: ") + ex.what());
handleTaskError(runtime, error);
onMicrotaskError(runtime, error);
}
retries++;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ class RuntimeScheduler_Modern final : public RuntimeSchedulerBase {
void clearQueues();

bool performingMicrotaskCheckpoint_{false};
void performMicrotaskCheckpoint(jsi::Runtime &runtime);
void performMicrotaskCheckpoint(jsi::Runtime &runtime, const RuntimeSchedulerTaskErrorHandler &onMicrotaskError);

void reportLongTasks(const Task &task, HighResTimeStamp startTime, HighResTimeStamp endTime);

Expand Down
Loading
Loading