FSTView.mm 19 KB

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