mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Convert iOS native module event arguments to JS without UTF-8
## Summary:
Native modules send events to JS with `RCTEventEmitter sendEventWithName:body:`, which ends in `RCTInstance -callFunctionOnJSModule:method:args:`. Core modules use it too: for example, `RCTNetworking` sends the whole text of an XHR response in `didReceiveNetworkData`, and `RCTWebSocketModule` sends each message.
**Current behavior.** The arguments go through `folly::dynamic`. On the sending thread, `convertIdToFollyDynamic` encodes every string as UTF-8. On the JS thread, `jsi::valueFromDynamic` decodes it again into a JS string. Text that isn't ASCII is the expensive case: a 1 MB response with accented text costs about 3.9 ms on the JS thread and 3.2 ms on the sending thread.
**With this change.**
- On the sending thread, `RCTInstance` reads the arguments into a small tree with the structure that `convertIdToFollyDynamic` creates. Strings keep their own ASCII or UTF-16 characters instead of being encoded as UTF-8. When CoreFoundation exposes the characters, the tree points at them in an immutable copy of the string; otherwise it copies them.
- On the JS thread, the JS values are created from the tree, without Objective-C calls, the same way `valueFromDynamic` does.
- `ReactInstance` gets a `callFunctionOnModule` overload that takes an `ArgFactory`, which creates the arguments on the JS thread. It has the same shape as `TurboModule::ArgFactory`, which `emitDeviceEvent` uses. Both overloads share the module lookup, so Android and other callers of the `folly::dynamic` overload run the same code as before.
JS receives the same values as before:
- Numbers use the same rules as `convertIdToFollyDynamic`.
- Number keys become strings, and other non-string keys are skipped.
- Values of unsupported types become `null`.
- Strings with a lone surrogate, which UTF-8 can't encode, keep the UTF-8 path, so they still arrive as `""`.
The order of properties in event objects now follows the `NSDictionary`. Before, it followed the `folly::dynamic` hash map, so it was arbitrary in both cases. On JSC, a string with both a NUL and non-ASCII characters is no longer cut off at the NUL, as `JSStringCreateWithUTF8CString` did. Hermes output is the same.
## Changelog:
[IOS] [CHANGED] - Events sent by native modules are converted to JS values without a UTF-8 round trip
## Test Plan:
- `clang-format --dry-run --Werror` on the changed files passes.
- RNTester built with `xcodebuild` in Release and run on a physical iPhone 15 Pro (iOS 26.6.1).
- Added `ReactInstanceTest.testCallFunctionOnModule_withArgFactory` and `testCallFunctionOnModule_withEmptyArgFactory` for the new overload. I couldn't run the C++ tests locally. I updated the C++ API snapshots by hand, because I couldn't run Doxygen here.
- **Same output.**
- A test payload was sent through the old and the new conversion in the same app run, and JS compared the results deeply. They were identical. The payload had:
- empty, NUL, BOM, emoji, accented, CJK and lone-surrogate strings, and a mutable string changed after sending;
- `BOOL`, `char`, `unsigned char`, `short`, `int`, negative, `unsigned long long`, 2^60, `float`, `double`, NaN and `NSDecimalNumber` numbers;
- `NSNull`, `NSDate` and `NSURL` values;
- nested arrays and dictionaries;
- number, bool and `NSNull` keys.
- Every XHR response text in the measurement below matched the original string.
- **Measurement.** RNTester Playground, XHR `GET` of `data:` URLs with ASCII or accented text: 1000 requests at 1 KB, 30 at 100 KB and 10 at 1 MB. Also 1000 small events sent from a background queue: a keyboard-like payload, and one with short keys and values created at run time.
- Timed on the JS thread: creating the JS arguments, `valueFromDynamic` before and the tree conversion after.
- Timed on the sending thread: `convertIdToFollyDynamic` before and building the tree after.
- The two arms are the same binary with the conversion switched by a launch argument, in the order before, after, after, before, 4 launches per arm. The presses were driven by [Argent](https://github.com/software-mansion/argent) on the physical iPhone.
- iPhone 15 Pro, Release, medians per event. The ranges of the two arms are separate in every row.
| Event | JS thread before | after | change | Sending thread before | after | change |
|---|--:|--:|--:|--:|--:|--:|
| `didReceiveNetworkData`, accented, 1 KB | 4.82 µs | 0.36 µs | −92% | 4.11 µs | 0.38 µs | −91% |
| `didReceiveNetworkData`, accented, 100 KB | 382 µs | 8.6 µs | −98% | 311 µs | 3.1 µs | −99% |
| `didReceiveNetworkData`, accented, 1 MB | 3.87 ms | 0.09 ms | −98% | 3.18 ms | 0.03 ms | −99% |
| `didReceiveNetworkData`, ASCII, 1 KB | 0.65 µs | 0.34 µs | −47% | 0.97 µs | 0.38 µs | −61% |
| `didReceiveNetworkData`, ASCII, 100 KB | 12.1 µs | 7.8 µs | −36% | 5.8 µs | 0.35 µs | −94% |
| `didReceiveNetworkData`, ASCII, 1 MB | 97.6 µs | 71.8 µs | −26% | 49.3 µs | 0.33 µs | −99% |
| `didReceiveNetworkResponse` (headers) | 1.08 µs | 0.74 µs | −31% | 2.45 µs | 0.78 µs | −68% |
| keyboard-like event | 1.79 µs | 1.17 µs | −35% | 5.83 µs | 2.28 µs | −61% |
| short strings created at run time | 1.04 µs | 0.61 µs | −41% | 2.58 µs | 0.79 µs | −70% |
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Differential Revision: D127583929
Pull Request resolved: https://github.com/react/react-native/pull/59449
This commit is contained in:
1 parent
16424c2ce0
commit
9b0200e703
8 files changed
+216
-48
No files matched your search
+10
-1
@@ -120,9 +120,18 @@ static jsi::Object convertNSDictionaryToJSIObject(jsi::Runtime &runtime, __unsaf
|
||||
});
|
||||
jsi::Object result = jsi::Object(runtime);
|
||||
for (NSUInteger i = 0; i < count; i++) {
|
||||
// Number keys become strings, and other keys that aren't strings are skipped, as
|
||||
// convertIdToFollyDynamic does.
|
||||
id key = keysAndObjects[i];
|
||||
if (![key isKindOfClass:[NSString class]]) {
|
||||
if (![key isKindOfClass:[NSNumber class]] || [key isKindOfClass:[@YES class]]) {
|
||||
continue;
|
||||
}
|
||||
key = [key stringValue];
|
||||
}
|
||||
result.setProperty(
|
||||
runtime,
|
||||
convertNSStringToJSI<jsi::PropNameID>(runtime, keysAndObjects[i]),
|
||||
convertNSStringToJSI<jsi::PropNameID>(runtime, key),
|
||||
convertUnretainedObjCObjectToJSIValue(runtime, keysAndObjects[count + i]));
|
||||
}
|
||||
return result;
|
||||
|
||||
@@ -309,6 +309,60 @@ void ReactInstance::loadScript(
|
||||
});
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/*
|
||||
* Calls a method on a JS module that has been registered with
|
||||
* `registerCallableModule`, with the arguments that `addArgs` adds.
|
||||
*/
|
||||
template <typename AddArgs>
|
||||
void callCallableModuleMethod(
|
||||
jsi::Runtime& runtime,
|
||||
std::unordered_map<std::string, std::variant<jsi::Function, jsi::Object>>&
|
||||
callableModules,
|
||||
const std::string& moduleName,
|
||||
const std::string& methodName,
|
||||
const AddArgs& addArgs) {
|
||||
TraceSection s(
|
||||
"ReactInstance::callFunctionOnModule",
|
||||
"moduleName",
|
||||
moduleName,
|
||||
"methodName",
|
||||
methodName);
|
||||
auto it = callableModules.find(moduleName);
|
||||
if (it == callableModules.end()) {
|
||||
std::ostringstream knownModules;
|
||||
int i = 0;
|
||||
for (it = callableModules.begin(); it != callableModules.end(); it++, i++) {
|
||||
const char* space = (i > 0 ? ", " : " ");
|
||||
knownModules << space << it->first;
|
||||
}
|
||||
throw jsi::JSError(
|
||||
runtime,
|
||||
"Failed to call into JavaScript module method " + moduleName + "." +
|
||||
methodName +
|
||||
"(). Module has not been registered as callable. Registered callable JavaScript modules (n = " +
|
||||
std::to_string(callableModules.size()) + "):" + knownModules.str() +
|
||||
". Did you forget to call `registerCallableModule`?");
|
||||
}
|
||||
|
||||
if (std::holds_alternative<jsi::Function>(it->second)) {
|
||||
auto module =
|
||||
std::get<jsi::Function>(it->second).call(runtime).asObject(runtime);
|
||||
it->second = std::move(module);
|
||||
}
|
||||
|
||||
auto& module = std::get<jsi::Object>(it->second);
|
||||
auto method = module.getPropertyAsFunction(runtime, methodName.c_str());
|
||||
|
||||
std::vector<jsi::Value> jsArgs;
|
||||
addArgs(jsArgs);
|
||||
method.callWithThis(
|
||||
runtime, module, (const jsi::Value*)jsArgs.data(), jsArgs.size());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/*
|
||||
* Calls a method on a JS module that has been registered with
|
||||
* `registerCallableModule`. Used to invoke a JS function from platform code.
|
||||
@@ -317,52 +371,51 @@ void ReactInstance::callFunctionOnModule(
|
||||
const std::string& moduleName,
|
||||
const std::string& methodName,
|
||||
folly::dynamic&& args) {
|
||||
bufferedRuntimeExecutor_->execute([this,
|
||||
moduleName = moduleName,
|
||||
methodName = methodName,
|
||||
args = std::move(args)](
|
||||
jsi::Runtime& runtime) {
|
||||
TraceSection s(
|
||||
"ReactInstance::callFunctionOnModule",
|
||||
"moduleName",
|
||||
moduleName,
|
||||
"methodName",
|
||||
methodName);
|
||||
auto it = callableModules_.find(moduleName);
|
||||
if (it == callableModules_.end()) {
|
||||
std::ostringstream knownModules;
|
||||
int i = 0;
|
||||
for (it = callableModules_.begin(); it != callableModules_.end();
|
||||
it++, i++) {
|
||||
const char* space = (i > 0 ? ", " : " ");
|
||||
knownModules << space << it->first;
|
||||
}
|
||||
throw jsi::JSError(
|
||||
runtime,
|
||||
"Failed to call into JavaScript module method " + moduleName + "." +
|
||||
methodName +
|
||||
"(). Module has not been registered as callable. Registered callable JavaScript modules (n = " +
|
||||
std::to_string(callableModules_.size()) +
|
||||
"):" + knownModules.str() +
|
||||
". Did you forget to call `registerCallableModule`?");
|
||||
}
|
||||
if (moduleName.empty() || methodName.empty()) {
|
||||
return;
|
||||
}
|
||||
bufferedRuntimeExecutor_->execute(
|
||||
[this,
|
||||
moduleName = moduleName,
|
||||
methodName = methodName,
|
||||
args = std::move(args)](jsi::Runtime& runtime) {
|
||||
callCallableModuleMethod(
|
||||
runtime,
|
||||
callableModules_,
|
||||
moduleName,
|
||||
methodName,
|
||||
[&](std::vector<jsi::Value>& jsArgs) {
|
||||
jsArgs.reserve(args.size());
|
||||
for (auto& arg : args) {
|
||||
jsArgs.push_back(jsi::valueFromDynamic(runtime, arg));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (std::holds_alternative<jsi::Function>(it->second)) {
|
||||
auto module =
|
||||
std::get<jsi::Function>(it->second).call(runtime).asObject(runtime);
|
||||
it->second = std::move(module);
|
||||
}
|
||||
|
||||
auto& module = std::get<jsi::Object>(it->second);
|
||||
auto method = module.getPropertyAsFunction(runtime, methodName.c_str());
|
||||
|
||||
std::vector<jsi::Value> jsArgs;
|
||||
for (auto& arg : args) {
|
||||
jsArgs.push_back(jsi::valueFromDynamic(runtime, arg));
|
||||
}
|
||||
method.callWithThis(
|
||||
runtime, module, (const jsi::Value*)jsArgs.data(), jsArgs.size());
|
||||
});
|
||||
void ReactInstance::callFunctionOnModule(
|
||||
const std::string& moduleName,
|
||||
const std::string& methodName,
|
||||
ArgFactory&& argFactory) {
|
||||
if (moduleName.empty() || methodName.empty()) {
|
||||
return;
|
||||
}
|
||||
bufferedRuntimeExecutor_->execute(
|
||||
[this,
|
||||
moduleName = moduleName,
|
||||
methodName = methodName,
|
||||
argFactory = std::move(argFactory)](jsi::Runtime& runtime) {
|
||||
callCallableModuleMethod(
|
||||
runtime,
|
||||
callableModules_,
|
||||
moduleName,
|
||||
methodName,
|
||||
[&](std::vector<jsi::Value>& jsArgs) {
|
||||
if (argFactory) {
|
||||
argFactory(runtime, jsArgs);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
void ReactInstance::registerSegment(
|
||||
|
||||
@@ -27,6 +27,7 @@ namespace facebook::react {
|
||||
class ReactInstance final : private jsinspector_modern::InstanceTargetDelegate {
|
||||
public:
|
||||
using BindingsInstallFunc = std::function<void(jsi::Runtime &runtime)>;
|
||||
using ArgFactory = std::function<void(jsi::Runtime &runtime, std::vector<jsi::Value> &args)>;
|
||||
|
||||
ReactInstance(
|
||||
std::unique_ptr<JSRuntime> runtime,
|
||||
@@ -71,6 +72,12 @@ class ReactInstance final : private jsinspector_modern::InstanceTargetDelegate {
|
||||
|
||||
void callFunctionOnModule(const std::string &moduleName, const std::string &methodName, folly::dynamic &&args);
|
||||
|
||||
/**
|
||||
* Like the overload above, but `argFactory` adds the arguments on the JS thread, so platform
|
||||
* values can be converted to JS values directly.
|
||||
*/
|
||||
void callFunctionOnModule(const std::string &moduleName, const std::string &methodName, ArgFactory &&argFactory);
|
||||
|
||||
void handleMemoryPressureJs(int pressureLevel);
|
||||
|
||||
/**
|
||||
|
||||
+13
-2
@@ -42,7 +42,6 @@
|
||||
#import <react/renderer/core/EventEmitterListener.h>
|
||||
#import <react/runtime/ReactInstance.h>
|
||||
#import <react/utils/ContextContainer.h>
|
||||
#import <react/utils/FollyConvert.h>
|
||||
#import <react/utils/ManagedObjectWrapper.h>
|
||||
|
||||
#import "ObjCTimerRegistry.h"
|
||||
@@ -174,6 +173,13 @@ using namespace facebook::react;
|
||||
|
||||
- (void)callFunctionOnJSModule:(NSString *)moduleName method:(NSString *)method args:(NSArray *)args
|
||||
{
|
||||
const char *moduleNameStr = [moduleName UTF8String];
|
||||
const char *methodNameStr = [method UTF8String];
|
||||
if (moduleNameStr == nullptr || methodNameStr == nullptr) {
|
||||
return;
|
||||
}
|
||||
// The arguments are converted on the JS thread, like the values of codegen's AsyncEventEmitter.
|
||||
NSArray *callArgs = [args copy];
|
||||
// This is called from arbitrary threads, while -invalidate destroys _reactInstance on
|
||||
// the JS thread, so checking _valid and dereferencing have to happen as one step.
|
||||
std::lock_guard<std::mutex> lock(_invalidationMutex);
|
||||
@@ -181,7 +187,12 @@ using namespace facebook::react;
|
||||
return;
|
||||
}
|
||||
_reactInstance->callFunctionOnModule(
|
||||
[moduleName UTF8String] ?: "", [method UTF8String] ?: "", convertIdToFollyDynamic(args ? args : @[]));
|
||||
moduleNameStr, methodNameStr, [callArgs](jsi::Runtime &runtime, std::vector<jsi::Value> &jsArgs) {
|
||||
jsArgs.reserve(callArgs.count);
|
||||
for (id arg in callArgs) {
|
||||
jsArgs.push_back(TurboModuleConvertUtils::convertObjCObjectToJSIValue(runtime, arg));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)invalidate
|
||||
|
||||
@@ -821,4 +821,86 @@ function getResult() {
|
||||
EXPECT_EQ(result.getNumber(), 1);
|
||||
}
|
||||
|
||||
TEST_F(ReactInstanceTest, testCallFunctionOnModule_withArgFactory) {
|
||||
initializeRuntimeWithScript(R"xyz123(
|
||||
let result;
|
||||
const module = {
|
||||
bar: (a, b) => {
|
||||
result = a + ':' + b;
|
||||
},
|
||||
};
|
||||
RN$registerCallableModule('foo', () => module);
|
||||
function getResult() {
|
||||
return result;
|
||||
}
|
||||
)xyz123");
|
||||
|
||||
instance_->callFunctionOnModule(
|
||||
"foo", "bar", [](jsi::Runtime& runtime, std::vector<jsi::Value>& args) {
|
||||
args.emplace_back(jsi::String::createFromAscii(runtime, "baz"));
|
||||
args.emplace_back(2);
|
||||
});
|
||||
step();
|
||||
|
||||
auto result = runtime_->global()
|
||||
.getPropertyAsFunction(*runtime_, "getResult")
|
||||
.call(*runtime_);
|
||||
EXPECT_EQ(result.getString(*runtime_).utf8(*runtime_), "baz:2");
|
||||
}
|
||||
|
||||
TEST_F(ReactInstanceTest, testCallFunctionOnModule_withEmptyArgFactory) {
|
||||
initializeRuntimeWithScript(R"xyz123(
|
||||
let result;
|
||||
const module = {
|
||||
bar: (...args) => {
|
||||
result = args.length;
|
||||
},
|
||||
};
|
||||
RN$registerCallableModule('foo', () => module);
|
||||
function getResult() {
|
||||
return result;
|
||||
}
|
||||
)xyz123");
|
||||
|
||||
instance_->callFunctionOnModule("foo", "bar", ReactInstance::ArgFactory{});
|
||||
step();
|
||||
|
||||
auto result = runtime_->global()
|
||||
.getPropertyAsFunction(*runtime_, "getResult")
|
||||
.call(*runtime_);
|
||||
EXPECT_EQ(result.getNumber(), 0);
|
||||
}
|
||||
|
||||
TEST_F(ReactInstanceTest, testCallFunctionOnModule_withEmptyNames) {
|
||||
initializeRuntimeWithScript(R"xyz123(
|
||||
let calls = 0;
|
||||
const module = {
|
||||
bar: () => {
|
||||
calls++;
|
||||
},
|
||||
};
|
||||
RN$registerCallableModule('foo', () => module);
|
||||
function getCalls() {
|
||||
return calls;
|
||||
}
|
||||
)xyz123");
|
||||
|
||||
bool argFactoryCalled = false;
|
||||
auto argFactory = [&](jsi::Runtime& /*runtime*/,
|
||||
std::vector<jsi::Value>& /*args*/) {
|
||||
argFactoryCalled = true;
|
||||
};
|
||||
instance_->callFunctionOnModule("", "bar", argFactory);
|
||||
instance_->callFunctionOnModule("foo", "", argFactory);
|
||||
instance_->callFunctionOnModule("", "bar", folly::dynamic::array());
|
||||
instance_->callFunctionOnModule("foo", "", folly::dynamic::array());
|
||||
step();
|
||||
|
||||
EXPECT_FALSE(argFactoryCalled);
|
||||
auto calls = runtime_->global()
|
||||
.getPropertyAsFunction(*runtime_, "getCalls")
|
||||
.call(*runtime_);
|
||||
EXPECT_EQ(calls.getNumber(), 0);
|
||||
}
|
||||
|
||||
} // namespace facebook::react
|
||||
@@ -3350,7 +3350,9 @@ class facebook::react::ReactInstance {
|
||||
public facebook::react::RuntimeExecutor getUnbufferedRuntimeExecutor() noexcept;
|
||||
public std::shared_ptr<facebook::react::CallInvoker> createJSCallInvoker() noexcept;
|
||||
public std::shared_ptr<facebook::react::RuntimeScheduler> getRuntimeScheduler() noexcept;
|
||||
public using ArgFactory = std::function<void(facebook::jsi::Runtime& runtime, std::vector<facebook::jsi::Value>& args)>;
|
||||
public using BindingsInstallFunc = std::function<void(facebook::jsi::Runtime& runtime)>;
|
||||
public void callFunctionOnModule(const std::string& moduleName, const std::string& methodName, facebook::react::ReactInstance::ArgFactory&& argFactory);
|
||||
public void callFunctionOnModule(const std::string& moduleName, const std::string& methodName, folly::dynamic&& args);
|
||||
public void handleMemoryPressureJs(int pressureLevel);
|
||||
public void initializeRuntime(facebook::react::ReactInstance::JSRuntimeFlags options, facebook::react::ReactInstance::BindingsInstallFunc bindingsInstallFunc) noexcept;
|
||||
|
||||
@@ -5537,7 +5537,9 @@ class facebook::react::ReactInstance {
|
||||
public facebook::react::RuntimeExecutor getUnbufferedRuntimeExecutor() noexcept;
|
||||
public std::shared_ptr<facebook::react::CallInvoker> createJSCallInvoker() noexcept;
|
||||
public std::shared_ptr<facebook::react::RuntimeScheduler> getRuntimeScheduler() noexcept;
|
||||
public using ArgFactory = std::function<void(facebook::jsi::Runtime& runtime, std::vector<facebook::jsi::Value>& args)>;
|
||||
public using BindingsInstallFunc = std::function<void(facebook::jsi::Runtime& runtime)>;
|
||||
public void callFunctionOnModule(const std::string& moduleName, const std::string& methodName, facebook::react::ReactInstance::ArgFactory&& argFactory);
|
||||
public void callFunctionOnModule(const std::string& moduleName, const std::string& methodName, folly::dynamic&& args);
|
||||
public void handleMemoryPressureJs(int pressureLevel);
|
||||
public void initializeRuntime(facebook::react::ReactInstance::JSRuntimeFlags options, facebook::react::ReactInstance::BindingsInstallFunc bindingsInstallFunc) noexcept;
|
||||
|
||||
@@ -1966,7 +1966,9 @@ class facebook::react::ReactInstance {
|
||||
public facebook::react::RuntimeExecutor getUnbufferedRuntimeExecutor() noexcept;
|
||||
public std::shared_ptr<facebook::react::CallInvoker> createJSCallInvoker() noexcept;
|
||||
public std::shared_ptr<facebook::react::RuntimeScheduler> getRuntimeScheduler() noexcept;
|
||||
public using ArgFactory = std::function<void(facebook::jsi::Runtime& runtime, std::vector<facebook::jsi::Value>& args)>;
|
||||
public using BindingsInstallFunc = std::function<void(facebook::jsi::Runtime& runtime)>;
|
||||
public void callFunctionOnModule(const std::string& moduleName, const std::string& methodName, facebook::react::ReactInstance::ArgFactory&& argFactory);
|
||||
public void callFunctionOnModule(const std::string& moduleName, const std::string& methodName, folly::dynamic&& args);
|
||||
public void handleMemoryPressureJs(int pressureLevel);
|
||||
public void initializeRuntime(facebook::react::ReactInstance::JSRuntimeFlags options, facebook::react::ReactInstance::BindingsInstallFunc bindingsInstallFunc) noexcept;
|
||||
|
||||
Reference in new issue
Block a user