Skip to content

Commit 5d607ea

Browse files
javachefacebook-github-bot
authored andcommitted
Allow C++ NetworkingModule response handlers (#60023)
Summary: Add an optional `INetworkingResponseHandler` to the C++ `NetworkingModule`. Hosts can convert supported response types, such as blob responses, into their native JavaScript representation. The existing string/base64 response path remains unchanged when no handler is registered or the handler does not support the response type. Networking copies the complete `IOBuf` chain directly into an owned `std::vector<uint8_t>` and moves it to the response handler on the JavaScript thread. The interface carries undecoded bytes rather than a string, avoiding a string-to-vector conversion. Changelog: [Internal] Differential Revision: D132255841
1 parent c761862 commit 5d607ea

3 files changed

Lines changed: 176 additions & 3 deletions

File tree

‎packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.cpp‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,10 @@ bool Requests::isStopped() {
109109

110110
NetworkingModule::NetworkingModule(
111111
std::shared_ptr<CallInvoker> jsInvoker,
112-
const HttpClientFactory& httpClientFactory)
113-
: NativeNetworkingAndroidCxxSpec(jsInvoker) {
112+
const HttpClientFactory& httpClientFactory,
113+
std::shared_ptr<INetworkingResponseHandler> responseHandler)
114+
: NativeNetworkingAndroidCxxSpec(jsInvoker),
115+
responseHandler_(std::move(responseHandler)) {
114116
httpClient_ = httpClientFactory();
115117
}
116118

@@ -299,6 +301,23 @@ void NetworkingModule::didReceiveNetworkData(
299301
return;
300302
}
301303

304+
if (responseHandler_ != nullptr && responseHandler_->supports(responseType)) {
305+
emitDeviceEvent(
306+
"didReceiveNetworkData",
307+
[requestId,
308+
body = buf->to<std::vector<uint8_t>>(),
309+
responseHandler = responseHandler_](
310+
jsi::Runtime& rt, std::vector<jsi::Value>& args) mutable {
311+
args.emplace_back(
312+
rt,
313+
jsi::Array::createWithElements(
314+
rt,
315+
static_cast<double>(requestId),
316+
responseHandler->toResponseData(rt, std::move(body))));
317+
});
318+
return;
319+
}
320+
302321
auto responseData = encodeResponseBody(responseType, buf->toString());
303322
emitDeviceEvent(
304323
"didReceiveNetworkData",

‎packages/react-native/ReactCxxPlatform/react/io/NetworkingModule.h‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,11 @@
99

1010
#include <FBReactNativeSpec/FBReactNativeSpecJSI.h>
1111
#include <react/http/IHttpClient.h>
12+
#include <cstdint>
1213
#include <memory>
1314
#include <optional>
1415
#include <string>
16+
#include <vector>
1517

1618
namespace facebook::react {
1719

@@ -64,11 +66,27 @@ class Requests {
6466
std::atomic<bool> stopped_{false};
6567
};
6668

69+
// Converts a response body into the value delivered to JS for a responseType
70+
// that NetworkingModule does not encode itself, e.g. "blob". Mirrors
71+
// NetworkingModule.ResponseHandler on Android.
72+
class INetworkingResponseHandler {
73+
public:
74+
virtual ~INetworkingResponseHandler() = default;
75+
76+
virtual bool supports(const std::string &responseType) const = 0;
77+
78+
// Called on the JavaScript thread with owned, undecoded response bytes.
79+
virtual jsi::Value toResponseData(jsi::Runtime &rt, std::vector<uint8_t> body) = 0;
80+
};
81+
6782
// Implementation of "Networking" TurboModule
6883
class NetworkingModule : public NativeNetworkingAndroidCxxSpec<NetworkingModule>,
6984
public std::enable_shared_from_this<NetworkingModule> {
7085
public:
71-
NetworkingModule(std::shared_ptr<CallInvoker> jsInvoker, const HttpClientFactory &httpClientFactory);
86+
NetworkingModule(
87+
std::shared_ptr<CallInvoker> jsInvoker,
88+
const HttpClientFactory &httpClientFactory,
89+
std::shared_ptr<INetworkingResponseHandler> responseHandler = nullptr);
7290

7391
~NetworkingModule() override;
7492

@@ -114,6 +132,7 @@ class NetworkingModule : public NativeNetworkingAndroidCxxSpec<NetworkingModule>
114132
void didCompleteNetworkResponse(uint32_t requestId, const std::string &error, bool timeoutError);
115133

116134
std::unique_ptr<IHttpClient> httpClient_;
135+
std::shared_ptr<INetworkingResponseHandler> responseHandler_;
117136
Requests requests_;
118137
};
119138

‎packages/react-native/ReactCxxPlatform/react/io/tests/NetworkingModuleTests.cpp‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,67 @@
2121

2222
namespace facebook::react {
2323

24+
namespace {
25+
26+
class FakeHttpClient : public IHttpClient {
27+
public:
28+
explicit FakeHttpClient(std::string body = "body bytes")
29+
: body_(std::move(body)) {}
30+
31+
std::unique_ptr<http::IRequestToken> sendRequest(
32+
http::NetworkCallbacks&& callbacks,
33+
const std::string& /*method*/,
34+
const std::string& /*url*/,
35+
const http::Headers& /*headers*/,
36+
const http::Body& /*body*/,
37+
uint32_t /*timeout*/,
38+
std::optional<std::string> /*loggingId*/) override {
39+
auto body = folly::IOBuf::copyBuffer(body_.substr(0, body_.size() / 2));
40+
body->appendToChain(
41+
folly::IOBuf::copyBuffer(body_.substr(body_.size() / 2)));
42+
callbacks.onBody(std::move(body));
43+
callbacks.onResponseComplete("", false);
44+
return nullptr;
45+
}
46+
47+
private:
48+
std::string body_;
49+
};
50+
51+
class FakeResponseHandler : public INetworkingResponseHandler {
52+
public:
53+
bool supports(const std::string& responseType) const override {
54+
return responseType == "blob";
55+
}
56+
57+
jsi::Value toResponseData(jsi::Runtime& rt, std::vector<uint8_t> body)
58+
override {
59+
auto data = jsi::Object(rt);
60+
data.setProperty(
61+
rt,
62+
"handled",
63+
jsi::String::createFromUtf8(rt, std::string(body.begin(), body.end())));
64+
return data;
65+
}
66+
};
67+
68+
class RecordingResponseHandler : public INetworkingResponseHandler {
69+
public:
70+
bool supports(const std::string& responseType) const override {
71+
return responseType == "blob";
72+
}
73+
74+
jsi::Value toResponseData(jsi::Runtime& /*rt*/, std::vector<uint8_t> body)
75+
override {
76+
bytes = std::move(body);
77+
return static_cast<double>(bytes.size());
78+
}
79+
80+
std::vector<uint8_t> bytes;
81+
};
82+
83+
} // namespace
84+
2485
class NetworkingModuleTests : public testing::Test {
2586
protected:
2687
void SetUp() override {
@@ -90,6 +151,80 @@ TEST_F(NetworkingModuleTests, formDataTest) {
90151
"form-data; name=\"header2\""});
91152
}
92153

154+
// A response handler replaces the body delivered for the response types it
155+
// supports and leaves every other response type alone.
156+
TEST_F(NetworkingModuleTests, responseHandlerTest) {
157+
auto module = std::make_shared<NetworkingModule>(
158+
jsInvoker_,
159+
[]() { return std::make_unique<FakeHttpClient>(); },
160+
std::make_shared<FakeResponseHandler>());
161+
rt_->evaluateJavaScript(
162+
std::make_shared<jsi::StringBuffer>(R"(
163+
var data = {};
164+
globalThis.__rctDeviceEventEmitter = {
165+
emit: function (name, payload) {
166+
if (name === 'didReceiveNetworkData') { data[payload[0]] = payload[1]; }
167+
},
168+
};
169+
)"),
170+
"responseHandlerTest.js");
171+
172+
module->sendRequest(
173+
*rt_, "GET", "https://example.com", 1, {}, {}, "blob", false, 0, false);
174+
module->sendRequest(
175+
*rt_, "GET", "https://example.com", 2, {}, {}, "text", false, 0, false);
176+
std::static_pointer_cast<TestCallInvoker>(jsInvoker_)->flushQueue();
177+
178+
auto data = rt_->global().getPropertyAsObject(*rt_, "data");
179+
auto blob = data.getProperty(*rt_, "1");
180+
ASSERT_TRUE(blob.isObject());
181+
EXPECT_EQ(
182+
blob.asObject(*rt_)
183+
.getProperty(*rt_, "handled")
184+
.asString(*rt_)
185+
.utf8(*rt_),
186+
"body bytes");
187+
auto text = data.getProperty(*rt_, "2");
188+
ASSERT_TRUE(text.isString());
189+
EXPECT_EQ(text.asString(*rt_).utf8(*rt_), "body bytes");
190+
}
191+
192+
TEST_F(NetworkingModuleTests, responseHandlerPreservesBinaryChainBytes) {
193+
auto handler = std::make_shared<RecordingResponseHandler>();
194+
auto module = std::make_shared<NetworkingModule>(
195+
jsInvoker_,
196+
[]() {
197+
return std::make_unique<FakeHttpClient>(std::string("\0\xFF\x80\0", 4));
198+
},
199+
handler);
200+
rt_->evaluateJavaScript(
201+
std::make_shared<jsi::StringBuffer>(R"(
202+
var received;
203+
globalThis.__rctDeviceEventEmitter = {
204+
emit: function (name, payload) {
205+
if (name === 'didReceiveNetworkData') { received = payload[1]; }
206+
},
207+
};
208+
)"),
209+
"binaryResponseHandlerTest.js");
210+
module->sendRequest(
211+
*rt_,
212+
"GET",
213+
"https://example.com/binary",
214+
1,
215+
{},
216+
{},
217+
"blob",
218+
false,
219+
0,
220+
false);
221+
std::static_pointer_cast<TestCallInvoker>(jsInvoker_)->flushQueue();
222+
const std::vector<uint8_t> expected{0, 255, 128, 0};
223+
EXPECT_EQ(handler->bytes, expected);
224+
EXPECT_EQ(
225+
rt_->global().getProperty(*rt_, "received").getNumber(), expected.size());
226+
}
227+
93228
// Test parsing a body with string data
94229
TEST_F(NetworkingModuleTests, stringDataTest) {
95230
auto dynamic = folly::parseJson(

0 commit comments

Comments
 (0)