FSTLevelDBMutationQueue.mm 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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 *> *)allMutationBatchesAffectingDocumentKey:
  269. (const DocumentKey &)documentKey {
  270. // Scan the document-mutation index starting with a prefix starting with the given documentKey.
  271. std::string indexPrefix = LevelDbDocumentMutationKey::KeyPrefix(_userID, documentKey.path());
  272. auto indexIterator = _db.currentTransaction->NewIterator();
  273. indexIterator->Seek(indexPrefix);
  274. // Simultaneously scan the mutation queue. This works because each (key, batchID) pair is unique
  275. // and ordered, so when scanning a table prefixed by exactly key, all the batchIDs encountered
  276. // will be unique and in order.
  277. std::string mutationsPrefix = LevelDbMutationKey::KeyPrefix(_userID);
  278. auto mutationIterator = _db.currentTransaction->NewIterator();
  279. NSMutableArray *result = [NSMutableArray array];
  280. LevelDbDocumentMutationKey rowKey;
  281. for (; indexIterator->Valid(); indexIterator->Next()) {
  282. // Only consider rows matching exactly the specific key of interest. Index rows have this
  283. // form (with markers in brackets):
  284. //
  285. // <User>user <Path>collection <Path>doc <BatchId>2 <Terminator>
  286. // <User>user <Path>collection <Path>doc <BatchId>3 <Terminator>
  287. // <User>user <Path>collection <Path>doc <Path>sub <Path>doc <BatchId>3 <Terminator>
  288. //
  289. // Note that Path markers sort after BatchId markers so this means that when searching for
  290. // collection/doc, all the entries for it will be contiguous in the table, allowing a break
  291. // after any mismatch.
  292. if (!absl::StartsWith(indexIterator->key(), indexPrefix) ||
  293. !rowKey.Decode(indexIterator->key()) || rowKey.document_key() != documentKey) {
  294. break;
  295. }
  296. // Each row is a unique combination of key and batchID, so this foreign key reference can
  297. // only occur once.
  298. std::string mutationKey = LevelDbMutationKey::Key(_userID, rowKey.batch_id());
  299. mutationIterator->Seek(mutationKey);
  300. if (!mutationIterator->Valid() || mutationIterator->key() != mutationKey) {
  301. HARD_FAIL(
  302. "Dangling document-mutation reference found: "
  303. "%s points to %s; seeking there found %s",
  304. DescribeKey(indexIterator), DescribeKey(mutationKey), DescribeKey(mutationIterator));
  305. }
  306. [result addObject:[self decodedMutationBatch:mutationIterator->value()]];
  307. }
  308. return result;
  309. }
  310. - (NSArray<FSTMutationBatch *> *)allMutationBatchesAffectingDocumentKeys:
  311. (const DocumentKeySet &)documentKeys {
  312. // Take a pass through the document keys and collect the set of unique mutation batchIDs that
  313. // affect them all. Some batches can affect more than one key.
  314. std::set<BatchId> batchIDs;
  315. auto indexIterator = _db.currentTransaction->NewIterator();
  316. LevelDbDocumentMutationKey rowKey;
  317. for (const DocumentKey &documentKey : documentKeys) {
  318. std::string indexPrefix = LevelDbDocumentMutationKey::KeyPrefix(_userID, documentKey.path());
  319. for (indexIterator->Seek(indexPrefix); indexIterator->Valid(); indexIterator->Next()) {
  320. // Only consider rows matching exactly the specific key of interest. Index rows have this
  321. // form (with markers in brackets):
  322. //
  323. // <User>user <Path>collection <Path>doc <BatchId>2 <Terminator>
  324. // <User>user <Path>collection <Path>doc <BatchId>3 <Terminator>
  325. // <User>user <Path>collection <Path>doc <Path>sub <Path>doc <BatchId>3 <Terminator>
  326. //
  327. // Note that Path markers sort after BatchId markers so this means that when searching for
  328. // collection/doc, all the entries for it will be contiguous in the table, allowing a break
  329. // after any mismatch.
  330. if (!absl::StartsWith(indexIterator->key(), indexPrefix) ||
  331. !rowKey.Decode(indexIterator->key()) || rowKey.document_key() != documentKey) {
  332. break;
  333. }
  334. batchIDs.insert(rowKey.batch_id());
  335. }
  336. }
  337. return [self allMutationBatchesWithBatchIDs:batchIDs];
  338. }
  339. - (NSArray<FSTMutationBatch *> *)allMutationBatchesAffectingQuery:(FSTQuery *)query {
  340. HARD_ASSERT(![query isDocumentQuery], "Document queries shouldn't go down this path");
  341. const ResourcePath &queryPath = query.path;
  342. size_t immediateChildrenPathLength = queryPath.size() + 1;
  343. // TODO(mcg): Actually implement a single-collection query
  344. //
  345. // This is actually executing an ancestor query, traversing the whole subtree below the
  346. // collection which can be horrifically inefficient for some structures. The right way to
  347. // solve this is to implement the full value index, but that's not in the cards in the near
  348. // future so this is the best we can do for the moment.
  349. //
  350. // Since we don't yet index the actual properties in the mutations, our current approach is to
  351. // just return all mutation batches that affect documents in the collection being queried.
  352. //
  353. // Unlike allMutationBatchesAffectingDocumentKey, this iteration will scan the document-mutation
  354. // index for more than a single document so the associated batchIDs will be neither necessarily
  355. // unique nor in order. This means an efficient simultaneous scan isn't possible.
  356. std::string indexPrefix = LevelDbDocumentMutationKey::KeyPrefix(_userID, queryPath);
  357. auto indexIterator = _db.currentTransaction->NewIterator();
  358. indexIterator->Seek(indexPrefix);
  359. LevelDbDocumentMutationKey rowKey;
  360. // Collect up unique batchIDs encountered during a scan of the index. Use a set<BatchId> to
  361. // accumulate batch IDs so they can be traversed in order in a scan of the main table.
  362. //
  363. // This method is faster than performing lookups of the keys with _db->Get and keeping a hash of
  364. // batchIDs that have already been looked up. The performance difference is minor for small
  365. // numbers of keys but > 30% faster for larger numbers of keys.
  366. std::set<BatchId> uniqueBatchIDs;
  367. for (; indexIterator->Valid(); indexIterator->Next()) {
  368. if (!absl::StartsWith(indexIterator->key(), indexPrefix) ||
  369. !rowKey.Decode(indexIterator->key())) {
  370. break;
  371. }
  372. // Rows with document keys more than one segment longer than the query path can't be matches.
  373. // For example, a query on 'rooms' can't match the document /rooms/abc/messages/xyx.
  374. // TODO(mcg): we'll need a different scanner when we implement ancestor queries.
  375. if (rowKey.document_key().path().size() != immediateChildrenPathLength) {
  376. continue;
  377. }
  378. uniqueBatchIDs.insert(rowKey.batch_id());
  379. }
  380. return [self allMutationBatchesWithBatchIDs:uniqueBatchIDs];
  381. }
  382. /**
  383. * Constructs an array of matching batches, sorted by batchID to ensure that multiple mutations
  384. * affecting the same document key are applied in order.
  385. */
  386. - (NSArray<FSTMutationBatch *> *)allMutationBatchesWithBatchIDs:
  387. (const std::set<BatchId> &)batchIDs {
  388. NSMutableArray *result = [NSMutableArray array];
  389. // Given an ordered set of unique batchIDs perform a skipping scan over the main table to find
  390. // the mutation batches.
  391. auto mutationIterator = _db.currentTransaction->NewIterator();
  392. for (BatchId batchID : batchIDs) {
  393. std::string mutationKey = LevelDbMutationKey::Key(_userID, batchID);
  394. mutationIterator->Seek(mutationKey);
  395. if (!mutationIterator->Valid() || mutationIterator->key() != mutationKey) {
  396. HARD_FAIL(
  397. "Dangling document-mutation reference found: "
  398. "Missing batch %s; seeking there found %s",
  399. DescribeKey(mutationKey), DescribeKey(mutationIterator));
  400. }
  401. [result addObject:[self decodedMutationBatch:mutationIterator->value()]];
  402. }
  403. return result;
  404. }
  405. - (NSArray<FSTMutationBatch *> *)allMutationBatches {
  406. std::string userKey = LevelDbMutationKey::KeyPrefix(_userID);
  407. auto it = _db.currentTransaction->NewIterator();
  408. it->Seek(userKey);
  409. NSMutableArray *result = [NSMutableArray array];
  410. for (; it->Valid() && absl::StartsWith(it->key(), userKey); it->Next()) {
  411. [result addObject:[self decodedMutationBatch:it->value()]];
  412. }
  413. return result;
  414. }
  415. - (void)removeMutationBatch:(FSTMutationBatch *)batch {
  416. auto checkIterator = _db.currentTransaction->NewIterator();
  417. BatchId batchID = batch.batchID;
  418. std::string key = LevelDbMutationKey::Key(_userID, batchID);
  419. // As a sanity check, verify that the mutation batch exists before deleting it.
  420. checkIterator->Seek(key);
  421. HARD_ASSERT(checkIterator->Valid(), "Mutation batch %s did not exist", DescribeKey(key));
  422. HARD_ASSERT(key == checkIterator->key(), "Mutation batch %s not found; found %s",
  423. DescribeKey(key), DescribeKey(checkIterator));
  424. _db.currentTransaction->Delete(key);
  425. for (FSTMutation *mutation in batch.mutations) {
  426. key = LevelDbDocumentMutationKey::Key(_userID, mutation.key, batchID);
  427. _db.currentTransaction->Delete(key);
  428. [_db.referenceDelegate removeMutationReference:mutation.key];
  429. }
  430. }
  431. - (void)performConsistencyCheck {
  432. if (![self isEmpty]) {
  433. return;
  434. }
  435. // Verify that there are no entries in the document-mutation index if the queue is empty.
  436. std::string indexPrefix = LevelDbDocumentMutationKey::KeyPrefix(_userID);
  437. auto indexIterator = _db.currentTransaction->NewIterator();
  438. indexIterator->Seek(indexPrefix);
  439. std::vector<std::string> danglingMutationReferences;
  440. for (; indexIterator->Valid(); indexIterator->Next()) {
  441. // Only consider rows matching this index prefix for the current user.
  442. if (!absl::StartsWith(indexIterator->key(), indexPrefix)) {
  443. break;
  444. }
  445. danglingMutationReferences.push_back(DescribeKey(indexIterator));
  446. }
  447. HARD_ASSERT(danglingMutationReferences.empty(),
  448. "Document leak -- detected dangling mutation references when queue "
  449. "is empty. Dangling keys: %s",
  450. util::ToString(danglingMutationReferences));
  451. }
  452. - (std::string)mutationKeyForBatch:(FSTMutationBatch *)batch {
  453. return LevelDbMutationKey::Key(_userID, batch.batchID);
  454. }
  455. - (std::string)mutationKeyForBatchID:(BatchId)batchID {
  456. return LevelDbMutationKey::Key(_userID, batchID);
  457. }
  458. /** Parses the MutationQueue metadata from the given LevelDB row contents. */
  459. - (FSTPBMutationQueue *)parsedMetadata:(Slice)slice {
  460. NSData *data =
  461. [[NSData alloc] initWithBytesNoCopy:(void *)slice.data() length:slice.size() freeWhenDone:NO];
  462. NSError *error;
  463. FSTPBMutationQueue *proto = [FSTPBMutationQueue parseFromData:data error:&error];
  464. if (!proto) {
  465. HARD_FAIL("FSTPBMutationQueue failed to parse: %s", error);
  466. }
  467. return proto;
  468. }
  469. - (FSTMutationBatch *)decodedMutationBatch:(absl::string_view)encoded {
  470. NSData *data = [[NSData alloc] initWithBytesNoCopy:(void *)encoded.data()
  471. length:encoded.size()
  472. freeWhenDone:NO];
  473. NSError *error;
  474. FSTPBWriteBatch *proto = [FSTPBWriteBatch parseFromData:data error:&error];
  475. if (!proto) {
  476. HARD_FAIL("FSTPBMutationBatch failed to parse: %s", error);
  477. }
  478. return [self.serializer decodedMutationBatch:proto];
  479. }
  480. @end
  481. NS_ASSUME_NONNULL_END