FSTMemoryMutationQueue.mm 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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/FSTMemoryMutationQueue.h"
  17. #include <set>
  18. #import "Firestore/Source/Core/FSTQuery.h"
  19. #import "Firestore/Source/Local/FSTDocumentReference.h"
  20. #import "Firestore/Source/Local/FSTMemoryPersistence.h"
  21. #import "Firestore/Source/Model/FSTMutation.h"
  22. #import "Firestore/Source/Model/FSTMutationBatch.h"
  23. #import "Firestore/third_party/Immutable/FSTImmutableSortedSet.h"
  24. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  25. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  26. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  27. using firebase::firestore::model::DocumentKey;
  28. using firebase::firestore::model::DocumentKeySet;
  29. using firebase::firestore::model::ResourcePath;
  30. NS_ASSUME_NONNULL_BEGIN
  31. static const NSComparator NumberComparator = ^NSComparisonResult(NSNumber *left, NSNumber *right) {
  32. return [left compare:right];
  33. };
  34. @interface FSTMemoryMutationQueue ()
  35. /**
  36. * A FIFO queue of all mutations to apply to the backend. Mutations are added to the end of the
  37. * queue as they're written, and removed from the front of the queue as the mutations become
  38. * visible or are rejected.
  39. *
  40. * When successfully applied, mutations must be acknowledged by the write stream and made visible
  41. * on the watch stream. It's possible for the watch stream to fall behind in which case the batches
  42. * at the head of the queue will be acknowledged but held until the watch stream sees the changes.
  43. *
  44. * If a batch is rejected while there are held write acknowledgements at the head of the queue
  45. * the rejected batch is converted to a tombstone: its mutations are removed but the batch remains
  46. * in the queue. This maintains a simple consecutive ordering of batches in the queue.
  47. *
  48. * Once the held write acknowledgements become visible they are removed from the head of the queue
  49. * along with any tombstones that follow.
  50. */
  51. @property(nonatomic, strong, readonly) NSMutableArray<FSTMutationBatch *> *queue;
  52. /** An ordered mapping between documents and the mutation batch IDs. */
  53. @property(nonatomic, strong) FSTImmutableSortedSet<FSTDocumentReference *> *batchesByDocumentKey;
  54. /** The next value to use when assigning sequential IDs to each mutation batch. */
  55. @property(nonatomic, assign) FSTBatchID nextBatchID;
  56. /** The highest acknowledged mutation in the queue. */
  57. @property(nonatomic, assign) FSTBatchID highestAcknowledgedBatchID;
  58. /**
  59. * The last received stream token from the server, used to acknowledge which responses the client
  60. * has processed. Stream tokens are opaque checkpoint markers whose only real value is their
  61. * inclusion in the next request.
  62. */
  63. @property(nonatomic, strong, nullable) NSData *lastStreamToken;
  64. @end
  65. @implementation FSTMemoryMutationQueue {
  66. FSTMemoryPersistence *_persistence;
  67. }
  68. - (instancetype)initWithPersistence:(FSTMemoryPersistence *)persistence {
  69. if (self = [super init]) {
  70. _persistence = persistence;
  71. _queue = [NSMutableArray array];
  72. _batchesByDocumentKey =
  73. [FSTImmutableSortedSet setWithComparator:FSTDocumentReferenceComparatorByKey];
  74. _nextBatchID = 1;
  75. _highestAcknowledgedBatchID = kFSTBatchIDUnknown;
  76. }
  77. return self;
  78. }
  79. #pragma mark - FSTMutationQueue implementation
  80. - (void)start {
  81. // Note: The queue may be shutdown / started multiple times, since we maintain the queue for the
  82. // duration of the app session in case a user logs out / back in. To behave like the
  83. // LevelDB-backed MutationQueue (and accommodate tests that expect as much), we reset nextBatchID
  84. // and highestAcknowledgedBatchID if the queue is empty.
  85. if (self.isEmpty) {
  86. self.nextBatchID = 1;
  87. self.highestAcknowledgedBatchID = kFSTBatchIDUnknown;
  88. }
  89. HARD_ASSERT(self.highestAcknowledgedBatchID < self.nextBatchID,
  90. "highestAcknowledgedBatchID must be less than the nextBatchID");
  91. }
  92. - (BOOL)isEmpty {
  93. // If the queue has any entries at all, the first entry must not be a tombstone (otherwise it
  94. // would have been removed already).
  95. return self.queue.count == 0;
  96. }
  97. - (FSTBatchID)highestAcknowledgedBatchID {
  98. return _highestAcknowledgedBatchID;
  99. }
  100. - (void)acknowledgeBatch:(FSTMutationBatch *)batch streamToken:(nullable NSData *)streamToken {
  101. NSMutableArray<FSTMutationBatch *> *queue = self.queue;
  102. FSTBatchID batchID = batch.batchID;
  103. HARD_ASSERT(batchID > self.highestAcknowledgedBatchID,
  104. "Mutation batchIDs must be acknowledged in order");
  105. NSInteger batchIndex = [self indexOfExistingBatchID:batchID action:@"acknowledged"];
  106. // Verify that the batch in the queue is the one to be acknowledged.
  107. FSTMutationBatch *check = queue[(NSUInteger)batchIndex];
  108. HARD_ASSERT(batchID == check.batchID, "Queue ordering failure: expected batch %s, got batch %s",
  109. batchID, check.batchID);
  110. HARD_ASSERT(![check isTombstone], "Can't acknowledge a previously removed batch");
  111. self.highestAcknowledgedBatchID = batchID;
  112. self.lastStreamToken = streamToken;
  113. }
  114. - (FSTMutationBatch *)addMutationBatchWithWriteTime:(FIRTimestamp *)localWriteTime
  115. mutations:(NSArray<FSTMutation *> *)mutations {
  116. HARD_ASSERT(mutations.count > 0, "Mutation batches should not be empty");
  117. FSTBatchID batchID = self.nextBatchID;
  118. self.nextBatchID += 1;
  119. NSMutableArray<FSTMutationBatch *> *queue = self.queue;
  120. if (queue.count > 0) {
  121. FSTMutationBatch *prior = queue[queue.count - 1];
  122. HARD_ASSERT(prior.batchID < batchID,
  123. "Mutation batchIDs must be monotonically increasing order");
  124. }
  125. FSTMutationBatch *batch = [[FSTMutationBatch alloc] initWithBatchID:batchID
  126. localWriteTime:localWriteTime
  127. mutations:mutations];
  128. [queue addObject:batch];
  129. // Track references by document key.
  130. FSTImmutableSortedSet<FSTDocumentReference *> *references = self.batchesByDocumentKey;
  131. for (FSTMutation *mutation in batch.mutations) {
  132. references = [references
  133. setByAddingObject:[[FSTDocumentReference alloc] initWithKey:mutation.key ID:batchID]];
  134. }
  135. self.batchesByDocumentKey = references;
  136. return batch;
  137. }
  138. - (nullable FSTMutationBatch *)lookupMutationBatch:(FSTBatchID)batchID {
  139. NSMutableArray<FSTMutationBatch *> *queue = self.queue;
  140. NSInteger index = [self indexOfBatchID:batchID];
  141. if (index < 0 || index >= queue.count) {
  142. return nil;
  143. }
  144. FSTMutationBatch *batch = queue[(NSUInteger)index];
  145. HARD_ASSERT(batch.batchID == batchID, "If found batch must match");
  146. return [batch isTombstone] ? nil : batch;
  147. }
  148. - (nullable FSTMutationBatch *)nextMutationBatchAfterBatchID:(FSTBatchID)batchID {
  149. NSMutableArray<FSTMutationBatch *> *queue = self.queue;
  150. NSUInteger count = queue.count;
  151. // All batches with batchID <= self.highestAcknowledgedBatchID have been acknowledged so the
  152. // first unacknowledged batch after batchID will have a batchID larger than both of these values.
  153. FSTBatchID nextBatchID = MAX(batchID, self.highestAcknowledgedBatchID) + 1;
  154. // The requested batchID may still be out of range so normalize it to the start of the queue.
  155. NSInteger rawIndex = [self indexOfBatchID:nextBatchID];
  156. NSUInteger index = rawIndex < 0 ? 0 : (NSUInteger)rawIndex;
  157. // Finally return the first non-tombstone batch.
  158. for (; index < count; index++) {
  159. FSTMutationBatch *batch = queue[index];
  160. if (![batch isTombstone]) {
  161. return batch;
  162. }
  163. }
  164. return nil;
  165. }
  166. - (NSArray<FSTMutationBatch *> *)allMutationBatches {
  167. return [self allLiveMutationBatchesBeforeIndex:self.queue.count];
  168. }
  169. - (NSArray<FSTMutationBatch *> *)allMutationBatchesThroughBatchID:(FSTBatchID)batchID {
  170. NSMutableArray<FSTMutationBatch *> *queue = self.queue;
  171. NSUInteger count = queue.count;
  172. NSInteger endIndex = [self indexOfBatchID:batchID];
  173. if (endIndex < 0) {
  174. endIndex = 0;
  175. } else if (endIndex >= count) {
  176. endIndex = count;
  177. } else {
  178. // The endIndex is in the queue so increment to pull everything in the queue including it.
  179. endIndex += 1;
  180. }
  181. return [self allLiveMutationBatchesBeforeIndex:(NSUInteger)endIndex];
  182. }
  183. - (NSArray<FSTMutationBatch *> *)allMutationBatchesAffectingDocumentKey:
  184. (const DocumentKey &)documentKey {
  185. FSTDocumentReference *start = [[FSTDocumentReference alloc] initWithKey:documentKey ID:0];
  186. NSMutableArray<FSTMutationBatch *> *result = [NSMutableArray array];
  187. FSTDocumentReferenceBlock block = ^(FSTDocumentReference *reference, BOOL *stop) {
  188. if (![documentKey isEqualToKey:reference.key]) {
  189. *stop = YES;
  190. return;
  191. }
  192. FSTMutationBatch *batch = [self lookupMutationBatch:reference.ID];
  193. HARD_ASSERT(batch, "Batches in the index must exist in the main table");
  194. [result addObject:batch];
  195. };
  196. [self.batchesByDocumentKey enumerateObjectsFrom:start to:nil usingBlock:block];
  197. return result;
  198. }
  199. - (NSArray<FSTMutationBatch *> *)allMutationBatchesAffectingDocumentKeys:
  200. (const DocumentKeySet &)documentKeys {
  201. // First find the set of affected batch IDs.
  202. __block std::set<FSTBatchID> batchIDs;
  203. for (const DocumentKey &key : documentKeys) {
  204. FSTDocumentReference *start = [[FSTDocumentReference alloc] initWithKey:key ID:0];
  205. FSTDocumentReferenceBlock block = ^(FSTDocumentReference *reference, BOOL *stop) {
  206. if (![key isEqualToKey:reference.key]) {
  207. *stop = YES;
  208. return;
  209. }
  210. batchIDs.insert(reference.ID);
  211. };
  212. [self.batchesByDocumentKey enumerateObjectsFrom:start to:nil usingBlock:block];
  213. }
  214. return [self allMutationBatchesWithBatchIDs:batchIDs];
  215. }
  216. - (NSArray<FSTMutationBatch *> *)allMutationBatchesAffectingQuery:(FSTQuery *)query {
  217. // Use the query path as a prefix for testing if a document matches the query.
  218. const ResourcePath &prefix = query.path;
  219. size_t immediateChildrenPathLength = prefix.size() + 1;
  220. // Construct a document reference for actually scanning the index. Unlike the prefix, the document
  221. // key in this reference must have an even number of segments. The empty segment can be used as
  222. // a suffix of the query path because it precedes all other segments in an ordered traversal.
  223. ResourcePath startPath = query.path;
  224. if (!DocumentKey::IsDocumentKey(startPath)) {
  225. startPath = startPath.Append("");
  226. }
  227. FSTDocumentReference *start =
  228. [[FSTDocumentReference alloc] initWithKey:DocumentKey{startPath} ID:0];
  229. // Find unique batchIDs referenced by all documents potentially matching the query.
  230. __block std::set<FSTBatchID> uniqueBatchIDs;
  231. FSTDocumentReferenceBlock block = ^(FSTDocumentReference *reference, BOOL *stop) {
  232. const ResourcePath &rowKeyPath = reference.key.path();
  233. if (!prefix.IsPrefixOf(rowKeyPath)) {
  234. *stop = YES;
  235. return;
  236. }
  237. // Rows with document keys more than one segment longer than the query path can't be matches.
  238. // For example, a query on 'rooms' can't match the document /rooms/abc/messages/xyx.
  239. // TODO(mcg): we'll need a different scanner when we implement ancestor queries.
  240. if (rowKeyPath.size() != immediateChildrenPathLength) {
  241. return;
  242. }
  243. uniqueBatchIDs.insert(reference.ID);
  244. };
  245. [self.batchesByDocumentKey enumerateObjectsFrom:start to:nil usingBlock:block];
  246. return [self allMutationBatchesWithBatchIDs:uniqueBatchIDs];
  247. }
  248. /**
  249. * Constructs an array of matching batches, sorted by batchID to ensure that multiple mutations
  250. * affecting the same document key are applied in order.
  251. */
  252. - (NSArray<FSTMutationBatch *> *)allMutationBatchesWithBatchIDs:
  253. (const std::set<FSTBatchID> &)batchIDs {
  254. NSMutableArray<FSTMutationBatch *> *result = [NSMutableArray array];
  255. for (FSTBatchID batchID : batchIDs) {
  256. FSTMutationBatch *batch = [self lookupMutationBatch:batchID];
  257. if (batch) {
  258. [result addObject:batch];
  259. }
  260. };
  261. return result;
  262. }
  263. - (void)removeMutationBatches:(NSArray<FSTMutationBatch *> *)batches {
  264. NSUInteger batchCount = batches.count;
  265. HARD_ASSERT(batchCount > 0, "Should not remove mutations when none exist.");
  266. FSTBatchID firstBatchID = batches[0].batchID;
  267. NSMutableArray<FSTMutationBatch *> *queue = self.queue;
  268. NSUInteger queueCount = queue.count;
  269. // Find the position of the first batch for removal. This need not be the first entry in the
  270. // queue.
  271. NSUInteger startIndex = [self indexOfExistingBatchID:firstBatchID action:@"removed"];
  272. HARD_ASSERT(queue[startIndex].batchID == firstBatchID, "Removed batches must exist in the queue");
  273. // Check that removed batches are contiguous (while excluding tombstones).
  274. NSUInteger batchIndex = 1;
  275. NSUInteger queueIndex = startIndex + 1;
  276. while (batchIndex < batchCount && queueIndex < queueCount) {
  277. FSTMutationBatch *batch = queue[queueIndex];
  278. if ([batch isTombstone]) {
  279. queueIndex++;
  280. continue;
  281. }
  282. HARD_ASSERT(batch.batchID == batches[batchIndex].batchID,
  283. "Removed batches must be contiguous in the queue");
  284. batchIndex++;
  285. queueIndex++;
  286. }
  287. // Only actually remove batches if removing at the front of the queue. Previously rejected batches
  288. // may have left tombstones in the queue, so expand the removal range to include any tombstones.
  289. if (startIndex == 0) {
  290. for (; queueIndex < queueCount; queueIndex++) {
  291. FSTMutationBatch *batch = queue[queueIndex];
  292. if (![batch isTombstone]) {
  293. break;
  294. }
  295. }
  296. NSUInteger length = queueIndex - startIndex;
  297. [queue removeObjectsInRange:NSMakeRange(startIndex, length)];
  298. } else {
  299. // Mark tombstones
  300. for (NSUInteger i = startIndex; i < queueIndex; i++) {
  301. queue[i] = [queue[i] toTombstone];
  302. }
  303. }
  304. // Remove entries from the index too.
  305. FSTImmutableSortedSet<FSTDocumentReference *> *references = self.batchesByDocumentKey;
  306. for (FSTMutationBatch *batch in batches) {
  307. FSTBatchID batchID = batch.batchID;
  308. for (FSTMutation *mutation in batch.mutations) {
  309. const DocumentKey &key = mutation.key;
  310. [_persistence.referenceDelegate removeMutationReference:key];
  311. FSTDocumentReference *reference = [[FSTDocumentReference alloc] initWithKey:key ID:batchID];
  312. references = [references setByRemovingObject:reference];
  313. }
  314. }
  315. self.batchesByDocumentKey = references;
  316. }
  317. - (void)performConsistencyCheck {
  318. if (self.queue.count == 0) {
  319. HARD_ASSERT([self.batchesByDocumentKey isEmpty],
  320. "Document leak -- detected dangling mutation references when queue is empty.");
  321. }
  322. }
  323. #pragma mark - FSTGarbageSource implementation
  324. - (BOOL)containsKey:(const DocumentKey &)key {
  325. // Create a reference with a zero ID as the start position to find any document reference with
  326. // this key.
  327. FSTDocumentReference *reference = [[FSTDocumentReference alloc] initWithKey:key ID:0];
  328. NSEnumerator<FSTDocumentReference *> *enumerator =
  329. [self.batchesByDocumentKey objectEnumeratorFrom:reference];
  330. FSTDocumentReference *_Nullable firstReference = [enumerator nextObject];
  331. return firstReference && firstReference.key == reference.key;
  332. }
  333. #pragma mark - Helpers
  334. /**
  335. * A private helper that collects all the mutation batches in the queue up to but not including
  336. * the given endIndex. All tombstones in the queue are excluded.
  337. */
  338. - (NSArray<FSTMutationBatch *> *)allLiveMutationBatchesBeforeIndex:(NSUInteger)endIndex {
  339. NSMutableArray<FSTMutationBatch *> *result = [NSMutableArray arrayWithCapacity:endIndex];
  340. NSUInteger index = 0;
  341. for (FSTMutationBatch *batch in self.queue) {
  342. if (index++ >= endIndex) break;
  343. if (![batch isTombstone]) {
  344. [result addObject:batch];
  345. }
  346. }
  347. return result;
  348. }
  349. /**
  350. * Finds the index of the given batchID in the mutation queue. This operation is O(1).
  351. *
  352. * @return The computed index of the batch with the given batchID, based on the state of the
  353. * queue. Note this index can negative if the requested batchID has already been removed from
  354. * the queue or past the end of the queue if the batchID is larger than the last added batch.
  355. */
  356. - (NSInteger)indexOfBatchID:(FSTBatchID)batchID {
  357. NSMutableArray<FSTMutationBatch *> *queue = self.queue;
  358. NSUInteger count = queue.count;
  359. if (count == 0) {
  360. // As an index this is past the end of the queue
  361. return 0;
  362. }
  363. // Examine the front of the queue to figure out the difference between the batchID and indexes
  364. // in the array. Note that since the queue is ordered by batchID, if the first batch has a larger
  365. // batchID then the requested batchID doesn't exist in the queue.
  366. FSTMutationBatch *firstBatch = queue[0];
  367. FSTBatchID firstBatchID = firstBatch.batchID;
  368. return batchID - firstBatchID;
  369. }
  370. /**
  371. * Finds the index of the given batchID in the mutation queue and asserts that the resulting
  372. * index is within the bounds of the queue.
  373. *
  374. * @param batchID The batchID to search for
  375. * @param action A description of what the caller is doing, phrased in passive form (e.g.
  376. * "acknowledged" in a routine that acknowledges batches).
  377. */
  378. - (NSUInteger)indexOfExistingBatchID:(FSTBatchID)batchID action:(NSString *)action {
  379. NSInteger index = [self indexOfBatchID:batchID];
  380. HARD_ASSERT(index >= 0 && index < self.queue.count, "Batches must exist to be %s", action);
  381. return (NSUInteger)index;
  382. }
  383. @end
  384. NS_ASSUME_NONNULL_END