FSTLevelDBMutationQueue.mm 23 KB

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