FSTLevelDBMigrationsTests.mm 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /*
  2. * Copyright 2018 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 <XCTest/XCTest.h>
  17. #include <memory>
  18. #include <string>
  19. #include <vector>
  20. #import "Firestore/Protos/objc/firestore/local/Target.pbobjc.h"
  21. #import "Firestore/Source/Local/FSTLevelDB.h"
  22. #import "Firestore/Source/Local/FSTLevelDBMutationQueue.h"
  23. #import "Firestore/Source/Local/FSTLevelDBQueryCache.h"
  24. #include "Firestore/core/src/firebase/firestore/local/leveldb_key.h"
  25. #include "Firestore/core/src/firebase/firestore/local/leveldb_migrations.h"
  26. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  27. #include "Firestore/core/src/firebase/firestore/model/types.h"
  28. #include "Firestore/core/src/firebase/firestore/util/ordered_code.h"
  29. #include "Firestore/core/src/firebase/firestore/util/status.h"
  30. #include "Firestore/core/test/firebase/firestore/testutil/testutil.h"
  31. #include "absl/strings/match.h"
  32. #include "leveldb/db.h"
  33. #import "Firestore/Example/Tests/Local/FSTPersistenceTestHelpers.h"
  34. NS_ASSUME_NONNULL_BEGIN
  35. using firebase::firestore::FirestoreErrorCode;
  36. using firebase::firestore::local::LevelDbDocumentTargetKey;
  37. using firebase::firestore::local::LevelDbMigrations;
  38. using firebase::firestore::local::LevelDbMutationKey;
  39. using firebase::firestore::local::LevelDbMutationQueueKey;
  40. using firebase::firestore::local::LevelDbQueryTargetKey;
  41. using firebase::firestore::local::LevelDbRemoteDocumentKey;
  42. using firebase::firestore::local::LevelDbTargetDocumentKey;
  43. using firebase::firestore::local::LevelDbTargetGlobalKey;
  44. using firebase::firestore::local::LevelDbTargetKey;
  45. using firebase::firestore::local::LevelDbTransaction;
  46. using firebase::firestore::model::BatchId;
  47. using firebase::firestore::model::DocumentKey;
  48. using firebase::firestore::model::ListenSequenceNumber;
  49. using firebase::firestore::model::TargetId;
  50. using firebase::firestore::testutil::Key;
  51. using firebase::firestore::util::OrderedCode;
  52. using firebase::firestore::util::Path;
  53. using leveldb::DB;
  54. using leveldb::Options;
  55. using leveldb::Status;
  56. using SchemaVersion = LevelDbMigrations::SchemaVersion;
  57. @interface FSTLevelDBMigrationsTests : XCTestCase
  58. @end
  59. @implementation FSTLevelDBMigrationsTests {
  60. std::unique_ptr<DB> _db;
  61. }
  62. - (void)setUp {
  63. Options options;
  64. options.error_if_exists = true;
  65. options.create_if_missing = true;
  66. Path dir = [FSTPersistenceTestHelpers levelDBDir];
  67. DB *db;
  68. Status status = DB::Open(options, dir.ToUtf8String(), &db);
  69. XCTAssert(status.ok(), @"Failed to create db: %s", status.ToString().c_str());
  70. _db.reset(db);
  71. }
  72. - (void)tearDown {
  73. _db.reset();
  74. }
  75. - (void)testAddsTargetGlobal {
  76. FSTPBTargetGlobal *metadata = [FSTLevelDBQueryCache readTargetMetadataFromDB:_db.get()];
  77. XCTAssertNil(metadata, @"Not expecting metadata yet, we should have an empty db");
  78. LevelDbMigrations::RunMigrations(_db.get());
  79. metadata = [FSTLevelDBQueryCache readTargetMetadataFromDB:_db.get()];
  80. XCTAssertNotNil(metadata, @"Migrations should have added the metadata");
  81. }
  82. - (void)testSetsVersionNumber {
  83. {
  84. LevelDbTransaction transaction(_db.get(), "testSetsVersionNumber before");
  85. SchemaVersion initial = LevelDbMigrations::ReadSchemaVersion(&transaction);
  86. XCTAssertEqual(0, initial, "No version should be equivalent to 0");
  87. }
  88. {
  89. // Pick an arbitrary high migration number and migrate to it.
  90. LevelDbMigrations::RunMigrations(_db.get());
  91. LevelDbTransaction transaction(_db.get(), "testSetsVersionNumber after");
  92. SchemaVersion actual = LevelDbMigrations::ReadSchemaVersion(&transaction);
  93. XCTAssertGreaterThan(actual, 0, @"Expected to migrate to a schema version > 0");
  94. }
  95. }
  96. #define ASSERT_NOT_FOUND(transaction, key) \
  97. do { \
  98. std::string unused_result; \
  99. Status status = transaction.Get(key, &unused_result); \
  100. XCTAssertTrue(status.IsNotFound()); \
  101. } while (0)
  102. #define ASSERT_FOUND(transaction, key) \
  103. do { \
  104. std::string unused_result; \
  105. Status status = transaction.Get(key, &unused_result); \
  106. XCTAssertTrue(status.ok()); \
  107. } while (0)
  108. - (void)testDropsTheQueryCache {
  109. std::string userID{"user"};
  110. BatchId batchID = 1;
  111. TargetId targetID = 2;
  112. FSTDocumentKey *key1 = Key("documents/1");
  113. FSTDocumentKey *key2 = Key("documents/2");
  114. std::string targetKeys[] = {
  115. LevelDbTargetKey::Key(targetID),
  116. LevelDbTargetDocumentKey::Key(targetID, key1),
  117. LevelDbTargetDocumentKey::Key(targetID, key2),
  118. LevelDbDocumentTargetKey::Key(key1, targetID),
  119. LevelDbDocumentTargetKey::Key(key2, targetID),
  120. LevelDbQueryTargetKey::Key("foo.bar.baz", targetID),
  121. };
  122. // Keys that should not be modified by the dropping the query cache
  123. std::string preservedKeys[] = {
  124. [self dummyKeyForTable:"targetA"],
  125. LevelDbMutationQueueKey::Key(userID),
  126. LevelDbMutationKey::Key(userID, batchID),
  127. };
  128. LevelDbMigrations::RunMigrations(_db.get(), 2);
  129. {
  130. // Setup some targets to be counted in the migration.
  131. LevelDbTransaction transaction(_db.get(), "testDropsTheQueryCache setup");
  132. for (const std::string &key : targetKeys) {
  133. transaction.Put(key, "target");
  134. }
  135. for (const std::string &key : preservedKeys) {
  136. transaction.Put(key, "preserved");
  137. }
  138. transaction.Commit();
  139. }
  140. LevelDbMigrations::RunMigrations(_db.get(), 3);
  141. {
  142. LevelDbTransaction transaction(_db.get(), "testDropsTheQueryCache");
  143. for (const std::string &key : targetKeys) {
  144. ASSERT_NOT_FOUND(transaction, key);
  145. }
  146. for (const std::string &key : preservedKeys) {
  147. ASSERT_FOUND(transaction, key);
  148. }
  149. FSTPBTargetGlobal *metadata = [FSTLevelDBQueryCache readTargetMetadataFromDB:_db.get()];
  150. XCTAssertNotNil(metadata, @"Metadata should have been added");
  151. XCTAssertEqual(metadata.targetCount, 0);
  152. }
  153. }
  154. - (void)testDropsTheQueryCacheWithThousandsOfEntries {
  155. LevelDbMigrations::RunMigrations(_db.get(), 2);
  156. {
  157. // Setup some targets to be destroyed.
  158. LevelDbTransaction transaction(_db.get(), "testDropsTheQueryCacheWithThousandsOfEntries setup");
  159. for (int i = 0; i < 10000; ++i) {
  160. transaction.Put(LevelDbTargetKey::Key(i), "");
  161. }
  162. transaction.Commit();
  163. }
  164. LevelDbMigrations::RunMigrations(_db.get(), 3);
  165. {
  166. LevelDbTransaction transaction(_db.get(), "Verify");
  167. std::string prefix = LevelDbTargetKey::KeyPrefix();
  168. auto it = transaction.NewIterator();
  169. std::vector<std::string> found_keys;
  170. for (it->Seek(prefix); it->Valid() && absl::StartsWith(it->key(), prefix); it->Next()) {
  171. found_keys.push_back(std::string{it->key()});
  172. }
  173. XCTAssertEqual(found_keys, std::vector<std::string>{});
  174. }
  175. }
  176. - (void)testAddsSentinelRows {
  177. ListenSequenceNumber old_sequence_number = 1;
  178. ListenSequenceNumber new_sequence_number = 2;
  179. std::string encoded_old_sequence_number =
  180. LevelDbDocumentTargetKey::EncodeSentinelValue(old_sequence_number);
  181. LevelDbMigrations::RunMigrations(_db.get(), 3);
  182. {
  183. std::string empty_buffer;
  184. LevelDbTransaction transaction(_db.get(), "Setup");
  185. // Set up target global
  186. FSTPBTargetGlobal *metadata = [FSTLevelDBQueryCache readTargetMetadataFromDB:_db.get()];
  187. // Expect that documents missing a row will get the new number
  188. metadata.highestListenSequenceNumber = new_sequence_number;
  189. transaction.Put(LevelDbTargetGlobalKey::Key(), metadata);
  190. // Set up some documents (we only need the keys)
  191. // For the odd ones, add sentinel rows.
  192. for (int i = 0; i < 10; i++) {
  193. DocumentKey key = DocumentKey::FromSegments({"docs", std::to_string(i)});
  194. transaction.Put(LevelDbRemoteDocumentKey::Key(key), empty_buffer);
  195. if (i % 2 == 1) {
  196. std::string sentinel_key = LevelDbDocumentTargetKey::SentinelKey(key);
  197. transaction.Put(sentinel_key, encoded_old_sequence_number);
  198. }
  199. }
  200. transaction.Commit();
  201. }
  202. LevelDbMigrations::RunMigrations(_db.get(), 4);
  203. {
  204. LevelDbTransaction transaction(_db.get(), "Verify");
  205. auto it = transaction.NewIterator();
  206. std::string documents_prefix = LevelDbRemoteDocumentKey::KeyPrefix();
  207. it->Seek(documents_prefix);
  208. int count = 0;
  209. LevelDbRemoteDocumentKey document_key;
  210. std::string buffer;
  211. for (; it->Valid() && absl::StartsWith(it->key(), documents_prefix); it->Next()) {
  212. count++;
  213. XCTAssertTrue(document_key.Decode(it->key()));
  214. const DocumentKey &key = document_key.document_key();
  215. std::string sentinel_key = LevelDbDocumentTargetKey::SentinelKey(key);
  216. XCTAssertTrue(transaction.Get(sentinel_key, &buffer).ok());
  217. int doc_number = atoi(key.path().last_segment().c_str());
  218. // If the document number is odd, we expect the original old sequence number that we wrote.
  219. // If it's even, we expect that the migration added the new sequence number from the target
  220. // global
  221. ListenSequenceNumber expected_sequence_number =
  222. doc_number % 2 == 1 ? old_sequence_number : new_sequence_number;
  223. ListenSequenceNumber sequence_number = LevelDbDocumentTargetKey::DecodeSentinelValue(buffer);
  224. XCTAssertEqual(expected_sequence_number, sequence_number);
  225. }
  226. XCTAssertEqual(10, count);
  227. }
  228. }
  229. /**
  230. * Creates the name of a dummy entry to make sure the iteration is correctly bounded.
  231. */
  232. - (std::string)dummyKeyForTable:(const char *)tableName {
  233. std::string dummyKey;
  234. // Magic number that indicates a table name follows. Needed to mimic the prefix to the target
  235. // table.
  236. OrderedCode::WriteSignedNumIncreasing(&dummyKey, 5);
  237. OrderedCode::WriteString(&dummyKey, tableName);
  238. return dummyKey;
  239. }
  240. @end
  241. NS_ASSUME_NONNULL_END