FSTLocalDocumentsView.mm 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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/FSTLocalDocumentsView.h"
  17. #import "Firestore/Source/Core/FSTQuery.h"
  18. #import "Firestore/Source/Local/FSTMutationQueue.h"
  19. #import "Firestore/Source/Local/FSTRemoteDocumentCache.h"
  20. #import "Firestore/Source/Model/FSTDocument.h"
  21. #import "Firestore/Source/Model/FSTDocumentDictionary.h"
  22. #import "Firestore/Source/Model/FSTMutation.h"
  23. #import "Firestore/Source/Model/FSTMutationBatch.h"
  24. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  25. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  26. #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
  27. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  28. using firebase::firestore::model::DocumentKey;
  29. using firebase::firestore::model::ResourcePath;
  30. using firebase::firestore::model::SnapshotVersion;
  31. using firebase::firestore::model::DocumentKeySet;
  32. NS_ASSUME_NONNULL_BEGIN
  33. @interface FSTLocalDocumentsView ()
  34. - (instancetype)initWithRemoteDocumentCache:(id<FSTRemoteDocumentCache>)remoteDocumentCache
  35. mutationQueue:(id<FSTMutationQueue>)mutationQueue
  36. NS_DESIGNATED_INITIALIZER;
  37. @property(nonatomic, strong, readonly) id<FSTRemoteDocumentCache> remoteDocumentCache;
  38. @property(nonatomic, strong, readonly) id<FSTMutationQueue> mutationQueue;
  39. @end
  40. @implementation FSTLocalDocumentsView
  41. + (instancetype)viewWithRemoteDocumentCache:(id<FSTRemoteDocumentCache>)remoteDocumentCache
  42. mutationQueue:(id<FSTMutationQueue>)mutationQueue {
  43. return [[FSTLocalDocumentsView alloc] initWithRemoteDocumentCache:remoteDocumentCache
  44. mutationQueue:mutationQueue];
  45. }
  46. - (instancetype)initWithRemoteDocumentCache:(id<FSTRemoteDocumentCache>)remoteDocumentCache
  47. mutationQueue:(id<FSTMutationQueue>)mutationQueue {
  48. if (self = [super init]) {
  49. _remoteDocumentCache = remoteDocumentCache;
  50. _mutationQueue = mutationQueue;
  51. }
  52. return self;
  53. }
  54. - (nullable FSTMaybeDocument *)documentForKey:(const DocumentKey &)key {
  55. FSTMaybeDocument *_Nullable remoteDoc = [self.remoteDocumentCache entryForKey:key];
  56. return [self localDocument:remoteDoc key:key];
  57. }
  58. - (FSTMaybeDocumentDictionary *)documentsForKeys:(const DocumentKeySet &)keys {
  59. FSTMaybeDocumentDictionary *results = [FSTMaybeDocumentDictionary maybeDocumentDictionary];
  60. for (const DocumentKey &key : keys) {
  61. // TODO(mikelehen): PERF: Consider fetching all remote documents at once rather than one-by-one.
  62. FSTMaybeDocument *maybeDoc = [self documentForKey:key];
  63. // TODO(http://b/32275378): Don't conflate missing / deleted.
  64. if (!maybeDoc) {
  65. maybeDoc = [FSTDeletedDocument documentWithKey:key version:SnapshotVersion::None()];
  66. }
  67. results = [results dictionaryBySettingObject:maybeDoc forKey:key];
  68. }
  69. return results;
  70. }
  71. - (FSTDocumentDictionary *)documentsMatchingQuery:(FSTQuery *)query {
  72. if (DocumentKey::IsDocumentKey(query.path)) {
  73. return [self documentsMatchingDocumentQuery:query.path];
  74. } else {
  75. return [self documentsMatchingCollectionQuery:query];
  76. }
  77. }
  78. - (FSTDocumentDictionary *)documentsMatchingDocumentQuery:(const ResourcePath &)docPath {
  79. FSTDocumentDictionary *result = [FSTDocumentDictionary documentDictionary];
  80. // Just do a simple document lookup.
  81. FSTMaybeDocument *doc = [self documentForKey:DocumentKey{docPath}];
  82. if ([doc isKindOfClass:[FSTDocument class]]) {
  83. result = [result dictionaryBySettingObject:(FSTDocument *)doc forKey:doc.key];
  84. }
  85. return result;
  86. }
  87. - (FSTDocumentDictionary *)documentsMatchingCollectionQuery:(FSTQuery *)query {
  88. // Query the remote documents and overlay mutations.
  89. // TODO(mikelehen): There may be significant overlap between the mutations affecting these
  90. // remote documents and the allMutationBatchesAffectingQuery mutations. Consider optimizing.
  91. __block FSTDocumentDictionary *results = [self.remoteDocumentCache documentsMatchingQuery:query];
  92. results = [self localDocuments:results];
  93. // Now use the mutation queue to discover any other documents that may match the query after
  94. // applying mutations.
  95. DocumentKeySet matchingKeys;
  96. NSArray<FSTMutationBatch *> *matchingMutationBatches =
  97. [self.mutationQueue allMutationBatchesAffectingQuery:query];
  98. for (FSTMutationBatch *batch in matchingMutationBatches) {
  99. for (FSTMutation *mutation in batch.mutations) {
  100. // TODO(mikelehen): PERF: Check if this mutation actually affects the query to reduce work.
  101. // If the key is already in the results, we can skip it.
  102. if (![results containsKey:mutation.key]) {
  103. matchingKeys = matchingKeys.insert(mutation.key);
  104. }
  105. }
  106. }
  107. // Now add in results for the matchingKeys.
  108. for (const DocumentKey &key : matchingKeys) {
  109. FSTMaybeDocument *doc = [self documentForKey:key];
  110. if ([doc isKindOfClass:[FSTDocument class]]) {
  111. results = [results dictionaryBySettingObject:(FSTDocument *)doc forKey:key];
  112. }
  113. }
  114. // Finally, filter out any documents that don't actually match the query. Note that the extra
  115. // reference here prevents ARC from deallocating the initial unfiltered results while we're
  116. // enumerating them.
  117. FSTDocumentDictionary *unfiltered = results;
  118. [unfiltered
  119. enumerateKeysAndObjectsUsingBlock:^(FSTDocumentKey *key, FSTDocument *doc, BOOL *stop) {
  120. if (![query matchesDocument:doc]) {
  121. results = [results dictionaryByRemovingObjectForKey:key];
  122. }
  123. }];
  124. return results;
  125. }
  126. /**
  127. * Takes a remote document and applies local mutations to generate the local view of the
  128. * document.
  129. *
  130. * @param document The base remote document to apply mutations to.
  131. * @param documentKey The key of the document (necessary when remoteDocument is nil).
  132. */
  133. - (nullable FSTMaybeDocument *)localDocument:(nullable FSTMaybeDocument *)document
  134. key:(const DocumentKey &)documentKey {
  135. NSArray<FSTMutationBatch *> *batches =
  136. [self.mutationQueue allMutationBatchesAffectingDocumentKey:documentKey];
  137. for (FSTMutationBatch *batch in batches) {
  138. document = [batch applyTo:document documentKey:documentKey];
  139. }
  140. return document;
  141. }
  142. /**
  143. * Takes a set of remote documents and applies local mutations to generate the local view of
  144. * the documents.
  145. *
  146. * @param documents The base remote documents to apply mutations to.
  147. * @return The local view of the documents.
  148. */
  149. - (FSTDocumentDictionary *)localDocuments:(FSTDocumentDictionary *)documents {
  150. __block FSTDocumentDictionary *result = documents;
  151. [documents enumerateKeysAndObjectsUsingBlock:^(FSTDocumentKey *key, FSTDocument *remoteDocument,
  152. BOOL *stop) {
  153. FSTMaybeDocument *mutatedDoc = [self localDocument:remoteDocument key:key];
  154. if ([mutatedDoc isKindOfClass:[FSTDeletedDocument class]]) {
  155. result = [result dictionaryByRemovingObjectForKey:key];
  156. } else if ([mutatedDoc isKindOfClass:[FSTDocument class]]) {
  157. result = [result dictionaryBySettingObject:(FSTDocument *)mutatedDoc forKey:key];
  158. } else {
  159. HARD_FAIL("Unknown document: %s", mutatedDoc);
  160. }
  161. }];
  162. return result;
  163. }
  164. @end
  165. NS_ASSUME_NONNULL_END