Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement NetworkRequestDelegate on iOS #44846

Closed
wants to merge 2 commits into from
Closed
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
11 changes: 10 additions & 1 deletion packages/react-native/React/Base/RCTBridge.mm
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#import "RCTConvert.h"
#if RCT_ENABLE_INSPECTOR
#import "RCTInspectorDevServerHelper.h"
#import "RCTInspectorNetworkHelper.h"
#endif
#import <jsinspector-modern/InspectorFlags.h>
#import <jsinspector-modern/InspectorInterfaces.h>
Expand Down Expand Up @@ -193,7 +194,9 @@ void RCTUIManagerSetDispatchAccessibilityManagerInitOntoMain(BOOL enabled)
class RCTBridgeHostTargetDelegate : public facebook::react::jsinspector_modern::HostTargetDelegate {
public:
RCTBridgeHostTargetDelegate(RCTBridge *bridge)
: bridge_(bridge), pauseOverlayController_([[RCTPausedInDebuggerOverlayController alloc] init])
: bridge_(bridge),
pauseOverlayController_([[RCTPausedInDebuggerOverlayController alloc] init]),
networkHelper_([[RCTInspectorNetworkHelper alloc] init])
{
}

Expand Down Expand Up @@ -226,9 +229,15 @@ void onSetPausedInDebuggerMessage(const OverlaySetPausedInDebuggerMessageRequest
}
}

void networkRequest(const std::string &url, RCTInspectorNetworkListener listener) override
{
[networkHelper_ networkRequestWithUrl:url listener:listener];
}

private:
__weak RCTBridge *bridge_;
RCTPausedInDebuggerOverlayController *pauseOverlayController_;
RCTInspectorNetworkHelper *networkHelper_;
};

@interface RCTBridge () <RCTReloadListener>
Expand Down
20 changes: 20 additions & 0 deletions packages/react-native/React/DevSupport/RCTInspectorNetworkHelper.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#import <jsinspector-modern/ReactCdp.h>

#import <Foundation/Foundation.h>

typedef std::shared_ptr<facebook::react::jsinspector_modern::NetworkRequestListener> RCTInspectorNetworkListener;

/**
* A helper class that wraps around NSURLSession to make network requests.
*/
@interface RCTInspectorNetworkHelper : NSObject
- (instancetype)init;
- (void)networkRequestWithUrl:(const std::string &)url listener:(RCTInspectorNetworkListener)listener;
@end
134 changes: 134 additions & 0 deletions packages/react-native/React/DevSupport/RCTInspectorNetworkHelper.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#import "RCTInspectorNetworkHelper.h"

// Wraps RCTInspectorNetworkListener (a C++ shared_ptr) in an NSObject,
// maintaining a ref while making it id-compatible for an NSDictionary.
@interface RCTInspectorNetworkListenerWrapper : NSObject
@property (nonatomic, readonly) RCTInspectorNetworkListener listener;
- (instancetype)initWithListener:(RCTInspectorNetworkListener)listener;
@end

@interface RCTInspectorNetworkHelper () <NSURLSessionDataDelegate>
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong)
NSMutableDictionary<NSNumber *, RCTInspectorNetworkListenerWrapper *> *listenerWrappersByTaskId;
@end

@implementation RCTInspectorNetworkHelper

- (instancetype)init
{
self = [super init];
if (self) {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
self.listenerWrappersByTaskId = [NSMutableDictionary new];
}
return self;
}

- (void)networkRequestWithUrl:(const std::string &)rawUrl listener:(RCTInspectorNetworkListener)listener
{
NSString *urlString = [NSString stringWithUTF8String:rawUrl.c_str()];
NSURL *url = [NSURL URLWithString:urlString];
if (url == nil) {
listener->onError([NSString stringWithFormat:@"Not a valid URL: %@", urlString].UTF8String);
return;
}

NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:@"GET"];
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:urlRequest];
__weak NSURLSessionDataTask *weakDataTask = dataTask;
listener->setCancelFunction([weakDataTask]() { [weakDataTask cancel]; });
// Store the listener using the task identifier as the key
RCTInspectorNetworkListenerWrapper *listenerWrapper =
[[RCTInspectorNetworkListenerWrapper alloc] initWithListener:listener];
self.listenerWrappersByTaskId[@(dataTask.taskIdentifier)] = listenerWrapper;
[dataTask resume];
}

