FSTMemoryMutationQueue.mm 16 KB

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