FSTMemoryMutationQueue.mm 15 KB

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