- (RCTInspectorNetworkListener)listenerForTask:(NSNumber *)taskIdentifier
{
auto *listenerWrapper = self.listenerWrappersByTaskId[taskIdentifier];
return listenerWrapper ? listenerWrapper.listener : nil;
}

#pragma mark - NSURLSessionDataDelegate

- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
RCTInspectorNetworkListener listener = [self listenerForTask:@(dataTask.taskIdentifier)];
if (!listener) {
[dataTask cancel];
return;
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
std::map<std::string, std::string> headersMap;
for (NSString *key in httpResponse.allHeaderFields) {
headersMap[[key UTF8String]] = [[httpResponse.allHeaderFields objectForKey:key] UTF8String];
}
completionHandler(NSURLSessionResponseAllow);
listener->onHeaders(httpResponse.statusCode, headersMap);
} else {
listener->onError("Unsupported response type");
completionHandler(NSURLSessionResponseCancel);
}
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
RCTInspectorNetworkListener listener = [self listenerForTask:@(dataTask.taskIdentifier)];
if (!listener) {
[dataTask cancel];
return;
}
if (data) {
listener->onData(std::string_view(static_cast<const char *>(data.bytes), data.length));
}
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
RCTInspectorNetworkListener listener = [self listenerForTask:@(task.taskIdentifier)];
if (!listener) {
return;
}
if (error != nil) {
listener->onError(error.localizedDescription.UTF8String);
} else {
listener->onEnd();
}
[self.listenerWrappersByTaskId removeObjectForKey:@(task.taskIdentifier)];
}

@end

@implementation RCTInspectorNetworkListenerWrapper {
RCTInspectorNetworkListener _listener;
}

- (instancetype)initWithListener:(RCTInspectorNetworkListener)listener
{
if (self = [super init]) {
_listener = listener;
}
return self;
}

- (RCTInspectorNetworkListener)listener
{
return _listener;
}

@end
139 changes: 135 additions & 4 deletions packages/react-native/ReactCommon/jsinspector-modern/HostAgent.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ HostAgent::HostAgent(
: frontendChannel_(frontendChannel),
targetController_(targetController),
sessionMetadata_(std::move(sessionMetadata)),
networkIO_(targetController.createNetworkHandler()),
sessionState_(sessionState) {}

void HostAgent::handleRequest(const cdp::PreparsedRequest& req) {
Expand Down Expand Up @@ -151,6 +152,15 @@ void HostAgent::handleRequest(const cdp::PreparsedRequest& req) {
folly::dynamic::object("dataLossOccurred", false)));
shouldSendOKResponse = true;
isFinishedHandlingRequest = true;
} else if (req.method == "Network.loadNetworkResource") {
handleLoadNetworkResource(req);
return;
} else if (req.method == "IO.read") {
handleIoRead(req);
return;
} else if (req.method == "IO.close") {
handleIoClose(req);
return;
}

if (!isFinishedHandlingRequest && instanceAgent_ &&
Expand All @@ -163,10 +173,131 @@ void HostAgent::handleRequest(const cdp::PreparsedRequest& req) {
return;
}

frontendChannel_(cdp::jsonError(
req.id,
cdp::ErrorCode::MethodNotFound,
req.method + " not implemented yet"));
throw NotImplementedException(req.method);
}

void HostAgent::handleLoadNetworkResource(const cdp::PreparsedRequest& req) {
long long requestId = req.id;
auto res = folly::dynamic::object("id", requestId);
if (!req.params.isObject()) {
frontendChannel_(cdp::jsonError(
req.id,
cdp::ErrorCode::InvalidParams,
"Invalid params: not an object."));
return;
}
if ((req.params.count("url") == 0u) || !req.params.at("url").isString()) {
frontendChannel_(cdp::jsonError(
requestId,
cdp::ErrorCode::InvalidParams,
"Invalid params: url is missing or not a string."));
return;
}

networkIO_->loadNetworkResource(
{.url = req.params.at("url").asString()},
targetController_.getDelegate(),
// This callback is always called, with resource.success=false on failure.
[requestId,
frontendChannel = frontendChannel_](NetworkResource resource) {
auto dynamicResource =
folly::dynamic::object("success", resource.success);

if (resource.stream) {
dynamicResource("stream", *resource.stream);
}

if (resource.netErrorName) {
dynamicResource("netErrorName", *resource.netErrorName);
}

if (resource.httpStatusCode) {
dynamicResource("httpStatusCode", *resource.httpStatusCode);
}

if (resource.headers) {
auto dynamicHeaders = folly::dynamic::object();
for (const auto& pair : *resource.headers) {
dynamicHeaders(pair.first, pair.second);
}
dynamicResource("headers", std::move(dynamicHeaders));
}

frontendChannel(cdp::jsonResult(
requestId,
folly::dynamic::object("resource", std::move(dynamicResource))));
});
}

