FSTView.mm 19 KB

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