diff --git a/packages/react-native/Libraries/Network/RCTNetworkTask.h b/packages/react-native/Libraries/Network/RCTNetworkTask.h index 1b7c20db2054..04a5b2823182 100644 --- a/packages/react-native/Libraries/Network/RCTNetworkTask.h +++ b/packages/react-native/Libraries/Network/RCTNetworkTask.h @@ -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 diff --git a/packages/react-native/Libraries/Network/RCTNetworkTask.mm b/packages/react-native/Libraries/Network/RCTNetworkTask.mm index 99c9e237a989..09833b4bc98c 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; + std::atomic _receivedLength; id _handler; dispatch_queue_t _callbackQueue; std::mutex _mutex; @@ -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); } @@ -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 lock(_mutex); @@ -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) { diff --git a/packages/react-native/Libraries/Network/RCTNetworking.mm b/packages/react-native/Libraries/Network/RCTNetworking.mm index d9c78b10e685..24904b1b44c3 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 874875ee0f91..03c9cd56facb 100644 --- a/packages/rn-tester/RNTesterUnitTests/RCTNetworkTaskTests.m +++ b/packages/rn-tester/RNTesterUnitTests/RCTNetworkTaskTests.m @@ -46,4 +46,106 @@ - (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 ])); +} + +- (void)testTracksConcurrentProgressWithoutBuffering +{ + RCTNetworkTask *task = [self createTask]; + task.buffersResponseData = NO; + + NSMutableArray *incrementalProgress = [NSMutableArray new]; + NSMutableArray *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 *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 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 5733ae36e244..ce6fd0d2ecc0 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 af897d88f1b6..6412518b1a5f 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 70d6e5c30013..6cebe3024ce0 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 4accfd8303a1..664ca75e45ae 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;