FSTView.mm 19 KB

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