FSTSyncEngine.mm 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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/FSTSyncEngine.h"
  17. #import <GRPCClient/GRPCCall.h>
  18. #include <map>
  19. #include <set>
  20. #include <unordered_map>
  21. #import "FIRFirestoreErrors.h"
  22. #import "Firestore/Source/Core/FSTQuery.h"
  23. #import "Firestore/Source/Core/FSTSnapshotVersion.h"
  24. #import "Firestore/Source/Core/FSTTransaction.h"
  25. #import "Firestore/Source/Core/FSTView.h"
  26. #import "Firestore/Source/Core/FSTViewSnapshot.h"
  27. #import "Firestore/Source/Local/FSTEagerGarbageCollector.h"
  28. #import "Firestore/Source/Local/FSTLocalStore.h"
  29. #import "Firestore/Source/Local/FSTLocalViewChanges.h"
  30. #import "Firestore/Source/Local/FSTLocalWriteResult.h"
  31. #import "Firestore/Source/Local/FSTQueryData.h"
  32. #import "Firestore/Source/Local/FSTReferenceSet.h"
  33. #import "Firestore/Source/Model/FSTDocument.h"
  34. #import "Firestore/Source/Model/FSTDocumentSet.h"
  35. #import "Firestore/Source/Model/FSTMutationBatch.h"
  36. #import "Firestore/Source/Remote/FSTRemoteEvent.h"
  37. #import "Firestore/Source/Util/FSTAssert.h"
  38. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  39. #import "Firestore/Source/Util/FSTLogger.h"
  40. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  41. #include "Firestore/core/src/firebase/firestore/core/target_id_generator.h"
  42. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  43. using firebase::firestore::auth::HashUser;
  44. using firebase::firestore::auth::User;
  45. using firebase::firestore::core::TargetIdGenerator;
  46. using firebase::firestore::model::DocumentKey;
  47. using firebase::firestore::model::TargetId;
  48. NS_ASSUME_NONNULL_BEGIN
  49. // Limbo documents don't use persistence, and are eagerly GC'd. So, listens for them don't need
  50. // real sequence numbers.
  51. static const FSTListenSequenceNumber kIrrelevantSequenceNumber = -1;
  52. #pragma mark - FSTQueryView
  53. /**
  54. * FSTQueryView contains all of the info that FSTSyncEngine needs to track for a particular
  55. * query and view.
  56. */
  57. @interface FSTQueryView : NSObject
  58. - (instancetype)initWithQuery:(FSTQuery *)query
  59. targetID:(FSTTargetID)targetID
  60. resumeToken:(NSData *)resumeToken
  61. view:(FSTView *)view NS_DESIGNATED_INITIALIZER;
  62. - (instancetype)init NS_UNAVAILABLE;
  63. /** The query itself. */
  64. @property(nonatomic, strong, readonly) FSTQuery *query;
  65. /** The targetID created by the client that is used in the watch stream to identify this query. */
  66. @property(nonatomic, assign, readonly) FSTTargetID targetID;
  67. /**
  68. * An identifier from the datastore backend that indicates the last state of the results that
  69. * was received. This can be used to indicate where to continue receiving new doc changes for the
  70. * query.
  71. */
  72. @property(nonatomic, copy, readonly) NSData *resumeToken;
  73. /**
  74. * The view is responsible for computing the final merged truth of what docs are in the query.
  75. * It gets notified of local and remote changes, and applies the query filters and limits to
  76. * determine the most correct possible results.
  77. */
  78. @property(nonatomic, strong, readonly) FSTView *view;
  79. @end
  80. @implementation FSTQueryView
  81. - (instancetype)initWithQuery:(FSTQuery *)query
  82. targetID:(FSTTargetID)targetID
  83. resumeToken:(NSData *)resumeToken
  84. view:(FSTView *)view {
  85. if (self = [super init]) {
  86. _query = query;
  87. _targetID = targetID;
  88. _resumeToken = resumeToken;
  89. _view = view;
  90. }
  91. return self;
  92. }
  93. @end
  94. #pragma mark - FSTSyncEngine
  95. @interface FSTSyncEngine ()
  96. /** The local store, used to persist mutations and cached documents. */
  97. @property(nonatomic, strong, readonly) FSTLocalStore *localStore;
  98. /** The remote store for sending writes, watches, etc. to the backend. */
  99. @property(nonatomic, strong, readonly) FSTRemoteStore *remoteStore;
  100. /** FSTQueryViews for all active queries, indexed by query. */
  101. @property(nonatomic, strong, readonly)
  102. NSMutableDictionary<FSTQuery *, FSTQueryView *> *queryViewsByQuery;
  103. /** FSTQueryViews for all active queries, indexed by target ID. */
  104. @property(nonatomic, strong, readonly)
  105. NSMutableDictionary<NSNumber *, FSTQueryView *> *queryViewsByTarget;
  106. /** Used to track any documents that are currently in limbo. */
  107. @property(nonatomic, strong, readonly) FSTReferenceSet *limboDocumentRefs;
  108. /** The garbage collector used to collect documents that are no longer in limbo. */
  109. @property(nonatomic, strong, readonly) FSTEagerGarbageCollector *limboCollector;
  110. @end
  111. @implementation FSTSyncEngine {
  112. /** Used for creating the FSTTargetIDs for the listens used to resolve limbo documents. */
  113. TargetIdGenerator _targetIdGenerator;
  114. /** Stores user completion blocks, indexed by user and FSTBatchID. */
  115. std::unordered_map<User, NSMutableDictionary<NSNumber *, FSTVoidErrorBlock> *, HashUser>
  116. _mutationCompletionBlocks;
  117. /**
  118. * When a document is in limbo, we create a special listen to resolve it. This maps the
  119. * DocumentKey of each limbo document to the TargetId of the listen resolving it.
  120. */
  121. std::map<DocumentKey, TargetId> _limboTargetsByKey;
  122. /** The inverse of _limboTargetsByKey, a map of TargetId to the key of the limbo doc. */
  123. std::map<TargetId, DocumentKey> _limboKeysByTarget;
  124. User _currentUser;
  125. }
  126. - (instancetype)initWithLocalStore:(FSTLocalStore *)localStore
  127. remoteStore:(FSTRemoteStore *)remoteStore
  128. initialUser:(const User &)initialUser {
  129. if (self = [super init]) {
  130. _localStore = localStore;
  131. _remoteStore = remoteStore;
  132. _queryViewsByQuery = [NSMutableDictionary dictionary];
  133. _queryViewsByTarget = [NSMutableDictionary dictionary];
  134. _limboCollector = [[FSTEagerGarbageCollector alloc] init];
  135. _limboDocumentRefs = [[FSTReferenceSet alloc] init];
  136. [_limboCollector addGarbageSource:_limboDocumentRefs];
  137. _targetIdGenerator = TargetIdGenerator::SyncEngineTargetIdGenerator(0);
  138. _currentUser = initialUser;
  139. }
  140. return self;
  141. }
  142. - (FSTTargetID)listenToQuery:(FSTQuery *)query {
  143. [self assertDelegateExistsForSelector:_cmd];
  144. FSTAssert(self.queryViewsByQuery[query] == nil, @"We already listen to query: %@", query);
  145. FSTQueryData *queryData = [self.localStore allocateQuery:query];
  146. FSTDocumentDictionary *docs = [self.localStore executeQuery:query];
  147. FSTDocumentKeySet *remoteKeys = [self.localStore remoteDocumentKeysForTarget:queryData.targetID];
  148. FSTView *view = [[FSTView alloc] initWithQuery:query remoteDocuments:remoteKeys];
  149. FSTViewDocumentChanges *viewDocChanges = [view computeChangesWithDocuments:docs];
  150. FSTViewChange *viewChange = [view applyChangesToDocuments:viewDocChanges];
  151. FSTAssert(viewChange.limboChanges.count == 0,
  152. @"View returned limbo docs before target ack from the server.");
  153. FSTQueryView *queryView = [[FSTQueryView alloc] initWithQuery:query
  154. targetID:queryData.targetID
  155. resumeToken:queryData.resumeToken
  156. view:view];
  157. self.queryViewsByQuery[query] = queryView;
  158. self.queryViewsByTarget[@(queryData.targetID)] = queryView;
  159. [self.delegate handleViewSnapshots:@[ viewChange.snapshot ]];
  160. [self.remoteStore listenToTargetWithQueryData:queryData];
  161. return queryData.targetID;
  162. }
  163. - (void)stopListeningToQuery:(FSTQuery *)query {
  164. [self assertDelegateExistsForSelector:_cmd];
  165. FSTQueryView *queryView = self.queryViewsByQuery[query];
  166. FSTAssert(queryView, @"Trying to stop listening to a query not found");
  167. [self.localStore releaseQuery:query];
  168. [self.remoteStore stopListeningToTargetID:queryView.targetID];
  169. [self removeAndCleanupQuery:queryView];
  170. [self.localStore collectGarbage];
  171. }
  172. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations
  173. completion:(FSTVoidErrorBlock)completion {
  174. [self assertDelegateExistsForSelector:_cmd];
  175. FSTLocalWriteResult *result = [self.localStore locallyWriteMutations:mutations];
  176. [self addMutationCompletionBlock:completion batchID:result.batchID];
  177. [self emitNewSnapshotsWithChanges:result.changes remoteEvent:nil];
  178. [self.remoteStore fillWritePipeline];
  179. }
  180. - (void)addMutationCompletionBlock:(FSTVoidErrorBlock)completion batchID:(FSTBatchID)batchID {
  181. NSMutableDictionary<NSNumber *, FSTVoidErrorBlock> *completionBlocks =
  182. _mutationCompletionBlocks[_currentUser];
  183. if (!completionBlocks) {
  184. completionBlocks = [NSMutableDictionary dictionary];
  185. _mutationCompletionBlocks[_currentUser] = completionBlocks;
  186. }
  187. [completionBlocks setObject:completion forKey:@(batchID)];
  188. }
  189. /**
  190. * Takes an updateBlock in which a set of reads and writes can be performed atomically. In the
  191. * updateBlock, user code can read and write values using a transaction object. After the
  192. * updateBlock, all changes will be committed. If someone else has changed any of the data
  193. * referenced, then the updateBlock will be called again. If the updateBlock still fails after the
  194. * given number of retries, then the transaction will be rejected.
  195. *
  196. * The transaction object passed to the updateBlock contains methods for accessing documents
  197. * and collections. Unlike other firestore access, data accessed with the transaction will not
  198. * reflect local changes that have not been committed. For this reason, it is required that all
  199. * reads are performed before any writes. Transactions must be performed while online.
  200. */
  201. - (void)transactionWithRetries:(int)retries
  202. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  203. updateBlock:(FSTTransactionBlock)updateBlock
  204. completion:(FSTVoidIDErrorBlock)completion {
  205. [workerDispatchQueue verifyIsCurrentQueue];
  206. FSTAssert(retries >= 0, @"Got negative number of retries for transaction");
  207. FSTTransaction *transaction = [self.remoteStore transaction];
  208. updateBlock(transaction, ^(id _Nullable result, NSError *_Nullable error) {
  209. [workerDispatchQueue dispatchAsync:^{
  210. if (error) {
  211. completion(nil, error);
  212. return;
  213. }
  214. [transaction commitWithCompletion:^(NSError *_Nullable transactionError) {
  215. if (!transactionError) {
  216. completion(result, nil);
  217. return;
  218. }
  219. // TODO(b/35201829): Only retry on real transaction failures.
  220. if (retries == 0) {
  221. NSError *wrappedError =
  222. [NSError errorWithDomain:FIRFirestoreErrorDomain
  223. code:FIRFirestoreErrorCodeFailedPrecondition
  224. userInfo:@{
  225. NSLocalizedDescriptionKey : @"Transaction failed all retries.",
  226. NSUnderlyingErrorKey : transactionError
  227. }];
  228. completion(nil, wrappedError);
  229. return;
  230. }
  231. [workerDispatchQueue verifyIsCurrentQueue];
  232. return [self transactionWithRetries:(retries - 1)
  233. workerDispatchQueue:workerDispatchQueue
  234. updateBlock:updateBlock
  235. completion:completion];
  236. }];
  237. }];
  238. });
  239. }
  240. - (void)applyRemoteEvent:(FSTRemoteEvent *)remoteEvent {
  241. [self assertDelegateExistsForSelector:_cmd];
  242. // Make sure limbo documents are deleted if there were no results.
  243. // Filter out document additions to targets that they already belong to.
  244. [remoteEvent.targetChanges enumerateKeysAndObjectsUsingBlock:^(
  245. FSTBoxedTargetID *_Nonnull targetID,
  246. FSTTargetChange *_Nonnull targetChange, BOOL *_Nonnull stop) {
  247. const auto iter = self->_limboKeysByTarget.find([targetID intValue]);
  248. if (iter == self->_limboKeysByTarget.end()) {
  249. FSTQueryView *qv = self.queryViewsByTarget[targetID];
  250. FSTAssert(qv, @"Missing queryview for non-limbo query: %i", [targetID intValue]);
  251. [remoteEvent filterUpdatesFromTargetChange:targetChange
  252. existingDocuments:qv.view.syncedDocuments];
  253. } else {
  254. [remoteEvent synthesizeDeleteForLimboTargetChange:targetChange key:iter->second];
  255. }
  256. }];
  257. FSTMaybeDocumentDictionary *changes = [self.localStore applyRemoteEvent:remoteEvent];
  258. [self emitNewSnapshotsWithChanges:changes remoteEvent:remoteEvent];
  259. }
  260. - (void)applyChangedOnlineState:(FSTOnlineState)onlineState {
  261. NSMutableArray<FSTViewSnapshot *> *newViewSnapshots = [NSMutableArray array];
  262. [self.queryViewsByQuery
  263. enumerateKeysAndObjectsUsingBlock:^(FSTQuery *query, FSTQueryView *queryView, BOOL *stop) {
  264. FSTViewChange *viewChange = [queryView.view applyChangedOnlineState:onlineState];
  265. FSTAssert(viewChange.limboChanges.count == 0,
  266. @"OnlineState should not affect limbo documents.");
  267. if (viewChange.snapshot) {
  268. [newViewSnapshots addObject:viewChange.snapshot];
  269. }
  270. }];
  271. [self.delegate handleViewSnapshots:newViewSnapshots];
  272. }
  273. - (void)rejectListenWithTargetID:(const TargetId)targetID error:(NSError *)error {
  274. [self assertDelegateExistsForSelector:_cmd];
  275. const auto iter = _limboKeysByTarget.find(targetID);
  276. if (iter != _limboKeysByTarget.end()) {
  277. const DocumentKey limboKey = iter->second;
  278. // Since this query failed, we won't want to manually unlisten to it.
  279. // So go ahead and remove it from bookkeeping.
  280. _limboTargetsByKey.erase(limboKey);
  281. _limboKeysByTarget.erase(targetID);
  282. // TODO(dimond): Retry on transient errors?
  283. // It's a limbo doc. Create a synthetic event saying it was deleted. This is kind of a hack.
  284. // Ideally, we would have a method in the local store to purge a document. However, it would
  285. // be tricky to keep all of the local store's invariants with another method.
  286. NSMutableDictionary<NSNumber *, FSTTargetChange *> *targetChanges =
  287. [NSMutableDictionary dictionary];
  288. FSTDeletedDocument *doc =
  289. [FSTDeletedDocument documentWithKey:limboKey version:[FSTSnapshotVersion noVersion]];
  290. FSTRemoteEvent *event = [FSTRemoteEvent eventWithSnapshotVersion:[FSTSnapshotVersion noVersion]
  291. targetChanges:targetChanges
  292. documentUpdates:{{limboKey, doc}}];
  293. [self applyRemoteEvent:event];
  294. } else {
  295. FSTQueryView *queryView = self.queryViewsByTarget[@(targetID)];
  296. FSTAssert(queryView, @"Unknown targetId: %d", targetID);
  297. [self.localStore releaseQuery:queryView.query];
  298. [self removeAndCleanupQuery:queryView];
  299. [self.delegate handleError:error forQuery:queryView.query];
  300. }
  301. }
  302. - (void)applySuccessfulWriteWithResult:(FSTMutationBatchResult *)batchResult {
  303. [self assertDelegateExistsForSelector:_cmd];
  304. // The local store may or may not be able to apply the write result and raise events immediately
  305. // (depending on whether the watcher is caught up), so we raise user callbacks first so that they
  306. // consistently happen before listen events.
  307. [self processUserCallbacksForBatchID:batchResult.batch.batchID error:nil];
  308. FSTMaybeDocumentDictionary *changes = [self.localStore acknowledgeBatchWithResult:batchResult];
  309. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  310. }
  311. - (void)rejectFailedWriteWithBatchID:(FSTBatchID)batchID error:(NSError *)error {
  312. [self assertDelegateExistsForSelector:_cmd];
  313. // The local store may or may not be able to apply the write result and raise events immediately
  314. // (depending on whether the watcher is caught up), so we raise user callbacks first so that they
  315. // consistently happen before listen events.
  316. [self processUserCallbacksForBatchID:batchID error:error];
  317. FSTMaybeDocumentDictionary *changes = [self.localStore rejectBatchID:batchID];
  318. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  319. }
  320. - (void)processUserCallbacksForBatchID:(FSTBatchID)batchID error:(NSError *_Nullable)error {
  321. NSMutableDictionary<NSNumber *, FSTVoidErrorBlock> *completionBlocks =
  322. _mutationCompletionBlocks[_currentUser];
  323. // NOTE: Mutations restored from persistence won't have completion blocks, so it's okay for
  324. // this (or the completion below) to be nil.
  325. if (completionBlocks) {
  326. NSNumber *boxedBatchID = @(batchID);
  327. FSTVoidErrorBlock completion = completionBlocks[boxedBatchID];
  328. if (completion) {
  329. completion(error);
  330. [completionBlocks removeObjectForKey:boxedBatchID];
  331. }
  332. }
  333. }
  334. - (void)assertDelegateExistsForSelector:(SEL)methodSelector {
  335. FSTAssert(self.delegate, @"Tried to call '%@' before delegate was registered.",
  336. NSStringFromSelector(methodSelector));
  337. }
  338. - (void)removeAndCleanupQuery:(FSTQueryView *)queryView {
  339. [self.queryViewsByQuery removeObjectForKey:queryView.query];
  340. [self.queryViewsByTarget removeObjectForKey:@(queryView.targetID)];
  341. [self.limboDocumentRefs removeReferencesForID:queryView.targetID];
  342. [self garbageCollectLimboDocuments];
  343. }
  344. /**
  345. * Computes a new snapshot from the changes and calls the registered callback with the new snapshot.
  346. */
  347. - (void)emitNewSnapshotsWithChanges:(FSTMaybeDocumentDictionary *)changes
  348. remoteEvent:(FSTRemoteEvent *_Nullable)remoteEvent {
  349. NSMutableArray<FSTViewSnapshot *> *newSnapshots = [NSMutableArray array];
  350. NSMutableArray<FSTLocalViewChanges *> *documentChangesInAllViews = [NSMutableArray array];
  351. [self.queryViewsByQuery
  352. enumerateKeysAndObjectsUsingBlock:^(FSTQuery *query, FSTQueryView *queryView, BOOL *stop) {
  353. FSTView *view = queryView.view;
  354. FSTViewDocumentChanges *viewDocChanges = [view computeChangesWithDocuments:changes];
  355. if (viewDocChanges.needsRefill) {
  356. // The query has a limit and some docs were removed/updated, so we need to re-run the
  357. // query against the local store to make sure we didn't lose any good docs that had been
  358. // past the limit.
  359. FSTDocumentDictionary *docs = [self.localStore executeQuery:queryView.query];
  360. viewDocChanges = [view computeChangesWithDocuments:docs previousChanges:viewDocChanges];
  361. }
  362. FSTTargetChange *_Nullable targetChange = remoteEvent.targetChanges[@(queryView.targetID)];
  363. FSTViewChange *viewChange =
  364. [queryView.view applyChangesToDocuments:viewDocChanges targetChange:targetChange];
  365. [self updateTrackedLimboDocumentsWithChanges:viewChange.limboChanges
  366. targetID:queryView.targetID];
  367. if (viewChange.snapshot) {
  368. [newSnapshots addObject:viewChange.snapshot];
  369. FSTLocalViewChanges *docChanges =
  370. [FSTLocalViewChanges changesForViewSnapshot:viewChange.snapshot];
  371. [documentChangesInAllViews addObject:docChanges];
  372. }
  373. }];
  374. [self.delegate handleViewSnapshots:newSnapshots];
  375. [self.localStore notifyLocalViewChanges:documentChangesInAllViews];
  376. [self.localStore collectGarbage];
  377. }
  378. /** Updates the limbo document state for the given targetID. */
  379. - (void)updateTrackedLimboDocumentsWithChanges:(NSArray<FSTLimboDocumentChange *> *)limboChanges
  380. targetID:(FSTTargetID)targetID {
  381. for (FSTLimboDocumentChange *limboChange in limboChanges) {
  382. switch (limboChange.type) {
  383. case FSTLimboDocumentChangeTypeAdded:
  384. [self.limboDocumentRefs addReferenceToKey:limboChange.key forID:targetID];
  385. [self trackLimboChange:limboChange];
  386. break;
  387. case FSTLimboDocumentChangeTypeRemoved:
  388. FSTLog(@"Document no longer in limbo: %s", limboChange.key.ToString().c_str());
  389. [self.limboDocumentRefs removeReferenceToKey:limboChange.key forID:targetID];
  390. break;
  391. default:
  392. FSTFail(@"Unknown limbo change type: %ld", (long)limboChange.type);
  393. }
  394. }
  395. [self garbageCollectLimboDocuments];
  396. }
  397. - (void)trackLimboChange:(FSTLimboDocumentChange *)limboChange {
  398. DocumentKey key{limboChange.key};
  399. if (_limboTargetsByKey.find(key) == _limboTargetsByKey.end()) {
  400. FSTLog(@"New document in limbo: %s", key.ToString().c_str());
  401. TargetId limboTargetID = _targetIdGenerator.NextId();
  402. FSTQuery *query = [FSTQuery queryWithPath:key.path()];
  403. FSTQueryData *queryData = [[FSTQueryData alloc] initWithQuery:query
  404. targetID:limboTargetID
  405. listenSequenceNumber:kIrrelevantSequenceNumber
  406. purpose:FSTQueryPurposeLimboResolution];
  407. _limboKeysByTarget[limboTargetID] = key;
  408. [self.remoteStore listenToTargetWithQueryData:queryData];
  409. _limboTargetsByKey[key] = limboTargetID;
  410. }
  411. }
  412. /** Garbage collect the limbo documents that we no longer need to track. */
  413. - (void)garbageCollectLimboDocuments {
  414. const std::set<DocumentKey> garbage = [self.limboCollector collectGarbage];
  415. for (const DocumentKey &key : garbage) {
  416. const auto iter = _limboTargetsByKey.find(key);
  417. if (iter == _limboTargetsByKey.end()) {
  418. // This target already got removed, because the query failed.
  419. return;
  420. }
  421. TargetId limboTargetID = iter->second;
  422. [self.remoteStore stopListeningToTargetID:limboTargetID];
  423. _limboTargetsByKey.erase(key);
  424. _limboKeysByTarget.erase(limboTargetID);
  425. }
  426. }
  427. // Used for testing
  428. - (std::map<DocumentKey, TargetId>)currentLimboDocuments {
  429. // Return defensive copy
  430. return _limboTargetsByKey;
  431. }
  432. - (void)userDidChange:(const User &)user {
  433. _currentUser = user;
  434. // Notify local store and emit any resulting events from swapping out the mutation queue.
  435. FSTMaybeDocumentDictionary *changes = [self.localStore userDidChange:user];
  436. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  437. // Notify remote store so it can restart its streams.
  438. [self.remoteStore userDidChange:user];
  439. }
  440. @end
  441. NS_ASSUME_NONNULL_END