FSTView.mm 19 KB

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