FSTRemoteEvent.mm 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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/Remote/FSTRemoteEvent.h"
  17. #include <map>
  18. #include <set>
  19. #include <unordered_map>
  20. #include <utility>
  21. #include <vector>
  22. #import "Firestore/Source/Core/FSTQuery.h"
  23. #import "Firestore/Source/Core/FSTViewSnapshot.h"
  24. #import "Firestore/Source/Local/FSTQueryData.h"
  25. #import "Firestore/Source/Model/FSTDocument.h"
  26. #import "Firestore/Source/Remote/FSTExistenceFilter.h"
  27. #import "Firestore/Source/Remote/FSTRemoteStore.h"
  28. #import "Firestore/Source/Remote/FSTWatchChange.h"
  29. #import "Firestore/Source/Util/FSTClasses.h"
  30. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  31. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  32. #include "Firestore/core/src/firebase/firestore/util/hashing.h"
  33. #include "Firestore/core/src/firebase/firestore/util/log.h"
  34. using firebase::firestore::model::DocumentKey;
  35. using firebase::firestore::model::DocumentKeyHash;
  36. using firebase::firestore::model::DocumentKeySet;
  37. using firebase::firestore::model::SnapshotVersion;
  38. using firebase::firestore::model::TargetId;
  39. using firebase::firestore::util::Hash;
  40. NS_ASSUME_NONNULL_BEGIN
  41. #pragma mark - FSTTargetChange
  42. @implementation FSTTargetChange {
  43. DocumentKeySet _addedDocuments;
  44. DocumentKeySet _modifiedDocuments;
  45. DocumentKeySet _removedDocuments;
  46. }
  47. - (instancetype)initWithResumeToken:(NSData *)resumeToken
  48. current:(BOOL)current
  49. addedDocuments:(DocumentKeySet)addedDocuments
  50. modifiedDocuments:(DocumentKeySet)modifiedDocuments
  51. removedDocuments:(DocumentKeySet)removedDocuments {
  52. if (self = [super init]) {
  53. _resumeToken = [resumeToken copy];
  54. _current = current;
  55. _addedDocuments = std::move(addedDocuments);
  56. _modifiedDocuments = std::move(modifiedDocuments);
  57. _removedDocuments = std::move(removedDocuments);
  58. }
  59. return self;
  60. }
  61. - (const DocumentKeySet &)addedDocuments {
  62. return _addedDocuments;
  63. }
  64. - (const DocumentKeySet &)modifiedDocuments {
  65. return _modifiedDocuments;
  66. }
  67. - (const DocumentKeySet &)removedDocuments {
  68. return _removedDocuments;
  69. }
  70. - (BOOL)isEqual:(id)other {
  71. if (other == self) {
  72. return YES;
  73. }
  74. if (![other isMemberOfClass:[FSTTargetChange class]]) {
  75. return NO;
  76. }
  77. return [self current] == [other current] &&
  78. [[self resumeToken] isEqualToData:[other resumeToken]] &&
  79. [self addedDocuments] == [other addedDocuments] &&
  80. [self modifiedDocuments] == [other modifiedDocuments] &&
  81. [self removedDocuments] == [other removedDocuments];
  82. }
  83. @end
  84. #pragma mark - FSTTargetState
  85. /** Tracks the internal state of a Watch target. */
  86. @interface FSTTargetState : NSObject
  87. /**
  88. * Whether this target has been marked 'current'.
  89. *
  90. * 'Current' has special meaning in the RPC protocol: It implies that the Watch backend has sent us
  91. * all changes up to the point at which the target was added and that the target is consistent with
  92. * the rest of the watch stream.
  93. */
  94. @property(nonatomic) BOOL current;
  95. /** The last resume token sent to us for this target. */
  96. @property(nonatomic, readonly, strong) NSData *resumeToken;
  97. /** Whether we have modified any state that should trigger a snapshot. */
  98. @property(nonatomic, readonly) BOOL hasPendingChanges;
  99. /** Whether this target has pending target adds or target removes. */
  100. - (BOOL)isPending;
  101. /**
  102. * Applies the resume token to the TargetChange, but only when it has a new value. Empty
  103. * resumeTokens are discarded.
  104. */
  105. - (void)updateResumeToken:(NSData *)resumeToken;
  106. /** Resets the document changes and sets `hasPendingChanges` to false. */
  107. - (void)clearPendingChanges;
  108. /**
  109. * Creates a target change from the current set of changes.
  110. *
  111. * To reset the document changes after raising this snapshot, call `clearPendingChanges()`.
  112. */
  113. - (FSTTargetChange *)toTargetChange;
  114. - (void)recordTargetRequest;
  115. - (void)recordTargetResponse;
  116. - (void)markCurrent;
  117. - (void)addDocumentChangeWithType:(FSTDocumentViewChangeType)type
  118. forKey:(const DocumentKey &)documentKey;
  119. - (void)removeDocumentChangeForKey:(const DocumentKey &)documentKey;
  120. @end
  121. @implementation FSTTargetState {
  122. /**
  123. * The number of outstanding responses (adds or removes) that we are waiting on. We only consider
  124. * targets active that have no outstanding responses.
  125. */
  126. int _outstandingResponses;
  127. /**
  128. * Keeps track of the document changes since the last raised snapshot.
  129. *
  130. * These changes are continuously updated as we receive document updates and always reflect the
  131. * current set of changes against the last issued snapshot.
  132. */
  133. std::unordered_map<DocumentKey, FSTDocumentViewChangeType, DocumentKeyHash> _documentChanges;
  134. }
  135. - (instancetype)init {
  136. if (self = [super init]) {
  137. _resumeToken = [NSData data];
  138. _outstandingResponses = 0;
  139. // We initialize to 'true' so that newly-added targets are included in the next RemoteEvent.
  140. _hasPendingChanges = YES;
  141. }
  142. return self;
  143. }
  144. - (BOOL)isPending {
  145. return _outstandingResponses != 0;
  146. }
  147. - (void)updateResumeToken:(NSData *)resumeToken {
  148. if (resumeToken.length > 0) {
  149. _hasPendingChanges = YES;
  150. _resumeToken = [resumeToken copy];
  151. }
  152. }
  153. - (void)clearPendingChanges {
  154. _hasPendingChanges = NO;
  155. _documentChanges.clear();
  156. }
  157. - (void)recordTargetRequest {
  158. _outstandingResponses += 1;
  159. }
  160. - (void)recordTargetResponse {
  161. _outstandingResponses -= 1;
  162. }
  163. - (void)markCurrent {
  164. _hasPendingChanges = YES;
  165. _current = true;
  166. }
  167. - (void)addDocumentChangeWithType:(FSTDocumentViewChangeType)type
  168. forKey:(const DocumentKey &)documentKey {
  169. _hasPendingChanges = YES;
  170. _documentChanges[documentKey] = type;
  171. }
  172. - (void)removeDocumentChangeForKey:(const DocumentKey &)documentKey {
  173. _hasPendingChanges = YES;
  174. _documentChanges.erase(documentKey);
  175. }
  176. - (FSTTargetChange *)toTargetChange {
  177. DocumentKeySet addedDocuments;
  178. DocumentKeySet modifiedDocuments;
  179. DocumentKeySet removedDocuments;
  180. for (const auto &entry : _documentChanges) {
  181. switch (entry.second) {
  182. case FSTDocumentViewChangeTypeAdded:
  183. addedDocuments = addedDocuments.insert(entry.first);
  184. break;
  185. case FSTDocumentViewChangeTypeModified:
  186. modifiedDocuments = modifiedDocuments.insert(entry.first);
  187. break;
  188. case FSTDocumentViewChangeTypeRemoved:
  189. removedDocuments = removedDocuments.insert(entry.first);
  190. break;
  191. default:
  192. HARD_FAIL("Encountered invalid change type: %s", entry.second);
  193. }
  194. }
  195. return [[FSTTargetChange alloc] initWithResumeToken:_resumeToken
  196. current:_current
  197. addedDocuments:std::move(addedDocuments)
  198. modifiedDocuments:std::move(modifiedDocuments)
  199. removedDocuments:std::move(removedDocuments)];
  200. }
  201. @end
  202. #pragma mark - FSTRemoteEvent
  203. @implementation FSTRemoteEvent {
  204. SnapshotVersion _snapshotVersion;
  205. std::unordered_map<TargetId, FSTTargetChange *> _targetChanges;
  206. std::unordered_set<TargetId> _targetMismatches;
  207. std::unordered_map<DocumentKey, FSTMaybeDocument *, DocumentKeyHash> _documentUpdates;
  208. DocumentKeySet _limboDocumentChanges;
  209. }
  210. - (instancetype)
  211. initWithSnapshotVersion:(SnapshotVersion)snapshotVersion
  212. targetChanges:(std::unordered_map<TargetId, FSTTargetChange *>)targetChanges
  213. targetMismatches:(std::unordered_set<TargetId>)targetMismatches
  214. documentUpdates:(std::unordered_map<DocumentKey, FSTMaybeDocument *, DocumentKeyHash>)
  215. documentUpdates
  216. limboDocuments:(DocumentKeySet)limboDocuments {
  217. self = [super init];
  218. if (self) {
  219. _snapshotVersion = std::move(snapshotVersion);
  220. _targetChanges = std::move(targetChanges);
  221. _targetMismatches = std::move(targetMismatches);
  222. _documentUpdates = std::move(documentUpdates);
  223. _limboDocumentChanges = std::move(limboDocuments);
  224. }
  225. return self;
  226. }
  227. - (const SnapshotVersion &)snapshotVersion {
  228. return _snapshotVersion;
  229. }
  230. - (const DocumentKeySet &)limboDocumentChanges {
  231. return _limboDocumentChanges;
  232. }
  233. - (const std::unordered_map<TargetId, FSTTargetChange *> &)targetChanges {
  234. return _targetChanges;
  235. }
  236. - (const std::unordered_map<DocumentKey, FSTMaybeDocument *, DocumentKeyHash> &)documentUpdates {
  237. return _documentUpdates;
  238. }
  239. - (const std::unordered_set<TargetId> &)targetMismatches {
  240. return _targetMismatches;
  241. }
  242. @end
  243. #pragma mark - FSTWatchChangeAggregator
  244. @implementation FSTWatchChangeAggregator {
  245. /** The internal state of all tracked targets. */
  246. std::unordered_map<TargetId, FSTTargetState *> _targetStates;
  247. /** Keeps track of document to update */
  248. std::unordered_map<DocumentKey, FSTMaybeDocument *, DocumentKeyHash> _pendingDocumentUpdates;
  249. /** A mapping of document keys to their set of target IDs. */
  250. std::unordered_map<DocumentKey, std::set<TargetId>, DocumentKeyHash>
  251. _pendingDocumentTargetMappings;
  252. /**
  253. * A list of targets with existence filter mismatches. These targets are known to be inconsistent
  254. * and their listens needs to be re-established by RemoteStore.
  255. */
  256. std::unordered_set<TargetId> _pendingTargetResets;
  257. id<FSTTargetMetadataProvider> _targetMetadataProvider;
  258. }
  259. - (instancetype)initWithTargetMetadataProvider:
  260. (id<FSTTargetMetadataProvider>)targetMetadataProvider {
  261. self = [super init];
  262. if (self) {
  263. _targetMetadataProvider = targetMetadataProvider;
  264. }
  265. return self;
  266. }
  267. - (void)handleDocumentChange:(FSTDocumentWatchChange *)documentChange {
  268. for (FSTBoxedTargetID *targetID in documentChange.updatedTargetIDs) {
  269. if ([documentChange.document isKindOfClass:[FSTDocument class]]) {
  270. [self addDocument:documentChange.document toTarget:targetID.intValue];
  271. } else if ([documentChange.document isKindOfClass:[FSTDeletedDocument class]]) {
  272. [self removeDocument:documentChange.document
  273. withKey:documentChange.documentKey
  274. fromTarget:targetID.intValue];
  275. }
  276. }
  277. for (FSTBoxedTargetID *targetID in documentChange.removedTargetIDs) {
  278. [self removeDocument:documentChange.document
  279. withKey:documentChange.documentKey
  280. fromTarget:targetID.intValue];
  281. }
  282. }
  283. - (void)handleTargetChange:(FSTWatchTargetChange *)targetChange {
  284. for (TargetId targetID : [self targetIdsForChange:targetChange]) {
  285. FSTTargetState *targetState = [self ensureTargetStateForTarget:targetID];
  286. switch (targetChange.state) {
  287. case FSTWatchTargetChangeStateNoChange:
  288. if ([self isActiveTarget:targetID]) {
  289. [targetState updateResumeToken:targetChange.resumeToken];
  290. }
  291. break;
  292. case FSTWatchTargetChangeStateAdded:
  293. // We need to decrement the number of pending acks needed from watch for this targetId.
  294. [targetState recordTargetResponse];
  295. if (!targetState.isPending) {
  296. // We have a freshly added target, so we need to reset any state that we had previously.
  297. // This can happen e.g. when remove and add back a target for existence filter mismatches.
  298. [targetState clearPendingChanges];
  299. }
  300. [targetState updateResumeToken:targetChange.resumeToken];
  301. break;
  302. case FSTWatchTargetChangeStateRemoved:
  303. // We need to keep track of removed targets to we can post-filter and remove any target
  304. // changes.
  305. [targetState recordTargetResponse];
  306. if (!targetState.isPending) {
  307. [self removeTarget:targetID];
  308. }
  309. HARD_ASSERT(!targetChange.cause, "WatchChangeAggregator does not handle errored targets");
  310. break;
  311. case FSTWatchTargetChangeStateCurrent:
  312. if ([self isActiveTarget:targetID]) {
  313. [targetState markCurrent];
  314. [targetState updateResumeToken:targetChange.resumeToken];
  315. }
  316. break;
  317. case FSTWatchTargetChangeStateReset:
  318. if ([self isActiveTarget:targetID]) {
  319. // Reset the target and synthesizes removes for all existing documents. The backend will
  320. // re-add any documents that still match the target before it sends the next global
  321. // snapshot.
  322. [self resetTarget:targetID];
  323. [targetState updateResumeToken:targetChange.resumeToken];
  324. }
  325. break;
  326. default:
  327. HARD_FAIL("Unknown target watch change state: %s", targetChange.state);
  328. }
  329. }
  330. }
  331. /**
  332. * Returns all targetIds that the watch change applies to: either the targetIds explicitly listed
  333. * in the change or the targetIds of all currently active targets.
  334. */
  335. - (std::vector<TargetId>)targetIdsForChange:(FSTWatchTargetChange *)targetChange {
  336. NSArray<NSNumber *> *targetIDs = targetChange.targetIDs;
  337. std::vector<TargetId> result;
  338. if (targetIDs.count > 0) {
  339. result.reserve(targetIDs.count);
  340. for (NSNumber *targetID in targetIDs) {
  341. result.push_back(targetID.intValue);
  342. }
  343. } else {
  344. result.reserve(_targetStates.size());
  345. for (const auto &entry : _targetStates) {
  346. result.push_back(entry.first);
  347. }
  348. }
  349. return result;
  350. }
  351. - (void)removeTarget:(TargetId)targetID {
  352. _targetStates.erase(targetID);
  353. }
  354. - (void)handleExistenceFilter:(FSTExistenceFilterWatchChange *)existenceFilter {
  355. TargetId targetID = existenceFilter.targetID;
  356. int expectedCount = existenceFilter.filter.count;
  357. FSTQueryData *queryData = [self queryDataForActiveTarget:targetID];
  358. if (queryData) {
  359. FSTQuery *query = queryData.query;
  360. if ([query isDocumentQuery]) {
  361. if (expectedCount == 0) {
  362. // The existence filter told us the document does not exist. We deduce that this document
  363. // does not exist and apply a deleted document to our updates. Without applying this deleted
  364. // document there might be another query that will raise this document as part of a snapshot
  365. // until it is resolved, essentially exposing inconsistency between queries.
  366. FSTDocumentKey *key = [FSTDocumentKey keyWithPath:query.path];
  367. [self
  368. removeDocument:[FSTDeletedDocument documentWithKey:key version:SnapshotVersion::None()]
  369. withKey:key
  370. fromTarget:targetID];
  371. } else {
  372. HARD_ASSERT(expectedCount == 1, "Single document existence filter with count: %s",
  373. expectedCount);
  374. }
  375. } else {
  376. int currentSize = [self currentDocumentCountForTarget:targetID];
  377. if (currentSize != expectedCount) {
  378. // Existence filter mismatch: We reset the mapping and raise a new snapshot with
  379. // `isFromCache:true`.
  380. [self resetTarget:targetID];
  381. _pendingTargetResets.insert(targetID);
  382. }
  383. }
  384. }
  385. }
  386. - (int)currentDocumentCountForTarget:(TargetId)targetID {
  387. FSTTargetState *targetState = [self ensureTargetStateForTarget:targetID];
  388. FSTTargetChange *targetChange = [targetState toTargetChange];
  389. return ([_targetMetadataProvider remoteKeysForTarget:@(targetID)].size() +
  390. targetChange.addedDocuments.size() - targetChange.removedDocuments.size());
  391. }
  392. /**
  393. * Resets the state of a Watch target to its initial state (e.g. sets 'current' to false, clears the
  394. * resume token and removes its target mapping from all documents).
  395. */
  396. - (void)resetTarget:(TargetId)targetID {
  397. auto currentTargetState = _targetStates.find(targetID);
  398. HARD_ASSERT(currentTargetState != _targetStates.end() && !(currentTargetState->second.isPending),
  399. "Should only reset active targets");
  400. _targetStates[targetID] = [FSTTargetState new];
  401. // Trigger removal for any documents currently mapped to this target. These removals will be part
  402. // of the initial snapshot if Watch does not resend these documents.
  403. DocumentKeySet existingKeys = [_targetMetadataProvider remoteKeysForTarget:@(targetID)];
  404. for (FSTDocumentKey *key : existingKeys) {
  405. [self removeDocument:nil withKey:key fromTarget:targetID];
  406. }
  407. }
  408. /**
  409. * Adds the provided document to the internal list of document updates and its document key to the
  410. * given target's mapping.
  411. */
  412. - (void)addDocument:(FSTMaybeDocument *)document toTarget:(TargetId)targetID {
  413. if (![self isActiveTarget:targetID]) {
  414. return;
  415. }
  416. FSTDocumentViewChangeType changeType = [self containsDocument:document.key inTarget:targetID]
  417. ? FSTDocumentViewChangeTypeModified
  418. : FSTDocumentViewChangeTypeAdded;
  419. FSTTargetState *targetState = [self ensureTargetStateForTarget:targetID];
  420. [targetState addDocumentChangeWithType:changeType forKey:document.key];
  421. _pendingDocumentUpdates[document.key] = document;
  422. _pendingDocumentTargetMappings[document.key].insert(targetID);
  423. }
  424. /**
  425. * Removes the provided document from the target mapping. If the document no longer matches the
  426. * target, but the document's state is still known (e.g. we know that the document was deleted or we
  427. * received the change that caused the filter mismatch), the new document can be provided to update
  428. * the remote document cache.
  429. */
  430. - (void)removeDocument:(FSTMaybeDocument *_Nullable)document
  431. withKey:(const DocumentKey &)key
  432. fromTarget:(TargetId)targetID {
  433. if (![self isActiveTarget:targetID]) {
  434. return;
  435. }
  436. FSTTargetState *targetState = [self ensureTargetStateForTarget:targetID];
  437. if ([self containsDocument:key inTarget:targetID]) {
  438. [targetState addDocumentChangeWithType:FSTDocumentViewChangeTypeRemoved forKey:key];
  439. } else {
  440. // The document may have entered and left the target before we raised a snapshot, so we can just
  441. // ignore the change.
  442. [targetState removeDocumentChangeForKey:key];
  443. }
  444. _pendingDocumentTargetMappings[key].insert(targetID);
  445. if (document) {
  446. _pendingDocumentUpdates[key] = document;
  447. }
  448. }
  449. /**
  450. * Returns whether the LocalStore considers the document to be part of the specified target.
  451. */
  452. - (BOOL)containsDocument:(FSTDocumentKey *)key inTarget:(TargetId)targetID {
  453. const DocumentKeySet &existingKeys = [_targetMetadataProvider remoteKeysForTarget:@(targetID)];
  454. return existingKeys.contains(key);
  455. }
  456. - (FSTTargetState *)ensureTargetStateForTarget:(TargetId)targetID {
  457. if (!_targetStates[targetID]) {
  458. _targetStates[targetID] = [FSTTargetState new];
  459. }
  460. return _targetStates[targetID];
  461. }
  462. /**
  463. * Returns YES if the given targetId is active. Active targets are those for which there are no
  464. * pending requests to add a listen and are in the current list of targets the client cares about.
  465. *
  466. * Clients can repeatedly listen and stop listening to targets, so this check is useful in
  467. * preventing in preventing race conditions for a target where events arrive but the server hasn't
  468. * yet acknowledged the intended change in state.
  469. */
  470. - (BOOL)isActiveTarget:(TargetId)targetID {
  471. return [self queryDataForActiveTarget:targetID] != nil;
  472. }
  473. - (nullable FSTQueryData *)queryDataForActiveTarget:(TargetId)targetID {
  474. auto targetState = _targetStates.find(targetID);
  475. return targetState != _targetStates.end() && targetState->second.isPending
  476. ? nil
  477. : [_targetMetadataProvider queryDataForTarget:@(targetID)];
  478. }
  479. - (FSTRemoteEvent *)remoteEventAtSnapshotVersion:(const SnapshotVersion &)snapshotVersion {
  480. std::unordered_map<TargetId, FSTTargetChange *> targetChanges;
  481. for (const auto &entry : _targetStates) {
  482. TargetId targetID = entry.first;
  483. FSTTargetState *targetState = entry.second;
  484. FSTQueryData *queryData = [self queryDataForActiveTarget:targetID];
  485. if (queryData) {
  486. if (targetState.current && [queryData.query isDocumentQuery]) {
  487. // Document queries for document that don't exist can produce an empty result set. To update
  488. // our local cache, we synthesize a document delete if we have not previously received the
  489. // document. This resolves the limbo state of the document, removing it from
  490. // limboDocumentRefs.
  491. FSTDocumentKey *key = [FSTDocumentKey keyWithPath:queryData.query.path];
  492. if (_pendingDocumentUpdates.find(key) == _pendingDocumentUpdates.end() &&
  493. ![self containsDocument:key inTarget:targetID]) {
  494. [self removeDocument:[FSTDeletedDocument documentWithKey:key version:snapshotVersion]
  495. withKey:key
  496. fromTarget:targetID];
  497. }
  498. }
  499. if (targetState.hasPendingChanges) {
  500. targetChanges[targetID] = [targetState toTargetChange];
  501. [targetState clearPendingChanges];
  502. }
  503. }
  504. }
  505. DocumentKeySet resolvedLimboDocuments;
  506. // We extract the set of limbo-only document updates as the GC logic special-cases documents that
  507. // do not appear in the query cache.
  508. //
  509. // TODO(gsoltis): Expand on this comment.
  510. for (const auto &entry : _pendingDocumentTargetMappings) {
  511. BOOL isOnlyLimboTarget = YES;
  512. for (TargetId targetID : entry.second) {
  513. FSTQueryData *queryData = [self queryDataForActiveTarget:targetID];
  514. if (queryData && queryData.purpose != FSTQueryPurposeLimboResolution) {
  515. isOnlyLimboTarget = NO;
  516. break;
  517. }
  518. }
  519. if (isOnlyLimboTarget) {
  520. resolvedLimboDocuments = resolvedLimboDocuments.insert(entry.first);
  521. }
  522. }
  523. FSTRemoteEvent *remoteEvent =
  524. [[FSTRemoteEvent alloc] initWithSnapshotVersion:snapshotVersion
  525. targetChanges:targetChanges
  526. targetMismatches:_pendingTargetResets
  527. documentUpdates:_pendingDocumentUpdates
  528. limboDocuments:resolvedLimboDocuments];
  529. _pendingDocumentUpdates.clear();
  530. _pendingDocumentTargetMappings.clear();
  531. _pendingTargetResets.clear();
  532. return remoteEvent;
  533. }
  534. - (void)recordTargetRequest:(FSTBoxedTargetID *)targetID {
  535. // For each request we get we need to record we need a response for it.
  536. FSTTargetState *targetState = [self ensureTargetStateForTarget:targetID.intValue];
  537. [targetState recordTargetRequest];
  538. }
  539. @end
  540. NS_ASSUME_NONNULL_END