FSTMemoryMutationQueue.mm 17 KB

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