Fixes race condition when setup image loader (#46153)

Summary:
Fixes https://github.com/facebook/react-native/issues/46115 .

## Changelog:

[IOS] [FIXED] - Fixes race condition when setup image loader

Pull Request resolved: https://github.com/facebook/react-native/pull/46153

Test Plan: crash in https://github.com/facebook/react-native/issues/46115

Reviewed By: cipolleschi

Differential Revision: D61662905

Pulled By: andrewdacenko

fbshipit-source-id: 22bc45b473c7c8e1c811e41f5030220ca7988e1f
This commit is contained in:
zhongwuzw
2024-08-23 08:08:58 -07:00
committed by Facebook GitHub Bot
parent a8be335a37
commit 6b104bbe01
@@ -68,6 +68,8 @@ static NSError *addResponseHeadersToError(NSError *originalError, NSHTTPURLRespo
@end
@implementation RCTImageLoader {
std::atomic<BOOL> _isLoaderSetup;
std::mutex _loaderSetupLock;
NSArray<id<RCTImageURLLoader>> * (^_loadersProvider)(RCTModuleRegistry *);
NSArray<id<RCTImageDataDecoder>> * (^_decodersProvider)(RCTModuleRegistry *);
NSArray<id<RCTImageURLLoader>> *_loaders;
@@ -106,6 +108,7 @@ RCT_EXPORT_MODULE()
{
if (self = [super init]) {
_redirectDelegate = redirectDelegate;
_isLoaderSetup = NO;
}
return self;
}
@@ -123,12 +126,16 @@ RCT_EXPORT_MODULE()
- (void)setUp
{
// Set defaults
_maxConcurrentLoadingTasks = _maxConcurrentLoadingTasks ?: 4;
_maxConcurrentDecodingTasks = _maxConcurrentDecodingTasks ?: 2;
_maxConcurrentDecodingBytes = _maxConcurrentDecodingBytes ?: 30 * 1024 * 1024; // 30MB
std::lock_guard<std::mutex> guard(_loaderSetupLock);
if (!_isLoaderSetup) {
// Set defaults
_maxConcurrentLoadingTasks = _maxConcurrentLoadingTasks ?: 4;
_maxConcurrentDecodingTasks = _maxConcurrentDecodingTasks ?: 2;
_maxConcurrentDecodingBytes = _maxConcurrentDecodingBytes ?: 30 * 1024 * 1024; // 30MB
_URLRequestQueue = dispatch_queue_create("com.facebook.react.ImageLoaderURLRequestQueue", DISPATCH_QUEUE_SERIAL);
_URLRequestQueue = dispatch_queue_create("com.facebook.react.ImageLoaderURLRequestQueue", DISPATCH_QUEUE_SERIAL);
_isLoaderSetup = YES;
}
}
- (float)handlerPriority
@@ -156,7 +163,7 @@ RCT_EXPORT_MODULE()
- (id<RCTImageURLLoader>)imageURLLoaderForURL:(NSURL *)URL
{
if (!_maxConcurrentLoadingTasks) {
if (!_isLoaderSetup) {
[self setUp];
}
@@ -229,7 +236,7 @@ RCT_EXPORT_MODULE()
- (id<RCTImageDataDecoder>)imageDataDecoderForData:(NSData *)data
{
if (!_maxConcurrentLoadingTasks) {
if (!_isLoaderSetup) {
[self setUp];
}
@@ -564,7 +571,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image, CGSize size, CGFloat scal
}
// All access to URL cache must be serialized
if (!_URLRequestQueue) {
if (!_isLoaderSetup) {
[self setUp];
}
@@ -979,7 +986,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image, CGSize size, CGFloat scal
});
};
if (!_URLRequestQueue) {
if (!_isLoaderSetup) {
[self setUp];
}
dispatch_async(_URLRequestQueue, ^{