FSTView.mm 19 KB

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