From daaf0eb462c576be01aafce1bb02f288d6671cad Mon Sep 17 00:00:00 2001 From: Espen Hovlandsdal Date: Mon, 23 Nov 2026 12:19:56 -0800 Subject: [PATCH 1/2] [iOS] Do not keep the response of incremental text requests in RCTNetworkTask RCTNetworkTask appends every chunk it receives to a buffer, so that it can give the full response to the completion block. For incremental text requests, RCTNetworking sends each chunk to JavaScript as it arrives, and the buffer is only used for the DevTools length and for text response handlers. A response that stays open, for example a stream of server-sent events, then keeps all of its data in memory until it ends. RCTNetworkTask gets a `buffersResponseData` property, YES by default. RCTNetworking sets it to NO for incremental text requests that no text response handler handles, and counts the received bytes for the DevTools network reporter itself. Other users of RCTNetworkTask, such as RCTImageLoader, do not change. --- .../Libraries/Network/RCTNetworkTask.h | 9 +++ .../Libraries/Network/RCTNetworkTask.mm | 37 ++++++----- .../Libraries/Network/RCTNetworking.mm | 24 ++++++- .../RNTesterUnitTests/RCTNetworkTaskTests.m | 63 +++++++++++++++++++ 4 files changed, 116 insertions(+), 17 deletions(-) diff --git a/packages/react-native/Libraries/Network/RCTNetworkTask.h b/packages/react-native/Libraries/Network/RCTNetworkTask.h index 1b7c20db2054..10d8f80578c6 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 99c9e237a989..5b2137787ac1 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 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..b5580ffd3776 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 From 85d25e389cb5dd204e0d2dad74689bc0e90297b1 Mon Sep 17 00:00:00 2001 From: Espen Hovlandsdal Date: Mon, 23 Nov 2026 16:26:40 -0800 Subject: [PATCH 2/2] Update the Apple C++ API snapshots for RCTNetworkTask.buffersResponseData --- scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api | 1 + scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api | 1 + scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api | 1 + scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api | 1 + 4 files changed, 4 insertions(+) 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;