-
Notifications
You must be signed in to change notification settings - Fork 466
/
RNCAsyncStorage.mm
905 lines (822 loc) · 32.6 KB
/
RNCAsyncStorage.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "RNCAsyncStorage.h"
#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonDigest.h>
#import <React/RCTConvert.h>
#import <React/RCTLog.h>
#import <React/RCTUtils.h>
static NSString *const RCTStorageDirectory = @"RCTAsyncLocalStorage_V1";
static NSString *const RCTOldStorageDirectory = @"RNCAsyncLocalStorage_V1";
static NSString *const RCTExpoStorageDirectory = @"RCTAsyncLocalStorage";
static NSString *const RCTManifestFileName = @"manifest.json";
static const NSUInteger RCTInlineValueThreshold = 1024;
#pragma mark - Static helper functions
static NSDictionary *RCTErrorForKey(NSString *key)
{
if (![key isKindOfClass:[NSString class]]) {
return RCTMakeAndLogError(@"Invalid key - must be a string. Key: ", key, @{@"key": key});
} else if (key.length < 1) {
return RCTMakeAndLogError(
@"Invalid key - must be at least one character. Key: ", key, @{@"key": key});
} else {
return nil;
}
}
static BOOL RCTAsyncStorageSetExcludedFromBackup(NSString *path, NSNumber *isExcluded)
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
BOOL isDir;
BOOL exists = [fileManager fileExistsAtPath:path isDirectory:&isDir];
BOOL success = false;
if (isDir && exists) {
NSURL *pathUrl = [NSURL fileURLWithPath:path];
NSError *error = nil;
success = [pathUrl setResourceValue:isExcluded
forKey:NSURLIsExcludedFromBackupKey
error:&error];
if (!success) {
NSLog(@"Could not exclude AsyncStorage dir from backup %@", error);
}
}
return success;
}
static void RCTAppendError(NSDictionary *error, NSMutableArray<NSDictionary *> **errors)
{
if (error && errors) {
if (!*errors) {
*errors = [NSMutableArray new];
}
[*errors addObject:error];
}
}
static NSArray<NSDictionary *> *RCTMakeErrors(NSArray<id<NSObject>> *results)
{
NSMutableArray<NSDictionary *> *errors;
for (id object in results) {
if ([object isKindOfClass:[NSError class]]) {
NSError *error = (NSError *)object;
NSDictionary *keyError = RCTMakeError(error.localizedDescription, error, nil);
RCTAppendError(keyError, &errors);
}
}
return errors;
}
static NSString *RCTReadFile(NSString *filePath, NSString *key, NSDictionary **errorOut)
{
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSError *error;
NSStringEncoding encoding;
NSString *entryString = [NSString stringWithContentsOfFile:filePath
usedEncoding:&encoding
error:&error];
NSDictionary *extraData = @{@"key": RCTNullIfNil(key)};
if (error) {
if (errorOut) {
*errorOut = RCTMakeError(@"Failed to read storage file.", error, extraData);
}
return nil;
}
if (encoding != NSUTF8StringEncoding) {
if (errorOut) {
*errorOut =
RCTMakeError(@"Incorrect encoding of storage file: ", @(encoding), extraData);
}
return nil;
}
return entryString;
}
return nil;
}
// DO NOT USE
// This is used internally to migrate data from the old file location to the new one.
// Please use `RCTCreateStorageDirectoryPath` instead
static NSString *RCTCreateStorageDirectoryPath_deprecated(NSString *storageDir)
{
NSString *storageDirectoryPath;
#if TARGET_OS_TV
storageDirectoryPath =
NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
#else
storageDirectoryPath =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
#endif
storageDirectoryPath = [storageDirectoryPath stringByAppendingPathComponent:storageDir];
return storageDirectoryPath;
}
static NSString *RCTCreateStorageDirectoryPath(NSString *storageDir)
{
NSString *storageDirectoryPath = @"";
#if TARGET_OS_TV
storageDirectoryPath =
NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
#else
storageDirectoryPath =
NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES)
.firstObject;
// We should use the "Application Support/[bundleID]" folder for persistent data storage that's
// hidden from users
storageDirectoryPath = [storageDirectoryPath
stringByAppendingPathComponent:[[NSBundle mainBundle] bundleIdentifier]];
#endif
// Per Apple's docs, all app content in Application Support must be within a subdirectory of the
// app's bundle identifier
storageDirectoryPath = [storageDirectoryPath stringByAppendingPathComponent:storageDir];
return storageDirectoryPath;
}
static NSString *RCTGetStorageDirectory()
{
static NSString *storageDirectory = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
#if TARGET_OS_TV
RCTLogWarn(
@"Persistent storage is not supported on tvOS, your data may be removed at any point.");
#endif
storageDirectory = RCTCreateStorageDirectoryPath(RCTStorageDirectory);
});
return storageDirectory;
}
static NSString *RCTCreateManifestFilePath(NSString *storageDirectory)
{
return [storageDirectory stringByAppendingPathComponent:RCTManifestFileName];
}
static NSString *RCTGetManifestFilePath()
{
static NSString *manifestFilePath = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manifestFilePath = RCTCreateManifestFilePath(RCTStorageDirectory);
});
return manifestFilePath;
}
// Only merges objects - all other types are just clobbered (including arrays)
static BOOL RCTMergeRecursive(NSMutableDictionary *destination, NSDictionary *source)
{
BOOL modified = NO;
for (NSString *key in source) {
id sourceValue = source[key];
id destinationValue = destination[key];
if ([sourceValue isKindOfClass:[NSDictionary class]]) {
if ([destinationValue isKindOfClass:[NSDictionary class]]) {
if ([destinationValue classForCoder] != [NSMutableDictionary class]) {
destinationValue = [destinationValue mutableCopy];
}
if (RCTMergeRecursive(destinationValue, sourceValue)) {
destination[key] = destinationValue;
modified = YES;
}
} else {
destination[key] = [sourceValue copy];
modified = YES;
}
} else if (![source isEqual:destinationValue]) {
destination[key] = [sourceValue copy];
modified = YES;
}
}
return modified;
}
static dispatch_queue_t RCTGetMethodQueue()
{
// We want all instances to share the same queue since they will be reading/writing the same
// files.
static dispatch_queue_t queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
queue =
dispatch_queue_create("com.facebook.react.AsyncLocalStorageQueue", DISPATCH_QUEUE_SERIAL);
});
return queue;
}
static NSCache *RCTGetCache()
{
// We want all instances to share the same cache since they will be reading/writing the same
// files.
static NSCache *cache;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
cache = [NSCache new];
cache.totalCostLimit = 2 * 1024 * 1024; // 2MB
#if !TARGET_OS_OSX
// Clear cache in the event of a memory warning
[[NSNotificationCenter defaultCenter]
addObserverForName:UIApplicationDidReceiveMemoryWarningNotification
object:nil
queue:nil
usingBlock:^(__unused NSNotification *note) {
[cache removeAllObjects];
}];
#endif // !TARGET_OS_OSX
});
return cache;
}
static BOOL RCTHasCreatedStorageDirectory = NO;
static NSDictionary *RCTDeleteStorageDirectory()
{
NSError *error;
[[NSFileManager defaultManager] removeItemAtPath:RCTGetStorageDirectory() error:&error];
RCTHasCreatedStorageDirectory = NO;
return error ? RCTMakeError(@"Failed to delete storage directory.", error, nil) : nil;
}
static NSDate *RCTManifestModificationDate(NSString *manifestFilePath)
{
NSDictionary *attributes =
[[NSFileManager defaultManager] attributesOfItemAtPath:manifestFilePath error:nil];
return [attributes fileModificationDate];
}
/**
* Creates an NSException used during Storage Directory Migration.
*/
static void RCTStorageDirectoryMigrationLogError(NSString *reason, NSError *error)
{
RCTLogWarn(@"%@: %@", reason, error ? error.description : @"");
}
static void RCTStorageDirectoryCleanupOld(NSString *oldDirectoryPath)
{
NSError *error;
if (![[NSFileManager defaultManager] removeItemAtPath:oldDirectoryPath error:&error]) {
RCTStorageDirectoryMigrationLogError(
@"Failed to remove old storage directory during migration", error);
}
}
static void _createStorageDirectory(NSString *storageDirectory, NSError **error)
{
[[NSFileManager defaultManager] createDirectoryAtPath:storageDirectory
withIntermediateDirectories:YES
attributes:nil
error:error];
}
static void RCTStorageDirectoryMigrate(NSString *oldDirectoryPath,
NSString *newDirectoryPath,
BOOL shouldCleanupOldDirectory)
{
NSError *error;
// Migrate data by copying old storage directory to new storage directory location
if (![[NSFileManager defaultManager] copyItemAtPath:oldDirectoryPath
toPath:newDirectoryPath
error:&error]) {
// the new storage directory "Application Support/[bundleID]/RCTAsyncLocalStorage_V1" seems
// unable to migrate because folder "Application Support/[bundleID]" doesn't exist.. create
// this folder and attempt folder copying again
if (error != nil && error.code == 4 &&
[newDirectoryPath isEqualToString:RCTGetStorageDirectory()]) {
NSError *error = nil;
_createStorageDirectory(RCTCreateStorageDirectoryPath(@""), &error);
if (error == nil) {
RCTStorageDirectoryMigrate(
oldDirectoryPath, newDirectoryPath, shouldCleanupOldDirectory);
} else {
RCTStorageDirectoryMigrationLogError(
@"Failed to create storage directory during migration.", error);
}
} else {
RCTStorageDirectoryMigrationLogError(
@"Failed to copy old storage directory to new storage directory location during "
@"migration",
error);
}
} else if (shouldCleanupOldDirectory) {
// If copying succeeds, remove old storage directory
RCTStorageDirectoryCleanupOld(oldDirectoryPath);
}
}
/**
* Determine which of RCTOldStorageDirectory or RCTExpoStorageDirectory needs to migrated.
* If both exist, we remove the least recently modified and return the most recently modified.
* Otherwise, this will return the path to whichever directory exists.
* If no directory exists, then return nil.
*/
static NSString *RCTGetStoragePathForMigration()
{
BOOL isDir;
NSString *oldStoragePath = RCTCreateStorageDirectoryPath_deprecated(RCTOldStorageDirectory);
NSString *expoStoragePath = RCTCreateStorageDirectoryPath_deprecated(RCTExpoStorageDirectory);
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL oldStorageDirectoryExists =
[fileManager fileExistsAtPath:oldStoragePath isDirectory:&isDir] && isDir;
BOOL expoStorageDirectoryExists =
[fileManager fileExistsAtPath:expoStoragePath isDirectory:&isDir] && isDir;
// Check if both the old storage directory and Expo storage directory exist
if (oldStorageDirectoryExists && expoStorageDirectoryExists) {
// If the old storage has been modified more recently than Expo storage, then clear Expo
// storage. Otherwise, clear the old storage.
if ([RCTManifestModificationDate(RCTCreateManifestFilePath(oldStoragePath))
compare:RCTManifestModificationDate(RCTCreateManifestFilePath(expoStoragePath))] ==
NSOrderedDescending) {
RCTStorageDirectoryCleanupOld(expoStoragePath);
return oldStoragePath;
} else {
RCTStorageDirectoryCleanupOld(oldStoragePath);
return expoStoragePath;
}
} else if (oldStorageDirectoryExists) {
return oldStoragePath;
} else if (expoStorageDirectoryExists) {
return expoStoragePath;
} else {
return nil;
}
}
/**
* This check is added to make sure that anyone coming from pre-1.2.2 does not lose cached data.
* Check that data is migrated from the old location to the new location
* fromStorageDirectory: the directory where the older data lives
* toStorageDirectory: the directory where the new data should live
* shouldCleanupOldDirectoryAndOverwriteNewDirectory: YES if we should delete the old directory's
* contents and overwrite the new directory's contents during the migration to the new directory
*/
static void
RCTStorageDirectoryMigrationCheck(NSString *fromStorageDirectory,
NSString *toStorageDirectory,
BOOL shouldCleanupOldDirectoryAndOverwriteNewDirectory)
{
NSError *error;
BOOL isDir;
NSFileManager *fileManager = [NSFileManager defaultManager];
// If the old directory exists, it means we may need to migrate old data to the new directory
if ([fileManager fileExistsAtPath:fromStorageDirectory isDirectory:&isDir] && isDir) {
// Check if the new storage directory location already exists
if ([fileManager fileExistsAtPath:toStorageDirectory]) {
// If new storage location exists, check if the new storage has been modified sooner in
// which case we may want to cleanup the old location
if ([RCTManifestModificationDate(RCTCreateManifestFilePath(toStorageDirectory))
compare:RCTManifestModificationDate(
RCTCreateManifestFilePath(fromStorageDirectory))] == 1) {
// If new location has been modified more recently, simply clean out old data
if (shouldCleanupOldDirectoryAndOverwriteNewDirectory) {
RCTStorageDirectoryCleanupOld(fromStorageDirectory);
}
} else if (shouldCleanupOldDirectoryAndOverwriteNewDirectory) {
// If old location has been modified more recently, remove new storage and migrate
if (![fileManager removeItemAtPath:toStorageDirectory error:&error]) {
RCTStorageDirectoryMigrationLogError(
@"Failed to remove new storage directory during migration", error);
} else {
RCTStorageDirectoryMigrate(fromStorageDirectory,
toStorageDirectory,
shouldCleanupOldDirectoryAndOverwriteNewDirectory);
}
}
} else {
// If new storage location doesn't exist, migrate data
RCTStorageDirectoryMigrate(fromStorageDirectory,
toStorageDirectory,
shouldCleanupOldDirectoryAndOverwriteNewDirectory);
}
}
}
#pragma mark - RNCAsyncStorage
@implementation RNCAsyncStorage {
BOOL _haveSetup;
// The manifest is a dictionary of all keys with small values inlined. Null values indicate
// values that are stored in separate files (as opposed to nil values which don't exist). The
// manifest is read off disk at startup, and written to disk after all mutations.
NSMutableDictionary<NSString *, NSString *> *_manifest;
}
+ (BOOL)requiresMainQueueSetup
{
return NO;
}
- (instancetype)init
{
if (!(self = [super init])) {
return nil;
}
// Get the path to any old storage directory that needs to be migrated. If multiple exist,
// the oldest are removed and the most recently modified is returned.
NSString *oldStoragePath = RCTGetStoragePathForMigration();
if (oldStoragePath != nil) {
// Migrate our deprecated path "Documents/.../RNCAsyncLocalStorage_V1" or
// "Documents/.../RCTAsyncLocalStorage" to "Documents/.../RCTAsyncLocalStorage_V1"
RCTStorageDirectoryMigrationCheck(
oldStoragePath, RCTCreateStorageDirectoryPath_deprecated(RCTStorageDirectory), YES);
}
// Migrate what's in "Documents/.../RCTAsyncLocalStorage_V1" to
// "Application Support/[bundleID]/RCTAsyncLocalStorage_V1"
RCTStorageDirectoryMigrationCheck(RCTCreateStorageDirectoryPath_deprecated(RCTStorageDirectory),
RCTCreateStorageDirectoryPath(RCTStorageDirectory),
NO);
return self;
}
RCT_EXPORT_MODULE()
- (dispatch_queue_t)methodQueue
{
return RCTGetMethodQueue();
}
- (void)clearAllData
{
dispatch_async(RCTGetMethodQueue(), ^{
[self->_manifest removeAllObjects];
[RCTGetCache() removeAllObjects];
RCTDeleteStorageDirectory();
});
}
+ (void)clearAllData
{
dispatch_async(RCTGetMethodQueue(), ^{
[RCTGetCache() removeAllObjects];
RCTDeleteStorageDirectory();
});
}
- (void)invalidate
{
if (_clearOnInvalidate) {
[RCTGetCache() removeAllObjects];
RCTDeleteStorageDirectory();
}
_clearOnInvalidate = NO;
[_manifest removeAllObjects];
_haveSetup = NO;
}
- (BOOL)isValid
{
return _haveSetup;
}
- (void)dealloc
{
[self invalidate];
}
- (NSString *)_filePathForKey:(NSString *)key
{
NSString *safeFileName = RCTMD5Hash(key);
return [RCTGetStorageDirectory() stringByAppendingPathComponent:safeFileName];
}
- (NSDictionary *)_ensureSetup
{
RCTAssertThread(RCTGetMethodQueue(), @"Must be executed on storage thread");
NSError *error = nil;
if (!RCTHasCreatedStorageDirectory) {
_createStorageDirectory(RCTGetStorageDirectory(), &error);
if (error) {
return RCTMakeError(@"Failed to create storage directory.", error, nil);
}
RCTHasCreatedStorageDirectory = YES;
}
if (!_haveSetup) {
// iCloud backup exclusion
NSNumber *isExcludedFromBackup =
[[NSBundle mainBundle] objectForInfoDictionaryKey:@"RCTAsyncStorageExcludeFromBackup"];
if (isExcludedFromBackup == nil) {
// by default, we want to exclude AsyncStorage data from backup
isExcludedFromBackup = @YES;
}
RCTAsyncStorageSetExcludedFromBackup(RCTCreateStorageDirectoryPath(RCTStorageDirectory),
isExcludedFromBackup);
NSDictionary *errorOut = nil;
NSString *serialized = RCTReadFile(RCTCreateStorageDirectoryPath(RCTGetManifestFilePath()),
RCTManifestFileName,
&errorOut);
if (!serialized) {
if (errorOut) {
// We cannot simply create a new manifest in case the file does exist but we have no
// access to it. This can happen when data protection is enabled for the app and we
// are trying to read the manifest while the device is locked. (The app can be
// started by the system even if the device is locked due to e.g. a geofence event.)
RCTLogError(
@"Could not open the existing manifest, perhaps data protection is "
@"enabled?\n\n%@",
errorOut);
return errorOut;
} else {
// We can get nil without errors only when the file does not exist.
RCTLogTrace(@"Manifest does not exist - creating a new one.\n\n%@", errorOut);
_manifest = [NSMutableDictionary new];
}
} else {
_manifest = RCTJSONParseMutable(serialized, &error);
if (!_manifest) {
RCTLogError(@"Failed to parse manifest - creating a new one.\n\n%@", error);
_manifest = [NSMutableDictionary new];
}
}
_haveSetup = YES;
}
return nil;
}
- (NSDictionary *)_writeManifest:(NSMutableArray<NSDictionary *> **)errors
{
NSError *error;
NSString *serialized = RCTJSONStringify(_manifest, &error);
[serialized writeToFile:RCTCreateStorageDirectoryPath(RCTGetManifestFilePath())
atomically:YES
encoding:NSUTF8StringEncoding
error:&error];
NSDictionary *errorOut;
if (error) {
errorOut = RCTMakeError(@"Failed to write manifest file.", error, nil);
RCTAppendError(errorOut, errors);
}
return errorOut;
}
- (NSDictionary *)_appendItemForKey:(NSString *)key
toArray:(NSMutableArray<NSArray<NSString *> *> *)result
{
NSDictionary *errorOut = RCTErrorForKey(key);
if (errorOut) {
return errorOut;
}
NSString *value = [self _getValueForKey:key errorOut:&errorOut];
[result addObject:@[key, RCTNullIfNil(value)]]; // Insert null if missing or failure.
return errorOut;
}
- (NSString *)_getValueForKey:(NSString *)key errorOut:(NSDictionary **)errorOut
{
NSString *value =
_manifest[key]; // nil means missing, null means there may be a data file, else: NSString
if (value == (id)kCFNull) {
value = [RCTGetCache() objectForKey:key];
if (!value) {
NSString *filePath = [self _filePathForKey:key];
value = RCTReadFile(filePath, key, errorOut);
if (value) {
[RCTGetCache() setObject:value forKey:key cost:value.length];
} else {
// file does not exist after all, so remove from manifest (no need to save
// manifest immediately though, as cost of checking again next time is negligible)
[_manifest removeObjectForKey:key];
}
}
}
return value;
}
- (NSDictionary *)_writeEntry:(NSArray<NSString *> *)entry changedManifest:(BOOL *)changedManifest
{
if (entry.count != 2) {
return RCTMakeAndLogError(
@"Entries must be arrays of the form [key: string, value: string], got: ", entry, nil);
}
NSString *key = entry[0];
NSDictionary *errorOut = RCTErrorForKey(key);
if (errorOut) {
return errorOut;
}
NSString *value = entry[1];
NSString *filePath = [self _filePathForKey:key];
NSError *error;
if (value.length <= RCTInlineValueThreshold) {
if (_manifest[key] == (id)kCFNull) {
// If the value already existed but wasn't inlined, remove the old file.
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
[RCTGetCache() removeObjectForKey:key];
}
*changedManifest = YES;
_manifest[key] = value;
return nil;
}
[value writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
[RCTGetCache() setObject:value forKey:key cost:value.length];
if (error) {
errorOut = RCTMakeError(@"Failed to write value.", error, @{@"key": key});
} else if (_manifest[key] != (id)kCFNull) {
*changedManifest = YES;
_manifest[key] = (id)kCFNull;
}
return errorOut;
}
- (void)_multiGet:(NSArray<NSString *> *)keys
callback:(RCTResponseSenderBlock)callback
getter:(NSString * (^)(NSUInteger i, NSString *key, NSDictionary **errorOut))getValue
{
NSMutableArray<NSDictionary *> *errors;
NSMutableArray<NSArray<NSString *> *> *result = [NSMutableArray arrayWithCapacity:keys.count];
for (NSUInteger i = 0; i < keys.count; ++i) {
NSString *key = keys[i];
id keyError;
id value = getValue(i, key, &keyError);
[result addObject:@[key, RCTNullIfNil(value)]];
RCTAppendError(keyError, &errors);
}
callback(@[RCTNullIfNil(errors), result]);
}
- (BOOL)_passthroughDelegate
{
return
[self.delegate respondsToSelector:@selector(isPassthrough)] && self.delegate.isPassthrough;
}
#pragma mark - Exported JS Functions
// clang-format off
RCT_EXPORT_METHOD(multiGet:(NSArray<NSString *> *)keys
callback:(RCTResponseSenderBlock)callback)
// clang-format on
{
if (self.delegate != nil) {
[self.delegate
valuesForKeys:keys
completion:^(NSArray<id<NSObject>> *valuesOrErrors) {
[self _multiGet:keys
callback:callback
getter:^NSString *(NSUInteger i, NSString *key, NSDictionary **errorOut) {
id valueOrError = valuesOrErrors[i];
if ([valueOrError isKindOfClass:[NSError class]]) {
NSError *error = (NSError *)valueOrError;
NSDictionary *extraData = @{@"key": RCTNullIfNil(key)};
*errorOut =
RCTMakeError(error.localizedDescription, error, extraData);
return nil;
} else {
return [valueOrError isKindOfClass:[NSString class]]
? (NSString *)valueOrError
: nil;
}
}];
}];
if (![self _passthroughDelegate]) {
return;
}
}
NSDictionary *errorOut = [self _ensureSetup];
if (errorOut) {
callback(@[@[errorOut], (id)kCFNull]);
return;
}
[self _multiGet:keys
callback:callback
getter:^(NSUInteger i, NSString *key, NSDictionary **errorOut) {
return [self _getValueForKey:key errorOut:errorOut];
}];
}
// clang-format off
RCT_EXPORT_METHOD(multiSet:(NSArray<NSArray<NSString *> *> *)kvPairs
callback:(RCTResponseSenderBlock)callback)
// clang-format on
{
if (self.delegate != nil) {
NSMutableArray<NSString *> *keys = [NSMutableArray arrayWithCapacity:kvPairs.count];
NSMutableArray<NSString *> *values = [NSMutableArray arrayWithCapacity:kvPairs.count];
for (NSArray<NSString *> *entry in kvPairs) {
[keys addObject:entry[0]];
[values addObject:entry[1]];
}
[self.delegate setValues:values
forKeys:keys
completion:^(NSArray<id<NSObject>> *results) {
NSArray<NSDictionary *> *errors = RCTMakeErrors(results);
callback(@[RCTNullIfNil(errors)]);
}];
if (![self _passthroughDelegate]) {
return;
}
}
NSDictionary *errorOut = [self _ensureSetup];
if (errorOut) {
callback(@[@[errorOut]]);
return;
}
BOOL changedManifest = NO;
NSMutableArray<NSDictionary *> *errors;
for (NSArray<NSString *> *entry in kvPairs) {
NSDictionary *keyError = [self _writeEntry:entry changedManifest:&changedManifest];
RCTAppendError(keyError, &errors);
}
if (changedManifest) {
[self _writeManifest:&errors];
}
callback(@[RCTNullIfNil(errors)]);
}
// clang-format off
RCT_EXPORT_METHOD(multiMerge:(NSArray<NSArray<NSString *> *> *)kvPairs
callback:(RCTResponseSenderBlock)callback)
// clang-format on
{
if (self.delegate != nil) {
NSMutableArray<NSString *> *keys = [NSMutableArray arrayWithCapacity:kvPairs.count];
NSMutableArray<NSString *> *values = [NSMutableArray arrayWithCapacity:kvPairs.count];
for (NSArray<NSString *> *entry in kvPairs) {
[keys addObject:entry[0]];
[values addObject:entry[1]];
}
[self.delegate mergeValues:values
forKeys:keys
completion:^(NSArray<id<NSObject>> *results) {
NSArray<NSDictionary *> *errors = RCTMakeErrors(results);
callback(@[RCTNullIfNil(errors)]);
}];
if (![self _passthroughDelegate]) {
return;
}
}
NSDictionary *errorOut = [self _ensureSetup];
if (errorOut) {
callback(@[@[errorOut]]);
return;
}
BOOL changedManifest = NO;
NSMutableArray<NSDictionary *> *errors;
for (__strong NSArray<NSString *> *entry in kvPairs) {
NSDictionary *keyError;
NSString *value = [self _getValueForKey:entry[0] errorOut:&keyError];
if (!keyError) {
if (value) {
NSError *jsonError;
NSMutableDictionary *mergedVal = RCTJSONParseMutable(value, &jsonError);
if (RCTMergeRecursive(mergedVal, RCTJSONParse(entry[1], &jsonError))) {
entry = @[entry[0], RCTNullIfNil(RCTJSONStringify(mergedVal, NULL))];
}
if (jsonError) {
keyError = RCTJSErrorFromNSError(jsonError);
}
}
if (!keyError) {
keyError = [self _writeEntry:entry changedManifest:&changedManifest];
}
}
RCTAppendError(keyError, &errors);
}
if (changedManifest) {
[self _writeManifest:&errors];
}
callback(@[RCTNullIfNil(errors)]);
}
// clang-format off
RCT_EXPORT_METHOD(multiRemove:(NSArray<NSString *> *)keys
callback:(RCTResponseSenderBlock)callback)
// clang-format on
{
if (self.delegate != nil) {
[self.delegate removeValuesForKeys:keys
completion:^(NSArray<id<NSObject>> *results) {
NSArray<NSDictionary *> *errors = RCTMakeErrors(results);
callback(@[RCTNullIfNil(errors)]);
}];
if (![self _passthroughDelegate]) {
return;
}
}
NSDictionary *errorOut = [self _ensureSetup];
if (errorOut) {
callback(@[@[errorOut]]);
return;
}
NSMutableArray<NSDictionary *> *errors;
BOOL changedManifest = NO;
for (NSString *key in keys) {
NSDictionary *keyError = RCTErrorForKey(key);
if (!keyError) {
if (_manifest[key] == (id)kCFNull) {
NSString *filePath = [self _filePathForKey:key];
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
[RCTGetCache() removeObjectForKey:key];
}
if (_manifest[key]) {
changedManifest = YES;
[_manifest removeObjectForKey:key];
}
}
RCTAppendError(keyError, &errors);
}
if (changedManifest) {
[self _writeManifest:&errors];
}
callback(@[RCTNullIfNil(errors)]);
}
// clang-format off
RCT_EXPORT_METHOD(clear:(RCTResponseSenderBlock)callback)
// clang-format on
{
if (self.delegate != nil) {
[self.delegate removeAllValues:^(NSError *error) {
NSDictionary *result = nil;
if (error != nil) {
result = RCTMakeError(error.localizedDescription, error, nil);
}
callback(@[RCTNullIfNil(result)]);
}];
return;
}
[_manifest removeAllObjects];
[RCTGetCache() removeAllObjects];
NSDictionary *error = RCTDeleteStorageDirectory();
callback(@[RCTNullIfNil(error)]);
}
// clang-format off
RCT_EXPORT_METHOD(getAllKeys:(RCTResponseSenderBlock)callback)
// clang-format on
{
if (self.delegate != nil) {
[self.delegate allKeys:^(NSArray<id<NSObject>> *keys) {
callback(@[(id)kCFNull, keys]);
}];
if (![self _passthroughDelegate]) {
return;
}
}
NSDictionary *errorOut = [self _ensureSetup];
if (errorOut) {
callback(@[errorOut, (id)kCFNull]);
} else {
callback(@[(id)kCFNull, _manifest.allKeys]);
}
}
#if RCT_NEW_ARCH_ENABLED
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
(const facebook::react::ObjCTurboModule::InitParams &)params
{
return std::make_shared<facebook::react::NativeAsyncStorageModuleSpecJSI>(params);
}
#endif
@end