FSTMemoryMutationQueue.mm 13 KB

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