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