FSTView.mm 18 KB

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