Skip to content

Commit 505443d

Browse files
RobertHerholdfacebook-github-bot
authored andcommitted
Let development tooling observe each JavaScript buffer ReactInstance evaluates (#60561)
Summary: Development tooling sometimes needs to know exactly which JavaScript a process ran, for example to tie a recording to the source it came from. `ReactInstance` evaluates JavaScript in four places: the main bundle (`loadScript`), segments registered from files (`registerSegment`), source evaluated through `globalEvalWithSourceUrl` (lazy segments fetched from a dev server and Fast Refresh updates), and Static Hermes units compiled into the binary. This adds `setJSEvaluationObserver`, a process-wide hook in `react/runtime/JSEvaluationObserver.h`. `ReactInstance` calls the installed observer on the JS thread immediately before each evaluation, with the exact bytes it is about to evaluate, the source URL and the kind of evaluation. With no observer installed, each path only counts the evaluation; `setJSEvaluationObserver` returns that count, so an observer installed late can tell that it missed some. The header is in the for-frameworks tier, like `ReactMarker`. Changelog: [General][Added] - Add `setJSEvaluationObserver` to observe the JavaScript `ReactInstance` evaluates Differential Revision: D136024543 Signed-off-by: Rob Herhold <rherhold@meta.com>
1 parent a174e2c commit 505443d

7 files changed

Lines changed: 322 additions & 68 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
#include "JSEvaluationObserver.h"
9+
10+
#include <atomic>
11+
12+
namespace facebook::react {
13+
14+
namespace {
15+
16+
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
17+
std::atomic<JSEvaluationObserver> observer{nullptr};
18+
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
19+
std::atomic<uint64_t> unobservedEvaluations{0};
20+
21+
} // namespace
22+
23+
uint64_t setJSEvaluationObserver(JSEvaluationObserver newObserver) {
24+
observer.store(newObserver);
25+
return unobservedEvaluations.load();
26+
}
27+
28+
void notifyJSEvaluation(
29+
JSEvaluationKind kind,
30+
const uint8_t* data,
31+
size_t size,
32+
const std::string& sourceURL) {
33+
if (auto current = observer.load()) {
34+
current(kind, data, size, sourceURL);
35+
} else {
36+
unobservedEvaluations.fetch_add(1);
37+
}
38+
}
39+
40+
} // namespace facebook::react
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
#pragma once
9+
10+
#include <react/cxxstableapi/FrameworksGuard.h>
11+
12+
#include <cstddef>
13+
#include <cstdint>
14+
#include <string>
15+
16+
#ifndef RN_EXPORT
17+
#define RN_EXPORT __attribute__((visibility("default")))
18+
#endif
19+
20+
namespace facebook::react {
21+
22+
/// How React Native came to evaluate a piece of JavaScript.
23+
enum class JSEvaluationKind {
24+
/// The main bundle a host loads.
25+
Bundle,
26+
/// A segment registered from a file.
27+
Segment,
28+
/// Source evaluated through `globalEvalWithSourceUrl`: lazy segments
29+
/// fetched from a dev server, and Fast Refresh updates.
30+
DevServerEval,
31+
/// A Static Hermes unit compiled into the app binary. It has no source
32+
/// buffer.
33+
SHUnit,
34+
};
35+
36+
/// Called on the JS thread immediately before React Native evaluates a piece
37+
/// of JavaScript, with the exact bytes it is about to evaluate (`data` is null
38+
/// and `size` is 0 for `SHUnit`) and where they came from: the URL a host
39+
/// loaded, a segment's file path, or the URL passed to
40+
/// `globalEvalWithSourceUrl`. Development tooling uses it to tell which
41+
/// JavaScript a process ran. It must not call into the runtime.
42+
using JSEvaluationObserver =
43+
void (*)(JSEvaluationKind kind, const uint8_t *data, size_t size, const std::string &sourceURL);
44+
45+
/// Installs the process-wide observer, replacing any earlier one; nullptr
46+
/// removes it. Returns how many evaluations happened while no observer was
47+
/// installed, so an observer installed late can tell that it missed some.
48+
RN_EXPORT uint64_t setJSEvaluationObserver(JSEvaluationObserver observer);
49+
50+
/// Reports an evaluation to the installed observer. Called by React Native's
51+
/// script loading paths.
52+
RN_EXPORT void
53+
notifyJSEvaluation(JSEvaluationKind kind, const uint8_t *data, size_t size, const std::string &sourceURL);
54+
55+
} // namespace facebook::react

‎packages/react-native/ReactCommon/react/runtime/ReactInstance.cpp‎

Lines changed: 80 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#include <react/featureflags/ReactNativeFeatureFlags.h>
2121
#include <react/performance/timeline/PerformanceEntryReporter.h>
2222
#include <react/renderer/runtimescheduler/RuntimeSchedulerBinding.h>
23+
#include <react/runtime/JSEvaluationObserver.h>
2324
#include <react/runtime/JSRuntimeBindings.h>
2425
#include <react/timing/primitives.h>
2526
#include <react/utils/jsi-utils.h>
@@ -250,63 +251,65 @@ void ReactInstance::loadScript(
250251
std::shared_ptr<const jsi::Buffer> buffer(std::move(script));
251252
std::string scriptName = simpleBasename(sourceURL);
252253

253-
runtimeScheduler_->scheduleWork(
254-
[jsErrorHandler = jsErrorHandler_,
255-
scriptName,
256-
sourceURL = sourceURL,
257-
buffer = std::move(buffer),
258-
weakBufferedRuntimeExecuter =
259-
std::weak_ptr<BufferedRuntimeExecutor>(bufferedRuntimeExecutor_),
260-
beforeLoad,
261-
afterLoad](jsi::Runtime& runtime) mutable {
262-
if (beforeLoad) {
263-
beforeLoad(runtime);
264-
}
265-
TraceSection s("ReactInstance::loadScript");
266-
bool hasLogger(ReactMarker::logTaggedMarkerImpl);
267-
if (hasLogger) {
268-
ReactMarker::logTaggedMarker(
269-
ReactMarker::RUN_JS_BUNDLE_START, scriptName.c_str());
270-
ReactMarker::logMarker(ReactMarker::INIT_REACT_RUNTIME_START);
271-
ReactMarker::logMarker(ReactMarker::APP_STARTUP_START);
272-
}
254+
runtimeScheduler_->scheduleWork([jsErrorHandler = jsErrorHandler_,
255+
scriptName,
256+
sourceURL = sourceURL,
257+
buffer = std::move(buffer),
258+
weakBufferedRuntimeExecuter =
259+
std::weak_ptr<BufferedRuntimeExecutor>(
260+
bufferedRuntimeExecutor_),
261+
beforeLoad,
262+
afterLoad](jsi::Runtime& runtime) mutable {
263+
if (beforeLoad) {
264+
beforeLoad(runtime);
265+
}
266+
TraceSection s("ReactInstance::loadScript");
267+
bool hasLogger(ReactMarker::logTaggedMarkerImpl);
268+
if (hasLogger) {
269+
ReactMarker::logTaggedMarker(
270+
ReactMarker::RUN_JS_BUNDLE_START, scriptName.c_str());
271+
ReactMarker::logMarker(ReactMarker::INIT_REACT_RUNTIME_START);
272+
ReactMarker::logMarker(ReactMarker::APP_STARTUP_START);
273+
}
273274

274-
// Check if the shermes unit is avaliable.
275-
auto* shUnitAPI = jsi::castInterface<hermes::IHermesSHUnit>(&runtime);
276-
auto* shUnitCreator =
277-
shUnitAPI ? shUnitAPI->getSHUnitCreator() : nullptr;
278-
if (shUnitCreator) {
279-
LOG(WARNING) << "ReactInstance: evaluateSHUnit";
280-
auto* hermesAPI = jsi::castInterface<hermes::IHermes>(&runtime);
281-
hermesAPI->evaluateSHUnit(shUnitCreator);
282-
} else {
283-
LOG(WARNING) << "ReactInstance: evaluateJavaScript() with JS bundle";
284-
runtime.evaluateJavaScript(buffer, sourceURL);
285-
}
275+
// Check if the shermes unit is avaliable.
276+
auto* shUnitAPI = jsi::castInterface<hermes::IHermesSHUnit>(&runtime);
277+
auto* shUnitCreator = shUnitAPI ? shUnitAPI->getSHUnitCreator() : nullptr;
278+
if (shUnitCreator) {
279+
LOG(WARNING) << "ReactInstance: evaluateSHUnit";
280+
notifyJSEvaluation(JSEvaluationKind::SHUnit, nullptr, 0, sourceURL);
281+
auto* hermesAPI = jsi::castInterface<hermes::IHermes>(&runtime);
282+
hermesAPI->evaluateSHUnit(shUnitCreator);
283+
} else {
284+
LOG(WARNING) << "ReactInstance: evaluateJavaScript() with JS bundle";
285+
notifyJSEvaluation(
286+
JSEvaluationKind::Bundle, buffer->data(), buffer->size(), sourceURL);
287+
runtime.evaluateJavaScript(buffer, sourceURL);
288+
}
286289

287-
/**
288-
* TODO(T183610671): We need a safe/reliable way to enable the js
289-
* pipeline from javascript. Remove this after we figure that out, or
290-
* after we just remove the js pipeline.
291-
*/
292-
if (!jsErrorHandler->hasHandledFatalError()) {
293-
jsErrorHandler->setRuntimeReady();
294-
}
290+
/**
291+
* TODO(T183610671): We need a safe/reliable way to enable the js
292+
* pipeline from javascript. Remove this after we figure that out, or
293+
* after we just remove the js pipeline.
294+
*/
295+
if (!jsErrorHandler->hasHandledFatalError()) {
296+
jsErrorHandler->setRuntimeReady();
297+
}
295298

296-
if (hasLogger) {
297-
ReactMarker::logTaggedMarker(
298-
ReactMarker::RUN_JS_BUNDLE_STOP, scriptName.c_str());
299-
ReactMarker::logMarker(ReactMarker::INIT_REACT_RUNTIME_STOP);
300-
ReactMarker::logMarker(ReactMarker::APP_STARTUP_STOP);
301-
}
302-
if (auto strongBufferedRuntimeExecuter =
303-
weakBufferedRuntimeExecuter.lock()) {
304-
strongBufferedRuntimeExecuter->flush();
305-
}
306-
if (afterLoad) {
307-
afterLoad(runtime);
308-
}
309-
});
299+
if (hasLogger) {
300+
ReactMarker::logTaggedMarker(
301+
ReactMarker::RUN_JS_BUNDLE_STOP, scriptName.c_str());
302+
ReactMarker::logMarker(ReactMarker::INIT_REACT_RUNTIME_STOP);
303+
ReactMarker::logMarker(ReactMarker::APP_STARTUP_STOP);
304+
}
305+
if (auto strongBufferedRuntimeExecuter =
306+
weakBufferedRuntimeExecuter.lock()) {
307+
strongBufferedRuntimeExecuter->flush();
308+
}
309+
if (afterLoad) {
310+
afterLoad(runtime);
311+
}
312+
});
310313
}
311314

312315
namespace {
@@ -442,20 +445,23 @@ void ReactInstance::registerSegment(
442445
"Empty segment registered with ID " + std::to_string(segmentId) +
443446
" from " + segmentPath);
444447
}
445-
runtimeScheduler_->scheduleWork(
446-
[script = std::move(script), segmentId](jsi::Runtime& runtime) {
447-
TraceSection s("ReactInstance::registerSegment");
448-
auto tag = std::to_string(segmentId);
449-
ReactMarker::logTaggedMarker(
450-
ReactMarker::REGISTER_JS_SEGMENT_START, tag.c_str());
451-
LOG(WARNING) << "Starting to evaluate segment " << segmentId
452-
<< " in ReactInstance::registerSegment";
453-
runtime.evaluateJavaScript(script, getSyntheticBundlePath(segmentId));
454-
LOG(WARNING) << "Finished evaluating segment " << segmentId
455-
<< " in ReactInstance::registerSegment";
456-
ReactMarker::logTaggedMarker(
457-
ReactMarker::REGISTER_JS_SEGMENT_STOP, tag.c_str());
458-
});
448+
runtimeScheduler_->scheduleWork([script = std::move(script),
449+
segmentId,
450+
segmentPath](jsi::Runtime& runtime) {
451+
TraceSection s("ReactInstance::registerSegment");
452+
auto tag = std::to_string(segmentId);
453+
ReactMarker::logTaggedMarker(
454+
ReactMarker::REGISTER_JS_SEGMENT_START, tag.c_str());
455+
LOG(WARNING) << "Starting to evaluate segment " << segmentId
456+
<< " in ReactInstance::registerSegment";
457+
notifyJSEvaluation(
458+
JSEvaluationKind::Segment, script->data(), script->size(), segmentPath);
459+
runtime.evaluateJavaScript(script, getSyntheticBundlePath(segmentId));
460+
LOG(WARNING) << "Finished evaluating segment " << segmentId
461+
<< " in ReactInstance::registerSegment";
462+
ReactMarker::logTaggedMarker(
463+
ReactMarker::REGISTER_JS_SEGMENT_STOP, tag.c_str());
464+
});
459465
}
460466

461467
namespace {
@@ -531,6 +537,12 @@ void ReactInstance::initializeRuntime(
531537
}
532538
// NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic)
533539

540+
notifyJSEvaluation(
541+
JSEvaluationKind::DevServerEval,
542+
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
543+
reinterpret_cast<const uint8_t*>(code.data()),
544+
code.size(),
545+
url);
534546
return rt.evaluateJavaScript(
535547
std::make_unique<jsi::StringBuffer>(std::move(code)), url);
536548
}));

0 commit comments

Comments
 (0)