FIRMessagingRmqManager.m 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseMessaging/Sources/FIRMessagingRmqManager.h"
  17. #import <sqlite3.h>
  18. #import "FirebaseMessaging/Sources/FIRMessagingConstants.h"
  19. #import "FirebaseMessaging/Sources/FIRMessagingDefines.h"
  20. #import "FirebaseMessaging/Sources/FIRMessagingLogger.h"
  21. #import "FirebaseMessaging/Sources/FIRMessagingPersistentSyncMessage.h"
  22. #import "FirebaseMessaging/Sources/FIRMessagingUtilities.h"
  23. #import "FirebaseMessaging/Sources/NSError+FIRMessaging.h"
  24. #ifndef _FIRMessagingRmqLogAndExit
  25. #define _FIRMessagingRmqLogAndExit(stmt, return_value) \
  26. do { \
  27. [self logErrorAndFinalizeStatement:stmt]; \
  28. return return_value; \
  29. } while (0)
  30. #endif
  31. #ifndef FIRMessagingRmqLogAndReturn
  32. #define FIRMessagingRmqLogAndReturn(stmt) \
  33. do { \
  34. [self logErrorAndFinalizeStatement:stmt]; \
  35. return; \
  36. } while (0)
  37. #endif
  38. #ifndef FIRMessaging_MUST_NOT_BE_MAIN_THREAD
  39. #define FIRMessaging_MUST_NOT_BE_MAIN_THREAD() \
  40. do { \
  41. NSAssert(![NSThread isMainThread], @"Must not be executing on the main thread."); \
  42. } while (0);
  43. #endif
  44. // table names
  45. NSString *const kTableOutgoingRmqMessages = @"outgoingRmqMessages";
  46. NSString *const kTableLastRmqId = @"lastrmqid";
  47. NSString *const kOldTableS2DRmqIds = @"s2dRmqIds";
  48. NSString *const kTableS2DRmqIds = @"s2dRmqIds_1";
  49. // Used to prevent de-duping of sync messages received both via APNS and MCS.
  50. NSString *const kTableSyncMessages = @"incomingSyncMessages";
  51. static NSString *const kTablePrefix = @"";
  52. // create tables
  53. static NSString *const kCreateTableOutgoingRmqMessages = @"create TABLE IF NOT EXISTS %@%@ "
  54. @"(_id INTEGER PRIMARY KEY, "
  55. @"rmq_id INTEGER, "
  56. @"type INTEGER, "
  57. @"ts INTEGER, "
  58. @"data BLOB)";
  59. static NSString *const kCreateTableLastRmqId = @"create TABLE IF NOT EXISTS %@%@ "
  60. @"(_id INTEGER PRIMARY KEY, "
  61. @"rmq_id INTEGER)";
  62. static NSString *const kCreateTableS2DRmqIds = @"create TABLE IF NOT EXISTS %@%@ "
  63. @"(_id INTEGER PRIMARY KEY, "
  64. @"rmq_id TEXT)";
  65. static NSString *const kCreateTableSyncMessages = @"create TABLE IF NOT EXISTS %@%@ "
  66. @"(_id INTEGER PRIMARY KEY, "
  67. @"rmq_id TEXT, "
  68. @"expiration_ts INTEGER, "
  69. @"apns_recv INTEGER, "
  70. @"mcs_recv INTEGER)";
  71. static NSString *const kDropTableCommand = @"drop TABLE if exists %@%@";
  72. // table infos
  73. static NSString *const kRmqIdColumn = @"rmq_id";
  74. static NSString *const kDataColumn = @"data";
  75. static NSString *const kProtobufTagColumn = @"type";
  76. static NSString *const kIdColumn = @"_id";
  77. static NSString *const kOutgoingRmqMessagesColumns = @"rmq_id, type, data";
  78. // Sync message columns
  79. static NSString *const kSyncMessagesColumns = @"rmq_id, expiration_ts, apns_recv, mcs_recv";
  80. // Message time expiration in seconds since 1970
  81. static NSString *const kSyncMessageExpirationTimestampColumn = @"expiration_ts";
  82. static NSString *const kSyncMessageAPNSReceivedColumn = @"apns_recv";
  83. static NSString *const kSyncMessageMCSReceivedColumn = @"mcs_recv";
  84. // Utility to create an NSString from a sqlite3 result code
  85. NSString *_Nonnull FIRMessagingStringFromSQLiteResult(int result) {
  86. #pragma clang diagnostic push
  87. #pragma clang diagnostic ignored "-Wunguarded-availability"
  88. const char *errorStr = sqlite3_errstr(result);
  89. #pragma clang diagnostic pop
  90. NSString *errorString = [NSString stringWithFormat:@"%d - %s", result, errorStr];
  91. return errorString;
  92. }
  93. @interface FIRMessagingRmqManager () {
  94. sqlite3 *_database;
  95. /// Serial queue for database read/write operations.
  96. dispatch_queue_t _databaseOperationQueue;
  97. }
  98. @property(nonatomic, readwrite, strong) NSString *databaseName;
  99. // map the category of an outgoing message with the number of messages for that category
  100. // should always have two keys -- the app, gcm
  101. @property(nonatomic, readwrite, strong) NSMutableDictionary *outstandingMessages;
  102. // Outgoing RMQ persistent id
  103. @property(nonatomic, readwrite, assign) int64_t rmqId;
  104. @end
  105. @implementation FIRMessagingRmqManager
  106. - (instancetype)initWithDatabaseName:(NSString *)databaseName {
  107. self = [super init];
  108. if (self) {
  109. _databaseOperationQueue =
  110. dispatch_queue_create("com.google.firebase.messaging.database.rmq", DISPATCH_QUEUE_SERIAL);
  111. _databaseName = [databaseName copy];
  112. [self openDatabase];
  113. _outstandingMessages = [NSMutableDictionary dictionaryWithCapacity:2];
  114. _rmqId = -1;
  115. }
  116. return self;
  117. }
  118. - (void)dealloc {
  119. sqlite3_close(_database);
  120. }
  121. #pragma mark - RMQ ID
  122. - (void)loadRmqId {
  123. if (self.rmqId >= 0) {
  124. return; // already done
  125. }
  126. [self loadInitialOutgoingPersistentId];
  127. if (self.outstandingMessages.count) {
  128. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeRmqManager000, @"Outstanding categories %ld",
  129. _FIRMessaging_UL(self.outstandingMessages.count));
  130. }
  131. }
  132. /**
  133. * Initialize the 'initial RMQ':
  134. * - max ID of any message in the queue
  135. * - if the queue is empty, stored value in separate DB.
  136. *
  137. * Stream acks will remove from RMQ, when we remove the highest message we keep track
  138. * of its ID.
  139. */
  140. - (void)loadInitialOutgoingPersistentId {
  141. // we shouldn't always trust the lastRmqId stored in the LastRmqId table, because
  142. // we only save to the LastRmqId table once in a while (after getting the lastRmqId sent
  143. // by the server after reconnect, and after getting a rmq ack from the server). The
  144. // rmq message with the highest rmq id tells the real story, so check against that first.
  145. __block int64_t rmqId;
  146. dispatch_sync(_databaseOperationQueue, ^{
  147. rmqId = [self queryHighestRmqId];
  148. });
  149. if (rmqId == 0) {
  150. dispatch_sync(_databaseOperationQueue, ^{
  151. rmqId = [self queryLastRmqId];
  152. });
  153. }
  154. self.rmqId = rmqId + 1;
  155. }
  156. /**
  157. * This is called when we delete the largest outgoing message from queue.
  158. */
  159. - (void)saveLastOutgoingRmqId:(int64_t)rmqID {
  160. dispatch_async(_databaseOperationQueue, ^{
  161. NSString *queryFormat = @"INSERT OR REPLACE INTO %@ (%@, %@) VALUES (?, ?)";
  162. NSString *query = [NSString stringWithFormat:queryFormat,
  163. kTableLastRmqId, // table
  164. kIdColumn, kRmqIdColumn]; // columns
  165. sqlite3_stmt *statement;
  166. if (sqlite3_prepare_v2(self->_database, [query UTF8String], -1, &statement, NULL) !=
  167. SQLITE_OK) {
  168. FIRMessagingRmqLogAndReturn(statement);
  169. }
  170. if (sqlite3_bind_int(statement, 1, 1) != SQLITE_OK) {
  171. FIRMessagingRmqLogAndReturn(statement);
  172. }
  173. if (sqlite3_bind_int64(statement, 2, rmqID) != SQLITE_OK) {
  174. FIRMessagingRmqLogAndReturn(statement);
  175. }
  176. if (sqlite3_step(statement) != SQLITE_DONE) {
  177. FIRMessagingRmqLogAndReturn(statement);
  178. }
  179. sqlite3_finalize(statement);
  180. });
  181. }
  182. - (void)saveS2dMessageWithRmqId:(NSString *)rmqId {
  183. dispatch_async(_databaseOperationQueue, ^{
  184. NSString *insertFormat = @"INSERT INTO %@ (%@) VALUES (?)";
  185. NSString *insertSQL = [NSString stringWithFormat:insertFormat, kTableS2DRmqIds, kRmqIdColumn];
  186. sqlite3_stmt *insert_statement;
  187. if (sqlite3_prepare_v2(self->_database, [insertSQL UTF8String], -1, &insert_statement, NULL) !=
  188. SQLITE_OK) {
  189. FIRMessagingRmqLogAndReturn(insert_statement);
  190. }
  191. if (sqlite3_bind_text(insert_statement, 1, [rmqId UTF8String], (int)[rmqId length],
  192. SQLITE_STATIC) != SQLITE_OK) {
  193. FIRMessagingRmqLogAndReturn(insert_statement);
  194. }
  195. if (sqlite3_step(insert_statement) != SQLITE_DONE) {
  196. FIRMessagingRmqLogAndReturn(insert_statement);
  197. }
  198. sqlite3_finalize(insert_statement);
  199. });
  200. }
  201. #pragma mark - Query
  202. - (int64_t)queryHighestRmqId {
  203. NSString *queryFormat = @"SELECT %@ FROM %@ ORDER BY %@ DESC LIMIT %d";
  204. NSString *query = [NSString stringWithFormat:queryFormat,
  205. kRmqIdColumn, // column
  206. kTableOutgoingRmqMessages, // table
  207. kRmqIdColumn, // order by column
  208. 1]; // limit
  209. sqlite3_stmt *statement;
  210. int64_t highestRmqId = 0;
  211. if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, NULL) != SQLITE_OK) {
  212. _FIRMessagingRmqLogAndExit(statement, highestRmqId);
  213. }
  214. if (sqlite3_step(statement) == SQLITE_ROW) {
  215. highestRmqId = sqlite3_column_int64(statement, 0);
  216. }
  217. sqlite3_finalize(statement);
  218. return highestRmqId;
  219. }
  220. - (int64_t)queryLastRmqId {
  221. NSString *queryFormat = @"SELECT %@ FROM %@ ORDER BY %@ DESC LIMIT %d";
  222. NSString *query = [NSString stringWithFormat:queryFormat,
  223. kRmqIdColumn, // column
  224. kTableLastRmqId, // table
  225. kRmqIdColumn, // order by column
  226. 1]; // limit
  227. sqlite3_stmt *statement;
  228. int64_t lastRmqId = 0;
  229. if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, NULL) != SQLITE_OK) {
  230. _FIRMessagingRmqLogAndExit(statement, lastRmqId);
  231. }
  232. if (sqlite3_step(statement) == SQLITE_ROW) {
  233. lastRmqId = sqlite3_column_int64(statement, 0);
  234. }
  235. sqlite3_finalize(statement);
  236. return lastRmqId;
  237. }
  238. #pragma mark - Sync Messages
  239. - (FIRMessagingPersistentSyncMessage *)querySyncMessageWithRmqID:(NSString *)rmqID {
  240. __block FIRMessagingPersistentSyncMessage *persistentMessage;
  241. dispatch_sync(_databaseOperationQueue, ^{
  242. NSString *queryFormat = @"SELECT %@ FROM %@ WHERE %@ = ?";
  243. NSString *query =
  244. [NSString stringWithFormat:queryFormat,
  245. kSyncMessagesColumns, // SELECT (rmq_id, expiration_ts,
  246. // apns_recv, mcs_recv)
  247. kTableSyncMessages, // FROM sync_rmq
  248. kRmqIdColumn // WHERE rmq_id
  249. ];
  250. sqlite3_stmt *stmt;
  251. if (sqlite3_prepare_v2(self->_database, [query UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
  252. [self logError];
  253. sqlite3_finalize(stmt);
  254. return;
  255. }
  256. if (sqlite3_bind_text(stmt, 1, [rmqID UTF8String], (int)[rmqID length], SQLITE_STATIC) !=
  257. SQLITE_OK) {
  258. [self logError];
  259. sqlite3_finalize(stmt);
  260. return;
  261. }
  262. const int rmqIDColumn = 0;
  263. const int expirationTimestampColumn = 1;
  264. const int apnsReceivedColumn = 2;
  265. const int mcsReceivedColumn = 3;
  266. int count = 0;
  267. while (sqlite3_step(stmt) == SQLITE_ROW) {
  268. NSString *rmqID =
  269. [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, rmqIDColumn)];
  270. int64_t expirationTimestamp = sqlite3_column_int64(stmt, expirationTimestampColumn);
  271. BOOL apnsReceived = sqlite3_column_int(stmt, apnsReceivedColumn);
  272. BOOL mcsReceived = sqlite3_column_int(stmt, mcsReceivedColumn);
  273. // create a new persistent message
  274. persistentMessage =
  275. [[FIRMessagingPersistentSyncMessage alloc] initWithRMQID:rmqID
  276. expirationTime:expirationTimestamp];
  277. persistentMessage.apnsReceived = apnsReceived;
  278. persistentMessage.mcsReceived = mcsReceived;
  279. count++;
  280. }
  281. sqlite3_finalize(stmt);
  282. });
  283. return persistentMessage;
  284. }
  285. - (void)deleteExpiredOrFinishedSyncMessages {
  286. dispatch_async(_databaseOperationQueue, ^{
  287. int64_t now = FIRMessagingCurrentTimestampInSeconds();
  288. NSString *deleteSQL = @"DELETE FROM %@ "
  289. @"WHERE %@ < %lld OR " // expirationTime < now
  290. @"(%@ = 1 AND %@ = 1)"; // apns_received = 1 AND mcs_received = 1
  291. NSString *query = [NSString
  292. stringWithFormat:deleteSQL, kTableSyncMessages, kSyncMessageExpirationTimestampColumn, now,
  293. kSyncMessageAPNSReceivedColumn, kSyncMessageMCSReceivedColumn];
  294. sqlite3_stmt *stmt;
  295. if (sqlite3_prepare_v2(self->_database, [query UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
  296. FIRMessagingRmqLogAndReturn(stmt);
  297. }
  298. if (sqlite3_step(stmt) != SQLITE_DONE) {
  299. FIRMessagingRmqLogAndReturn(stmt);
  300. }
  301. sqlite3_finalize(stmt);
  302. int deleteCount = sqlite3_changes(self->_database);
  303. if (deleteCount > 0) {
  304. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSyncMessageManager001,
  305. @"Successfully deleted %d sync messages from store", deleteCount);
  306. }
  307. });
  308. }
  309. - (void)saveSyncMessageWithRmqID:(NSString *)rmqID expirationTime:(int64_t)expirationTime {
  310. BOOL apnsReceived = YES;
  311. BOOL mcsReceived = NO;
  312. dispatch_async(_databaseOperationQueue, ^{
  313. NSString *insertFormat = @"INSERT INTO %@ (%@, %@, %@, %@) VALUES (?, ?, ?, ?)";
  314. NSString *insertSQL =
  315. [NSString stringWithFormat:insertFormat,
  316. kTableSyncMessages, // Table name
  317. kRmqIdColumn, // rmq_id
  318. kSyncMessageExpirationTimestampColumn, // expiration_ts
  319. kSyncMessageAPNSReceivedColumn, // apns_recv
  320. kSyncMessageMCSReceivedColumn /* mcs_recv */];
  321. sqlite3_stmt *stmt;
  322. if (sqlite3_prepare_v2(self->_database, [insertSQL UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
  323. FIRMessagingRmqLogAndReturn(stmt);
  324. }
  325. if (sqlite3_bind_text(stmt, 1, [rmqID UTF8String], (int)[rmqID length], NULL) != SQLITE_OK) {
  326. FIRMessagingRmqLogAndReturn(stmt);
  327. }
  328. if (sqlite3_bind_int64(stmt, 2, expirationTime) != SQLITE_OK) {
  329. FIRMessagingRmqLogAndReturn(stmt);
  330. }
  331. if (sqlite3_bind_int(stmt, 3, apnsReceived ? 1 : 0) != SQLITE_OK) {
  332. FIRMessagingRmqLogAndReturn(stmt);
  333. }
  334. if (sqlite3_bind_int(stmt, 4, mcsReceived ? 1 : 0) != SQLITE_OK) {
  335. FIRMessagingRmqLogAndReturn(stmt);
  336. }
  337. if (sqlite3_step(stmt) != SQLITE_DONE) {
  338. FIRMessagingRmqLogAndReturn(stmt);
  339. }
  340. sqlite3_finalize(stmt);
  341. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeSyncMessageManager004,
  342. @"Added sync message to cache: %@", rmqID);
  343. });
  344. }
  345. - (void)updateSyncMessageViaAPNSWithRmqID:(NSString *)rmqID {
  346. dispatch_async(_databaseOperationQueue, ^{
  347. if (![self updateSyncMessageWithRmqID:rmqID column:kSyncMessageAPNSReceivedColumn value:YES]) {
  348. FIRMessagingLoggerError(kFIRMessagingMessageCodeSyncMessageManager005,
  349. @"Failed to update APNS state for sync message %@", rmqID);
  350. }
  351. });
  352. }
  353. - (BOOL)updateSyncMessageWithRmqID:(NSString *)rmqID column:(NSString *)column value:(BOOL)value {
  354. FIRMessaging_MUST_NOT_BE_MAIN_THREAD();
  355. NSString *queryFormat = @"UPDATE %@ " // Table name
  356. @"SET %@ = %d " // column=value
  357. @"WHERE %@ = ?"; // condition
  358. NSString *query = [NSString
  359. stringWithFormat:queryFormat, kTableSyncMessages, column, value ? 1 : 0, kRmqIdColumn];
  360. sqlite3_stmt *stmt;
  361. if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
  362. _FIRMessagingRmqLogAndExit(stmt, NO);
  363. }
  364. if (sqlite3_bind_text(stmt, 1, [rmqID UTF8String], (int)[rmqID length], NULL) != SQLITE_OK) {
  365. _FIRMessagingRmqLogAndExit(stmt, NO);
  366. }
  367. if (sqlite3_step(stmt) != SQLITE_DONE) {
  368. _FIRMessagingRmqLogAndExit(stmt, NO);
  369. }
  370. sqlite3_finalize(stmt);
  371. return YES;
  372. }
  373. #pragma mark - Database
  374. - (NSString *)pathForDatabase {
  375. return [[self class] pathForDatabaseWithName:_databaseName];
  376. }
  377. + (NSString *)pathForDatabaseWithName:(NSString *)databaseName {
  378. NSString *dbNameWithExtension = [NSString stringWithFormat:@"%@.sqlite", databaseName];
  379. NSArray *paths =
  380. NSSearchPathForDirectoriesInDomains(FIRMessagingSupportedDirectory(), NSUserDomainMask, YES);
  381. NSArray *components = @[ paths.lastObject, kFIRMessagingSubDirectoryName, dbNameWithExtension ];
  382. return [NSString pathWithComponents:components];
  383. }
  384. - (void)createTableWithName:(NSString *)tableName command:(NSString *)command {
  385. FIRMessaging_MUST_NOT_BE_MAIN_THREAD();
  386. char *error = NULL;
  387. NSString *createDatabase = [NSString stringWithFormat:command, kTablePrefix, tableName];
  388. if (sqlite3_exec(self->_database, [createDatabase UTF8String], NULL, NULL, &error) != SQLITE_OK) {
  389. // remove db before failing
  390. [self removeDatabase];
  391. NSString *sqlError;
  392. if (error != NULL) {
  393. sqlError = [NSString stringWithCString:error encoding:NSUTF8StringEncoding];
  394. sqlite3_free(error);
  395. } else {
  396. sqlError = @"(null)";
  397. }
  398. NSString *errorMessage =
  399. [NSString stringWithFormat:@"Couldn't create table: %@ with command: %@ error: %@",
  400. kCreateTableOutgoingRmqMessages, createDatabase, sqlError];
  401. FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStoreErrorCreatingTable, @"%@",
  402. errorMessage);
  403. NSAssert(NO, errorMessage);
  404. }
  405. }
  406. - (void)dropTableWithName:(NSString *)tableName {
  407. FIRMessaging_MUST_NOT_BE_MAIN_THREAD();
  408. char *error;
  409. NSString *dropTableSQL = [NSString stringWithFormat:kDropTableCommand, kTablePrefix, tableName];
  410. if (sqlite3_exec(self->_database, [dropTableSQL UTF8String], NULL, NULL, &error) != SQLITE_OK) {
  411. FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStore002,
  412. @"Failed to remove table %@", tableName);
  413. }
  414. }
  415. - (void)removeDatabase {
  416. // Ensure database is removed in a sync queue as this sometimes makes test have race conditions.
  417. dispatch_async(_databaseOperationQueue, ^{
  418. NSString *path = [self pathForDatabase];
  419. [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
  420. });
  421. }
  422. - (void)openDatabase {
  423. dispatch_async(_databaseOperationQueue, ^{
  424. NSFileManager *fileManager = [NSFileManager defaultManager];
  425. NSString *path = [self pathForDatabase];
  426. BOOL didOpenDatabase = YES;
  427. if (![fileManager fileExistsAtPath:path]) {
  428. // We've to separate between different versions here because of backward compatibility issues.
  429. int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
  430. #ifdef SQLITE_OPEN_FILEPROTECTION_NONE
  431. flags |= SQLITE_OPEN_FILEPROTECTION_NONE;
  432. #endif
  433. int result = sqlite3_open_v2([path UTF8String], &self -> _database, flags, NULL);
  434. if (result != SQLITE_OK) {
  435. NSString *errorString = FIRMessagingStringFromSQLiteResult(result);
  436. NSString *errorMessage = [NSString
  437. stringWithFormat:@"Could not open existing RMQ database at path %@, error: %@", path,
  438. errorString];
  439. FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStoreErrorOpeningDatabase,
  440. @"%@", errorMessage);
  441. NSAssert(NO, errorMessage);
  442. return;
  443. }
  444. [self createTableWithName:kTableOutgoingRmqMessages command:kCreateTableOutgoingRmqMessages];
  445. [self createTableWithName:kTableLastRmqId command:kCreateTableLastRmqId];
  446. [self createTableWithName:kTableS2DRmqIds command:kCreateTableS2DRmqIds];
  447. } else {
  448. // Calling sqlite3_open should create the database, since the file doesn't exist.
  449. int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
  450. #ifdef SQLITE_OPEN_FILEPROTECTION_NONE
  451. flags |= SQLITE_OPEN_FILEPROTECTION_NONE;
  452. #endif
  453. int result = sqlite3_open_v2([path UTF8String], &self -> _database, flags, NULL);
  454. if (result != SQLITE_OK) {
  455. NSString *errorString = FIRMessagingStringFromSQLiteResult(result);
  456. NSString *errorMessage =
  457. [NSString stringWithFormat:@"Could not create RMQ database at path %@, error: %@", path,
  458. errorString];
  459. FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStoreErrorCreatingDatabase,
  460. @"%@", errorMessage);
  461. NSAssert(NO, errorMessage);
  462. didOpenDatabase = NO;
  463. } else {
  464. [self updateDBWithStringRmqID];
  465. }
  466. }
  467. if (didOpenDatabase) {
  468. [self createTableWithName:kTableSyncMessages command:kCreateTableSyncMessages];
  469. }
  470. });
  471. }
  472. - (void)updateDBWithStringRmqID {
  473. dispatch_async(_databaseOperationQueue, ^{
  474. [self createTableWithName:kTableS2DRmqIds command:kCreateTableS2DRmqIds];
  475. [self dropTableWithName:kOldTableS2DRmqIds];
  476. });
  477. }
  478. #pragma mark - Private
  479. - (BOOL)saveMessageWithRmqId:(int64_t)rmqId tag:(int8_t)tag data:(NSData *)data {
  480. FIRMessaging_MUST_NOT_BE_MAIN_THREAD();
  481. NSString *insertFormat = @"INSERT INTO %@ (%@, %@, %@) VALUES (?, ?, ?)";
  482. NSString *insertSQL =
  483. [NSString stringWithFormat:insertFormat,
  484. kTableOutgoingRmqMessages, // table
  485. kRmqIdColumn, kProtobufTagColumn, kDataColumn /* columns */];
  486. sqlite3_stmt *insert_statement;
  487. if (sqlite3_prepare_v2(self->_database, [insertSQL UTF8String], -1, &insert_statement, NULL) !=
  488. SQLITE_OK) {
  489. _FIRMessagingRmqLogAndExit(insert_statement, NO);
  490. }
  491. if (sqlite3_bind_int64(insert_statement, 1, rmqId) != SQLITE_OK) {
  492. _FIRMessagingRmqLogAndExit(insert_statement, NO);
  493. }
  494. if (sqlite3_bind_int(insert_statement, 2, tag) != SQLITE_OK) {
  495. _FIRMessagingRmqLogAndExit(insert_statement, NO);
  496. }
  497. if (sqlite3_bind_blob(insert_statement, 3, [data bytes], (int)[data length], NULL) != SQLITE_OK) {
  498. _FIRMessagingRmqLogAndExit(insert_statement, NO);
  499. }
  500. if (sqlite3_step(insert_statement) != SQLITE_DONE) {
  501. _FIRMessagingRmqLogAndExit(insert_statement, NO);
  502. }
  503. sqlite3_finalize(insert_statement);
  504. return YES;
  505. }
  506. - (void)deleteMessagesFromTable:(NSString *)tableName withRmqIds:(NSArray *)rmqIds {
  507. dispatch_async(_databaseOperationQueue, ^{
  508. BOOL isRmqIDString = NO;
  509. // RmqID is a string only for outgoing messages
  510. if ([tableName isEqualToString:kTableS2DRmqIds] ||
  511. [tableName isEqualToString:kTableSyncMessages]) {
  512. isRmqIDString = YES;
  513. }
  514. NSMutableString *delete =
  515. [NSMutableString stringWithFormat:@"DELETE FROM %@ WHERE ", tableName];
  516. NSString *toDeleteArgument = [NSString stringWithFormat:@"%@ = ? OR ", kRmqIdColumn];
  517. int toDelete = (int)[rmqIds count];
  518. if (toDelete == 0) {
  519. return;
  520. }
  521. int maxBatchSize = 100;
  522. int start = 0;
  523. int deleteCount = 0;
  524. while (start < toDelete) {
  525. // construct the WHERE argument
  526. int end = MIN(start + maxBatchSize, toDelete);
  527. NSMutableString *whereArgument = [NSMutableString string];
  528. for (int i = start; i < end; i++) {
  529. [whereArgument appendString:toDeleteArgument];
  530. }
  531. // remove the last * OR * from argument
  532. NSRange range = NSMakeRange([whereArgument length] - 4, 4);
  533. [whereArgument deleteCharactersInRange:range];
  534. NSString *deleteQuery = [NSString stringWithFormat:@"%@ %@", delete, whereArgument];
  535. // sqlite update
  536. sqlite3_stmt *delete_statement;
  537. if (sqlite3_prepare_v2(self->_database, [deleteQuery UTF8String], -1, &delete_statement,
  538. NULL) != SQLITE_OK) {
  539. FIRMessagingRmqLogAndReturn(delete_statement);
  540. }
  541. // bind values
  542. int rmqIndex = 0;
  543. int placeholderIndex = 1; // placeholders in sqlite3 start with 1
  544. for (NSString *rmqId in rmqIds) { // objectAtIndex: is O(n) -- would make it slow
  545. if (rmqIndex < start) {
  546. rmqIndex++;
  547. continue;
  548. } else if (rmqIndex >= end) {
  549. break;
  550. } else {
  551. if (isRmqIDString) {
  552. if (sqlite3_bind_text(delete_statement, placeholderIndex, [rmqId UTF8String],
  553. (int)[rmqId length], SQLITE_STATIC) != SQLITE_OK) {
  554. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeRmq2PersistentStore003,
  555. @"Failed to bind rmqID %@", rmqId);
  556. FIRMessagingLoggerError(kFIRMessagingMessageCodeSyncMessageManager007,
  557. @"Failed to delete sync message %@", rmqId);
  558. continue;
  559. }
  560. } else {
  561. int64_t rmqIdValue = [rmqId longLongValue];
  562. sqlite3_bind_int64(delete_statement, placeholderIndex, rmqIdValue);
  563. }
  564. placeholderIndex++;
  565. }
  566. rmqIndex++;
  567. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeSyncMessageManager008,
  568. @"Successfully deleted sync message from cache %@", rmqId);
  569. }
  570. if (sqlite3_step(delete_statement) != SQLITE_DONE) {
  571. FIRMessagingRmqLogAndReturn(delete_statement);
  572. }
  573. sqlite3_finalize(delete_statement);
  574. deleteCount += sqlite3_changes(self->_database);
  575. start = end;
  576. }
  577. // if we are here all of our sqlite queries should have succeeded
  578. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeRmq2PersistentStore004,
  579. @"Trying to delete %d s2D ID's, successfully deleted %d", toDelete,
  580. deleteCount);
  581. });
  582. }
  583. - (int64_t)nextRmqId {
  584. return ++self.rmqId;
  585. }
  586. - (NSString *)lastErrorMessage {
  587. return [NSString stringWithFormat:@"%s", sqlite3_errmsg(_database)];
  588. }
  589. - (int)lastErrorCode {
  590. return sqlite3_errcode(_database);
  591. }
  592. - (void)logError {
  593. FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStore006,
  594. @"Error: code (%d) message: %@", [self lastErrorCode],
  595. [self lastErrorMessage]);
  596. }
  597. - (void)logErrorAndFinalizeStatement:(sqlite3_stmt *)stmt {
  598. [self logError];
  599. sqlite3_finalize(stmt);
  600. }
  601. - (dispatch_queue_t)databaseOperationQueue {
  602. return _databaseOperationQueue;
  603. }
  604. @end