Skip to content
Open
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
9 changes: 9 additions & 0 deletions packages/react-native/Libraries/Network/RCTNetworkTask.h
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ typedef NS_ENUM(NSInteger, RCTNetworkTaskStatus) {
@property (nonatomic, copy) RCTURLRequestResponseBlock responseBlock;
@property (nonatomic, copy) RCTURLRequestProgressBlock uploadProgressBlock;

/**
* Whether the task keeps the response data it receives, to give it to the completion block.
* The default is YES. Set it to NO before `start` when the incremental data block uses each chunk
* and the completion block does not need the full response. The completion block then gets nil data.
* This stops a long-lived response, for example a stream of server-sent events, from keeping all of
* its data in memory until it ends.
*/
@property (nonatomic, assign) BOOL buffersResponseData;

@property (atomic, readonly) RCTNetworkTaskStatus status;

- (instancetype)initWithRequest:(NSURLRequest *)request
Expand Down
37 changes: 21 additions & 16 deletions packages/react-native/Libraries/Network/RCTNetworkTask.mm
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

@implementation RCTNetworkTask {
NSMutableData *_data;
int64_t _receivedLength;
id<RCTURLRequestHandler> _handler;
dispatch_queue_t _callbackQueue;
std::mutex _mutex;
Expand Down Expand Up @@ -50,6 +51,7 @@ - (instancetype)initWithDevToolsRequestId:(NSString *)devToolsRequestId
_handler = handler;
_callbackQueue = callbackQueue;
_atomicStatus = RCTNetworkTaskPending;
_buffersResponseData = YES;

dispatch_queue_set_specific(callbackQueue, (__bridge void *)self, (__bridge void *)self, NULL);
}
Expand Down Expand Up @@ -179,25 +181,28 @@ - (void)URLRequest:(id)requestToken didReceiveData:(NSData *)data
// NSData is not thread-safe and this method could be called from different threads as
// RCTURLRequestHandlers does not provide any guarantee of which thread we are called on.
std::lock_guard<std::mutex> lock(_mutex);
if (!_data) {
_data = [NSMutableData new];
}
@try {
[_data appendData:data];
} @catch (NSException *exception) {
_atomicStatus = RCTNetworkTaskFinished;
if (_completionBlock) {
RCTURLRequestCompletionBlock completionBlock = _completionBlock;
[self dispatchCallback:^{
completionBlock(
self->_response, nil, RCTErrorWithMessage(exception.reason ?: @"Request's received data too long."));
}];
if (_buffersResponseData) {
if (!_data) {
_data = [NSMutableData new];
}
@try {
[_data appendData:data];
} @catch (NSException *exception) {
_atomicStatus = RCTNetworkTaskFinished;
if (_completionBlock) {
RCTURLRequestCompletionBlock completionBlock = _completionBlock;
[self dispatchCallback:^{
completionBlock(
self->_response, nil, RCTErrorWithMessage(exception.reason ?: @"Request's received data too long."));
}];
}
[self invalidate];
return;
}
[self invalidate];
return;
}

length = _data.length;
_receivedLength += data.length;
length = _receivedLength;
}

int64_t total = _response.expectedContentLength;
Expand Down
24 changes: 23 additions & 1 deletion packages/react-native/Libraries/Network/RCTNetworking.mm
Original file line number Diff line number Diff line change
Expand Up @@ -627,13 +627,17 @@ - (void)sendRequest:(NSURLRequest *)request
// we only send progress updates and not incremental data updates to JS here.
RCTURLRequestIncrementalDataBlock incrementalDataBlock = nil;
RCTURLRequestProgressBlock downloadProgressBlock = nil;
// For incremental text updates, the task usually does not keep the response (see below). The completion
// block then has no data to measure, so count the bytes here.
__block int64_t incrementalDataLength = 0;
if (incrementalUpdates) {
if ([responseType isEqualToString:@"text"]) {
// We need this to carry over bytes, which could not be decoded into text (such as broken UTF-8 characters).
// The incremental data block holds the ownership of this object, and will be released upon release of the block.
NSMutableData *incrementalDataCarry = [NSMutableData new];

incrementalDataBlock = ^(NSData *data, int64_t progress, int64_t total) {
incrementalDataLength = progress;
NSUInteger initialCarryLength = incrementalDataCarry.length;

id responseString = [RCTNetworking decodeTextData:data
Expand Down Expand Up @@ -693,7 +697,8 @@ - (void)sendRequest:(NSURLRequest *)request
if (error != nullptr) {
[RCTInspectorNetworkReporter reportRequestFailed:task.devToolsRequestId cancelled:NO];
} else {
[RCTInspectorNetworkReporter reportResponseEnd:task.devToolsRequestId encodedDataLength:data.length];
[RCTInspectorNetworkReporter reportResponseEnd:task.devToolsRequestId
encodedDataLength:data ? data.length : incrementalDataLength];
}
[strongSelf sendEventWithName:@"didCompleteNetworkResponse" body:responseJSON];
[strongSelf->_tasksByRequestID removeObjectForKey:task.requestID];
Expand All @@ -705,6 +710,13 @@ - (void)sendRequest:(NSURLRequest *)request
task.responseBlock = responseBlock;
task.uploadProgressBlock = uploadProgressBlock;

// Incremental text updates send each chunk to JS as it arrives, so the full response is only needed
// at completion by a text response handler. Without one, keeping it would let a long-lived response,
// for example a stream of server-sent events, use more memory until it ends.
if (incrementalDataBlock && ![self hasTextResponseHandlerForRequest:request]) {
task.buffersResponseData = NO;
}

if (task.requestID) {
if (!_tasksByRequestID) {
_tasksByRequestID = [NSMutableDictionary new];
Expand Down Expand Up @@ -746,6 +758,16 @@ - (void)addTextResponseHandler:(id<RCTNetworkingTextResponseHandler>)handler
[_textResponseHandlers addObject:handler];
}

- (BOOL)hasTextResponseHandlerForRequest:(NSURLRequest *)request
{
for (id<RCTNetworkingTextResponseHandler> handler in _textResponseHandlers) {
if ([handler canHandleNetworkingTextResponseForRequest:request]) {
return YES;
}
}
return NO;
}

- (void)removeRequestHandler:(id<RCTNetworkingRequestHandler>)handler
{
[_requestHandlers removeObject:handler];
Expand Down
63 changes: 63 additions & 0 deletions packages/rn-tester/RNTesterUnitTests/RCTNetworkTaskTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,67 @@ - (void)testCanReadTaskStatus
XCTAssertEqual(task.status, RCTNetworkTaskFinished);
}

- (void)testBuffersResponseDataByDefault
{
RCTNetworkTask *task = [self createTask];
XCTAssertTrue(task.buffersResponseData);

NSMutableArray<NSNumber *> *progress = [NSMutableArray new];
NSData *data = [self completeTask:task withChunks:@[ @"abc", @"def" ] progress:progress];

XCTAssertEqualObjects([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding], @"abcdef");
XCTAssertEqualObjects(progress, (@[ @3, @6 ]));
}

- (void)testDoesNotBufferResponseDataWhenDisabled
{
RCTNetworkTask *task = [self createTask];
task.buffersResponseData = NO;

NSMutableArray<NSNumber *> *progress = [NSMutableArray new];
NSData *data = [self completeTask:task withChunks:@[ @"abc", @"def" ] progress:progress];

XCTAssertNil(data);
XCTAssertEqualObjects(progress, (@[ @3, @6 ]));
}

- (RCTNetworkTask *)createTask
{
NSURL *url = [[NSURL alloc] initWithString:@"https://developers.facebook.com"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
dispatch_queue_t callbackQueue = dispatch_queue_create("RCTNetworkTaskTests", DISPATCH_QUEUE_SERIAL);
id<RCTURLRequestHandler> testHandler = (id<RCTURLRequestHandler>)[[TestHandler alloc] init];
return [[RCTNetworkTask alloc] initWithRequest:request handler:testHandler callbackQueue:callbackQueue];
}

/**
* Feeds the chunks to the task the way a request handler would, and returns the data that the
* completion block gets. Adds the progress that the incremental data block gets to `progress`.
*/
- (NSData *)completeTask:(RCTNetworkTask *)task
withChunks:(NSArray<NSString *> *)chunks
progress:(NSMutableArray<NSNumber *> *)progress
{
__block NSData *completionData = nil;
XCTestExpectation *completion = [self expectationWithDescription:@"completion block called"];
task.incrementalDataBlock = ^(NSData *data, int64_t bytesReceived, int64_t total) {
[progress addObject:@(bytesReceived)];
};
task.completionBlock = ^(NSURLResponse *response, NSData *data, NSError *error) {
completionData = data;
[completion fulfill];
};

[task start];
id token = task.requestToken;
for (NSString *chunk in chunks) {
[task URLRequest:token didReceiveData:[chunk dataUsingEncoding:NSUTF8StringEncoding]];
}
[task URLRequest:token didCompleteWithError:nil];

// The task calls the blocks on its callback queue, in order, so the progress is complete as well
[self waitForExpectations:@[ completion ] timeout:1];
return completionData;
}

@end
1 change: 1 addition & 0 deletions scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api
Original file line number Diff line number Diff line change
Expand Up @@ -1418,6 +1418,7 @@ interface RCTNativeAnimatedTurboModule : public RCTEventEmitter <RCTBridgeModule
}

interface RCTNetworkTask : public NSObject <RCTURLRequestDelegate> {
public @property (assign) BOOL buffersResponseData;
public @property (assign, readonly) NSNumber* requestID;
public @property (assign, readonly) NSString* devToolsRequestId;
public @property (assign, readonly) NSURLRequest* request;
Expand Down
1 change: 1 addition & 0 deletions scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api
Original file line number Diff line number Diff line change
Expand Up @@ -1461,6 +1461,7 @@ interface RCTNativeAnimatedTurboModule : public RCTEventEmitter <RCTBridgeModule
}

interface RCTNetworkTask : public NSObject <RCTURLRequestDelegate> {
public @property (assign) BOOL buffersResponseData;
public @property (assign, readonly) NSNumber* requestID;
public @property (assign, readonly) NSString* devToolsRequestId;
public @property (assign, readonly) NSURLRequest* request;
Expand Down
1 change: 1 addition & 0 deletions scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api
Original file line number Diff line number Diff line change
Expand Up @@ -1418,6 +1418,7 @@ interface RCTNativeAnimatedTurboModule : public RCTEventEmitter <RCTBridgeModule
}

interface RCTNetworkTask : public NSObject <RCTURLRequestDelegate> {
public @property (assign) BOOL buffersResponseData;
public @property (assign, readonly) NSNumber* requestID;
public @property (assign, readonly) NSString* devToolsRequestId;
public @property (assign, readonly) NSURLRequest* request;
Expand Down
1 change: 1 addition & 0 deletions scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api
Original file line number Diff line number Diff line change
Expand Up @@ -1418,6 +1418,7 @@ interface RCTNativeAnimatedTurboModule : public RCTEventEmitter <RCTBridgeModule
}

interface RCTNetworkTask : public NSObject <RCTURLRequestDelegate> {
public @property (assign) BOOL buffersResponseData;
public @property (assign, readonly) NSNumber* requestID;
public @property (assign, readonly) NSString* devToolsRequestId;
public @property (assign, readonly) NSURLRequest* request;
Expand Down
Loading