FSTLevelDBMigrationsTests.mm 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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 <map>
  18. #include <memory>
  19. #include <string>
  20. #include <vector>
  21. #import "Firestore/Protos/objc/firestore/local/Mutation.pbobjc.h"
  22. #import "Firestore/Protos/objc/firestore/local/Target.pbobjc.h"
  23. #import "Firestore/Source/Local/FSTLevelDB.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/local/leveldb_query_cache.h"
  27. #include "Firestore/core/src/firebase/firestore/util/ordered_code.h"
  28. #include "Firestore/core/test/firebase/firestore/testutil/testutil.h"
  29. #include "absl/strings/match.h"
  30. #include "leveldb/db.h"
  31. #import "Firestore/Example/Tests/Local/FSTPersistenceTestHelpers.h"
  32. NS_ASSUME_NONNULL_BEGIN
  33. using firebase::firestore::FirestoreErrorCode;
  34. using firebase::firestore::local::LevelDbCollectionParentKey;
  35. using firebase::firestore::local::LevelDbDocumentMutationKey;
  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::LevelDbQueryCache;
  41. using firebase::firestore::local::LevelDbQueryTargetKey;
  42. using firebase::firestore::local::LevelDbRemoteDocumentKey;
  43. using firebase::firestore::local::LevelDbTargetDocumentKey;
  44. using firebase::firestore::local::LevelDbTargetGlobalKey;
  45. using firebase::firestore::local::LevelDbTargetKey;
  46. using firebase::firestore::local::LevelDbTransaction;
  47. using firebase::firestore::model::BatchId;
  48. using firebase::firestore::model::DocumentKey;
  49. using firebase::firestore::model::ListenSequenceNumber;
  50. using firebase::firestore::model::TargetId;
  51. using firebase::firestore::testutil::Key;
  52. using firebase::firestore::util::OrderedCode;
  53. using firebase::firestore::util::Path;
  54. using leveldb::DB;
  55. using leveldb::Options;
  56. using leveldb::Status;
  57. using SchemaVersion = LevelDbMigrations::SchemaVersion;
  58. @interface FSTLevelDBMigrationsTests : XCTestCase
  59. @end
  60. @implementation FSTLevelDBMigrationsTests {
  61. std::unique_ptr<DB> _db;
  62. }
  63. - (void)setUp {
  64. Options options;
  65. options.error_if_exists = true;
  66. options.create_if_missing = true;
  67. Path dir = [FSTPersistenceTestHelpers levelDBDir];
  68. DB *db;
  69. Status status = DB::Open(options, dir.ToUtf8String(), &db);
  70. XCTAssert(status.ok(), @"Failed to create db: %s", status.ToString().c_str());
  71. _db.reset(db);
  72. }
  73. - (void)tearDown {
  74. _db.reset();
  75. }
  76. - (void)testAddsTargetGlobal {
  77. FSTPBTargetGlobal *metadata = LevelDbQueryCache::ReadMetadata(_db.get());
  78. XCTAssertNil(metadata, @"Not expecting metadata yet, we should have an empty db");
  79. LevelDbMigrations::RunMigrations(_db.get());
  80. metadata = LevelDbQueryCache::ReadMetadata(_db.get());
  81. XCTAssertNotNil(metadata, @"Migrations should have added the metadata");
  82. }
  83. - (void)testSetsVersionNumber {
  84. SchemaVersion initial = LevelDbMigrations::ReadSchemaVersion(_db.get());
  85. XCTAssertEqual(0, initial, "No version should be equivalent to 0");
  86. // Pick an arbitrary high migration number and migrate to it.
  87. LevelDbMigrations::RunMigrations(_db.get());
  88. SchemaVersion actual = LevelDbMigrations::ReadSchemaVersion(_db.get());
  89. XCTAssertGreaterThan(actual, 0, @"Expected to migrate to a schema version > 0");
  90. }
  91. #define ASSERT_NOT_FOUND(transaction, key) \
  92. do { \
  93. std::string unused_result; \
  94. Status status = transaction.Get(key, &unused_result); \
  95. XCTAssertTrue(status.IsNotFound()); \
  96. } while (0)
  97. #define ASSERT_FOUND(transaction, key) \
  98. do { \
  99. std::string unused_result; \
  100. Status status = transaction.Get(key, &unused_result); \
  101. XCTAssertTrue(status.ok()); \
  102. } while (0)
  103. - (void)testDropsTheQueryCache {
  104. std::string userID{"user"};
  105. BatchId batchID = 1;
  106. TargetId targetID = 2;
  107. DocumentKey key1 = Key("documents/1");
  108. DocumentKey key2 = Key("documents/2");
  109. std::string targetKeys[] = {
  110. LevelDbTargetKey::Key(targetID),
  111. LevelDbTargetDocumentKey::Key(targetID, key1),
  112. LevelDbTargetDocumentKey::Key(targetID, key2),
  113. LevelDbDocumentTargetKey::Key(key1, targetID),
  114. LevelDbDocumentTargetKey::Key(key2, targetID),
  115. LevelDbQueryTargetKey::Key("foo.bar.baz", targetID),
  116. };
  117. // Keys that should not be modified by the dropping the query cache
  118. std::string preservedKeys[] = {
  119. [self dummyKeyForTable:"targetA"],
  120. LevelDbMutationQueueKey::Key(userID),
  121. LevelDbMutationKey::Key(userID, batchID),
  122. };
  123. LevelDbMigrations::RunMigrations(_db.get(), 2);
  124. {
  125. // Setup some targets to be counted in the migration.
  126. LevelDbTransaction transaction(_db.get(), "testDropsTheQueryCache setup");
  127. for (const std::string &key : targetKeys) {
  128. transaction.Put(key, "target");
  129. }
  130. for (const std::string &key : preservedKeys) {
  131. transaction.Put(key, "preserved");
  132. }
  133. transaction.Commit();
  134. }
  135. LevelDbMigrations::RunMigrations(_db.get(), 3);
  136. {
  137. LevelDbTransaction transaction(_db.get(), "testDropsTheQueryCache");
  138. for (const std::string &key : targetKeys) {
  139. ASSERT_NOT_FOUND(transaction, key);
  140. }
  141. for (const std::string &key : preservedKeys) {
  142. ASSERT_FOUND(transaction, key);
  143. }
  144. FSTPBTargetGlobal *metadata = LevelDbQueryCache::ReadMetadata(_db.get());
  145. XCTAssertNotNil(metadata, @"Metadata should have been added");
  146. XCTAssertEqual(metadata.targetCount, 0);
  147. }
  148. }
  149. - (void)testDropsTheQueryCacheWithThousandsOfEntries {
  150. LevelDbMigrations::RunMigrations(_db.get(), 2);
  151. {
  152. // Setup some targets to be destroyed.
  153. LevelDbTransaction transaction(_db.get(), "testDropsTheQueryCacheWithThousandsOfEntries setup");
  154. for (int i = 0; i < 10000; ++i) {
  155. transaction.Put(LevelDbTargetKey::Key(i), "");
  156. }
  157. transaction.Commit();
  158. }
  159. LevelDbMigrations::RunMigrations(_db.get(), 3);
  160. {
  161. LevelDbTransaction transaction(_db.get(), "Verify");
  162. std::string prefix = LevelDbTargetKey::KeyPrefix();
  163. auto it = transaction.NewIterator();
  164. std::vector<std::string> found_keys;
  165. for (it->Seek(prefix); it->Valid() && absl::StartsWith(it->key(), prefix); it->Next()) {
  166. found_keys.push_back(std::string{it->key()});
  167. }
  168. XCTAssertEqual(found_keys, std::vector<std::string>{});
  169. }
  170. }
  171. - (void)testAddsSentinelRows {
  172. ListenSequenceNumber old_sequence_number = 1;
  173. ListenSequenceNumber new_sequence_number = 2;
  174. std::string encoded_old_sequence_number =
  175. LevelDbDocumentTargetKey::EncodeSentinelValue(old_sequence_number);
  176. LevelDbMigrations::RunMigrations(_db.get(), 3);
  177. {
  178. std::string empty_buffer;
  179. LevelDbTransaction transaction(_db.get(), "Setup");
  180. // Set up target global
  181. FSTPBTargetGlobal *metadata = LevelDbQueryCache::ReadMetadata(_db.get());
  182. // Expect that documents missing a row will get the new number
  183. metadata.highestListenSequenceNumber = new_sequence_number;
  184. transaction.Put(LevelDbTargetGlobalKey::Key(), metadata);
  185. // Set up some documents (we only need the keys)
  186. // For the odd ones, add sentinel rows.
  187. for (int i = 0; i < 10; i++) {
  188. DocumentKey key = DocumentKey::FromSegments({"docs", std::to_string(i)});
  189. transaction.Put(LevelDbRemoteDocumentKey::Key(key), empty_buffer);
  190. if (i % 2 == 1) {
  191. std::string sentinel_key = LevelDbDocumentTargetKey::SentinelKey(key);
  192. transaction.Put(sentinel_key, encoded_old_sequence_number);
  193. }
  194. }
  195. transaction.Commit();
  196. }
  197. LevelDbMigrations::RunMigrations(_db.get(), 4);
  198. {
  199. LevelDbTransaction transaction(_db.get(), "Verify");
  200. auto it = transaction.NewIterator();
  201. std::string documents_prefix = LevelDbRemoteDocumentKey::KeyPrefix();
  202. it->Seek(documents_prefix);
  203. int count = 0;
  204. LevelDbRemoteDocumentKey document_key;
  205. std::string buffer;
  206. for (; it->Valid() && absl::StartsWith(it->key(), documents_prefix); it->Next()) {
  207. count++;
  208. XCTAssertTrue(document_key.Decode(it->key()));
  209. const DocumentKey &key = document_key.document_key();
  210. std::string sentinel_key = LevelDbDocumentTargetKey::SentinelKey(key);
  211. XCTAssertTrue(transaction.Get(sentinel_key, &buffer).ok());
  212. int doc_number = atoi(key.path().last_segment().c_str());
  213. // If the document number is odd, we expect the original old sequence number that we wrote.
  214. // If it's even, we expect that the migration added the new sequence number from the target
  215. // global
  216. ListenSequenceNumber expected_sequence_number =
  217. doc_number % 2 == 1 ? old_sequence_number : new_sequence_number;
  218. ListenSequenceNumber sequence_number = LevelDbDocumentTargetKey::DecodeSentinelValue(buffer);
  219. XCTAssertEqual(expected_sequence_number, sequence_number);
  220. }
  221. XCTAssertEqual(10, count);
  222. }
  223. }
  224. - (void)testRemovesMutationBatches {
  225. std::string emptyBuffer;
  226. DocumentKey testWriteFoo = DocumentKey::FromPathString("docs/foo");
  227. DocumentKey testWriteBar = DocumentKey::FromPathString("docs/bar");
  228. DocumentKey testWriteBaz = DocumentKey::FromPathString("docs/baz");
  229. DocumentKey testWritePending = DocumentKey::FromPathString("docs/pending");
  230. // Do everything up until the mutation batch migration.
  231. LevelDbMigrations::RunMigrations(_db.get(), 3);
  232. // Set up data
  233. {
  234. LevelDbTransaction transaction(_db.get(), "Setup Foo");
  235. // User 'foo' has two acknowledged mutations and one that is pending.
  236. FSTPBMutationQueue *fooQueue = [[FSTPBMutationQueue alloc] init];
  237. fooQueue.lastAcknowledgedBatchId = 2;
  238. std::string fooKey = LevelDbMutationQueueKey::Key("foo");
  239. transaction.Put(fooKey, fooQueue);
  240. FSTPBWriteBatch *fooBatch1 = [[FSTPBWriteBatch alloc] init];
  241. fooBatch1.batchId = 1;
  242. std::string fooBatchKey1 = LevelDbMutationKey::Key("foo", 1);
  243. transaction.Put(fooBatchKey1, fooBatch1);
  244. transaction.Put(LevelDbDocumentMutationKey::Key("foo", testWriteFoo, 1), emptyBuffer);
  245. FSTPBWriteBatch *fooBatch2 = [[FSTPBWriteBatch alloc] init];
  246. fooBatch2.batchId = 2;
  247. std::string fooBatchKey2 = LevelDbMutationKey::Key("foo", 2);
  248. transaction.Put(fooBatchKey2, fooBatch2);
  249. transaction.Put(LevelDbDocumentMutationKey::Key("foo", testWriteFoo, 2), emptyBuffer);
  250. FSTPBWriteBatch *fooBatch3 = [[FSTPBWriteBatch alloc] init];
  251. fooBatch3.batchId = 5;
  252. std::string fooBatchKey3 = LevelDbMutationKey::Key("foo", 5);
  253. transaction.Put(fooBatchKey3, fooBatch3);
  254. transaction.Put(LevelDbDocumentMutationKey::Key("foo", testWritePending, 5), emptyBuffer);
  255. transaction.Commit();
  256. }
  257. {
  258. LevelDbTransaction transaction(_db.get(), "Setup Bar");
  259. // User 'bar' has one acknowledged mutation and one that is pending
  260. FSTPBMutationQueue *barQueue = [[FSTPBMutationQueue alloc] init];
  261. barQueue.lastAcknowledgedBatchId = 3;
  262. std::string barKey = LevelDbMutationQueueKey::Key("bar");
  263. transaction.Put(barKey, barQueue);
  264. FSTPBWriteBatch *barBatch1 = [[FSTPBWriteBatch alloc] init];
  265. barBatch1.batchId = 3;
  266. std::string barBatchKey1 = LevelDbMutationKey::Key("bar", 3);
  267. transaction.Put(barBatchKey1, barBatch1);
  268. transaction.Put(LevelDbDocumentMutationKey::Key("bar", testWriteBar, 3), emptyBuffer);
  269. transaction.Put(LevelDbDocumentMutationKey::Key("bar", testWriteBaz, 3), emptyBuffer);
  270. FSTPBWriteBatch *barBatch2 = [[FSTPBWriteBatch alloc] init];
  271. barBatch2.batchId = 4;
  272. std::string barBatchKey2 = LevelDbMutationKey::Key("bar", 4);
  273. transaction.Put(barBatchKey2, barBatch2);
  274. transaction.Put(LevelDbDocumentMutationKey::Key("bar", testWritePending, 4), emptyBuffer);
  275. transaction.Commit();
  276. }
  277. {
  278. LevelDbTransaction transaction(_db.get(), "Setup Empty");
  279. // User 'empty' has no mutations
  280. FSTPBMutationQueue *emptyQueue = [[FSTPBMutationQueue alloc] init];
  281. emptyQueue.lastAcknowledgedBatchId = -1;
  282. std::string emptyKey = LevelDbMutationQueueKey::Key("empty");
  283. transaction.Put(emptyKey, emptyQueue);
  284. transaction.Commit();
  285. }
  286. LevelDbMigrations::RunMigrations(_db.get(), 5);
  287. {
  288. // Verify
  289. std::string buffer;
  290. LevelDbTransaction transaction(_db.get(), "Verify");
  291. // verify that we deleted the correct batches
  292. XCTAssertTrue(transaction.Get(LevelDbMutationKey::Key("foo", 1), &buffer).IsNotFound());
  293. XCTAssertTrue(transaction.Get(LevelDbMutationKey::Key("foo", 2), &buffer).IsNotFound());
  294. XCTAssertTrue(transaction.Get(LevelDbMutationKey::Key("foo", 5), &buffer).ok());
  295. XCTAssertTrue(transaction.Get(LevelDbMutationKey::Key("bar", 3), &buffer).IsNotFound());
  296. XCTAssertTrue(transaction.Get(LevelDbMutationKey::Key("bar", 4), &buffer).ok());
  297. // verify document associations have been removed
  298. XCTAssertTrue(transaction.Get(LevelDbDocumentMutationKey::Key("foo", testWriteFoo, 1), &buffer)
  299. .IsNotFound());
  300. XCTAssertTrue(transaction.Get(LevelDbDocumentMutationKey::Key("foo", testWriteFoo, 2), &buffer)
  301. .IsNotFound());
  302. XCTAssertTrue(
  303. transaction.Get(LevelDbDocumentMutationKey::Key("foo", testWritePending, 5), &buffer).ok());
  304. XCTAssertTrue(transaction.Get(LevelDbDocumentMutationKey::Key("bar", testWriteBar, 3), &buffer)
  305. .IsNotFound());
  306. XCTAssertTrue(transaction.Get(LevelDbDocumentMutationKey::Key("bar", testWriteBaz, 3), &buffer)
  307. .IsNotFound());
  308. XCTAssertTrue(
  309. transaction.Get(LevelDbDocumentMutationKey::Key("bar", testWritePending, 4), &buffer).ok());
  310. }
  311. }
  312. - (void)testCreateCollectionParentsIndex {
  313. // This test creates a database with schema version 5 that has a few
  314. // mutations and a few remote documents and then ensures that appropriate
  315. // entries are written to the collectionParentIndex.
  316. std::vector<std::string> write_paths{"cg1/x", "cg1/y", "cg1/x/cg1/x", "cg2/x", "cg1/x/cg2/x"};
  317. std::vector<std::string> remote_doc_paths{"cg1/z", "cg1/y/cg1/x", "cg2/x/cg3/x",
  318. "blah/x/blah/x/cg3/x"};
  319. std::map<std::string, std::vector<std::string>> expected_parents{
  320. {"cg1", {"", "cg1/x", "cg1/y"}}, {"cg2", {"", "cg1/x"}}, {"cg3", {"blah/x/blah/x", "cg2/x"}}};
  321. std::string empty_buffer;
  322. LevelDbMigrations::RunMigrations(_db.get(), 5);
  323. {
  324. LevelDbTransaction transaction(_db.get(), "Write Mutations and Remote Documents");
  325. // Write mutations.
  326. for (auto write_path : write_paths) {
  327. // We "cheat" and only write the DbDocumentMutation index entries, since
  328. // that's all the migration uses.
  329. DocumentKey key = DocumentKey::FromPathString(write_path);
  330. transaction.Put(LevelDbDocumentMutationKey::Key("dummy-uid", key, /*dummy batchId=*/123),
  331. empty_buffer);
  332. }
  333. // Write remote document entries.
  334. for (auto remote_doc_path : remote_doc_paths) {
  335. DocumentKey key = DocumentKey::FromPathString(remote_doc_path);
  336. transaction.Put(LevelDbRemoteDocumentKey::Key(key), empty_buffer);
  337. }
  338. transaction.Commit();
  339. }
  340. // Migrate to v6 and verify index entries.
  341. LevelDbMigrations::RunMigrations(_db.get(), 6);
  342. {
  343. LevelDbTransaction transaction(_db.get(), "Verify");
  344. std::map<std::string, std::vector<std::string>> actual_parents;
  345. auto index_iterator = transaction.NewIterator();
  346. std::string index_prefix = LevelDbCollectionParentKey::KeyPrefix();
  347. LevelDbCollectionParentKey row_key;
  348. for (index_iterator->Seek(index_prefix); index_iterator->Valid(); index_iterator->Next()) {
  349. if (!absl::StartsWith(index_iterator->key(), index_prefix) ||
  350. !row_key.Decode(index_iterator->key()))
  351. break;
  352. std::vector<std::string> &parents = actual_parents[row_key.collection_id()];
  353. parents.push_back(row_key.parent().CanonicalString());
  354. }
  355. XCTAssertEqual(actual_parents, expected_parents);
  356. }
  357. }
  358. - (void)testCanDowngrade {
  359. // First, run all of the migrations
  360. LevelDbMigrations::RunMigrations(_db.get());
  361. LevelDbMigrations::SchemaVersion latestVersion = LevelDbMigrations::ReadSchemaVersion(_db.get());
  362. // Downgrade to an early version.
  363. LevelDbMigrations::SchemaVersion downgradeVersion = 1;
  364. LevelDbMigrations::RunMigrations(_db.get(), downgradeVersion);
  365. LevelDbMigrations::SchemaVersion postDowngradeVersion =
  366. LevelDbMigrations::ReadSchemaVersion(_db.get());
  367. XCTAssertEqual(downgradeVersion, postDowngradeVersion);
  368. // Verify that we can upgrade again to the latest version.
  369. LevelDbMigrations::RunMigrations(_db.get());
  370. LevelDbMigrations::SchemaVersion finalVersion = LevelDbMigrations::ReadSchemaVersion(_db.get());
  371. XCTAssertEqual(finalVersion, latestVersion);
  372. }
  373. /**
  374. * Creates the name of a dummy entry to make sure the iteration is correctly bounded.
  375. */
  376. - (std::string)dummyKeyForTable:(const char *)tableName {
  377. std::string dummyKey;
  378. // Magic number that indicates a table name follows. Needed to mimic the prefix to the target
  379. // table.
  380. OrderedCode::WriteSignedNumIncreasing(&dummyKey, 5);
  381. OrderedCode::WriteString(&dummyKey, tableName);
  382. return dummyKey;
  383. }
  384. @end
  385. NS_ASSUME_NONNULL_END