FSTView.mm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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/Core/FSTView.h"
  17. #include <utility>
  18. #import "Firestore/Source/Core/FSTQuery.h"
  19. #import "Firestore/Source/Core/FSTViewSnapshot.h"
  20. #import "Firestore/Source/Model/FSTDocument.h"
  21. #import "Firestore/Source/Model/FSTDocumentSet.h"
  22. #import "Firestore/Source/Model/FSTFieldValue.h"
  23. #import "Firestore/Source/Remote/FSTRemoteEvent.h"
  24. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  25. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  26. using firebase::firestore::model::DocumentKey;
  27. using firebase::firestore::model::DocumentKeySet;
  28. using firebase::firestore::model::OnlineState;
  29. NS_ASSUME_NONNULL_BEGIN
  30. #pragma mark - FSTViewDocumentChanges
  31. /** The result of applying a set of doc changes to a view. */
  32. @interface FSTViewDocumentChanges ()
  33. - (instancetype)initWithDocumentSet:(FSTDocumentSet *)documentSet
  34. changeSet:(FSTDocumentViewChangeSet *)changeSet
  35. needsRefill:(BOOL)needsRefill
  36. mutatedKeys:(DocumentKeySet)mutatedKeys NS_DESIGNATED_INITIALIZER;
  37. @end
  38. @implementation FSTViewDocumentChanges {
  39. DocumentKeySet _mutatedKeys;
  40. }
  41. - (instancetype)initWithDocumentSet:(FSTDocumentSet *)documentSet
  42. changeSet:(FSTDocumentViewChangeSet *)changeSet
  43. needsRefill:(BOOL)needsRefill
  44. mutatedKeys:(DocumentKeySet)mutatedKeys {
  45. self = [super init];
  46. if (self) {
  47. _documentSet = documentSet;
  48. _changeSet = changeSet;
  49. _needsRefill = needsRefill;
  50. _mutatedKeys = std::move(mutatedKeys);
  51. }
  52. return self;
  53. }
  54. - (const DocumentKeySet &)mutatedKeys {
  55. return _mutatedKeys;
  56. }
  57. @end
  58. #pragma mark - FSTLimboDocumentChange
  59. @interface FSTLimboDocumentChange ()
  60. + (instancetype)changeWithType:(FSTLimboDocumentChangeType)type key:(DocumentKey)key;
  61. - (instancetype)initWithType:(FSTLimboDocumentChangeType)type
  62. key:(DocumentKey)key NS_DESIGNATED_INITIALIZER;
  63. @end
  64. @implementation FSTLimboDocumentChange {
  65. DocumentKey _key;
  66. }
  67. + (instancetype)changeWithType:(FSTLimboDocumentChangeType)type key:(DocumentKey)key {
  68. return [[FSTLimboDocumentChange alloc] initWithType:type key:std::move(key)];
  69. }
  70. - (instancetype)initWithType:(FSTLimboDocumentChangeType)type key:(DocumentKey)key {
  71. self = [super init];
  72. if (self) {
  73. _type = type;
  74. _key = std::move(key);
  75. }
  76. return self;
  77. }
  78. - (const DocumentKey &)key {
  79. return _key;
  80. }
  81. - (BOOL)isEqual:(id)other {
  82. if (self == other) {
  83. return YES;
  84. }
  85. if (![other isKindOfClass:[FSTLimboDocumentChange class]]) {
  86. return NO;
  87. }
  88. FSTLimboDocumentChange *otherChange = (FSTLimboDocumentChange *)other;
  89. return self.type == otherChange.type && self.key == otherChange.key;
  90. }
  91. - (NSUInteger)hash {
  92. NSUInteger hash = self.type;
  93. hash = hash * 31u + [self.key hash];
  94. return hash;
  95. }
  96. @end
  97. #pragma mark - FSTViewChange
  98. @interface FSTViewChange ()
  99. + (FSTViewChange *)changeWithSnapshot:(nullable FSTViewSnapshot *)snapshot
  100. limboChanges:(NSArray<FSTLimboDocumentChange *> *)limboChanges;
  101. - (instancetype)initWithSnapshot:(nullable FSTViewSnapshot *)snapshot
  102. limboChanges:(NSArray<FSTLimboDocumentChange *> *)limboChanges
  103. NS_DESIGNATED_INITIALIZER;
  104. @end
  105. @implementation FSTViewChange
  106. + (FSTViewChange *)changeWithSnapshot:(nullable FSTViewSnapshot *)snapshot
  107. limboChanges:(NSArray<FSTLimboDocumentChange *> *)limboChanges {
  108. return [[self alloc] initWithSnapshot:snapshot limboChanges:limboChanges];
  109. }
  110. - (instancetype)initWithSnapshot:(nullable FSTViewSnapshot *)snapshot
  111. limboChanges:(NSArray<FSTLimboDocumentChange *> *)limboChanges {
  112. self = [super init];
  113. if (self) {
  114. _snapshot = snapshot;
  115. _limboChanges = limboChanges;
  116. }
  117. return self;
  118. }
  119. @end
  120. #pragma mark - FSTView
  121. static NSComparisonResult FSTCompareDocumentViewChangeTypes(FSTDocumentViewChangeType c1,
  122. FSTDocumentViewChangeType c2);
  123. @interface FSTView ()
  124. @property(nonatomic, strong, readonly) FSTQuery *query;
  125. @property(nonatomic, assign) FSTSyncState syncState;
  126. /**
  127. * A flag whether the view is current with the backend. A view is considered current after it
  128. * has seen the current flag from the backend and did not lose consistency within the watch stream
  129. * (e.g. because of an existence filter mismatch).
  130. */
  131. @property(nonatomic, assign, getter=isCurrent) BOOL current;
  132. @property(nonatomic, strong) FSTDocumentSet *documentSet;
  133. @end
  134. @implementation FSTView {
  135. /** Documents included in the remote target. */
  136. DocumentKeySet _syncedDocuments;
  137. /** Documents in the view but not in the remote target */
  138. DocumentKeySet _limboDocuments;
  139. /** Document Keys that have local changes. */
  140. DocumentKeySet _mutatedKeys;
  141. }
  142. - (instancetype)initWithQuery:(FSTQuery *)query remoteDocuments:(DocumentKeySet)remoteDocuments {
  143. self = [super init];
  144. if (self) {
  145. _query = query;
  146. _documentSet = [FSTDocumentSet documentSetWithComparator:query.comparator];
  147. _syncedDocuments = std::move(remoteDocuments);
  148. }
  149. return self;
  150. }
  151. - (const DocumentKeySet &)syncedDocuments {
  152. return _syncedDocuments;
  153. }
  154. - (FSTViewDocumentChanges *)computeChangesWithDocuments:(FSTMaybeDocumentDictionary *)docChanges {
  155. return [self computeChangesWithDocuments:docChanges previousChanges:nil];
  156. }
  157. - (FSTViewDocumentChanges *)computeChangesWithDocuments:(FSTMaybeDocumentDictionary *)docChanges
  158. previousChanges:
  159. (nullable FSTViewDocumentChanges *)previousChanges {
  160. FSTDocumentViewChangeSet *changeSet =
  161. previousChanges ? previousChanges.changeSet : [FSTDocumentViewChangeSet changeSet];
  162. FSTDocumentSet *oldDocumentSet = previousChanges ? previousChanges.documentSet : self.documentSet;
  163. __block DocumentKeySet newMutatedKeys =
  164. previousChanges ? previousChanges.mutatedKeys : _mutatedKeys;
  165. __block FSTDocumentSet *newDocumentSet = oldDocumentSet;
  166. __block BOOL needsRefill = NO;
  167. // Track the last doc in a (full) limit. This is necessary, because some update (a delete, or an
  168. // update moving a doc past the old limit) might mean there is some other document in the local
  169. // cache that either should come (1) between the old last limit doc and the new last document,
  170. // in the case of updates, or (2) after the new last document, in the case of deletes. So we
  171. // keep this doc at the old limit to compare the updates to.
  172. //
  173. // Note that this should never get used in a refill (when previousChanges is set), because there
  174. // will only be adds -- no deletes or updates.
  175. FSTDocument *_Nullable lastDocInLimit =
  176. (self.query.limit && oldDocumentSet.count == self.query.limit) ? oldDocumentSet.lastDocument
  177. : nil;
  178. [docChanges enumerateKeysAndObjectsUsingBlock:^(FSTDocumentKey *key,
  179. FSTMaybeDocument *maybeNewDoc, BOOL *stop) {
  180. FSTDocument *_Nullable oldDoc = [oldDocumentSet documentForKey:key];
  181. FSTDocument *_Nullable newDoc = nil;
  182. if ([maybeNewDoc isKindOfClass:[FSTDocument class]]) {
  183. newDoc = (FSTDocument *)maybeNewDoc;
  184. }
  185. if (newDoc) {
  186. HARD_ASSERT([key isEqual:newDoc.key], "Mismatching key in document changes: %s != %s", key,
  187. newDoc.key.ToString());
  188. if (![self.query matchesDocument:newDoc]) {
  189. newDoc = nil;
  190. }
  191. }
  192. if (newDoc) {
  193. newDocumentSet = [newDocumentSet documentSetByAddingDocument:newDoc];
  194. if (newDoc.hasLocalMutations) {
  195. newMutatedKeys = newMutatedKeys.insert(key);
  196. } else {
  197. newMutatedKeys = newMutatedKeys.erase(key);
  198. }
  199. } else {
  200. newDocumentSet = [newDocumentSet documentSetByRemovingKey:key];
  201. newMutatedKeys = newMutatedKeys.erase(key);
  202. }
  203. // Calculate change
  204. if (oldDoc && newDoc) {
  205. BOOL docsEqual = [oldDoc.data isEqual:newDoc.data];
  206. if (!docsEqual || oldDoc.hasLocalMutations != newDoc.hasLocalMutations) {
  207. // only report a change if document actually changed.
  208. if (docsEqual) {
  209. [changeSet addChange:[FSTDocumentViewChange
  210. changeWithDocument:newDoc
  211. type:FSTDocumentViewChangeTypeMetadata]];
  212. } else {
  213. [changeSet addChange:[FSTDocumentViewChange
  214. changeWithDocument:newDoc
  215. type:FSTDocumentViewChangeTypeModified]];
  216. }
  217. if (lastDocInLimit && self.query.comparator(newDoc, lastDocInLimit) > 0) {
  218. // This doc moved from inside the limit to after the limit. That means there may be some
  219. // doc in the local cache that's actually less than this one.
  220. needsRefill = YES;
  221. }
  222. }
  223. } else if (!oldDoc && newDoc) {
  224. [changeSet
  225. addChange:[FSTDocumentViewChange changeWithDocument:newDoc
  226. type:FSTDocumentViewChangeTypeAdded]];
  227. } else if (oldDoc && !newDoc) {
  228. [changeSet
  229. addChange:[FSTDocumentViewChange changeWithDocument:oldDoc
  230. type:FSTDocumentViewChangeTypeRemoved]];
  231. if (lastDocInLimit) {
  232. // A doc was removed from a full limit query. We'll need to re-query from the local cache
  233. // to see if we know about some other doc that should be in the results.
  234. needsRefill = YES;
  235. }
  236. }
  237. }];
  238. if (self.query.limit) {
  239. // TODO(klimt): Make DocumentSet size be constant time.
  240. while (newDocumentSet.count > self.query.limit) {
  241. FSTDocument *oldDoc = [newDocumentSet lastDocument];
  242. newDocumentSet = [newDocumentSet documentSetByRemovingKey:oldDoc.key];
  243. [changeSet
  244. addChange:[FSTDocumentViewChange changeWithDocument:oldDoc
  245. type:FSTDocumentViewChangeTypeRemoved]];
  246. }
  247. }
  248. HARD_ASSERT(!needsRefill || !previousChanges,
  249. "View was refilled using docs that themselves needed refilling.");
  250. return [[FSTViewDocumentChanges alloc] initWithDocumentSet:newDocumentSet
  251. changeSet:changeSet
  252. needsRefill:needsRefill
  253. mutatedKeys:newMutatedKeys];
  254. }
  255. - (FSTViewChange *)applyChangesToDocuments:(FSTViewDocumentChanges *)docChanges {
  256. return [self applyChangesToDocuments:docChanges targetChange:nil];
  257. }
  258. - (FSTViewChange *)applyChangesToDocuments:(FSTViewDocumentChanges *)docChanges
  259. targetChange:(nullable FSTTargetChange *)targetChange {
  260. HARD_ASSERT(!docChanges.needsRefill, "Cannot apply changes that need a refill");
  261. FSTDocumentSet *oldDocuments = self.documentSet;
  262. self.documentSet = docChanges.documentSet;
  263. _mutatedKeys = docChanges.mutatedKeys;
  264. // Sort changes based on type and query comparator.
  265. NSArray<FSTDocumentViewChange *> *changes = [docChanges.changeSet changes];
  266. changes = [changes sortedArrayUsingComparator:^NSComparisonResult(FSTDocumentViewChange *c1,
  267. FSTDocumentViewChange *c2) {
  268. NSComparisonResult typeComparison = FSTCompareDocumentViewChangeTypes(c1.type, c2.type);
  269. if (typeComparison != NSOrderedSame) {
  270. return typeComparison;
  271. }
  272. return self.query.comparator(c1.document, c2.document);
  273. }];
  274. [self applyTargetChange:targetChange];
  275. NSArray<FSTLimboDocumentChange *> *limboChanges = [self updateLimboDocuments];
  276. BOOL synced = _limboDocuments.empty() && self.isCurrent;
  277. FSTSyncState newSyncState = synced ? FSTSyncStateSynced : FSTSyncStateLocal;
  278. BOOL syncStateChanged = newSyncState != self.syncState;
  279. self.syncState = newSyncState;
  280. if (changes.count == 0 && !syncStateChanged) {
  281. // No changes.
  282. return [FSTViewChange changeWithSnapshot:nil limboChanges:limboChanges];
  283. } else {
  284. FSTViewSnapshot *snapshot =
  285. [[FSTViewSnapshot alloc] initWithQuery:self.query
  286. documents:docChanges.documentSet
  287. oldDocuments:oldDocuments
  288. documentChanges:changes
  289. fromCache:newSyncState == FSTSyncStateLocal
  290. hasPendingWrites:!docChanges.mutatedKeys.empty()
  291. syncStateChanged:syncStateChanged];
  292. return [FSTViewChange changeWithSnapshot:snapshot limboChanges:limboChanges];
  293. }
  294. }
  295. - (FSTViewChange *)applyChangedOnlineState:(OnlineState)onlineState {
  296. if (self.isCurrent && onlineState == OnlineState::Offline) {
  297. // If we're offline, set `current` to NO and then call applyChanges to refresh our syncState
  298. // and generate an FSTViewChange as appropriate. We are guaranteed to get a new FSTTargetChange
  299. // that sets `current` back to YES once the client is back online.
  300. self.current = NO;
  301. return
  302. [self applyChangesToDocuments:[[FSTViewDocumentChanges alloc]
  303. initWithDocumentSet:self.documentSet
  304. changeSet:[FSTDocumentViewChangeSet changeSet]
  305. needsRefill:NO
  306. mutatedKeys:_mutatedKeys]];
  307. } else {
  308. // No effect, just return a no-op FSTViewChange.
  309. return [[FSTViewChange alloc] initWithSnapshot:nil limboChanges:@[]];
  310. }
  311. }
  312. #pragma mark - Private methods
  313. /** Returns whether the doc for the given key should be in limbo. */
  314. - (BOOL)shouldBeLimboDocumentKey:(const DocumentKey &)key {
  315. // If the remote end says it's part of this query, it's not in limbo.
  316. if (_syncedDocuments.contains(key)) {
  317. return NO;
  318. }
  319. // The local store doesn't think it's a result, so it shouldn't be in limbo.
  320. if (![self.documentSet containsKey:key]) {
  321. return NO;
  322. }
  323. // If there are local changes to the doc, they might explain why the server doesn't know that it's
  324. // part of the query. So don't put it in limbo.
  325. // TODO(klimt): Ideally, we would only consider changes that might actually affect this specific
  326. // query.
  327. if ([self.documentSet documentForKey:key].hasLocalMutations) {
  328. return NO;
  329. }
  330. // Everything else is in limbo.
  331. return YES;
  332. }
  333. /**
  334. * Updates syncedDocuments and current based on the given change.
  335. */
  336. - (void)applyTargetChange:(nullable FSTTargetChange *)targetChange {
  337. if (targetChange) {
  338. for (const DocumentKey &key : targetChange.addedDocuments) {
  339. _syncedDocuments = _syncedDocuments.insert(key);
  340. }
  341. for (const DocumentKey &key : targetChange.modifiedDocuments) {
  342. HARD_ASSERT(_syncedDocuments.find(key) != _syncedDocuments.end(),
  343. "Modified document %s not found in view.", key.ToString());
  344. }
  345. for (const DocumentKey &key : targetChange.removedDocuments) {
  346. _syncedDocuments = _syncedDocuments.erase(key);
  347. }
  348. self.current = targetChange.current;
  349. }
  350. }
  351. /** Updates limboDocuments and returns any changes as FSTLimboDocumentChanges. */
  352. - (NSArray<FSTLimboDocumentChange *> *)updateLimboDocuments {
  353. // We can only determine limbo documents when we're in-sync with the server.
  354. if (!self.isCurrent) {
  355. return @[];
  356. }
  357. // TODO(klimt): Do this incrementally so that it's not quadratic when updating many documents.
  358. DocumentKeySet oldLimboDocuments = std::move(_limboDocuments);
  359. _limboDocuments = DocumentKeySet{};
  360. for (FSTDocument *doc in self.documentSet.documentEnumerator) {
  361. if ([self shouldBeLimboDocumentKey:doc.key]) {
  362. _limboDocuments = _limboDocuments.insert(doc.key);
  363. }
  364. }
  365. // Diff the new limbo docs with the old limbo docs.
  366. NSMutableArray<FSTLimboDocumentChange *> *changes =
  367. [NSMutableArray arrayWithCapacity:(oldLimboDocuments.size() + _limboDocuments.size())];
  368. for (const DocumentKey &key : oldLimboDocuments) {
  369. if (!_limboDocuments.contains(key)) {
  370. [changes addObject:[FSTLimboDocumentChange changeWithType:FSTLimboDocumentChangeTypeRemoved
  371. key:key]];
  372. }
  373. }
  374. for (const DocumentKey &key : _limboDocuments) {
  375. if (!oldLimboDocuments.contains(key)) {
  376. [changes addObject:[FSTLimboDocumentChange changeWithType:FSTLimboDocumentChangeTypeAdded
  377. key:key]];
  378. }
  379. }
  380. return changes;
  381. }
  382. @end
  383. static inline int DocumentViewChangeTypePosition(FSTDocumentViewChangeType changeType) {
  384. switch (changeType) {
  385. case FSTDocumentViewChangeTypeRemoved:
  386. return 0;
  387. case FSTDocumentViewChangeTypeAdded:
  388. return 1;
  389. case FSTDocumentViewChangeTypeModified:
  390. return 2;
  391. case FSTDocumentViewChangeTypeMetadata:
  392. // A metadata change is converted to a modified change at the public API layer. Since we sort
  393. // by document key and then change type, metadata and modified changes must be sorted
  394. // equivalently.
  395. return 2;
  396. default:
  397. HARD_FAIL("Unknown FSTDocumentViewChangeType %s", changeType);
  398. }
  399. }
  400. static NSComparisonResult FSTCompareDocumentViewChangeTypes(FSTDocumentViewChangeType c1,
  401. FSTDocumentViewChangeType c2) {
  402. int pos1 = DocumentViewChangeTypePosition(c1);
  403. int pos2 = DocumentViewChangeTypePosition(c2);
  404. if (pos1 == pos2) {
  405. return NSOrderedSame;
  406. } else if (pos1 < pos2) {
  407. return NSOrderedAscending;
  408. } else {
  409. return NSOrderedDescending;
  410. }
  411. }
  412. NS_ASSUME_NONNULL_END