FSTView.mm 19 KB

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