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/Model/FSTDocument.h"
  21. #include "Firestore/core/src/firebase/firestore/core/query.h"
  22. #include "Firestore/core/src/firebase/firestore/core/view_snapshot.h"
  23. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  24. #include "Firestore/core/src/firebase/firestore/model/document_key_set.h"
  25. #include "Firestore/core/src/firebase/firestore/model/document_set.h"
  26. #include "Firestore/core/src/firebase/firestore/remote/remote_event.h"
  27. #include "Firestore/core/src/firebase/firestore/util/delayed_constructor.h"
  28. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  29. namespace util = firebase::firestore::util;
  30. using firebase::firestore::core::DocumentViewChange;
  31. using firebase::firestore::core::DocumentViewChangeSet;
  32. using firebase::firestore::core::Query;
  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, assign) firebase::firestore::core::SyncState syncState;
  168. /**
  169. * A flag whether the view is current with the backend. A view is considered current after it
  170. * has seen the current flag from the backend and did not lose consistency within the watch stream
  171. * (e.g. because of an existence filter mismatch).
  172. */
  173. @property(nonatomic, assign, getter=isCurrent) BOOL current;
  174. @end
  175. @implementation FSTView {
  176. Query _query;
  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:(Query)query remoteDocuments:(DocumentKeySet)remoteDocuments {
  186. self = [super init];
  187. if (self) {
  188. _query = std::move(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 _documentSet->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. (_query.limit() != Query::kNoLimit && oldDocumentSet.size() == _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 (!_query.Matches(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 == 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. int32_t limit = _query.limit();
  293. if (limit != Query::kNoLimit && newDocumentSet.size() > limit) {
  294. for (size_t i = newDocumentSet.size() - 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{_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