void HostAgent::handleIoRead(const cdp::PreparsedRequest& req) {
long long requestId = req.id;
if (!req.params.isObject()) {
frontendChannel_(cdp::jsonError(
requestId,
cdp::ErrorCode::InvalidParams,
"Invalid params: not an object."));
return;
}
if ((req.params.count("handle") == 0u) ||
!req.params.at("handle").isString()) {
frontendChannel_(cdp::jsonError(
requestId,
cdp::ErrorCode::InvalidParams,
"Invalid params: handle is missing or not a string."));
return;
}
std::optional<unsigned long> size = std::nullopt;
if ((req.params.count("size") != 0u) && req.params.at("size").isInt()) {
size = req.params.at("size").asInt();
}
networkIO_->readStream(
{.handle = req.params.at("handle").asString(), .size = size},
[requestId, frontendChannel = frontendChannel_](
std::variant<IOReadError, IOReadResult> resultOrError) {
if (std::holds_alternative<IOReadError>(resultOrError)) {
frontendChannel(cdp::jsonError(
requestId,
cdp::ErrorCode::InternalError,
std::get<IOReadError>(resultOrError)));
} else {
const auto& result = std::get<IOReadResult>(resultOrError);
auto stringResult = cdp::jsonResult(
requestId,
folly::dynamic::object("data", result.data)("eof", result.eof)(
"base64Encoded", result.base64Encoded));
frontendChannel(stringResult);
}
});
}

void HostAgent::handleIoClose(const cdp::PreparsedRequest& req) {
long long requestId = req.id;
if (!req.params.isObject()) {
frontendChannel_(cdp::jsonError(
requestId,
cdp::ErrorCode::InvalidParams,
"Invalid params: not an object."));
return;
}
if ((req.params.count("handle") == 0u) ||
!req.params.at("handle").isString()) {
frontendChannel_(cdp::jsonError(
requestId,
cdp::ErrorCode::InvalidParams,
"Invalid params: handle is missing or not a string."));
return;
}
networkIO_->closeStream(
req.params.at("handle").asString(),
[requestId, frontendChannel = frontendChannel_](
std::optional<std::string> maybeError) {
if (maybeError) {
frontendChannel(cdp::jsonError(
requestId, cdp::ErrorCode::InternalError, *maybeError));
} else {
frontendChannel(cdp::jsonResult(requestId));
}
});
}

HostAgent::~HostAgent() {
Expand Down
10 changes: 10 additions & 0 deletions packages/react-native/ReactCommon/jsinspector-modern/HostAgent.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@

#pragma once

#include "CdpJson.h"
#include "HostTarget.h"
#include "NetworkIO.h"
#include "SessionState.h"

#include <jsinspector-modern/InspectorInterfaces.h>
Expand Down Expand Up @@ -98,12 +100,20 @@ class HostAgent final {
std::shared_ptr<InstanceAgent> instanceAgent_;
FuseboxClientType fuseboxClientType_{FuseboxClientType::Unknown};
bool isPausedInDebuggerOverlayVisible_{false};
std::shared_ptr<NetworkIO> networkIO_;

/**
* A shared reference to the session's state. This is only safe to access
* during handleRequest and other method calls on the same thread.
*/
SessionState& sessionState_;

/** Handle a Network.loadNetworkResource CDP request. */
void handleLoadNetworkResource(const cdp::PreparsedRequest& req);
/** Handle an IO.read CDP request. */
void handleIoRead(const cdp::PreparsedRequest& req);
/** Handle an IO.close CDP request. */
void handleIoClose(const cdp::PreparsedRequest& req);
};

} // namespace facebook::react::jsinspector_modern
Loading
Loading