FSTSyncEngine.m 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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)applyChangedOnlineState:(FSTOnlineState)onlineState {
  270. NSMutableArray<FSTViewSnapshot *> *newViewSnapshots = [NSMutableArray array];
  271. [self.queryViewsByQuery
  272. enumerateKeysAndObjectsUsingBlock:^(FSTQuery *query, FSTQueryView *queryView, BOOL *stop) {
  273. FSTViewChange *viewChange = [queryView.view applyChangedOnlineState:onlineState];
  274. FSTAssert(viewChange.limboChanges.count == 0,
  275. @"OnlineState should not affect limbo documents.");
  276. if (viewChange.snapshot) {
  277. [newViewSnapshots addObject:viewChange.snapshot];
  278. }
  279. }];
  280. [self.delegate handleViewSnapshots:newViewSnapshots];
  281. }
  282. - (void)rejectListenWithTargetID:(FSTBoxedTargetID *)targetID error:(NSError *)error {
  283. [self assertDelegateExistsForSelector:_cmd];
  284. FSTDocumentKey *limboKey = self.limboKeysByTarget[targetID];
  285. if (limboKey) {
  286. // Since this query failed, we won't want to manually unlisten to it.
  287. // So go ahead and remove it from bookkeeping.
  288. [self.limboTargetsByKey removeObjectForKey:limboKey];
  289. [self.limboKeysByTarget removeObjectForKey:targetID];
  290. // TODO(dimond): Retry on transient errors?
  291. // It's a limbo doc. Create a synthetic event saying it was deleted. This is kind of a hack.
  292. // Ideally, we would have a method in the local store to purge a document. However, it would
  293. // be tricky to keep all of the local store's invariants with another method.
  294. NSMutableDictionary<NSNumber *, FSTTargetChange *> *targetChanges =
  295. [NSMutableDictionary dictionary];
  296. FSTDeletedDocument *doc =
  297. [FSTDeletedDocument documentWithKey:limboKey version:[FSTSnapshotVersion noVersion]];
  298. NSMutableDictionary<FSTDocumentKey *, FSTMaybeDocument *> *docUpdate =
  299. [NSMutableDictionary dictionaryWithObject:doc forKey:limboKey];
  300. FSTRemoteEvent *event = [FSTRemoteEvent eventWithSnapshotVersion:[FSTSnapshotVersion noVersion]
  301. targetChanges:targetChanges
  302. documentUpdates:docUpdate];
  303. [self applyRemoteEvent:event];
  304. } else {
  305. FSTQueryView *queryView = self.queryViewsByTarget[targetID];
  306. FSTAssert(queryView, @"Unknown targetId: %@", targetID);
  307. [self.localStore releaseQuery:queryView.query];
  308. [self removeAndCleanupQuery:queryView];
  309. [self.delegate handleError:error forQuery:queryView.query];
  310. }
  311. }
  312. - (void)applySuccessfulWriteWithResult:(FSTMutationBatchResult *)batchResult {
  313. [self assertDelegateExistsForSelector:_cmd];
  314. // The local store may or may not be able to apply the write result and raise events immediately
  315. // (depending on whether the watcher is caught up), so we raise user callbacks first so that they
  316. // consistently happen before listen events.
  317. [self processUserCallbacksForBatchID:batchResult.batch.batchID error:nil];
  318. FSTMaybeDocumentDictionary *changes = [self.localStore acknowledgeBatchWithResult:batchResult];
  319. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  320. }
  321. - (void)rejectFailedWriteWithBatchID:(FSTBatchID)batchID error:(NSError *)error {
  322. [self assertDelegateExistsForSelector:_cmd];
  323. // The local store may or may not be able to apply the write result and raise events immediately
  324. // (depending on whether the watcher is caught up), so we raise user callbacks first so that they
  325. // consistently happen before listen events.
  326. [self processUserCallbacksForBatchID:batchID error:error];
  327. FSTMaybeDocumentDictionary *changes = [self.localStore rejectBatchID:batchID];
  328. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  329. }
  330. - (void)processUserCallbacksForBatchID:(FSTBatchID)batchID error:(NSError *_Nullable)error {
  331. NSMutableDictionary<NSNumber *, FSTVoidErrorBlock> *completionBlocks =
  332. self.mutationCompletionBlocks[self.currentUser];
  333. // NOTE: Mutations restored from persistence won't have completion blocks, so it's okay for
  334. // this (or the completion below) to be nil.
  335. if (completionBlocks) {
  336. NSNumber *boxedBatchID = @(batchID);
  337. FSTVoidErrorBlock completion = completionBlocks[boxedBatchID];
  338. if (completion) {
  339. completion(error);
  340. [completionBlocks removeObjectForKey:boxedBatchID];
  341. }
  342. }
  343. }
  344. - (void)assertDelegateExistsForSelector:(SEL)methodSelector {
  345. FSTAssert(self.delegate, @"Tried to call '%@' before delegate was registered.",
  346. NSStringFromSelector(methodSelector));
  347. }
  348. - (void)removeAndCleanupQuery:(FSTQueryView *)queryView {
  349. [self.queryViewsByQuery removeObjectForKey:queryView.query];
  350. [self.queryViewsByTarget removeObjectForKey:@(queryView.targetID)];
  351. [self.limboDocumentRefs removeReferencesForID:queryView.targetID];
  352. [self garbageCollectLimboDocuments];
  353. }
  354. /**
  355. * Computes a new snapshot from the changes and calls the registered callback with the new snapshot.
  356. */
  357. - (void)emitNewSnapshotsWithChanges:(FSTMaybeDocumentDictionary *)changes
  358. remoteEvent:(FSTRemoteEvent *_Nullable)remoteEvent {
  359. NSMutableArray<FSTViewSnapshot *> *newSnapshots = [NSMutableArray array];
  360. NSMutableArray<FSTLocalViewChanges *> *documentChangesInAllViews = [NSMutableArray array];
  361. [self.queryViewsByQuery
  362. enumerateKeysAndObjectsUsingBlock:^(FSTQuery *query, FSTQueryView *queryView, BOOL *stop) {
  363. FSTView *view = queryView.view;
  364. FSTViewDocumentChanges *viewDocChanges = [view computeChangesWithDocuments:changes];
  365. if (viewDocChanges.needsRefill) {
  366. // The query has a limit and some docs were removed/updated, so we need to re-run the
  367. // query against the local store to make sure we didn't lose any good docs that had been
  368. // past the limit.
  369. FSTDocumentDictionary *docs = [self.localStore executeQuery:queryView.query];
  370. viewDocChanges = [view computeChangesWithDocuments:docs previousChanges:viewDocChanges];
  371. }
  372. FSTTargetChange *_Nullable targetChange = remoteEvent.targetChanges[@(queryView.targetID)];
  373. FSTViewChange *viewChange =
  374. [queryView.view applyChangesToDocuments:viewDocChanges targetChange:targetChange];
  375. [self updateTrackedLimboDocumentsWithChanges:viewChange.limboChanges
  376. targetID:queryView.targetID];
  377. if (viewChange.snapshot) {
  378. [newSnapshots addObject:viewChange.snapshot];
  379. FSTLocalViewChanges *docChanges =
  380. [FSTLocalViewChanges changesForViewSnapshot:viewChange.snapshot];
  381. [documentChangesInAllViews addObject:docChanges];
  382. }
  383. }];
  384. [self.delegate handleViewSnapshots:newSnapshots];
  385. [self.localStore notifyLocalViewChanges:documentChangesInAllViews];
  386. [self.localStore collectGarbage];
  387. }
  388. /** Updates the limbo document state for the given targetID. */
  389. - (void)updateTrackedLimboDocumentsWithChanges:(NSArray<FSTLimboDocumentChange *> *)limboChanges
  390. targetID:(FSTTargetID)targetID {
  391. for (FSTLimboDocumentChange *limboChange in limboChanges) {
  392. switch (limboChange.type) {
  393. case FSTLimboDocumentChangeTypeAdded:
  394. [self.limboDocumentRefs addReferenceToKey:limboChange.key forID:targetID];
  395. [self trackLimboChange:limboChange];
  396. break;
  397. case FSTLimboDocumentChangeTypeRemoved:
  398. FSTLog(@"Document no longer in limbo: %@", limboChange.key);
  399. [self.limboDocumentRefs removeReferenceToKey:limboChange.key forID:targetID];
  400. break;
  401. default:
  402. FSTFail(@"Unknown limbo change type: %ld", (long)limboChange.type);
  403. }
  404. }
  405. [self garbageCollectLimboDocuments];
  406. }
  407. - (void)trackLimboChange:(FSTLimboDocumentChange *)limboChange {
  408. FSTDocumentKey *key = limboChange.key;
  409. if (!self.limboTargetsByKey[key]) {
  410. FSTLog(@"New document in limbo: %@", key);
  411. FSTTargetID limboTargetID = [self.targetIdGenerator nextID];
  412. FSTQuery *query = [FSTQuery queryWithPath:key.path];
  413. FSTQueryData *queryData = [[FSTQueryData alloc] initWithQuery:query
  414. targetID:limboTargetID
  415. purpose:FSTQueryPurposeLimboResolution];
  416. self.limboKeysByTarget[@(limboTargetID)] = key;
  417. [self.remoteStore listenToTargetWithQueryData:queryData];
  418. self.limboTargetsByKey[key] = @(limboTargetID);
  419. }
  420. }
  421. /** Garbage collect the limbo documents that we no longer need to track. */
  422. - (void)garbageCollectLimboDocuments {
  423. NSSet<FSTDocumentKey *> *garbage = [self.limboCollector collectGarbage];
  424. for (FSTDocumentKey *key in garbage) {
  425. FSTBoxedTargetID *limboTarget = self.limboTargetsByKey[key];
  426. if (!limboTarget) {
  427. // This target already got removed, because the query failed.
  428. return;
  429. }
  430. FSTTargetID limboTargetID = limboTarget.intValue;
  431. [self.remoteStore stopListeningToTargetID:limboTargetID];
  432. [self.limboTargetsByKey removeObjectForKey:key];
  433. [self.limboKeysByTarget removeObjectForKey:limboTarget];
  434. }
  435. }
  436. // Used for testing
  437. - (NSDictionary<FSTDocumentKey *, FSTBoxedTargetID *> *)currentLimboDocuments {
  438. // Return defensive copy
  439. return [self.limboTargetsByKey copy];
  440. }
  441. - (void)userDidChange:(FSTUser *)user {
  442. self.currentUser = user;
  443. // Notify local store and emit any resulting events from swapping out the mutation queue.
  444. FSTMaybeDocumentDictionary *changes = [self.localStore userDidChange:user];
  445. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  446. // Notify remote store so it can restart its streams.
  447. [self.remoteStore userDidChange:user];
  448. }
  449. @end
  450. NS_ASSUME_NONNULL_END