FSTSyncEngine.m 22 KB

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