FSTSyncEngine.mm 21 KB

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