FSTMemoryMutationQueue.mm 17 KB

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