-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
RCNConfigDBManager.m
1302 lines (1169 loc) · 49.9 KB
/
RCNConfigDBManager.m
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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2019 Google
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import <sqlite3.h>
#import "FirebaseRemoteConfig/Sources/RCNConfigDBManager.h"
#import "FirebaseRemoteConfig/Sources/RCNConfigDefines.h"
#import "FirebaseRemoteConfig/Sources/RCNConfigValue_Internal.h"
#import "FirebaseCore/Extension/FirebaseCoreInternal.h"
/// Using macro for securely preprocessing string concatenation in query before runtime.
#define RCNTableNameMain "main"
#define RCNTableNameMainActive "main_active"
#define RCNTableNameMainDefault "main_default"
#define RCNTableNameMetadataDeprecated "fetch_metadata"
#define RCNTableNameMetadata "fetch_metadata_v2"
#define RCNTableNameInternalMetadata "internal_metadata"
#define RCNTableNameExperiment "experiment"
#define RCNTableNamePersonalization "personalization"
#define RCNTableNameRollout "rollout"
static BOOL gIsNewDatabase;
/// SQLite file name in versions 0, 1 and 2.
static NSString *const RCNDatabaseName = @"RemoteConfig.sqlite3";
/// The storage sub-directory that the Remote Config database resides in.
static NSString *const RCNRemoteConfigStorageSubDirectory = @"Google/RemoteConfig";
/// Remote Config database path for deprecated V0 version.
static NSString *RemoteConfigPathForOldDatabaseV0(void) {
NSArray *dirPaths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = dirPaths.firstObject;
return [docPath stringByAppendingPathComponent:RCNDatabaseName];
}
/// Remote Config database path for current database.
static NSString *RemoteConfigPathForDatabase(void) {
#if TARGET_OS_TV
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
#else
NSArray *dirPaths =
NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
#endif
NSString *storageDirPath = dirPaths.firstObject;
NSArray *components = @[ storageDirPath, RCNRemoteConfigStorageSubDirectory, RCNDatabaseName ];
return [NSString pathWithComponents:components];
}
static BOOL RemoteConfigAddSkipBackupAttributeToItemAtPath(NSString *filePathString) {
NSURL *URL = [NSURL fileURLWithPath:filePathString];
assert([[NSFileManager defaultManager] fileExistsAtPath:[URL path]]);
NSError *error = nil;
BOOL success = [URL setResourceValue:[NSNumber numberWithBool:YES]
forKey:NSURLIsExcludedFromBackupKey
error:&error];
if (!success) {
FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000017", @"Error excluding %@ from backup %@.",
[URL lastPathComponent], error);
}
return success;
}
static BOOL RemoteConfigCreateFilePathIfNotExist(NSString *filePath) {
if (!filePath || !filePath.length) {
FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000018",
@"Failed to create subdirectory for an empty file path.");
return NO;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:filePath]) {
gIsNewDatabase = YES;
NSError *error;
[fileManager createDirectoryAtPath:[filePath stringByDeletingLastPathComponent]
withIntermediateDirectories:YES
attributes:nil
error:&error];
if (error) {
FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000019",
@"Failed to create subdirectory for database file: %@.", error);
return NO;
}
}
return YES;
}
static NSArray *RemoteConfigMetadataTableColumnsInOrder(void) {
return @[
RCNKeyBundleIdentifier, RCNKeyNamespace, RCNKeyFetchTime, RCNKeyDigestPerNamespace,
RCNKeyDeviceContext, RCNKeyAppContext, RCNKeySuccessFetchTime, RCNKeyFailureFetchTime,
RCNKeyLastFetchStatus, RCNKeyLastFetchError, RCNKeyLastApplyTime, RCNKeyLastSetDefaultsTime
];
}
@interface RCNConfigDBManager () {
/// Database storing all the config information.
sqlite3 *_database;
/// Serial queue for database read/write operations.
dispatch_queue_t _databaseOperationQueue;
}
@end
@implementation RCNConfigDBManager
+ (instancetype)sharedInstance {
static dispatch_once_t onceToken;
static RCNConfigDBManager *sharedInstance;
dispatch_once(&onceToken, ^{
sharedInstance = [[RCNConfigDBManager alloc] init];
});
return sharedInstance;
}
/// Returns the current version of the Remote Config database.
+ (NSString *)remoteConfigPathForDatabase {
return RemoteConfigPathForDatabase();
}
- (instancetype)init {
self = [super init];
if (self) {
_databaseOperationQueue =
dispatch_queue_create("com.google.GoogleConfigService.database", DISPATCH_QUEUE_SERIAL);
[self createOrOpenDatabase];
}
return self;
}
#pragma mark - database
- (void)migrateV1NamespaceToV2Namespace {
for (int table = 0; table < 3; table++) {
NSString *tableName = @"" RCNTableNameMain;
switch (table) {
case 1:
tableName = @"" RCNTableNameMainActive;
break;
case 2:
tableName = @"" RCNTableNameMainDefault;
break;
default:
break;
}
NSString *SQLString = [NSString
stringWithFormat:@"SELECT namespace FROM %@ WHERE namespace NOT LIKE '%%:%%'", tableName];
const char *SQL = [SQLString UTF8String];
sqlite3_stmt *statement = [self prepareSQL:SQL];
if (!statement) {
return;
}
NSMutableArray<NSString *> *namespaceArray = [[NSMutableArray alloc] init];
while (sqlite3_step(statement) == SQLITE_ROW) {
NSString *configNamespace =
[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
[namespaceArray addObject:configNamespace];
}
sqlite3_finalize(statement);
// Update.
for (NSString *namespaceToUpdate in namespaceArray) {
NSString *newNamespace =
[NSString stringWithFormat:@"%@:%@", namespaceToUpdate, kFIRDefaultAppName];
NSString *updateSQLString =
[NSString stringWithFormat:@"UPDATE %@ SET namespace = ? WHERE namespace = ?", tableName];
const char *updateSQL = [updateSQLString UTF8String];
sqlite3_stmt *updateStatement = [self prepareSQL:updateSQL];
if (!updateStatement) {
return;
}
NSArray<NSString *> *updateParams = @[ newNamespace, namespaceToUpdate ];
[self bindStringsToStatement:updateStatement stringArray:updateParams];
int result = sqlite3_step(updateStatement);
if (result != SQLITE_DONE) {
[self logErrorWithSQL:SQL finalizeStatement:updateStatement returnValue:NO];
return;
}
sqlite3_finalize(updateStatement);
}
}
}
- (void)createOrOpenDatabase {
__weak RCNConfigDBManager *weakSelf = self;
dispatch_async(_databaseOperationQueue, ^{
RCNConfigDBManager *strongSelf = weakSelf;
if (!strongSelf) {
return;
}
NSString *oldV0DBPath = RemoteConfigPathForOldDatabaseV0();
// Backward Compatibility
if ([[NSFileManager defaultManager] fileExistsAtPath:oldV0DBPath]) {
FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000009",
@"Old database V0 exists, removed it and replace with the new one.");
[strongSelf removeDatabase:oldV0DBPath];
}
NSString *dbPath = [RCNConfigDBManager remoteConfigPathForDatabase];
FIRLogInfo(kFIRLoggerRemoteConfig, @"I-RCN000062", @"Loading database at path %@", dbPath);
const char *databasePath = dbPath.UTF8String;
// Create or open database path.
if (!RemoteConfigCreateFilePathIfNotExist(dbPath)) {
return;
}
int flags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE |
SQLITE_OPEN_FILEPROTECTION_COMPLETEUNTILFIRSTUSERAUTHENTICATION |
SQLITE_OPEN_FULLMUTEX;
if (sqlite3_open_v2(databasePath, &strongSelf->_database, flags, NULL) == SQLITE_OK) {
// Always try to create table if not exists for backward compatibility.
if (![strongSelf createTableSchema]) {
// Remove database before fail.
[strongSelf removeDatabase:dbPath];
FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000010", @"Failed to create table.");
// Create a new database if existing database file is corrupted.
if (!RemoteConfigCreateFilePathIfNotExist(dbPath)) {
return;
}
if (sqlite3_open_v2(databasePath, &strongSelf->_database, flags, NULL) == SQLITE_OK) {
if (![strongSelf createTableSchema]) {
// Remove database before fail.
[strongSelf removeDatabase:dbPath];
// If it failed again, there's nothing we can do here.
FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000010", @"Failed to create table.");
} else {
// Exclude the app data used from iCloud backup.
RemoteConfigAddSkipBackupAttributeToItemAtPath(dbPath);
}
} else {
[strongSelf logDatabaseError];
}
} else {
// DB file already exists. Migrate any V1 namespace column entries to V2 fully qualified
// 'namespace:FIRApp' entries.
[self migrateV1NamespaceToV2Namespace];
// Exclude the app data used from iCloud backup.
RemoteConfigAddSkipBackupAttributeToItemAtPath(dbPath);
}
} else {
[strongSelf logDatabaseError];
}
});
}
- (BOOL)createTableSchema {
RCN_MUST_NOT_BE_MAIN_THREAD();
static const char *createTableMain =
"create TABLE IF NOT EXISTS " RCNTableNameMain
" (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT, key TEXT, value BLOB)";
static const char *createTableMainActive =
"create TABLE IF NOT EXISTS " RCNTableNameMainActive
" (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT, key TEXT, value BLOB)";
static const char *createTableMainDefault =
"create TABLE IF NOT EXISTS " RCNTableNameMainDefault
" (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT, key TEXT, value BLOB)";
static const char *createTableMetadata =
"create TABLE IF NOT EXISTS " RCNTableNameMetadata
" (_id INTEGER PRIMARY KEY, bundle_identifier TEXT, namespace TEXT,"
" fetch_time INTEGER, digest_per_ns BLOB, device_context BLOB, app_context BLOB, "
"success_fetch_time BLOB, failure_fetch_time BLOB, last_fetch_status INTEGER, "
"last_fetch_error INTEGER, last_apply_time INTEGER, last_set_defaults_time INTEGER)";
static const char *createTableInternalMetadata =
"create TABLE IF NOT EXISTS " RCNTableNameInternalMetadata
" (_id INTEGER PRIMARY KEY, key TEXT, value BLOB)";
static const char *createTableExperiment = "create TABLE IF NOT EXISTS " RCNTableNameExperiment
" (_id INTEGER PRIMARY KEY, key TEXT, value BLOB)";
static const char *createTablePersonalization =
"create TABLE IF NOT EXISTS " RCNTableNamePersonalization
" (_id INTEGER PRIMARY KEY, key INTEGER, value BLOB)";
static const char *createTableRollout = "create TABLE IF NOT EXISTS " RCNTableNameRollout
" (_id INTEGER PRIMARY KEY, key TEXT, value BLOB)";
return [self executeQuery:createTableMain] && [self executeQuery:createTableMainActive] &&
[self executeQuery:createTableMainDefault] && [self executeQuery:createTableMetadata] &&
[self executeQuery:createTableInternalMetadata] &&
[self executeQuery:createTableExperiment] &&
[self executeQuery:createTablePersonalization] && [self executeQuery:createTableRollout];
}
- (void)removeDatabaseOnDatabaseQueueAtPath:(NSString *)path {
__weak RCNConfigDBManager *weakSelf = self;
dispatch_sync(_databaseOperationQueue, ^{
RCNConfigDBManager *strongSelf = weakSelf;
if (!strongSelf) {
return;
}
if (sqlite3_close(strongSelf->_database) != SQLITE_OK) {
[self logDatabaseError];
}
strongSelf->_database = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
if (![fileManager removeItemAtPath:path error:&error]) {
FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000011",
@"Failed to remove database at path %@ for error %@.", path, error);
}
});
}
- (void)removeDatabase:(NSString *)path {
if (sqlite3_close(_database) != SQLITE_OK) {
[self logDatabaseError];
}
_database = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
if (![fileManager removeItemAtPath:path error:&error]) {
FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000011",
@"Failed to remove database at path %@ for error %@.", path, error);
}
}
#pragma mark - execute
- (BOOL)executeQuery:(const char *)SQL {
RCN_MUST_NOT_BE_MAIN_THREAD();
char *error;
if (sqlite3_exec(_database, SQL, nil, nil, &error) != SQLITE_OK) {
FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000012", @"Failed to execute query with error %s.",
error);
return NO;
}
return YES;
}
#pragma mark - insert
- (void)insertMetadataTableWithValues:(NSDictionary *)columnNameToValue
completionHandler:(RCNDBCompletion)handler {
__weak RCNConfigDBManager *weakSelf = self;
dispatch_async(_databaseOperationQueue, ^{
BOOL success = [weakSelf insertMetadataTableWithValues:columnNameToValue];
if (handler) {
dispatch_async(dispatch_get_main_queue(), ^{
handler(success, nil);
});
}
});
}
- (BOOL)insertMetadataTableWithValues:(NSDictionary *)columnNameToValue {
RCN_MUST_NOT_BE_MAIN_THREAD();
static const char *SQL =
"INSERT INTO " RCNTableNameMetadata
" (bundle_identifier, namespace, fetch_time, digest_per_ns, device_context, "
"app_context, success_fetch_time, failure_fetch_time, last_fetch_status, "
"last_fetch_error, last_apply_time, last_set_defaults_time) values (?, ?, ?, ?, ?, ?, "
"?, ?, ?, ?, ?, ?)";
sqlite3_stmt *statement = [self prepareSQL:SQL];
if (!statement) {
[self logErrorWithSQL:SQL finalizeStatement:nil returnValue:NO];
return NO;
}
NSArray *columns = RemoteConfigMetadataTableColumnsInOrder();
int index = 0;
for (NSString *columnName in columns) {
if ([columnName isEqualToString:RCNKeyBundleIdentifier] ||
[columnName isEqualToString:RCNKeyNamespace]) {
NSString *value = columnNameToValue[columnName];
if (![self bindStringToStatement:statement index:++index string:value]) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
} else if ([columnName isEqualToString:RCNKeyFetchTime] ||
[columnName isEqualToString:RCNKeyLastApplyTime] ||
[columnName isEqualToString:RCNKeyLastSetDefaultsTime]) {
double value = [columnNameToValue[columnName] doubleValue];
if (sqlite3_bind_double(statement, ++index, value) != SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
} else if ([columnName isEqualToString:RCNKeyLastFetchStatus] ||
[columnName isEqualToString:RCNKeyLastFetchError]) {
int value = [columnNameToValue[columnName] intValue];
if (sqlite3_bind_int(statement, ++index, value) != SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
} else {
NSData *data = columnNameToValue[columnName];
if (sqlite3_bind_blob(statement, ++index, data.bytes, (int)data.length, NULL) != SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
}
}
if (sqlite3_step(statement) != SQLITE_DONE) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
sqlite3_finalize(statement);
return YES;
}
- (void)insertMainTableWithValues:(NSArray *)values
fromSource:(RCNDBSource)source
completionHandler:(RCNDBCompletion)handler {
__weak RCNConfigDBManager *weakSelf = self;
dispatch_async(_databaseOperationQueue, ^{
BOOL success = [weakSelf insertMainTableWithValues:values fromSource:source];
if (handler) {
dispatch_async(dispatch_get_main_queue(), ^{
handler(success, nil);
});
}
});
}
- (BOOL)insertMainTableWithValues:(NSArray *)values fromSource:(RCNDBSource)source {
RCN_MUST_NOT_BE_MAIN_THREAD();
if (values.count != 4) {
FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000013",
@"Failed to insert config record. Wrong number of give parameters, current "
@"number is %ld, correct number is 4.",
(long)values.count);
return NO;
}
const char *SQL = "INSERT INTO " RCNTableNameMain
" (bundle_identifier, namespace, key, value) values (?, ?, ?, ?)";
if (source == RCNDBSourceDefault) {
SQL = "INSERT INTO " RCNTableNameMainDefault
" (bundle_identifier, namespace, key, value) values (?, ?, ?, ?)";
} else if (source == RCNDBSourceActive) {
SQL = "INSERT INTO " RCNTableNameMainActive
" (bundle_identifier, namespace, key, value) values (?, ?, ?, ?)";
}
sqlite3_stmt *statement = [self prepareSQL:SQL];
if (!statement) {
return NO;
}
NSString *aString = values[0];
if (![self bindStringToStatement:statement index:1 string:aString]) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
aString = values[1];
if (![self bindStringToStatement:statement index:2 string:aString]) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
aString = values[2];
if (![self bindStringToStatement:statement index:3 string:aString]) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
NSData *blobData = values[3];
if (sqlite3_bind_blob(statement, 4, blobData.bytes, (int)blobData.length, NULL) != SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
if (sqlite3_step(statement) != SQLITE_DONE) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
sqlite3_finalize(statement);
return YES;
}
- (void)insertInternalMetadataTableWithValues:(NSArray *)values
completionHandler:(RCNDBCompletion)handler {
__weak RCNConfigDBManager *weakSelf = self;
dispatch_async(_databaseOperationQueue, ^{
BOOL success = [weakSelf insertInternalMetadataWithValues:values];
if (handler) {
dispatch_async(dispatch_get_main_queue(), ^{
handler(success, nil);
});
}
});
}
- (BOOL)insertInternalMetadataWithValues:(NSArray *)values {
RCN_MUST_NOT_BE_MAIN_THREAD();
if (values.count != 2) {
return NO;
}
const char *SQL =
"INSERT OR REPLACE INTO " RCNTableNameInternalMetadata " (key, value) values (?, ?)";
sqlite3_stmt *statement = [self prepareSQL:SQL];
if (!statement) {
return NO;
}
NSString *aString = values[0];
if (![self bindStringToStatement:statement index:1 string:aString]) {
[self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
return NO;
}
NSData *blobData = values[1];
if (sqlite3_bind_blob(statement, 2, blobData.bytes, (int)blobData.length, NULL) != SQLITE_OK) {
[self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
return NO;
}
if (sqlite3_step(statement) != SQLITE_DONE) {
[self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
return NO;
}
sqlite3_finalize(statement);
return YES;
}
- (void)insertExperimentTableWithKey:(NSString *)key
value:(NSData *)serializedValue
completionHandler:(RCNDBCompletion)handler {
dispatch_async(_databaseOperationQueue, ^{
BOOL success = [self insertExperimentTableWithKey:key value:serializedValue];
if (handler) {
dispatch_async(dispatch_get_main_queue(), ^{
handler(success, nil);
});
}
});
}
- (BOOL)insertExperimentTableWithKey:(NSString *)key value:(NSData *)dataValue {
if ([key isEqualToString:@RCNExperimentTableKeyMetadata]) {
return [self updateExperimentMetadata:dataValue];
}
RCN_MUST_NOT_BE_MAIN_THREAD();
const char *SQL = "INSERT INTO " RCNTableNameExperiment " (key, value) values (?, ?)";
sqlite3_stmt *statement = [self prepareSQL:SQL];
if (!statement) {
return NO;
}
if (![self bindStringToStatement:statement index:1 string:key]) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
if (sqlite3_bind_blob(statement, 2, dataValue.bytes, (int)dataValue.length, NULL) != SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
if (sqlite3_step(statement) != SQLITE_DONE) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
sqlite3_finalize(statement);
return YES;
}
- (BOOL)updateExperimentMetadata:(NSData *)dataValue {
RCN_MUST_NOT_BE_MAIN_THREAD();
const char *SQL = "INSERT OR REPLACE INTO " RCNTableNameExperiment
" (_id, key, value) values ((SELECT _id from " RCNTableNameExperiment
" WHERE key = ?), ?, ?)";
sqlite3_stmt *statement = [self prepareSQL:SQL];
if (!statement) {
return NO;
}
if (![self bindStringToStatement:statement index:1 string:@RCNExperimentTableKeyMetadata]) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
if (![self bindStringToStatement:statement index:2 string:@RCNExperimentTableKeyMetadata]) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
if (sqlite3_bind_blob(statement, 3, dataValue.bytes, (int)dataValue.length, NULL) != SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
if (sqlite3_step(statement) != SQLITE_DONE) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
sqlite3_finalize(statement);
return YES;
}
- (BOOL)insertOrUpdatePersonalizationConfig:(NSDictionary *)dataValue
fromSource:(RCNDBSource)source {
RCN_MUST_NOT_BE_MAIN_THREAD();
NSError *error;
NSData *JSONPayload = [NSJSONSerialization dataWithJSONObject:dataValue
options:NSJSONWritingPrettyPrinted
error:&error];
if (!JSONPayload || error) {
FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000075",
@"Invalid Personalization payload to be serialized.");
}
const char *SQL = "INSERT OR REPLACE INTO " RCNTableNamePersonalization
" (_id, key, value) values ((SELECT _id from " RCNTableNamePersonalization
" WHERE key = ?), ?, ?)";
sqlite3_stmt *statement = [self prepareSQL:SQL];
if (!statement) {
return NO;
}
if (sqlite3_bind_int(statement, 1, (int)source) != SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
if (sqlite3_bind_int(statement, 2, (int)source) != SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
if (sqlite3_bind_blob(statement, 3, JSONPayload.bytes, (int)JSONPayload.length, NULL) !=
SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
if (sqlite3_step(statement) != SQLITE_DONE) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
sqlite3_finalize(statement);
return YES;
}
- (void)insertOrUpdateRolloutTableWithKey:(NSString *)key
value:(NSArray<NSDictionary *> *)metadataList
completionHandler:(RCNDBCompletion)handler {
dispatch_async(_databaseOperationQueue, ^{
BOOL success = [self insertOrUpdateRolloutTableWithKey:key value:metadataList];
if (handler) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
handler(success, nil);
});
}
});
}
- (BOOL)insertOrUpdateRolloutTableWithKey:(NSString *)key
value:(NSArray<NSDictionary *> *)arrayValue {
RCN_MUST_NOT_BE_MAIN_THREAD();
NSError *error;
NSData *dataValue = [NSJSONSerialization dataWithJSONObject:arrayValue
options:NSJSONWritingPrettyPrinted
error:&error];
const char *SQL =
"INSERT OR REPLACE INTO " RCNTableNameRollout
" (_id, key, value) values ((SELECT _id from " RCNTableNameRollout " WHERE key = ?), ?, ?)";
sqlite3_stmt *statement = [self prepareSQL:SQL];
if (!statement) {
return NO;
}
if (![self bindStringToStatement:statement index:1 string:key]) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
if (![self bindStringToStatement:statement index:2 string:key]) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
if (sqlite3_bind_blob(statement, 3, dataValue.bytes, (int)dataValue.length, NULL) != SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
if (sqlite3_step(statement) != SQLITE_DONE) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
sqlite3_finalize(statement);
return YES;
}
#pragma mark - update
- (void)updateMetadataWithOption:(RCNUpdateOption)option
namespace:(NSString *)namespace
values:(NSArray *)values
completionHandler:(RCNDBCompletion)handler {
dispatch_async(_databaseOperationQueue, ^{
BOOL success = [self updateMetadataTableWithOption:option namespace:namespace andValues:values];
if (handler) {
dispatch_async(dispatch_get_main_queue(), ^{
handler(success, nil);
});
}
});
}
- (BOOL)updateMetadataTableWithOption:(RCNUpdateOption)option
namespace:(NSString *)namespace
andValues:(NSArray *)values {
RCN_MUST_NOT_BE_MAIN_THREAD();
static const char *SQL =
"UPDATE " RCNTableNameMetadata " (last_fetch_status, last_fetch_error, last_apply_time, "
"last_set_defaults_time) values (?, ?, ?, ?) WHERE namespace = ?";
if (option == RCNUpdateOptionFetchStatus) {
SQL = "UPDATE " RCNTableNameMetadata
" SET last_fetch_status = ?, last_fetch_error = ? WHERE namespace = ?";
} else if (option == RCNUpdateOptionApplyTime) {
SQL = "UPDATE " RCNTableNameMetadata " SET last_apply_time = ? WHERE namespace = ?";
} else if (option == RCNUpdateOptionDefaultTime) {
SQL = "UPDATE " RCNTableNameMetadata " SET last_set_defaults_time = ? WHERE namespace = ?";
} else {
return NO;
}
sqlite3_stmt *statement = [self prepareSQL:SQL];
if (!statement) {
return NO;
}
int index = 0;
if ((option == RCNUpdateOptionApplyTime || option == RCNUpdateOptionDefaultTime) &&
values.count == 1) {
double value = [values[0] doubleValue];
if (sqlite3_bind_double(statement, ++index, value) != SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
} else if (option == RCNUpdateOptionFetchStatus && values.count == 2) {
int value = [values[0] intValue];
if (sqlite3_bind_int(statement, ++index, value) != SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
value = [values[1] intValue];
if (sqlite3_bind_int(statement, ++index, value) != SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
}
// bind namespace to query
if (sqlite3_bind_text(statement, ++index, [namespace UTF8String], -1, SQLITE_TRANSIENT) !=
SQLITE_OK) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
if (sqlite3_step(statement) != SQLITE_DONE) {
return [self logErrorWithSQL:SQL finalizeStatement:statement returnValue:NO];
}
sqlite3_finalize(statement);
return YES;
}
#pragma mark - read from DB
- (NSDictionary *)loadMetadataWithBundleIdentifier:(NSString *)bundleIdentifier
namespace:(NSString *)namespace {
__block NSDictionary *metadataTableResult;
__weak RCNConfigDBManager *weakSelf = self;
dispatch_sync(_databaseOperationQueue, ^{
metadataTableResult = [weakSelf loadMetadataTableWithBundleIdentifier:bundleIdentifier
namespace:namespace];
});
if (metadataTableResult) {
return metadataTableResult;
}
return [[NSDictionary alloc] init];
}
- (NSMutableDictionary *)loadMetadataTableWithBundleIdentifier:(NSString *)bundleIdentifier
namespace:(NSString *)namespace {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
const char *SQL =
"SELECT bundle_identifier, fetch_time, digest_per_ns, device_context, app_context, "
"success_fetch_time, failure_fetch_time , last_fetch_status, "
"last_fetch_error, last_apply_time, last_set_defaults_time FROM " RCNTableNameMetadata
" WHERE bundle_identifier = ? and namespace = ?";
sqlite3_stmt *statement = [self prepareSQL:SQL];
if (!statement) {
return nil;
}
NSArray *params = @[ bundleIdentifier, namespace ];
[self bindStringsToStatement:statement stringArray:params];
while (sqlite3_step(statement) == SQLITE_ROW) {
NSString *dbBundleIdentifier =
[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
if (dbBundleIdentifier && ![dbBundleIdentifier isEqualToString:bundleIdentifier]) {
FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000014",
@"Load Metadata from table error: Wrong package name %@, should be %@.",
dbBundleIdentifier, bundleIdentifier);
return nil;
}
double fetchTime = sqlite3_column_double(statement, 1);
NSData *digestPerNamespace = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 2)
length:sqlite3_column_bytes(statement, 2)];
NSData *deviceContext = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 3)
length:sqlite3_column_bytes(statement, 3)];
NSData *appContext = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 4)
length:sqlite3_column_bytes(statement, 4)];
NSData *successTimeDigest = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 5)
length:sqlite3_column_bytes(statement, 5)];
NSData *failureTimeDigest = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 6)
length:sqlite3_column_bytes(statement, 6)];
int lastFetchStatus = sqlite3_column_int(statement, 7);
int lastFetchFailReason = sqlite3_column_int(statement, 8);
double lastApplyTimestamp = sqlite3_column_double(statement, 9);
double lastSetDefaultsTimestamp = sqlite3_column_double(statement, 10);
NSError *error;
NSMutableDictionary *deviceContextDict = nil;
if (deviceContext) {
deviceContextDict = [NSJSONSerialization JSONObjectWithData:deviceContext
options:NSJSONReadingMutableContainers
error:&error];
}
NSMutableDictionary *appContextDict = nil;
if (appContext) {
appContextDict = [NSJSONSerialization JSONObjectWithData:appContext
options:NSJSONReadingMutableContainers
error:&error];
}
NSMutableDictionary<NSString *, id> *digestPerNamespaceDictionary = nil;
if (digestPerNamespace) {
digestPerNamespaceDictionary =
[NSJSONSerialization JSONObjectWithData:digestPerNamespace
options:NSJSONReadingMutableContainers
error:&error];
}
NSMutableArray *successTimes = nil;
if (successTimeDigest) {
successTimes = [NSJSONSerialization JSONObjectWithData:successTimeDigest
options:NSJSONReadingMutableContainers
error:&error];
}
NSMutableArray *failureTimes = nil;
if (failureTimeDigest) {
failureTimes = [NSJSONSerialization JSONObjectWithData:failureTimeDigest
options:NSJSONReadingMutableContainers
error:&error];
}
dict[RCNKeyBundleIdentifier] = bundleIdentifier;
dict[RCNKeyFetchTime] = @(fetchTime);
dict[RCNKeyDigestPerNamespace] = digestPerNamespaceDictionary;
dict[RCNKeyDeviceContext] = deviceContextDict;
dict[RCNKeyAppContext] = appContextDict;
dict[RCNKeySuccessFetchTime] = successTimes;
dict[RCNKeyFailureFetchTime] = failureTimes;
dict[RCNKeyLastFetchStatus] = @(lastFetchStatus);
dict[RCNKeyLastFetchError] = @(lastFetchFailReason);
dict[RCNKeyLastApplyTime] = @(lastApplyTimestamp);
dict[RCNKeyLastSetDefaultsTime] = @(lastSetDefaultsTimestamp);
break;
}
sqlite3_finalize(statement);
return dict;
}
- (void)loadExperimentWithCompletionHandler:(RCNDBCompletion)handler {
__weak RCNConfigDBManager *weakSelf = self;
dispatch_async(_databaseOperationQueue, ^{
RCNConfigDBManager *strongSelf = weakSelf;
if (!strongSelf) {
return;
}
NSMutableArray *experimentPayloads =
[strongSelf loadExperimentTableFromKey:@RCNExperimentTableKeyPayload];
if (!experimentPayloads) {
experimentPayloads = [[NSMutableArray alloc] init];
}
NSMutableDictionary *experimentMetadata;
NSMutableArray *experiments =
[strongSelf loadExperimentTableFromKey:@RCNExperimentTableKeyMetadata];
// There should be only one entry for experiment metadata.
if (experiments.count > 0) {
NSError *error;
experimentMetadata = [NSJSONSerialization JSONObjectWithData:experiments[0]
options:NSJSONReadingMutableContainers
error:&error];
}
if (!experimentMetadata) {
experimentMetadata = [[NSMutableDictionary alloc] init];
}
/// Load activated experiments payload.
NSMutableArray *activeExperimentPayloads =
[strongSelf loadExperimentTableFromKey:@RCNExperimentTableKeyActivePayload];
if (!activeExperimentPayloads) {
activeExperimentPayloads = [[NSMutableArray alloc] init];
}
if (handler) {
dispatch_async(dispatch_get_main_queue(), ^{
handler(
YES, @{
@RCNExperimentTableKeyPayload : [experimentPayloads copy],
@RCNExperimentTableKeyMetadata : [experimentMetadata copy],
/// Activated experiments only need ExperimentsDescriptions data, which
/// experimentPayloads contains.
@RCNExperimentTableKeyActivePayload : [activeExperimentPayloads copy]
});
});
}
});
}
- (NSMutableArray<NSData *> *)loadExperimentTableFromKey:(NSString *)key {
RCN_MUST_NOT_BE_MAIN_THREAD();
const char *SQL = "SELECT value FROM " RCNTableNameExperiment " WHERE key = ?";
sqlite3_stmt *statement = [self prepareSQL:SQL];
if (!statement) {
return nil;
}
NSArray *params = @[ key ];
[self bindStringsToStatement:statement stringArray:params];
NSMutableArray *results = [self loadValuesFromStatement:statement];
return results;
}
- (NSArray<NSDictionary *> *)loadRolloutTableFromKey:(NSString *)key {
RCN_MUST_NOT_BE_MAIN_THREAD();
const char *SQL = "SELECT value FROM " RCNTableNameRollout " WHERE key = ?";
sqlite3_stmt *statement = [self prepareSQL:SQL];
if (!statement) {
return nil;
}
NSArray *params = @[ key ];
[self bindStringsToStatement:statement stringArray:params];
NSMutableArray *results = [self loadValuesFromStatement:statement];
// There should be only one entry in this table.
if (results.count != 1) {
return nil;
}
NSArray *rollout;
// Convert from NSData to NSArray
if (results[0]) {
NSError *error;
rollout = [NSJSONSerialization JSONObjectWithData:results[0] options:0 error:&error];
if (!rollout) {
FIRLogError(kFIRLoggerRemoteConfig, @"I-RCN000011",
@"Failed to convert NSData to NSAarry for Rollout Metadata with error %@.",
error);
}
}
if (!rollout) {
rollout = [[NSArray alloc] init];
}
return rollout;
}
- (NSMutableArray *)loadValuesFromStatement:(sqlite3_stmt *)statement {
NSMutableArray *results = [[NSMutableArray alloc] init];
NSData *value;
while (sqlite3_step(statement) == SQLITE_ROW) {
value = [NSData dataWithBytes:(char *)sqlite3_column_blob(statement, 0)
length:sqlite3_column_bytes(statement, 0)];
if (value) {
[results addObject:value];
}
}
sqlite3_finalize(statement);
return results;
}
- (void)loadPersonalizationWithCompletionHandler:(RCNDBLoadCompletion)handler {
__weak RCNConfigDBManager *weakSelf = self;
dispatch_async(_databaseOperationQueue, ^{
RCNConfigDBManager *strongSelf = weakSelf;
if (!strongSelf) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
handler(NO, [NSMutableDictionary new], [NSMutableDictionary new], nil, nil);
});
return;
}
NSDictionary *activePersonalization;
NSData *personalizationResult = [strongSelf loadPersonalizationTableFromKey:RCNDBSourceActive];
// There should be only one entry for Personalization metadata.
if (personalizationResult) {
NSError *error;
activePersonalization = [NSJSONSerialization JSONObjectWithData:personalizationResult
options:0
error:&error];
}
if (!activePersonalization) {
activePersonalization = [[NSMutableDictionary alloc] init];
}
NSDictionary *fetchedPersonalization;
personalizationResult = [strongSelf loadPersonalizationTableFromKey:RCNDBSourceFetched];
// There should be only one entry for Personalization metadata.
if (personalizationResult) {
NSError *error;
fetchedPersonalization = [NSJSONSerialization JSONObjectWithData:personalizationResult
options:0
error:&error];
}
if (!fetchedPersonalization) {
fetchedPersonalization = [[NSMutableDictionary alloc] init];
}
if (handler) {