FSTSyncEngine.mm 23 KB

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