FSTSyncEngine.mm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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 <unordered_map>
  18. #import <GRPCClient/GRPCCall.h>
  19. #import "FIRFirestoreErrors.h"
  20. #import "Firestore/Source/Core/FSTQuery.h"
  21. #import "Firestore/Source/Core/FSTSnapshotVersion.h"
  22. #import "Firestore/Source/Core/FSTTransaction.h"
  23. #import "Firestore/Source/Core/FSTView.h"
  24. #import "Firestore/Source/Core/FSTViewSnapshot.h"
  25. #import "Firestore/Source/Local/FSTEagerGarbageCollector.h"
  26. #import "Firestore/Source/Local/FSTLocalStore.h"
  27. #import "Firestore/Source/Local/FSTLocalViewChanges.h"
  28. #import "Firestore/Source/Local/FSTLocalWriteResult.h"
  29. #import "Firestore/Source/Local/FSTQueryData.h"
  30. #import "Firestore/Source/Local/FSTReferenceSet.h"
  31. #import "Firestore/Source/Model/FSTDocument.h"
  32. #import "Firestore/Source/Model/FSTDocumentKey.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. using firebase::firestore::auth::HashUser;
  42. using firebase::firestore::auth::User;
  43. using firebase::firestore::core::TargetIdGenerator;
  44. NS_ASSUME_NONNULL_BEGIN
  45. // Limbo documents don't use persistence, and are eagerly GC'd. So, listens for them don't need
  46. // real sequence numbers.
  47. static const FSTListenSequenceNumber kIrrelevantSequenceNumber = -1;
  48. #pragma mark - FSTQueryView
  49. /**
  50. * FSTQueryView contains all of the info that FSTSyncEngine needs to track for a particular
  51. * query and view.
  52. */
  53. @interface FSTQueryView : NSObject
  54. - (instancetype)initWithQuery:(FSTQuery *)query
  55. targetID:(FSTTargetID)targetID
  56. resumeToken:(NSData *)resumeToken
  57. view:(FSTView *)view NS_DESIGNATED_INITIALIZER;
  58. - (instancetype)init NS_UNAVAILABLE;
  59. /** The query itself. */
  60. @property(nonatomic, strong, readonly) FSTQuery *query;
  61. /** The targetID created by the client that is used in the watch stream to identify this query. */
  62. @property(nonatomic, assign, readonly) FSTTargetID targetID;
  63. /**
  64. * An identifier from the datastore backend that indicates the last state of the results that
  65. * was received. This can be used to indicate where to continue receiving new doc changes for the
  66. * query.
  67. */
  68. @property(nonatomic, copy, readonly) NSData *resumeToken;
  69. /**
  70. * The view is responsible for computing the final merged truth of what docs are in the query.
  71. * It gets notified of local and remote changes, and applies the query filters and limits to
  72. * determine the most correct possible results.
  73. */
  74. @property(nonatomic, strong, readonly) FSTView *view;
  75. @end
  76. @implementation FSTQueryView
  77. - (instancetype)initWithQuery:(FSTQuery *)query
  78. targetID:(FSTTargetID)targetID
  79. resumeToken:(NSData *)resumeToken
  80. view:(FSTView *)view {
  81. if (self = [super init]) {
  82. _query = query;
  83. _targetID = targetID;
  84. _resumeToken = resumeToken;
  85. _view = view;
  86. }
  87. return self;
  88. }
  89. @end
  90. #pragma mark - FSTSyncEngine
  91. @interface FSTSyncEngine ()
  92. /** The local store, used to persist mutations and cached documents. */
  93. @property(nonatomic, strong, readonly) FSTLocalStore *localStore;
  94. /** The remote store for sending writes, watches, etc. to the backend. */
  95. @property(nonatomic, strong, readonly) FSTRemoteStore *remoteStore;
  96. /** FSTQueryViews for all active queries, indexed by query. */
  97. @property(nonatomic, strong, readonly)
  98. NSMutableDictionary<FSTQuery *, FSTQueryView *> *queryViewsByQuery;
  99. /** FSTQueryViews for all active queries, indexed by target ID. */
  100. @property(nonatomic, strong, readonly)
  101. NSMutableDictionary<NSNumber *, FSTQueryView *> *queryViewsByTarget;
  102. /**
  103. * When a document is in limbo, we create a special listen to resolve it. This maps the
  104. * FSTDocumentKey of each limbo document to the FSTTargetID of the listen resolving it.
  105. */
  106. @property(nonatomic, strong, readonly)
  107. NSMutableDictionary<FSTDocumentKey *, FSTBoxedTargetID *> *limboTargetsByKey;
  108. /** The inverse of limboTargetsByKey, a map of FSTTargetID to the key of the limbo doc. */
  109. @property(nonatomic, strong, readonly)
  110. NSMutableDictionary<FSTBoxedTargetID *, FSTDocumentKey *> *limboKeysByTarget;
  111. /** Used to track any documents that are currently in limbo. */
  112. @property(nonatomic, strong, readonly) FSTReferenceSet *limboDocumentRefs;
  113. /** The garbage collector used to collect documents that are no longer in limbo. */
  114. @property(nonatomic, strong, readonly) FSTEagerGarbageCollector *limboCollector;
  115. @end
  116. @implementation FSTSyncEngine {
  117. /** Used for creating the FSTTargetIDs for the listens used to resolve limbo documents. */
  118. TargetIdGenerator _targetIdGenerator;
  119. /** Stores user completion blocks, indexed by user and FSTBatchID. */
  120. std::unordered_map<User, NSMutableDictionary<NSNumber *, FSTVoidErrorBlock> *, HashUser>
  121. _mutationCompletionBlocks;
  122. User _currentUser;
  123. }
  124. - (instancetype)initWithLocalStore:(FSTLocalStore *)localStore
  125. remoteStore:(FSTRemoteStore *)remoteStore
  126. initialUser:(const User &)initialUser {
  127. if (self = [super init]) {
  128. _localStore = localStore;
  129. _remoteStore = remoteStore;
  130. _queryViewsByQuery = [NSMutableDictionary dictionary];
  131. _queryViewsByTarget = [NSMutableDictionary dictionary];
  132. _limboTargetsByKey = [NSMutableDictionary dictionary];
  133. _limboKeysByTarget = [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. [remoteEvent.targetChanges enumerateKeysAndObjectsUsingBlock:^(
  244. FSTBoxedTargetID *_Nonnull targetID,
  245. FSTTargetChange *_Nonnull targetChange, BOOL *_Nonnull stop) {
  246. FSTDocumentKey *limboKey = self.limboKeysByTarget[targetID];
  247. if (limboKey && targetChange.currentStatusUpdate == FSTCurrentStatusUpdateMarkCurrent &&
  248. remoteEvent.documentUpdates[limboKey] == nil) {
  249. // When listening to a query the server responds with a snapshot containing documents
  250. // matching the query and a current marker telling us we're now in sync. It's possible for
  251. // these to arrive as separate remote events or as a single remote event. For a document
  252. // query, there will be no documents sent in the response if the document doesn't exist.
  253. //
  254. // If the snapshot arrives separately from the current marker, we handle it normally and
  255. // updateTrackedLimboDocumentsWithChanges:targetID: will resolve the limbo status of the
  256. // document, removing it from limboDocumentRefs. This works because clients only initiate
  257. // limbo resolution when a target is current and because all current targets are always at a
  258. // consistent snapshot.
  259. //
  260. // However, if the document doesn't exist and the current marker arrives, the document is
  261. // not present in the snapshot and our normal view handling would consider the document to
  262. // remain in limbo indefinitely because there are no updates to the document. To avoid this,
  263. // we specially handle this just this case here: synthesizing a delete.
  264. //
  265. // TODO(dimond): Ideally we would have an explicit lookup query instead resulting in an
  266. // explicit delete message and we could remove this special logic.
  267. [remoteEvent
  268. addDocumentUpdate:[FSTDeletedDocument documentWithKey:limboKey
  269. version:remoteEvent.snapshotVersion]];
  270. }
  271. }];
  272. FSTMaybeDocumentDictionary *changes = [self.localStore applyRemoteEvent:remoteEvent];
  273. [self emitNewSnapshotsWithChanges:changes remoteEvent:remoteEvent];
  274. }
  275. - (void)applyChangedOnlineState:(FSTOnlineState)onlineState {
  276. NSMutableArray<FSTViewSnapshot *> *newViewSnapshots = [NSMutableArray array];
  277. [self.queryViewsByQuery
  278. enumerateKeysAndObjectsUsingBlock:^(FSTQuery *query, FSTQueryView *queryView, BOOL *stop) {
  279. FSTViewChange *viewChange = [queryView.view applyChangedOnlineState:onlineState];
  280. FSTAssert(viewChange.limboChanges.count == 0,
  281. @"OnlineState should not affect limbo documents.");
  282. if (viewChange.snapshot) {
  283. [newViewSnapshots addObject:viewChange.snapshot];
  284. }
  285. }];
  286. [self.delegate handleViewSnapshots:newViewSnapshots];
  287. }
  288. - (void)rejectListenWithTargetID:(FSTBoxedTargetID *)targetID error:(NSError *)error {
  289. [self assertDelegateExistsForSelector:_cmd];
  290. FSTDocumentKey *limboKey = self.limboKeysByTarget[targetID];
  291. if (limboKey) {
  292. // Since this query failed, we won't want to manually unlisten to it.
  293. // So go ahead and remove it from bookkeeping.
  294. [self.limboTargetsByKey removeObjectForKey:limboKey];
  295. [self.limboKeysByTarget removeObjectForKey:targetID];
  296. // TODO(dimond): Retry on transient errors?
  297. // It's a limbo doc. Create a synthetic event saying it was deleted. This is kind of a hack.
  298. // Ideally, we would have a method in the local store to purge a document. However, it would
  299. // be tricky to keep all of the local store's invariants with another method.
  300. NSMutableDictionary<NSNumber *, FSTTargetChange *> *targetChanges =
  301. [NSMutableDictionary dictionary];
  302. FSTDeletedDocument *doc =
  303. [FSTDeletedDocument documentWithKey:limboKey version:[FSTSnapshotVersion noVersion]];
  304. NSMutableDictionary<FSTDocumentKey *, FSTMaybeDocument *> *docUpdate =
  305. [NSMutableDictionary dictionaryWithObject:doc forKey:limboKey];
  306. FSTRemoteEvent *event = [FSTRemoteEvent eventWithSnapshotVersion:[FSTSnapshotVersion noVersion]
  307. targetChanges:targetChanges
  308. documentUpdates:docUpdate];
  309. [self applyRemoteEvent:event];
  310. } else {
  311. FSTQueryView *queryView = self.queryViewsByTarget[targetID];
  312. FSTAssert(queryView, @"Unknown targetId: %@", targetID);
  313. [self.localStore releaseQuery:queryView.query];
  314. [self removeAndCleanupQuery:queryView];
  315. [self.delegate handleError:error forQuery:queryView.query];
  316. }
  317. }
  318. - (void)applySuccessfulWriteWithResult:(FSTMutationBatchResult *)batchResult {
  319. [self assertDelegateExistsForSelector:_cmd];
  320. // The local store may or may not be able to apply the write result and raise events immediately
  321. // (depending on whether the watcher is caught up), so we raise user callbacks first so that they
  322. // consistently happen before listen events.
  323. [self processUserCallbacksForBatchID:batchResult.batch.batchID error:nil];
  324. FSTMaybeDocumentDictionary *changes = [self.localStore acknowledgeBatchWithResult:batchResult];
  325. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  326. }
  327. - (void)rejectFailedWriteWithBatchID:(FSTBatchID)batchID error:(NSError *)error {
  328. [self assertDelegateExistsForSelector:_cmd];
  329. // The local store may or may not be able to apply the write result and raise events immediately
  330. // (depending on whether the watcher is caught up), so we raise user callbacks first so that they
  331. // consistently happen before listen events.
  332. [self processUserCallbacksForBatchID:batchID error:error];
  333. FSTMaybeDocumentDictionary *changes = [self.localStore rejectBatchID:batchID];
  334. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  335. }
  336. - (void)processUserCallbacksForBatchID:(FSTBatchID)batchID error:(NSError *_Nullable)error {
  337. NSMutableDictionary<NSNumber *, FSTVoidErrorBlock> *completionBlocks =
  338. _mutationCompletionBlocks[_currentUser];
  339. // NOTE: Mutations restored from persistence won't have completion blocks, so it's okay for
  340. // this (or the completion below) to be nil.
  341. if (completionBlocks) {
  342. NSNumber *boxedBatchID = @(batchID);
  343. FSTVoidErrorBlock completion = completionBlocks[boxedBatchID];
  344. if (completion) {
  345. completion(error);
  346. [completionBlocks removeObjectForKey:boxedBatchID];
  347. }
  348. }
  349. }
  350. - (void)assertDelegateExistsForSelector:(SEL)methodSelector {
  351. FSTAssert(self.delegate, @"Tried to call '%@' before delegate was registered.",
  352. NSStringFromSelector(methodSelector));
  353. }
  354. - (void)removeAndCleanupQuery:(FSTQueryView *)queryView {
  355. [self.queryViewsByQuery removeObjectForKey:queryView.query];
  356. [self.queryViewsByTarget removeObjectForKey:@(queryView.targetID)];
  357. [self.limboDocumentRefs removeReferencesForID:queryView.targetID];
  358. [self garbageCollectLimboDocuments];
  359. }
  360. /**
  361. * Computes a new snapshot from the changes and calls the registered callback with the new snapshot.
  362. */
  363. - (void)emitNewSnapshotsWithChanges:(FSTMaybeDocumentDictionary *)changes
  364. remoteEvent:(FSTRemoteEvent *_Nullable)remoteEvent {
  365. NSMutableArray<FSTViewSnapshot *> *newSnapshots = [NSMutableArray array];
  366. NSMutableArray<FSTLocalViewChanges *> *documentChangesInAllViews = [NSMutableArray array];
  367. [self.queryViewsByQuery
  368. enumerateKeysAndObjectsUsingBlock:^(FSTQuery *query, FSTQueryView *queryView, BOOL *stop) {
  369. FSTView *view = queryView.view;
  370. FSTViewDocumentChanges *viewDocChanges = [view computeChangesWithDocuments:changes];
  371. if (viewDocChanges.needsRefill) {
  372. // The query has a limit and some docs were removed/updated, so we need to re-run the
  373. // query against the local store to make sure we didn't lose any good docs that had been
  374. // past the limit.
  375. FSTDocumentDictionary *docs = [self.localStore executeQuery:queryView.query];
  376. viewDocChanges = [view computeChangesWithDocuments:docs previousChanges:viewDocChanges];
  377. }
  378. FSTTargetChange *_Nullable targetChange = remoteEvent.targetChanges[@(queryView.targetID)];
  379. FSTViewChange *viewChange =
  380. [queryView.view applyChangesToDocuments:viewDocChanges targetChange:targetChange];
  381. [self updateTrackedLimboDocumentsWithChanges:viewChange.limboChanges
  382. targetID:queryView.targetID];
  383. if (viewChange.snapshot) {
  384. [newSnapshots addObject:viewChange.snapshot];
  385. FSTLocalViewChanges *docChanges =
  386. [FSTLocalViewChanges changesForViewSnapshot:viewChange.snapshot];
  387. [documentChangesInAllViews addObject:docChanges];
  388. }
  389. }];
  390. [self.delegate handleViewSnapshots:newSnapshots];
  391. [self.localStore notifyLocalViewChanges:documentChangesInAllViews];
  392. [self.localStore collectGarbage];
  393. }
  394. /** Updates the limbo document state for the given targetID. */
  395. - (void)updateTrackedLimboDocumentsWithChanges:(NSArray<FSTLimboDocumentChange *> *)limboChanges
  396. targetID:(FSTTargetID)targetID {
  397. for (FSTLimboDocumentChange *limboChange in limboChanges) {
  398. switch (limboChange.type) {
  399. case FSTLimboDocumentChangeTypeAdded:
  400. [self.limboDocumentRefs addReferenceToKey:limboChange.key forID:targetID];
  401. [self trackLimboChange:limboChange];
  402. break;
  403. case FSTLimboDocumentChangeTypeRemoved:
  404. FSTLog(@"Document no longer in limbo: %@", limboChange.key);
  405. [self.limboDocumentRefs removeReferenceToKey:limboChange.key forID:targetID];
  406. break;
  407. default:
  408. FSTFail(@"Unknown limbo change type: %ld", (long)limboChange.type);
  409. }
  410. }
  411. [self garbageCollectLimboDocuments];
  412. }
  413. - (void)trackLimboChange:(FSTLimboDocumentChange *)limboChange {
  414. FSTDocumentKey *key = limboChange.key;
  415. if (!self.limboTargetsByKey[key]) {
  416. FSTLog(@"New document in limbo: %@", key);
  417. FSTTargetID limboTargetID = _targetIdGenerator.NextId();
  418. FSTQuery *query = [FSTQuery queryWithPath:key.path];
  419. FSTQueryData *queryData = [[FSTQueryData alloc] initWithQuery:query
  420. targetID:limboTargetID
  421. listenSequenceNumber:kIrrelevantSequenceNumber
  422. purpose:FSTQueryPurposeLimboResolution];
  423. self.limboKeysByTarget[@(limboTargetID)] = key;
  424. [self.remoteStore listenToTargetWithQueryData:queryData];
  425. self.limboTargetsByKey[key] = @(limboTargetID);
  426. }
  427. }
  428. /** Garbage collect the limbo documents that we no longer need to track. */
  429. - (void)garbageCollectLimboDocuments {
  430. NSSet<FSTDocumentKey *> *garbage = [self.limboCollector collectGarbage];
  431. for (FSTDocumentKey *key in garbage) {
  432. FSTBoxedTargetID *limboTarget = self.limboTargetsByKey[key];
  433. if (!limboTarget) {
  434. // This target already got removed, because the query failed.
  435. return;
  436. }
  437. FSTTargetID limboTargetID = limboTarget.intValue;
  438. [self.remoteStore stopListeningToTargetID:limboTargetID];
  439. [self.limboTargetsByKey removeObjectForKey:key];
  440. [self.limboKeysByTarget removeObjectForKey:limboTarget];
  441. }
  442. }
  443. // Used for testing
  444. - (NSDictionary<FSTDocumentKey *, FSTBoxedTargetID *> *)currentLimboDocuments {
  445. // Return defensive copy
  446. return [self.limboTargetsByKey copy];
  447. }
  448. - (void)userDidChange:(const User &)user {
  449. _currentUser = user;
  450. // Notify local store and emit any resulting events from swapping out the mutation queue.
  451. FSTMaybeDocumentDictionary *changes = [self.localStore userDidChange:user];
  452. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  453. // Notify remote store so it can restart its streams.
  454. [self.remoteStore userDidChange:user];
  455. }
  456. @end
  457. NS_ASSUME_NONNULL_END