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
10 changes: 10 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,16 @@ 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.
* Do not change this value after calling `start`.
*/
@property (nonatomic, assign) BOOL buffersResponseData;

@property (atomic, readonly) RCTNetworkTaskStatus status;

- (instancetype)initWithRequest:(NSURLRequest *)request
Expand Down
10 changes: 5 additions & 5 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;
std::atomic<int64_t> _receivedLength;
id<RCTURLRequestHandler> _handler;
dispatch_queue_t _callbackQueue;
std::mutex _mutex;
Expand Down Expand Up @@ -50,6 +51,8 @@ - (instancetype)initWithDevToolsRequestId:(NSString *)devToolsRequestId
_handler = handler;
_callbackQueue = callbackQueue;
_atomicStatus = RCTNetworkTaskPending;
_receivedLength = 0;
_buffersResponseData = YES;

dispatch_queue_set_specific(callbackQueue, (__bridge void *)self, (__bridge void *)self, NULL);
}
Expand Down Expand Up @@ -173,9 +176,7 @@ - (void)URLRequest:(id)requestToken didReceiveData:(NSData *)data
return;
}

int64_t length = 0;

{
if (_buffersResponseData) {
// 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);
Comment thread
javache marked this conversation as resolved.
Resolved
Expand All @@ -196,10 +197,9 @@ - (void)URLRequest:(id)requestToken didReceiveData:(NSData *)data
[self invalidate];
return;
}

length = _data.length;
}

const int64_t length = _receivedLength.fetch_add(data.length, std::memory_order_relaxed) + data.length;
int64_t total = _response.expectedContentLength;

if (_incrementalDataBlock) {
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
102 changes: 102 additions & 0 deletions packages/rn-tester/RNTesterUnitTests/RCTNetworkTaskTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,106 @@ - (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 ]));
}

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

NSMutableArray<NSNumber *> *incrementalProgress = [NSMutableArray new];
NSMutableArray<NSNumber *> *downloadProgress = [NSMutableArray new];
XCTestExpectation *completion = [self expectationWithDescription:@"completion block called"];
task.incrementalDataBlock = ^(NSData *data, int64_t bytesReceived, int64_t total) {
[incrementalProgress addObject:@(bytesReceived)];
};
task.downloadProgressBlock = ^(int64_t bytesReceived, int64_t total) {
[downloadProgress addObject:@(bytesReceived)];
};
task.completionBlock = ^(NSURLResponse *response, NSData *data, NSError *error) {
XCTAssertNil(data);
XCTAssertNil(error);
[completion fulfill];
};

[task start];
id token = task.requestToken;
NSData *chunk = [@"abc" dataUsingEncoding:NSUTF8StringEncoding];
const NSUInteger chunkCount = 256;
dispatch_apply(chunkCount, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^(size_t index) {
[task URLRequest:token didReceiveData:chunk];
});
[task URLRequest:token didCompleteWithError:nil];
[self waitForExpectations:@[ completion ] timeout:5];

NSMutableArray<NSNumber *> *expectedProgress = [NSMutableArray new];
for (NSUInteger index = 1; index <= chunkCount; index++) {
[expectedProgress addObject:@(index * chunk.length)];
}
// Concurrent callers can enqueue callbacks out of order, but each chunk must advance the count exactly once.
XCTAssertEqualObjects([incrementalProgress sortedArrayUsingSelector:@selector(compare:)], expectedProgress);
XCTAssertEqualObjects([downloadProgress sortedArrayUsingSelector:@selector(compare:)], expectedProgress);
}

- (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