FSTLevelDBMigrationsTests.mm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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/Mutation.pbobjc.h"
  21. #import "Firestore/Protos/objc/firestore/local/Target.pbobjc.h"
  22. #import "Firestore/Source/Local/FSTLevelDB.h"
  23. #import "Firestore/Source/Local/FSTLevelDBMutationQueue.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::LevelDbDocumentMutationKey;
  35. using firebase::firestore::local::LevelDbDocumentTargetKey;
  36. using firebase::firestore::local::LevelDbMigrations;
  37. using firebase::firestore::local::LevelDbMutationKey;
  38. using firebase::firestore::local::LevelDbMutationQueueKey;
  39. using firebase::firestore::local::LevelDbQueryCache;
  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 = LevelDbQueryCache::ReadMetadata(_db.get());
  77. XCTAssertNil(metadata, @"Not expecting metadata yet, we should have an empty db");
  78. LevelDbMigrations::RunMigrations(_db.get());
  79. metadata = LevelDbQueryCache::ReadMetadata(_db.get());
  80. XCTAssertNotNil(metadata, @"Migrations should have added the metadata");
  81. }
  82. - (void)testSetsVersionNumber {
  83. SchemaVersion initial = LevelDbMigrations::ReadSchemaVersion(_db.get());
  84. XCTAssertEqual(0, initial, "No version should be equivalent to 0");
  85. // Pick an arbitrary high migration number and migrate to it.
  86. LevelDbMigrations::RunMigrations(_db.get());
  87. SchemaVersion actual = LevelDbMigrations::ReadSchemaVersion(_db.get());
  88. XCTAssertGreaterThan(actual, 0, @"Expected to migrate to a schema version > 0");
  89. }
  90. #define ASSERT_NOT_FOUND(transaction, key) \
  91. do { \
  92. std::string unused_result; \
  93. Status status = transaction.Get(key, &unused_result); \
  94. XCTAssertTrue(status.IsNotFound()); \
  95. } while (0)
  96. #define ASSERT_FOUND(transaction, key) \
  97. do { \
  98. std::string unused_result; \
  99. Status status = transaction.Get(key, &unused_result); \
  100. XCTAssertTrue(status.ok()); \
  101. } while (0)
  102. - (void)testDropsTheQueryCache {
  103. std::string userID{"user"};
  104. BatchId batchID = 1;
  105. TargetId targetID = 2;
  106. DocumentKey key1 = Key("documents/1");
  107. DocumentKey key2 = Key("documents/2");
  108. std::string targetKeys[] = {
  109. LevelDbTargetKey::Key(targetID),
  110. LevelDbTargetDocumentKey::Key(targetID, key1),
  111. LevelDbTargetDocumentKey::Key(targetID, key2),
  112. LevelDbDocumentTargetKey::Key(key1, targetID),
  113. LevelDbDocumentTargetKey::Key(key2, targetID),
  114. LevelDbQueryTargetKey::Key("foo.bar.baz", targetID),
  115. };
  116. // Keys that should not be modified by the dropping the query cache
  117. std::string preservedKeys[] = {
  118. [self dummyKeyForTable:"targetA"],
  119. LevelDbMutationQueueKey::Key(userID),
  120. LevelDbMutationKey::Key(userID, batchID),
  121. };
  122. LevelDbMigrations::RunMigrations(_db.get(), 2);
  123. {
  124. // Setup some targets to be counted in the migration.
  125. LevelDbTransaction transaction(_db.get(), "testDropsTheQueryCache setup");
  126. for (const std::string &key : targetKeys) {
  127. transaction.Put(key, "target");
  128. }
  129. for (const std::string &key : preservedKeys) {
  130. transaction.Put(key, "preserved");
  131. }
  132. transaction.Commit();
  133. }
  134. LevelDbMigrations::RunMigrations(_db.get(), 3);
  135. {
  136. LevelDbTransaction transaction(_db.get(), "testDropsTheQueryCache");
  137. for (const std::string &key : targetKeys) {
  138. ASSERT_NOT_FOUND(transaction, key);
  139. }
  140. for (const std::string &key : preservedKeys) {
  141. ASSERT_FOUND(transaction, key);
  142. }
  143. FSTPBTargetGlobal *metadata = LevelDbQueryCache::ReadMetadata(_db.get());
  144. XCTAssertNotNil(metadata, @"Metadata should have been added");
  145. XCTAssertEqual(metadata.targetCount, 0);
  146. }
  147. }
  148. - (void)testDropsTheQueryCacheWithThousandsOfEntries {
  149. LevelDbMigrations::RunMigrations(_db.get(), 2);
  150. {
  151. // Setup some targets to be destroyed.
  152. LevelDbTransaction transaction(_db.get(), "testDropsTheQueryCacheWithThousandsOfEntries setup");
  153. for (int i = 0; i < 10000; ++i) {
  154. transaction.Put(LevelDbTargetKey::Key(i), "");
  155. }
  156. transaction.Commit();
  157. }
  158. LevelDbMigrations::RunMigrations(_db.get(), 3);
  159. {
  160. LevelDbTransaction transaction(_db.get(), "Verify");
  161. std::string prefix = LevelDbTargetKey::KeyPrefix();
  162. auto it = transaction.NewIterator();
  163. std::vector<std::string> found_keys;
  164. for (it->Seek(prefix); it->Valid() && absl::StartsWith(it->key(), prefix); it->Next()) {
  165. found_keys.push_back(std::string{it->key()});
  166. }
  167. XCTAssertEqual(found_keys, std::vector<std::string>{});
  168. }
  169. }
  170. - (void)testAddsSentinelRows {
  171. ListenSequenceNumber old_sequence_number = 1;
  172. ListenSequenceNumber new_sequence_number = 2;
  173. std::string encoded_old_sequence_number =
  174. LevelDbDocumentTargetKey::EncodeSentinelValue(old_sequence_number);
  175. LevelDbMigrations::RunMigrations(_db.get(), 3);
  176. {
  177. std::string empty_buffer;
  178. LevelDbTransaction transaction(_db.get(), "Setup");
  179. // Set up target global
  180. FSTPBTargetGlobal *metadata = LevelDbQueryCache::ReadMetadata(_db.get());
  181. // Expect that documents missing a row will get the new number
  182. metadata.highestListenSequenceNumber = new_sequence_number;
  183. transaction.Put(LevelDbTargetGlobalKey::Key(), metadata);
  184. // Set up some documents (we only need the keys)
  185. // For the odd ones, add sentinel rows.
  186. for (int i = 0; i < 10; i++) {
  187. DocumentKey key = DocumentKey::FromSegments({"docs", std::to_string(i)});
  188. transaction.Put(LevelDbRemoteDocumentKey::Key(key), empty_buffer);
  189. if (i % 2 == 1) {
  190. std::string sentinel_key = LevelDbDocumentTargetKey::SentinelKey(key);
  191. transaction.Put(sentinel_key, encoded_old_sequence_number);
  192. }
  193. }
  194. transaction.Commit();
  195. }
  196. LevelDbMigrations::RunMigrations(_db.get(), 4);
  197. {
  198. LevelDbTransaction transaction(_db.get(), "Verify");
  199. auto it = transaction.NewIterator();
  200. std::string documents_prefix = LevelDbRemoteDocumentKey::KeyPrefix();
  201. it->Seek(documents_prefix);
  202. int count = 0;
  203. LevelDbRemoteDocumentKey document_key;
  204. std::string buffer;
  205. for (; it->Valid() && absl::StartsWith(it->key(), documents_prefix); it->Next()) {
  206. count++;
  207. XCTAssertTrue(document_key.Decode(it->key()));
  208. const DocumentKey &key = document_key.document_key();
  209. std::string sentinel_key = LevelDbDocumentTargetKey::SentinelKey(key);
  210. XCTAssertTrue(transaction.Get(sentinel_key, &buffer).ok());
  211. int doc_number = atoi(key.path().last_segment().c_str());
  212. // If the document number is odd, we expect the original old sequence number that we wrote.
  213. // If it's even, we expect that the migration added the new sequence number from the target
  214. // global
  215. ListenSequenceNumber expected_sequence_number =
  216. doc_number % 2 == 1 ? old_sequence_number : new_sequence_number;
  217. ListenSequenceNumber sequence_number = LevelDbDocumentTargetKey::DecodeSentinelValue(buffer);
  218. XCTAssertEqual(expected_sequence_number, sequence_number);
  219. }
  220. XCTAssertEqual(10, count);
  221. }
  222. }
  223. - (void)testRemovesMutationBatches {
  224. std::string emptyBuffer;
  225. DocumentKey testWriteFoo = DocumentKey::FromPathString("docs/foo");
  226. DocumentKey testWriteBar = DocumentKey::FromPathString("docs/bar");
  227. DocumentKey testWriteBaz = DocumentKey::FromPathString("docs/baz");
  228. DocumentKey testWritePending = DocumentKey::FromPathString("docs/pending");
  229. // Do everything up until the mutation batch migration.
  230. LevelDbMigrations::RunMigrations(_db.get(), 3);
  231. // Set up data
  232. {
  233. LevelDbTransaction transaction(_db.get(), "Setup Foo");
  234. // User 'foo' has two acknowledged mutations and one that is pending.
  235. FSTPBMutationQueue *fooQueue = [[FSTPBMutationQueue alloc] init];
  236. fooQueue.lastAcknowledgedBatchId = 2;
  237. std::string fooKey = LevelDbMutationQueueKey::Key("foo");
  238. transaction.Put(fooKey, fooQueue);
  239. FSTPBWriteBatch *fooBatch1 = [[FSTPBWriteBatch alloc] init];
  240. fooBatch1.batchId = 1;
  241. std::string fooBatchKey1 = LevelDbMutationKey::Key("foo", 1);
  242. transaction.Put(fooBatchKey1, fooBatch1);
  243. transaction.Put(LevelDbDocumentMutationKey::Key("foo", testWriteFoo, 1), emptyBuffer);
  244. FSTPBWriteBatch *fooBatch2 = [[FSTPBWriteBatch alloc] init];
  245. fooBatch2.batchId = 2;
  246. std::string fooBatchKey2 = LevelDbMutationKey::Key("foo", 2);
  247. transaction.Put(fooBatchKey2, fooBatch2);
  248. transaction.Put(LevelDbDocumentMutationKey::Key("foo", testWriteFoo, 2), emptyBuffer);
  249. FSTPBWriteBatch *fooBatch3 = [[FSTPBWriteBatch alloc] init];
  250. fooBatch3.batchId = 5;
  251. std::string fooBatchKey3 = LevelDbMutationKey::Key("foo", 5);
  252. transaction.Put(fooBatchKey3, fooBatch3);
  253. transaction.Put(LevelDbDocumentMutationKey::Key("foo", testWritePending, 5), emptyBuffer);
  254. transaction.Commit();
  255. }
  256. {
  257. LevelDbTransaction transaction(_db.get(), "Setup Bar");
  258. // User 'bar' has one acknowledged mutation and one that is pending
  259. FSTPBMutationQueue *barQueue = [[FSTPBMutationQueue alloc] init];
  260. barQueue.lastAcknowledgedBatchId = 3;
  261. std::string barKey = LevelDbMutationQueueKey::Key("bar");
  262. transaction.Put(barKey, barQueue);
  263. FSTPBWriteBatch *barBatch1 = [[FSTPBWriteBatch alloc] init];
  264. barBatch1.batchId = 3;
  265. std::string barBatchKey1 = LevelDbMutationKey::Key("bar", 3);
  266. transaction.Put(barBatchKey1, barBatch1);
  267. transaction.Put(LevelDbDocumentMutationKey::Key("bar", testWriteBar, 3), emptyBuffer);
  268. transaction.Put(LevelDbDocumentMutationKey::Key("bar", testWriteBaz, 3), emptyBuffer);
  269. FSTPBWriteBatch *barBatch2 = [[FSTPBWriteBatch alloc] init];
  270. barBatch2.batchId = 4;
  271. std::string barBatchKey2 = LevelDbMutationKey::Key("bar", 4);
  272. transaction.Put(barBatchKey2, barBatch2);
  273. transaction.Put(LevelDbDocumentMutationKey::Key("bar", testWritePending, 4), emptyBuffer);
  274. transaction.Commit();
  275. }
  276. {
  277. LevelDbTransaction transaction(_db.get(), "Setup Empty");
  278. // User 'empty' has no mutations
  279. FSTPBMutationQueue *emptyQueue = [[FSTPBMutationQueue alloc] init];
  280. emptyQueue.lastAcknowledgedBatchId = -1;
  281. std::string emptyKey = LevelDbMutationQueueKey::Key("empty");
  282. transaction.Put(emptyKey, emptyQueue);
  283. transaction.Commit();
  284. }
  285. LevelDbMigrations::RunMigrations(_db.get(), 5);
  286. {
  287. // Verify
  288. std::string buffer;
  289. LevelDbTransaction transaction(_db.get(), "Verify");
  290. auto it = transaction.NewIterator();
  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)testCanDowngrade {
  313. // First, run all of the migrations
  314. LevelDbMigrations::RunMigrations(_db.get());
  315. LevelDbMigrations::SchemaVersion latestVersion = LevelDbMigrations::ReadSchemaVersion(_db.get());
  316. // Downgrade to an early version.
  317. LevelDbMigrations::SchemaVersion downgradeVersion = 1;
  318. LevelDbMigrations::RunMigrations(_db.get(), downgradeVersion);
  319. LevelDbMigrations::SchemaVersion postDowngradeVersion =
  320. LevelDbMigrations::ReadSchemaVersion(_db.get());
  321. XCTAssertEqual(downgradeVersion, postDowngradeVersion);
  322. // Verify that we can upgrade again to the latest version.
  323. LevelDbMigrations::RunMigrations(_db.get());
  324. LevelDbMigrations::SchemaVersion finalVersion = LevelDbMigrations::ReadSchemaVersion(_db.get());
  325. XCTAssertEqual(finalVersion, latestVersion);
  326. }
  327. /**
  328. * Creates the name of a dummy entry to make sure the iteration is correctly bounded.
  329. */
  330. - (std::string)dummyKeyForTable:(const char *)tableName {
  331. std::string dummyKey;
  332. // Magic number that indicates a table name follows. Needed to mimic the prefix to the target
  333. // table.
  334. OrderedCode::WriteSignedNumIncreasing(&dummyKey, 5);
  335. OrderedCode::WriteString(&dummyKey, tableName);
  336. return dummyKey;
  337. }
  338. @end
  339. NS_ASSUME_NONNULL_END