FSTLevelDBMutationQueue.mm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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 "Firestore/Source/Local/FSTLevelDBMutationQueue.h"
  17. #include <memory>
  18. #include <set>
  19. #include <string>
  20. #include <utility>
  21. #include <vector>
  22. #import "Firestore/Protos/objc/firestore/local/Mutation.pbobjc.h"
  23. #import "Firestore/Source/Core/FSTQuery.h"
  24. #import "Firestore/Source/Local/FSTLevelDB.h"
  25. #import "Firestore/Source/Local/FSTLocalSerializer.h"
  26. #import "Firestore/Source/Model/FSTMutation.h"
  27. #import "Firestore/Source/Model/FSTMutationBatch.h"
  28. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  29. #include "Firestore/core/src/firebase/firestore/local/leveldb_key.h"
  30. #include "Firestore/core/src/firebase/firestore/local/leveldb_transaction.h"
  31. #include "Firestore/core/src/firebase/firestore/local/leveldb_util.h"
  32. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  33. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  34. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  35. #include "Firestore/core/src/firebase/firestore/util/string_util.h"
  36. #include "absl/strings/match.h"
  37. #include "leveldb/db.h"
  38. #include "leveldb/write_batch.h"
  39. NS_ASSUME_NONNULL_BEGIN
  40. namespace util = firebase::firestore::util;
  41. using firebase::firestore::auth::User;
  42. using firebase::firestore::local::DescribeKey;
  43. using firebase::firestore::local::LevelDbDocumentMutationKey;
  44. using firebase::firestore::local::LevelDbMutationKey;
  45. using firebase::firestore::local::LevelDbMutationQueueKey;
  46. using firebase::firestore::local::LevelDbTransaction;
  47. using firebase::firestore::local::MakeStringView;
  48. using firebase::firestore::model::BatchId;
  49. using firebase::firestore::model::DocumentKey;
  50. using firebase::firestore::model::DocumentKeySet;
  51. using firebase::firestore::model::ResourcePath;
  52. using leveldb::DB;
  53. using leveldb::Iterator;
  54. using leveldb::ReadOptions;
  55. using leveldb::Slice;
  56. using leveldb::Status;
  57. using leveldb::WriteBatch;
  58. using leveldb::WriteOptions;
  59. @interface FSTLevelDBMutationQueue ()
  60. - (instancetype)initWithUserID:(std::string)userID
  61. db:(FSTLevelDB *)db
  62. serializer:(FSTLocalSerializer *)serializer NS_DESIGNATED_INITIALIZER;
  63. /**
  64. * Next value to use when assigning sequential IDs to each mutation batch.
  65. *
  66. * NOTE: There can only be one FSTLevelDBMutationQueue for a given db at a time, hence it is safe
  67. * to track nextBatchID as an instance-level property. Should we ever relax this constraint we'll
  68. * need to revisit this.
  69. */
  70. @property(nonatomic, assign) BatchId nextBatchID;
  71. /** A write-through cache copy of the metadata describing the current queue. */
  72. @property(nonatomic, strong, nullable) FSTPBMutationQueue *metadata;
  73. @property(nonatomic, strong, readonly) FSTLocalSerializer *serializer;
  74. @end
  75. @implementation FSTLevelDBMutationQueue {
  76. FSTLevelDB *_db;
  77. /** The normalized userID (e.g. nil UID => @"" userID) used in our LevelDB keys. */
  78. std::string _userID;
  79. }
  80. + (instancetype)mutationQueueWithUser:(const User &)user
  81. db:(FSTLevelDB *)db
  82. serializer:(FSTLocalSerializer *)serializer {
  83. std::string userID = user.is_authenticated() ? user.uid() : "";
  84. return [[FSTLevelDBMutationQueue alloc] initWithUserID:std::move(userID)
  85. db:db
  86. serializer:serializer];
  87. }
  88. - (instancetype)initWithUserID:(std::string)userID
  89. db:(FSTLevelDB *)db
  90. serializer:(FSTLocalSerializer *)serializer {
  91. if (self = [super init]) {
  92. _userID = std::move(userID);
  93. _db = db;
  94. _serializer = serializer;
  95. }
  96. return self;
  97. }
  98. - (void)start {
  99. BatchId nextBatchID = [FSTLevelDBMutationQueue loadNextBatchIDFromDB:_db.ptr];
  100. // On restart, nextBatchId may end up lower than lastAcknowledgedBatchId since it's computed from
  101. // the queue contents, and there may be no mutations in the queue. In this case, we need to reset
  102. // lastAcknowledgedBatchId (which is safe since the queue must be empty).
  103. std::string key = [self keyForCurrentMutationQueue];
  104. FSTPBMutationQueue *metadata = [self metadataForKey:key];
  105. if (!metadata) {
  106. metadata = [FSTPBMutationQueue message];
  107. // proto3's default value for lastAcknowledgedBatchId is zero, but that would consider the first
  108. // entry in the queue to be acknowledged without that acknowledgement actually happening.
  109. metadata.lastAcknowledgedBatchId = kFSTBatchIDUnknown;
  110. } else {
  111. BatchId lastAcked = metadata.lastAcknowledgedBatchId;
  112. if (lastAcked >= nextBatchID) {
  113. HARD_ASSERT([self isEmpty], "Reset nextBatchID is only possible when the queue is empty");
  114. lastAcked = kFSTBatchIDUnknown;
  115. metadata.lastAcknowledgedBatchId = lastAcked;
  116. _db.currentTransaction->Put([self keyForCurrentMutationQueue], metadata);
  117. }
  118. }
  119. self.nextBatchID = nextBatchID;
  120. self.metadata = metadata;
  121. }
  122. + (BatchId)loadNextBatchIDFromDB:(DB *)db {
  123. // TODO(gsoltis): implement Prev() and SeekToLast() on LevelDbTransaction::Iterator, then port
  124. // this to a transaction.
  125. std::unique_ptr<Iterator> it(db->NewIterator(LevelDbTransaction::DefaultReadOptions()));
  126. auto tableKey = LevelDbMutationKey::KeyPrefix();
  127. LevelDbMutationKey rowKey;
  128. BatchId maxBatchID = kFSTBatchIDUnknown;
  129. BOOL moreUserIDs = NO;
  130. std::string nextUserID;
  131. it->Seek(tableKey);
  132. if (it->Valid() && rowKey.Decode(MakeStringView(it->key()))) {
  133. moreUserIDs = YES;
  134. nextUserID = rowKey.user_id();
  135. }
  136. // This loop assumes that nextUserId contains the next username at the start of the iteration.
  137. while (moreUserIDs) {
  138. // Compute the first key after the last mutation for nextUserID.
  139. auto userEnd = LevelDbMutationKey::KeyPrefix(nextUserID);
  140. userEnd = util::PrefixSuccessor(userEnd);
  141. // Seek to that key with the intent of finding the boundary between nextUserID's mutations
  142. // and the one after that (if any).
  143. it->Seek(userEnd);
  144. // At this point there are three possible cases to handle differently. Each case must prepare
  145. // the next iteration (by assigning to nextUserID or setting moreUserIDs = NO) and seek the
  146. // iterator to the last row in the current user's mutation sequence.
  147. if (!it->Valid()) {
  148. // The iterator is past the last row altogether (there are no additional userIDs and now
  149. // rows in any table after mutations). The last row will have the highest batchID.
  150. moreUserIDs = NO;
  151. it->SeekToLast();
  152. } else if (rowKey.Decode(MakeStringView(it->key()))) {
  153. // The iterator is valid and the key decoded successfully so the next user was just decoded.
  154. nextUserID = rowKey.user_id();
  155. it->Prev();
  156. } else {
  157. // The iterator is past the end of the mutations table but there are other rows.
  158. moreUserIDs = NO;
  159. it->Prev();
  160. }
  161. // In all the cases above there was at least one row for the current user and each case has
  162. // set things up such that iterator points to it.
  163. if (!rowKey.Decode(MakeStringView(it->key()))) {
  164. HARD_FAIL("There should have been a key previous to %s", userEnd);
  165. }
  166. if (rowKey.batch_id() > maxBatchID) {
  167. maxBatchID = rowKey.batch_id();
  168. }
  169. }
  170. return maxBatchID + 1;
  171. }
  172. - (BOOL)isEmpty {
  173. std::string userKey = LevelDbMutationKey::KeyPrefix(_userID);
  174. auto it = _db.currentTransaction->NewIterator();
  175. it->Seek(userKey);
  176. BOOL empty = YES;
  177. if (it->Valid() && absl::StartsWith(it->key(), userKey)) {
  178. empty = NO;
  179. }
  180. return empty;
  181. }
  182. - (BatchId)highestAcknowledgedBatchID {
  183. return self.metadata.lastAcknowledgedBatchId;
  184. }
  185. - (void)acknowledgeBatch:(FSTMutationBatch *)batch streamToken:(nullable NSData *)streamToken {
  186. BatchId batchID = batch.batchID;
  187. HARD_ASSERT(batchID > self.highestAcknowledgedBatchID,
  188. "Mutation batchIDs must be acknowledged in order");
  189. FSTPBMutationQueue *metadata = self.metadata;
  190. metadata.lastAcknowledgedBatchId = batchID;
  191. metadata.lastStreamToken = streamToken;
  192. _db.currentTransaction->Put([self keyForCurrentMutationQueue], metadata);
  193. }
  194. - (nullable NSData *)lastStreamToken {
  195. return self.metadata.lastStreamToken;
  196. }
  197. - (void)setLastStreamToken:(nullable NSData *)streamToken {
  198. FSTPBMutationQueue *metadata = self.metadata;
  199. metadata.lastStreamToken = streamToken;
  200. _db.currentTransaction->Put([self keyForCurrentMutationQueue], metadata);
  201. }
  202. - (std::string)keyForCurrentMutationQueue {
  203. return LevelDbMutationQueueKey::Key(_userID);
  204. }
  205. - (nullable FSTPBMutationQueue *)metadataForKey:(const std::string &)key {
  206. std::string value;
  207. Status status = _db.currentTransaction->Get(key, &value);
  208. if (status.ok()) {
  209. return [self parsedMetadata:value];
  210. } else if (status.IsNotFound()) {
  211. return nil;
  212. } else {
  213. HARD_FAIL("metadataForKey: failed loading key %s with status: %s", key, status.ToString());
  214. }
  215. }
  216. - (FSTMutationBatch *)addMutationBatchWithWriteTime:(FIRTimestamp *)localWriteTime
  217. mutations:(NSArray<FSTMutation *> *)mutations {
  218. BatchId batchID = self.nextBatchID;
  219. self.nextBatchID += 1;
  220. FSTMutationBatch *batch = [[FSTMutationBatch alloc] initWithBatchID:batchID
  221. localWriteTime:localWriteTime
  222. mutations:mutations];
  223. std::string key = [self mutationKeyForBatch:batch];
  224. _db.currentTransaction->Put(key, [self.serializer encodedMutationBatch:batch]);
  225. // Store an empty value in the index which is equivalent to serializing a GPBEmpty message. In the
  226. // future if we wanted to store some other kind of value here, we can parse these empty values as
  227. // with some other protocol buffer (and the parser will see all default values).
  228. std::string emptyBuffer;
  229. for (FSTMutation *mutation in mutations) {
  230. key = LevelDbDocumentMutationKey::Key(_userID, mutation.key, batchID);
  231. _db.currentTransaction->Put(key, emptyBuffer);
  232. }
  233. return batch;
  234. }
  235. - (nullable FSTMutationBatch *)lookupMutationBatch:(BatchId)batchID {
  236. std::string key = [self mutationKeyForBatchID:batchID];
  237. std::string value;
  238. Status status = _db.currentTransaction->Get(key, &value);
  239. if (!status.ok()) {
  240. if (status.IsNotFound()) {
  241. return nil;
  242. }
  243. HARD_FAIL("Lookup mutation batch (%s, %s) failed with status: %s", _userID, batchID,
  244. status.ToString());
  245. }
  246. return [self decodedMutationBatch:value];
  247. }
  248. - (nullable FSTMutationBatch *)nextMutationBatchAfterBatchID:(BatchId)batchID {
  249. // All batches with batchID <= self.metadata.lastAcknowledgedBatchId have been acknowledged so
  250. // the first unacknowledged batch after batchID will have a batchID larger than both of these
  251. // values.
  252. BatchId nextBatchID = MAX(batchID, self.metadata.lastAcknowledgedBatchId) + 1;
  253. std::string key = [self mutationKeyForBatchID:nextBatchID];
  254. auto it = _db.currentTransaction->NewIterator();
  255. it->Seek(key);
  256. LevelDbMutationKey rowKey;
  257. if (!it->Valid() || !rowKey.Decode(it->key())) {
  258. // Past the last row in the DB or out of the mutations table
  259. return nil;
  260. }
  261. if (rowKey.user_id() != _userID) {
  262. // Jumped past the last mutation for this user
  263. return nil;
  264. }
  265. HARD_ASSERT(rowKey.batch_id() >= nextBatchID, "Should have found mutation after %s", nextBatchID);
  266. return [self decodedMutationBatch:it->value()];
  267. }
  268. - (NSArray<FSTMutationBatch *> *)allMutationBatchesThroughBatchID:(BatchId)batchID {
  269. std::string userKey = LevelDbMutationKey::KeyPrefix(_userID);
  270. auto it = _db.currentTransaction->NewIterator();
  271. it->Seek(userKey);
  272. NSMutableArray *result = [NSMutableArray array];
  273. LevelDbMutationKey rowKey;
  274. for (; it->Valid() && rowKey.Decode(it->key()); it->Next()) {
  275. if (rowKey.user_id() != _userID) {
  276. // End of this user's mutations
  277. break;
  278. } else if (rowKey.batch_id() > batchID) {
  279. // This mutation is past what we're looking for
  280. break;
  281. }
  282. [result addObject:[self decodedMutationBatch:it->value()]];
  283. }
  284. return result;
  285. }
  286. - (NSArray<FSTMutationBatch *> *)allMutationBatchesAffectingDocumentKey:
  287. (const DocumentKey &)documentKey {
  288. // Scan the document-mutation index starting with a prefix starting with the given documentKey.
  289. std::string indexPrefix = LevelDbDocumentMutationKey::KeyPrefix(_userID, documentKey.path());
  290. auto indexIterator = _db.currentTransaction->NewIterator();
  291. indexIterator->Seek(indexPrefix);
  292. // Simultaneously scan the mutation queue. This works because each (key, batchID) pair is unique
  293. // and ordered, so when scanning a table prefixed by exactly key, all the batchIDs encountered
  294. // will be unique and in order.
  295. std::string mutationsPrefix = LevelDbMutationKey::KeyPrefix(_userID);
  296. auto mutationIterator = _db.currentTransaction->NewIterator();
  297. NSMutableArray *result = [NSMutableArray array];
  298. LevelDbDocumentMutationKey rowKey;
  299. for (; indexIterator->Valid(); indexIterator->Next()) {
  300. // Only consider rows matching exactly the specific key of interest. Index rows have this
  301. // form (with markers in brackets):
  302. //
  303. // <User>user <Path>collection <Path>doc <BatchId>2 <Terminator>
  304. // <User>user <Path>collection <Path>doc <BatchId>3 <Terminator>
  305. // <User>user <Path>collection <Path>doc <Path>sub <Path>doc <BatchId>3 <Terminator>
  306. //
  307. // Note that Path markers sort after BatchId markers so this means that when searching for
  308. // collection/doc, all the entries for it will be contiguous in the table, allowing a break
  309. // after any mismatch.
  310. if (!absl::StartsWith(indexIterator->key(), indexPrefix) ||
  311. !rowKey.Decode(indexIterator->key()) || rowKey.document_key() != documentKey) {
  312. break;
  313. }
  314. // Each row is a unique combination of key and batchID, so this foreign key reference can
  315. // only occur once.
  316. std::string mutationKey = LevelDbMutationKey::Key(_userID, rowKey.batch_id());
  317. mutationIterator->Seek(mutationKey);
  318. if (!mutationIterator->Valid() || mutationIterator->key() != mutationKey) {
  319. HARD_FAIL(
  320. "Dangling document-mutation reference found: "
  321. "%s points to %s; seeking there found %s",
  322. DescribeKey(indexIterator), DescribeKey(mutationKey), DescribeKey(mutationIterator));
  323. }
  324. [result addObject:[self decodedMutationBatch:mutationIterator->value()]];
  325. }
  326. return result;
  327. }
  328. - (NSArray<FSTMutationBatch *> *)allMutationBatchesAffectingDocumentKeys:
  329. (const DocumentKeySet &)documentKeys {
  330. // Take a pass through the document keys and collect the set of unique mutation batchIDs that
  331. // affect them all. Some batches can affect more than one key.
  332. std::set<BatchId> batchIDs;
  333. auto indexIterator = _db.currentTransaction->NewIterator();
  334. LevelDbDocumentMutationKey rowKey;
  335. for (const DocumentKey &documentKey : documentKeys) {
  336. std::string indexPrefix = LevelDbDocumentMutationKey::KeyPrefix(_userID, documentKey.path());
  337. for (indexIterator->Seek(indexPrefix); indexIterator->Valid(); indexIterator->Next()) {
  338. // Only consider rows matching exactly the specific key of interest. Index rows have this
  339. // form (with markers in brackets):
  340. //
  341. // <User>user <Path>collection <Path>doc <BatchId>2 <Terminator>
  342. // <User>user <Path>collection <Path>doc <BatchId>3 <Terminator>
  343. // <User>user <Path>collection <Path>doc <Path>sub <Path>doc <BatchId>3 <Terminator>
  344. //
  345. // Note that Path markers sort after BatchId markers so this means that when searching for
  346. // collection/doc, all the entries for it will be contiguous in the table, allowing a break
  347. // after any mismatch.
  348. if (!absl::StartsWith(indexIterator->key(), indexPrefix) ||
  349. !rowKey.Decode(indexIterator->key()) || rowKey.document_key() != documentKey) {
  350. break;
  351. }
  352. batchIDs.insert(rowKey.batch_id());
  353. }
  354. }
  355. return [self allMutationBatchesWithBatchIDs:batchIDs];
  356. }
  357. - (NSArray<FSTMutationBatch *> *)allMutationBatchesAffectingQuery:(FSTQuery *)query {
  358. HARD_ASSERT(![query isDocumentQuery], "Document queries shouldn't go down this path");
  359. const ResourcePath &queryPath = query.path;
  360. size_t immediateChildrenPathLength = queryPath.size() + 1;
  361. // TODO(mcg): Actually implement a single-collection query
  362. //
  363. // This is actually executing an ancestor query, traversing the whole subtree below the
  364. // collection which can be horrifically inefficient for some structures. The right way to
  365. // solve this is to implement the full value index, but that's not in the cards in the near
  366. // future so this is the best we can do for the moment.
  367. //
  368. // Since we don't yet index the actual properties in the mutations, our current approach is to
  369. // just return all mutation batches that affect documents in the collection being queried.
  370. //
  371. // Unlike allMutationBatchesAffectingDocumentKey, this iteration will scan the document-mutation
  372. // index for more than a single document so the associated batchIDs will be neither necessarily
  373. // unique nor in order. This means an efficient simultaneous scan isn't possible.
  374. std::string indexPrefix = LevelDbDocumentMutationKey::KeyPrefix(_userID, queryPath);
  375. auto indexIterator = _db.currentTransaction->NewIterator();
  376. indexIterator->Seek(indexPrefix);
  377. LevelDbDocumentMutationKey rowKey;
  378. // Collect up unique batchIDs encountered during a scan of the index. Use a set<BatchId> to
  379. // accumulate batch IDs so they can be traversed in order in a scan of the main table.
  380. //
  381. // This method is faster than performing lookups of the keys with _db->Get and keeping a hash of
  382. // batchIDs that have already been looked up. The performance difference is minor for small
  383. // numbers of keys but > 30% faster for larger numbers of keys.
  384. std::set<BatchId> uniqueBatchIDs;
  385. for (; indexIterator->Valid(); indexIterator->Next()) {
  386. if (!absl::StartsWith(indexIterator->key(), indexPrefix) ||
  387. !rowKey.Decode(indexIterator->key())) {
  388. break;
  389. }
  390. // Rows with document keys more than one segment longer than the query path can't be matches.
  391. // For example, a query on 'rooms' can't match the document /rooms/abc/messages/xyx.
  392. // TODO(mcg): we'll need a different scanner when we implement ancestor queries.
  393. if (rowKey.document_key().path().size() != immediateChildrenPathLength) {
  394. continue;
  395. }
  396. uniqueBatchIDs.insert(rowKey.batch_id());
  397. }
  398. return [self allMutationBatchesWithBatchIDs:uniqueBatchIDs];
  399. }
  400. /**
  401. * Constructs an array of matching batches, sorted by batchID to ensure that multiple mutations
  402. * affecting the same document key are applied in order.
  403. */
  404. - (NSArray<FSTMutationBatch *> *)allMutationBatchesWithBatchIDs:
  405. (const std::set<BatchId> &)batchIDs {
  406. NSMutableArray *result = [NSMutableArray array];
  407. // Given an ordered set of unique batchIDs perform a skipping scan over the main table to find
  408. // the mutation batches.
  409. auto mutationIterator = _db.currentTransaction->NewIterator();
  410. for (BatchId batchID : batchIDs) {
  411. std::string mutationKey = LevelDbMutationKey::Key(_userID, batchID);
  412. mutationIterator->Seek(mutationKey);
  413. if (!mutationIterator->Valid() || mutationIterator->key() != mutationKey) {
  414. HARD_FAIL(
  415. "Dangling document-mutation reference found: "
  416. "Missing batch %s; seeking there found %s",
  417. DescribeKey(mutationKey), DescribeKey(mutationIterator));
  418. }
  419. [result addObject:[self decodedMutationBatch:mutationIterator->value()]];
  420. }
  421. return result;
  422. }
  423. - (NSArray<FSTMutationBatch *> *)allMutationBatches {
  424. std::string userKey = LevelDbMutationKey::KeyPrefix(_userID);
  425. auto it = _db.currentTransaction->NewIterator();
  426. it->Seek(userKey);
  427. NSMutableArray *result = [NSMutableArray array];
  428. for (; it->Valid() && absl::StartsWith(it->key(), userKey); it->Next()) {
  429. [result addObject:[self decodedMutationBatch:it->value()]];
  430. }
  431. return result;
  432. }
  433. - (void)removeMutationBatches:(NSArray<FSTMutationBatch *> *)batches {
  434. auto checkIterator = _db.currentTransaction->NewIterator();
  435. for (FSTMutationBatch *batch in batches) {
  436. BatchId batchID = batch.batchID;
  437. std::string key = LevelDbMutationKey::Key(_userID, batchID);
  438. // As a sanity check, verify that the mutation batch exists before deleting it.
  439. checkIterator->Seek(key);
  440. HARD_ASSERT(checkIterator->Valid(), "Mutation batch %s did not exist", DescribeKey(key));
  441. HARD_ASSERT(key == checkIterator->key(), "Mutation batch %s not found; found %s",
  442. DescribeKey(key), DescribeKey(checkIterator));
  443. _db.currentTransaction->Delete(key);
  444. for (FSTMutation *mutation in batch.mutations) {
  445. key = LevelDbDocumentMutationKey::Key(_userID, mutation.key, batchID);
  446. _db.currentTransaction->Delete(key);
  447. [_db.referenceDelegate removeMutationReference:mutation.key];
  448. }
  449. }
  450. }
  451. - (void)performConsistencyCheck {
  452. if (![self isEmpty]) {
  453. return;
  454. }
  455. // Verify that there are no entries in the document-mutation index if the queue is empty.
  456. std::string indexPrefix = LevelDbDocumentMutationKey::KeyPrefix(_userID);
  457. auto indexIterator = _db.currentTransaction->NewIterator();
  458. indexIterator->Seek(indexPrefix);
  459. std::vector<std::string> danglingMutationReferences;
  460. for (; indexIterator->Valid(); indexIterator->Next()) {
  461. // Only consider rows matching this index prefix for the current user.
  462. if (!absl::StartsWith(indexIterator->key(), indexPrefix)) {
  463. break;
  464. }
  465. danglingMutationReferences.push_back(DescribeKey(indexIterator));
  466. }
  467. HARD_ASSERT(danglingMutationReferences.empty(),
  468. "Document leak -- detected dangling mutation references when queue "
  469. "is empty. Dangling keys: %s",
  470. util::ToString(danglingMutationReferences));
  471. }
  472. - (std::string)mutationKeyForBatch:(FSTMutationBatch *)batch {
  473. return LevelDbMutationKey::Key(_userID, batch.batchID);
  474. }
  475. - (std::string)mutationKeyForBatchID:(BatchId)batchID {
  476. return LevelDbMutationKey::Key(_userID, batchID);
  477. }
  478. /** Parses the MutationQueue metadata from the given LevelDB row contents. */
  479. - (FSTPBMutationQueue *)parsedMetadata:(Slice)slice {
  480. NSData *data =
  481. [[NSData alloc] initWithBytesNoCopy:(void *)slice.data() length:slice.size() freeWhenDone:NO];
  482. NSError *error;
  483. FSTPBMutationQueue *proto = [FSTPBMutationQueue parseFromData:data error:&error];
  484. if (!proto) {
  485. HARD_FAIL("FSTPBMutationQueue failed to parse: %s", error);
  486. }
  487. return proto;
  488. }
  489. - (FSTMutationBatch *)decodedMutationBatch:(absl::string_view)encoded {
  490. NSData *data = [[NSData alloc] initWithBytesNoCopy:(void *)encoded.data()
  491. length:encoded.size()
  492. freeWhenDone:NO];
  493. NSError *error;
  494. FSTPBWriteBatch *proto = [FSTPBWriteBatch parseFromData:data error:&error];
  495. if (!proto) {
  496. HARD_FAIL("FSTPBMutationBatch failed to parse: %s", error);
  497. }
  498. return [self.serializer decodedMutationBatch:proto];
  499. }
  500. @end
  501. NS_ASSUME_NONNULL_END