diff --git a/packages/react-native/Libraries/Network/RCTNetworkTask.h b/packages/react-native/Libraries/Network/RCTNetworkTask.h index 1b7c20db205..10d8f80578c 100644 --- a/packages/react-native/Libraries/Network/RCTNetworkTask.h +++ b/packages/react-native/Libraries/Network/RCTNetworkTask.h @@ -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 diff --git a/packages/react-native/Libraries/Network/RCTNetworkTask.mm b/packages/react-native/Libraries/Network/RCTNetworkTask.mm index 99c9e237a98..5b2137787ac 100644 --- a/packages/react-native/Libraries/Network/RCTNetworkTask.mm +++ b/packages/react-native/Libraries/Network/RCTNetworkTask.mm @@ -14,6 +14,7 @@ @implementation RCTNetworkTask { NSMutableData *_data; + int64_t _receivedLength; id _handler; dispatch_queue_t _callbackQueue; std::mutex _mutex; @@ -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); } @@ -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 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; diff --git a/packages/react-native/Libraries/Network/RCTNetworking.mm b/packages/react-native/Libraries/Network/RCTNetworking.mm index d9c78b10e68..24904b1b44c 100644 --- a/packages/react-native/Libraries/Network/RCTNetworking.mm +++ b/packages/react-native/Libraries/Network/RCTNetworking.mm @@ -627,6 +627,9 @@ - (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). @@ -634,6 +637,7 @@ - (void)sendRequest:(NSURLRequest *)request NSMutableData *incrementalDataCarry = [NSMutableData new]; incrementalDataBlock = ^(NSData *data, int64_t progress, int64_t total) { + incrementalDataLength = progress; NSUInteger initialCarryLength = incrementalDataCarry.length; id responseString = [RCTNetworking decodeTextData:data @@ -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]; @@ -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]; @@ -746,6 +758,16 @@ - (void)addTextResponseHandler:(id)handler [_textResponseHandlers addObject:handler]; } +- (BOOL)hasTextResponseHandlerForRequest:(NSURLRequest *)request +{ + for (id handler in _textResponseHandlers) { + if ([handler canHandleNetworkingTextResponseForRequest:request]) { + return YES; + } + } + return NO; +} + - (void)removeRequestHandler:(id)handler { [_requestHandlers removeObject:handler]; diff --git a/packages/rn-tester/RNTesterUnitTests/RCTNetworkTaskTests.m b/packages/rn-tester/RNTesterUnitTests/RCTNetworkTaskTests.m index 874875ee0f9..b5580ffd377 100644 --- a/packages/rn-tester/RNTesterUnitTests/RCTNetworkTaskTests.m +++ b/packages/rn-tester/RNTesterUnitTests/RCTNetworkTaskTests.m @@ -46,4 +46,67 @@ - (void)testCanReadTaskStatus XCTAssertEqual(task.status, RCTNetworkTaskFinished); } +- (void)testBuffersResponseDataByDefault +{ + RCTNetworkTask *task = [self createTask]; + XCTAssertTrue(task.buffersResponseData); + + NSMutableArray *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 *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 testHandler = (id)[[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 *)chunks + progress:(NSMutableArray *)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 diff --git a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api index 5733ae36e24..ce6fd0d2ecc 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api @@ -1418,6 +1418,7 @@ interface RCTNativeAnimatedTurboModule : public RCTEventEmitter { + public @property (assign) BOOL buffersResponseData; public @property (assign, readonly) NSNumber* requestID; public @property (assign, readonly) NSString* devToolsRequestId; public @property (assign, readonly) NSURLRequest* request; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api index af897d88f1b..6412518b1a5 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -1461,6 +1461,7 @@ interface RCTNativeAnimatedTurboModule : public RCTEventEmitter { + public @property (assign) BOOL buffersResponseData; public @property (assign, readonly) NSNumber* requestID; public @property (assign, readonly) NSString* devToolsRequestId; public @property (assign, readonly) NSURLRequest* request; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api index 70d6e5c3001..6cebe3024ce 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api @@ -1418,6 +1418,7 @@ interface RCTNativeAnimatedTurboModule : public RCTEventEmitter { + public @property (assign) BOOL buffersResponseData; public @property (assign, readonly) NSNumber* requestID; public @property (assign, readonly) NSString* devToolsRequestId; public @property (assign, readonly) NSURLRequest* request; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api index 4accfd8303a..664ca75e45a 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api @@ -1418,6 +1418,7 @@ interface RCTNativeAnimatedTurboModule : public RCTEventEmitter { + public @property (assign) BOOL buffersResponseData; public @property (assign, readonly) NSNumber* requestID; public @property (assign, readonly) NSString* devToolsRequestId; public @property (assign, readonly) NSURLRequest* request;