FIRMessagingRmqManager.m 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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. rmqID];
  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. const int rmqIDColumn = 0;
  257. const int expirationTimestampColumn = 1;
  258. const int apnsReceivedColumn = 2;
  259. const int mcsReceivedColumn = 3;
  260. int count = 0;
  261. while (sqlite3_step(stmt) == SQLITE_ROW) {
  262. NSString *rmqID =
  263. [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, rmqIDColumn)];
  264. int64_t expirationTimestamp = sqlite3_column_int64(stmt, expirationTimestampColumn);
  265. BOOL apnsReceived = sqlite3_column_int(stmt, apnsReceivedColumn);
  266. BOOL mcsReceived = sqlite3_column_int(stmt, mcsReceivedColumn);
  267. // create a new persistent message
  268. persistentMessage =
  269. [[FIRMessagingPersistentSyncMessage alloc] initWithRMQID:rmqID
  270. expirationTime:expirationTimestamp];
  271. persistentMessage.apnsReceived = apnsReceived;
  272. persistentMessage.mcsReceived = mcsReceived;
  273. count++;
  274. }
  275. sqlite3_finalize(stmt);
  276. });
  277. return persistentMessage;
  278. }
  279. - (void)deleteExpiredOrFinishedSyncMessages {
  280. dispatch_async(_databaseOperationQueue, ^{
  281. int64_t now = FIRMessagingCurrentTimestampInSeconds();
  282. NSString *deleteSQL = @"DELETE FROM %@ "
  283. @"WHERE %@ < %lld OR " // expirationTime < now
  284. @"(%@ = 1 AND %@ = 1)"; // apns_received = 1 AND mcs_received = 1
  285. NSString *query = [NSString
  286. stringWithFormat:deleteSQL, kTableSyncMessages, kSyncMessageExpirationTimestampColumn, now,
  287. kSyncMessageAPNSReceivedColumn, kSyncMessageMCSReceivedColumn];
  288. sqlite3_stmt *stmt;
  289. if (sqlite3_prepare_v2(self->_database, [query UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
  290. FIRMessagingRmqLogAndReturn(stmt);
  291. }
  292. if (sqlite3_step(stmt) != SQLITE_DONE) {
  293. FIRMessagingRmqLogAndReturn(stmt);
  294. }
  295. sqlite3_finalize(stmt);
  296. int deleteCount = sqlite3_changes(self->_database);
  297. if (deleteCount > 0) {
  298. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeSyncMessageManager001,
  299. @"Successfully deleted %d sync messages from store", deleteCount);
  300. }
  301. });
  302. }
  303. - (void)saveSyncMessageWithRmqID:(NSString *)rmqID expirationTime:(int64_t)expirationTime {
  304. BOOL apnsReceived = YES;
  305. BOOL mcsReceived = NO;
  306. dispatch_async(_databaseOperationQueue, ^{
  307. NSString *insertFormat = @"INSERT INTO %@ (%@, %@, %@, %@) VALUES (?, ?, ?, ?)";
  308. NSString *insertSQL =
  309. [NSString stringWithFormat:insertFormat,
  310. kTableSyncMessages, // Table name
  311. kRmqIdColumn, // rmq_id
  312. kSyncMessageExpirationTimestampColumn, // expiration_ts
  313. kSyncMessageAPNSReceivedColumn, // apns_recv
  314. kSyncMessageMCSReceivedColumn /* mcs_recv */];
  315. sqlite3_stmt *stmt;
  316. if (sqlite3_prepare_v2(self->_database, [insertSQL UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
  317. FIRMessagingRmqLogAndReturn(stmt);
  318. }
  319. if (sqlite3_bind_text(stmt, 1, [rmqID UTF8String], (int)[rmqID length], NULL) != SQLITE_OK) {
  320. FIRMessagingRmqLogAndReturn(stmt);
  321. }
  322. if (sqlite3_bind_int64(stmt, 2, expirationTime) != SQLITE_OK) {
  323. FIRMessagingRmqLogAndReturn(stmt);
  324. }
  325. if (sqlite3_bind_int(stmt, 3, apnsReceived ? 1 : 0) != SQLITE_OK) {
  326. FIRMessagingRmqLogAndReturn(stmt);
  327. }
  328. if (sqlite3_bind_int(stmt, 4, mcsReceived ? 1 : 0) != SQLITE_OK) {
  329. FIRMessagingRmqLogAndReturn(stmt);
  330. }
  331. if (sqlite3_step(stmt) != SQLITE_DONE) {
  332. FIRMessagingRmqLogAndReturn(stmt);
  333. }
  334. sqlite3_finalize(stmt);
  335. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeSyncMessageManager004,
  336. @"Added sync message to cache: %@", rmqID);
  337. });
  338. }
  339. - (void)updateSyncMessageViaAPNSWithRmqID:(NSString *)rmqID {
  340. dispatch_async(_databaseOperationQueue, ^{
  341. if (![self updateSyncMessageWithRmqID:rmqID column:kSyncMessageAPNSReceivedColumn value:YES]) {
  342. FIRMessagingLoggerError(kFIRMessagingMessageCodeSyncMessageManager005,
  343. @"Failed to update APNS state for sync message %@", rmqID);
  344. }
  345. });
  346. }
  347. - (BOOL)updateSyncMessageWithRmqID:(NSString *)rmqID column:(NSString *)column value:(BOOL)value {
  348. FIRMessaging_MUST_NOT_BE_MAIN_THREAD();
  349. NSString *queryFormat = @"UPDATE %@ " // Table name
  350. @"SET %@ = %d " // column=value
  351. @"WHERE %@ = ?"; // condition
  352. NSString *query = [NSString
  353. stringWithFormat:queryFormat, kTableSyncMessages, column, value ? 1 : 0, kRmqIdColumn];
  354. sqlite3_stmt *stmt;
  355. if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
  356. _FIRMessagingRmqLogAndExit(stmt, NO);
  357. }
  358. if (sqlite3_bind_text(stmt, 1, [rmqID UTF8String], (int)[rmqID length], NULL) != SQLITE_OK) {
  359. _FIRMessagingRmqLogAndExit(stmt, NO);
  360. }
  361. if (sqlite3_step(stmt) != SQLITE_DONE) {
  362. _FIRMessagingRmqLogAndExit(stmt, NO);
  363. }
  364. sqlite3_finalize(stmt);
  365. return YES;
  366. }
  367. #pragma mark - Database
  368. - (NSString *)pathForDatabase {
  369. return [[self class] pathForDatabaseWithName:_databaseName];
  370. }
  371. + (NSString *)pathForDatabaseWithName:(NSString *)databaseName {
  372. NSString *dbNameWithExtension = [NSString stringWithFormat:@"%@.sqlite", databaseName];
  373. NSArray *paths =
  374. NSSearchPathForDirectoriesInDomains(FIRMessagingSupportedDirectory(), NSUserDomainMask, YES);
  375. NSArray *components = @[ paths.lastObject, kFIRMessagingSubDirectoryName, dbNameWithExtension ];
  376. return [NSString pathWithComponents:components];
  377. }
  378. - (void)createTableWithName:(NSString *)tableName command:(NSString *)command {
  379. FIRMessaging_MUST_NOT_BE_MAIN_THREAD();
  380. char *error;
  381. NSString *createDatabase = [NSString stringWithFormat:command, kTablePrefix, tableName];
  382. if (sqlite3_exec(self->_database, [createDatabase UTF8String], NULL, NULL, &error) != SQLITE_OK) {
  383. // remove db before failing
  384. [self removeDatabase];
  385. NSString *errorMessage = [NSString
  386. stringWithFormat:@"Couldn't create table: %@ %@", kCreateTableOutgoingRmqMessages,
  387. [NSString stringWithCString:error encoding:NSUTF8StringEncoding]];
  388. FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStoreErrorCreatingTable, @"%@",
  389. errorMessage);
  390. NSAssert(NO, errorMessage);
  391. }
  392. }
  393. - (void)dropTableWithName:(NSString *)tableName {
  394. FIRMessaging_MUST_NOT_BE_MAIN_THREAD();
  395. char *error;
  396. NSString *dropTableSQL = [NSString stringWithFormat:kDropTableCommand, kTablePrefix, tableName];
  397. if (sqlite3_exec(self->_database, [dropTableSQL UTF8String], NULL, NULL, &error) != SQLITE_OK) {
  398. FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStore002,
  399. @"Failed to remove table %@", tableName);
  400. }
  401. }
  402. - (void)removeDatabase {
  403. // Ensure database is removed in a sync queue as this sometimes makes test have race conditions.
  404. dispatch_async(_databaseOperationQueue, ^{
  405. NSString *path = [self pathForDatabase];
  406. [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
  407. });
  408. }
  409. - (void)openDatabase {
  410. dispatch_async(_databaseOperationQueue, ^{
  411. NSFileManager *fileManager = [NSFileManager defaultManager];
  412. NSString *path = [self pathForDatabase];
  413. BOOL didOpenDatabase = YES;
  414. if (![fileManager fileExistsAtPath:path]) {
  415. // We've to separate between different versions here because of backwards compatbility issues.
  416. int result = sqlite3_open_v2(
  417. [path UTF8String], &self -> _database,
  418. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FILEPROTECTION_NONE, NULL);
  419. if (result != SQLITE_OK) {
  420. NSString *errorString = FIRMessagingStringFromSQLiteResult(result);
  421. NSString *errorMessage = [NSString
  422. stringWithFormat:@"Could not open existing RMQ database at path %@, error: %@", path,
  423. errorString];
  424. FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStoreErrorOpeningDatabase,
  425. @"%@", errorMessage);
  426. NSAssert(NO, errorMessage);
  427. return;
  428. }
  429. [self createTableWithName:kTableOutgoingRmqMessages command:kCreateTableOutgoingRmqMessages];
  430. [self createTableWithName:kTableLastRmqId command:kCreateTableLastRmqId];
  431. [self createTableWithName:kTableS2DRmqIds command:kCreateTableS2DRmqIds];
  432. } else {
  433. // Calling sqlite3_open should create the database, since the file doesn't exist.
  434. int result = sqlite3_open_v2(
  435. [path UTF8String], &self -> _database,
  436. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FILEPROTECTION_NONE, NULL);
  437. if (result != SQLITE_OK) {
  438. NSString *errorString = FIRMessagingStringFromSQLiteResult(result);
  439. NSString *errorMessage =
  440. [NSString stringWithFormat:@"Could not create RMQ database at path %@, error: %@", path,
  441. errorString];
  442. FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStoreErrorCreatingDatabase,
  443. @"%@", errorMessage);
  444. NSAssert(NO, errorMessage);
  445. didOpenDatabase = NO;
  446. } else {
  447. [self updateDBWithStringRmqID];
  448. }
  449. }
  450. if (didOpenDatabase) {
  451. [self createTableWithName:kTableSyncMessages command:kCreateTableSyncMessages];
  452. }
  453. });
  454. }
  455. - (void)updateDBWithStringRmqID {
  456. dispatch_async(_databaseOperationQueue, ^{
  457. [self createTableWithName:kTableS2DRmqIds command:kCreateTableS2DRmqIds];
  458. [self dropTableWithName:kOldTableS2DRmqIds];
  459. });
  460. }
  461. #pragma mark - Private
  462. - (BOOL)saveMessageWithRmqId:(int64_t)rmqId tag:(int8_t)tag data:(NSData *)data {
  463. FIRMessaging_MUST_NOT_BE_MAIN_THREAD();
  464. NSString *insertFormat = @"INSERT INTO %@ (%@, %@, %@) VALUES (?, ?, ?)";
  465. NSString *insertSQL =
  466. [NSString stringWithFormat:insertFormat,
  467. kTableOutgoingRmqMessages, // table
  468. kRmqIdColumn, kProtobufTagColumn, kDataColumn /* columns */];
  469. sqlite3_stmt *insert_statement;
  470. if (sqlite3_prepare_v2(self->_database, [insertSQL UTF8String], -1, &insert_statement, NULL) !=
  471. SQLITE_OK) {
  472. _FIRMessagingRmqLogAndExit(insert_statement, NO);
  473. }
  474. if (sqlite3_bind_int64(insert_statement, 1, rmqId) != SQLITE_OK) {
  475. _FIRMessagingRmqLogAndExit(insert_statement, NO);
  476. }
  477. if (sqlite3_bind_int(insert_statement, 2, tag) != SQLITE_OK) {
  478. _FIRMessagingRmqLogAndExit(insert_statement, NO);
  479. }
  480. if (sqlite3_bind_blob(insert_statement, 3, [data bytes], (int)[data length], NULL) != SQLITE_OK) {
  481. _FIRMessagingRmqLogAndExit(insert_statement, NO);
  482. }
  483. if (sqlite3_step(insert_statement) != SQLITE_DONE) {
  484. _FIRMessagingRmqLogAndExit(insert_statement, NO);
  485. }
  486. sqlite3_finalize(insert_statement);
  487. return YES;
  488. }
  489. - (void)deleteMessagesFromTable:(NSString *)tableName withRmqIds:(NSArray *)rmqIds {
  490. dispatch_async(_databaseOperationQueue, ^{
  491. BOOL isRmqIDString = NO;
  492. // RmqID is a string only for outgoing messages
  493. if ([tableName isEqualToString:kTableS2DRmqIds] ||
  494. [tableName isEqualToString:kTableSyncMessages]) {
  495. isRmqIDString = YES;
  496. }
  497. NSMutableString *delete =
  498. [NSMutableString stringWithFormat:@"DELETE FROM %@ WHERE ", tableName];
  499. NSString *toDeleteArgument = [NSString stringWithFormat:@"%@ = ? OR ", kRmqIdColumn];
  500. int toDelete = (int)[rmqIds count];
  501. if (toDelete == 0) {
  502. return;
  503. }
  504. int maxBatchSize = 100;
  505. int start = 0;
  506. int deleteCount = 0;
  507. while (start < toDelete) {
  508. // construct the WHERE argument
  509. int end = MIN(start + maxBatchSize, toDelete);
  510. NSMutableString *whereArgument = [NSMutableString string];
  511. for (int i = start; i < end; i++) {
  512. [whereArgument appendString:toDeleteArgument];
  513. }
  514. // remove the last * OR * from argument
  515. NSRange range = NSMakeRange([whereArgument length] - 4, 4);
  516. [whereArgument deleteCharactersInRange:range];
  517. NSString *deleteQuery = [NSString stringWithFormat:@"%@ %@", delete, whereArgument];
  518. // sqlite update
  519. sqlite3_stmt *delete_statement;
  520. if (sqlite3_prepare_v2(self->_database, [deleteQuery UTF8String], -1, &delete_statement,
  521. NULL) != SQLITE_OK) {
  522. FIRMessagingRmqLogAndReturn(delete_statement);
  523. }
  524. // bind values
  525. int rmqIndex = 0;
  526. int placeholderIndex = 1; // placeholders in sqlite3 start with 1
  527. for (NSString *rmqId in rmqIds) { // objectAtIndex: is O(n) -- would make it slow
  528. if (rmqIndex < start) {
  529. rmqIndex++;
  530. continue;
  531. } else if (rmqIndex >= end) {
  532. break;
  533. } else {
  534. if (isRmqIDString) {
  535. if (sqlite3_bind_text(delete_statement, placeholderIndex, [rmqId UTF8String],
  536. (int)[rmqId length], SQLITE_STATIC) != SQLITE_OK) {
  537. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeRmq2PersistentStore003,
  538. @"Failed to bind rmqID %@", rmqId);
  539. FIRMessagingLoggerError(kFIRMessagingMessageCodeSyncMessageManager007,
  540. @"Failed to delete sync message %@", rmqId);
  541. continue;
  542. }
  543. } else {
  544. int64_t rmqIdValue = [rmqId longLongValue];
  545. sqlite3_bind_int64(delete_statement, placeholderIndex, rmqIdValue);
  546. }
  547. placeholderIndex++;
  548. }
  549. rmqIndex++;
  550. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeSyncMessageManager008,
  551. @"Successfully deleted sync message from cache %@", rmqId);
  552. }
  553. if (sqlite3_step(delete_statement) != SQLITE_DONE) {
  554. FIRMessagingRmqLogAndReturn(delete_statement);
  555. }
  556. sqlite3_finalize(delete_statement);
  557. deleteCount += sqlite3_changes(self->_database);
  558. start = end;
  559. }
  560. // if we are here all of our sqlite queries should have succeeded
  561. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeRmq2PersistentStore004,
  562. @"Trying to delete %d s2D ID's, successfully deleted %d", toDelete,
  563. deleteCount);
  564. });
  565. }
  566. - (int64_t)nextRmqId {
  567. return ++self.rmqId;
  568. }
  569. - (NSString *)lastErrorMessage {
  570. return [NSString stringWithFormat:@"%s", sqlite3_errmsg(_database)];
  571. }
  572. - (int)lastErrorCode {
  573. return sqlite3_errcode(_database);
  574. }
  575. - (void)logError {
  576. FIRMessagingLoggerError(kFIRMessagingMessageCodeRmq2PersistentStore006,
  577. @"Error: code (%d) message: %@", [self lastErrorCode],
  578. [self lastErrorMessage]);
  579. }
  580. - (void)logErrorAndFinalizeStatement:(sqlite3_stmt *)stmt {
  581. [self logError];
  582. sqlite3_finalize(stmt);
  583. }
  584. - (dispatch_queue_t)databaseOperationQueue {
  585. return _databaseOperationQueue;
  586. }
  587. @end