FSTLevelDBMutationQueue.mm 24 KB

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