FSTMemoryMutationQueue.m 17 KB

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