FSTSyncEngine.mm 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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 - LimboResolution
  97. /** Tracks a limbo resolution. */
  98. class LimboResolution {
  99. public:
  100. LimboResolution() {
  101. }
  102. explicit LimboResolution(const DocumentKey &key) : key{key} {
  103. }
  104. DocumentKey key;
  105. /**
  106. * Set to true once we've received a document. This is used in remoteKeysForTarget and
  107. * ultimately used by FSTWatchChangeAggregator to decide whether it needs to manufacture a delete
  108. * event for the target once the target is CURRENT.
  109. */
  110. bool document_received = false;
  111. };
  112. #pragma mark - FSTSyncEngine
  113. @interface FSTSyncEngine ()
  114. /** The local store, used to persist mutations and cached documents. */
  115. @property(nonatomic, strong, readonly) FSTLocalStore *localStore;
  116. /** The remote store for sending writes, watches, etc. to the backend. */
  117. @property(nonatomic, strong, readonly) FSTRemoteStore *remoteStore;
  118. /** FSTQueryViews for all active queries, indexed by query. */
  119. @property(nonatomic, strong, readonly)
  120. NSMutableDictionary<FSTQuery *, FSTQueryView *> *queryViewsByQuery;
  121. /** FSTQueryViews for all active queries, indexed by target ID. */
  122. @property(nonatomic, strong, readonly)
  123. NSMutableDictionary<NSNumber *, FSTQueryView *> *queryViewsByTarget;
  124. /** Used to track any documents that are currently in limbo. */
  125. @property(nonatomic, strong, readonly) FSTReferenceSet *limboDocumentRefs;
  126. @end
  127. @implementation FSTSyncEngine {
  128. /** Used for creating the FSTTargetIDs for the listens used to resolve limbo documents. */
  129. TargetIdGenerator _targetIdGenerator;
  130. /** Stores user completion blocks, indexed by user and FSTBatchID. */
  131. std::unordered_map<User, NSMutableDictionary<NSNumber *, FSTVoidErrorBlock> *, HashUser>
  132. _mutationCompletionBlocks;
  133. /**
  134. * When a document is in limbo, we create a special listen to resolve it. This maps the
  135. * DocumentKey of each limbo document to the TargetId of the listen resolving it.
  136. */
  137. std::map<DocumentKey, TargetId> _limboTargetsByKey;
  138. /**
  139. * Basically the inverse of limboTargetsByKey, a map of target ID to a LimboResolution (which
  140. * includes the DocumentKey as well as whether we've received a document for the target).
  141. */
  142. std::map<TargetId, LimboResolution> _limboResolutionsByTarget;
  143. User _currentUser;
  144. }
  145. - (instancetype)initWithLocalStore:(FSTLocalStore *)localStore
  146. remoteStore:(FSTRemoteStore *)remoteStore
  147. initialUser:(const User &)initialUser {
  148. if (self = [super init]) {
  149. _localStore = localStore;
  150. _remoteStore = remoteStore;
  151. _queryViewsByQuery = [NSMutableDictionary dictionary];
  152. _queryViewsByTarget = [NSMutableDictionary dictionary];
  153. _limboDocumentRefs = [[FSTReferenceSet alloc] init];
  154. _targetIdGenerator = TargetIdGenerator::SyncEngineTargetIdGenerator(0);
  155. _currentUser = initialUser;
  156. }
  157. return self;
  158. }
  159. - (FSTTargetID)listenToQuery:(FSTQuery *)query {
  160. [self assertDelegateExistsForSelector:_cmd];
  161. HARD_ASSERT(self.queryViewsByQuery[query] == nil, "We already listen to query: %s", query);
  162. FSTQueryData *queryData = [self.localStore allocateQuery:query];
  163. FSTDocumentDictionary *docs = [self.localStore executeQuery:query];
  164. DocumentKeySet remoteKeys = [self.localStore remoteDocumentKeysForTarget:queryData.targetID];
  165. FSTView *view = [[FSTView alloc] initWithQuery:query remoteDocuments:std::move(remoteKeys)];
  166. FSTViewDocumentChanges *viewDocChanges = [view computeChangesWithDocuments:docs];
  167. FSTViewChange *viewChange = [view applyChangesToDocuments:viewDocChanges];
  168. HARD_ASSERT(viewChange.limboChanges.count == 0,
  169. "View returned limbo docs before target ack from the server.");
  170. FSTQueryView *queryView = [[FSTQueryView alloc] initWithQuery:query
  171. targetID:queryData.targetID
  172. resumeToken:queryData.resumeToken
  173. view:view];
  174. self.queryViewsByQuery[query] = queryView;
  175. self.queryViewsByTarget[@(queryData.targetID)] = queryView;
  176. [self.delegate handleViewSnapshots:@[ viewChange.snapshot ]];
  177. [self.remoteStore listenToTargetWithQueryData:queryData];
  178. return queryData.targetID;
  179. }
  180. - (void)stopListeningToQuery:(FSTQuery *)query {
  181. [self assertDelegateExistsForSelector:_cmd];
  182. FSTQueryView *queryView = self.queryViewsByQuery[query];
  183. HARD_ASSERT(queryView, "Trying to stop listening to a query not found");
  184. [self.localStore releaseQuery:query];
  185. [self.remoteStore stopListeningToTargetID:queryView.targetID];
  186. [self removeAndCleanupQuery:queryView];
  187. }
  188. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations
  189. completion:(FSTVoidErrorBlock)completion {
  190. [self assertDelegateExistsForSelector:_cmd];
  191. FSTLocalWriteResult *result = [self.localStore locallyWriteMutations:mutations];
  192. [self addMutationCompletionBlock:completion batchID:result.batchID];
  193. [self emitNewSnapshotsWithChanges:result.changes remoteEvent:nil];
  194. [self.remoteStore fillWritePipeline];
  195. }
  196. - (void)addMutationCompletionBlock:(FSTVoidErrorBlock)completion batchID:(FSTBatchID)batchID {
  197. NSMutableDictionary<NSNumber *, FSTVoidErrorBlock> *completionBlocks =
  198. _mutationCompletionBlocks[_currentUser];
  199. if (!completionBlocks) {
  200. completionBlocks = [NSMutableDictionary dictionary];
  201. _mutationCompletionBlocks[_currentUser] = completionBlocks;
  202. }
  203. [completionBlocks setObject:completion forKey:@(batchID)];
  204. }
  205. /**
  206. * Takes an updateBlock in which a set of reads and writes can be performed atomically. In the
  207. * updateBlock, user code can read and write values using a transaction object. After the
  208. * updateBlock, all changes will be committed. If someone else has changed any of the data
  209. * referenced, then the updateBlock will be called again. If the updateBlock still fails after the
  210. * given number of retries, then the transaction will be rejected.
  211. *
  212. * The transaction object passed to the updateBlock contains methods for accessing documents
  213. * and collections. Unlike other firestore access, data accessed with the transaction will not
  214. * reflect local changes that have not been committed. For this reason, it is required that all
  215. * reads are performed before any writes. Transactions must be performed while online.
  216. */
  217. - (void)transactionWithRetries:(int)retries
  218. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  219. updateBlock:(FSTTransactionBlock)updateBlock
  220. completion:(FSTVoidIDErrorBlock)completion {
  221. [workerDispatchQueue verifyIsCurrentQueue];
  222. HARD_ASSERT(retries >= 0, "Got negative number of retries for transaction");
  223. FSTTransaction *transaction = [self.remoteStore transaction];
  224. updateBlock(transaction, ^(id _Nullable result, NSError *_Nullable error) {
  225. [workerDispatchQueue dispatchAsync:^{
  226. if (error) {
  227. completion(nil, error);
  228. return;
  229. }
  230. [transaction commitWithCompletion:^(NSError *_Nullable transactionError) {
  231. if (!transactionError) {
  232. completion(result, nil);
  233. return;
  234. }
  235. // TODO(b/35201829): Only retry on real transaction failures.
  236. if (retries == 0) {
  237. NSError *wrappedError =
  238. [NSError errorWithDomain:FIRFirestoreErrorDomain
  239. code:FIRFirestoreErrorCodeFailedPrecondition
  240. userInfo:@{
  241. NSLocalizedDescriptionKey : @"Transaction failed all retries.",
  242. NSUnderlyingErrorKey : transactionError
  243. }];
  244. completion(nil, wrappedError);
  245. return;
  246. }
  247. [workerDispatchQueue verifyIsCurrentQueue];
  248. return [self transactionWithRetries:(retries - 1)
  249. workerDispatchQueue:workerDispatchQueue
  250. updateBlock:updateBlock
  251. completion:completion];
  252. }];
  253. }];
  254. });
  255. }
  256. - (void)applyRemoteEvent:(FSTRemoteEvent *)remoteEvent {
  257. [self assertDelegateExistsForSelector:_cmd];
  258. // Update `receivedDocument` as appropriate for any limbo targets.
  259. for (const auto &entry : remoteEvent.targetChanges) {
  260. FSTTargetID targetID = entry.first;
  261. FSTTargetChange *change = entry.second;
  262. const auto iter = _limboResolutionsByTarget.find(targetID);
  263. if (iter != _limboResolutionsByTarget.end()) {
  264. LimboResolution &limboResolution = iter->second;
  265. // Since this is a limbo resolution lookup, it's for a single document and it could be
  266. // added, modified, or removed, but not a combination.
  267. HARD_ASSERT(change.addedDocuments.size() + change.modifiedDocuments.size() +
  268. change.removedDocuments.size() <=
  269. 1,
  270. "Limbo resolution for single document contains multiple changes.");
  271. if (change.addedDocuments.size() > 0) {
  272. limboResolution.document_received = true;
  273. } else if (change.modifiedDocuments.size() > 0) {
  274. HARD_ASSERT(limboResolution.document_received,
  275. "Received change for limbo target document without add.");
  276. } else if (change.removedDocuments.size() > 0) {
  277. HARD_ASSERT(limboResolution.document_received,
  278. "Received remove for limbo target document without add.");
  279. limboResolution.document_received = false;
  280. } else {
  281. // This was probably just a CURRENT targetChange or similar.
  282. }
  283. }
  284. }
  285. FSTMaybeDocumentDictionary *changes = [self.localStore applyRemoteEvent:remoteEvent];
  286. [self emitNewSnapshotsWithChanges:changes remoteEvent:remoteEvent];
  287. }
  288. - (void)applyChangedOnlineState:(FSTOnlineState)onlineState {
  289. NSMutableArray<FSTViewSnapshot *> *newViewSnapshots = [NSMutableArray array];
  290. [self.queryViewsByQuery
  291. enumerateKeysAndObjectsUsingBlock:^(FSTQuery *query, FSTQueryView *queryView, BOOL *stop) {
  292. FSTViewChange *viewChange = [queryView.view applyChangedOnlineState:onlineState];
  293. HARD_ASSERT(viewChange.limboChanges.count == 0,
  294. "OnlineState should not affect limbo documents.");
  295. if (viewChange.snapshot) {
  296. [newViewSnapshots addObject:viewChange.snapshot];
  297. }
  298. }];
  299. [self.delegate handleViewSnapshots:newViewSnapshots];
  300. }
  301. - (void)rejectListenWithTargetID:(const TargetId)targetID error:(NSError *)error {
  302. [self assertDelegateExistsForSelector:_cmd];
  303. const auto iter = _limboResolutionsByTarget.find(targetID);
  304. if (iter != _limboResolutionsByTarget.end()) {
  305. const DocumentKey limboKey = iter->second.key;
  306. // Since this query failed, we won't want to manually unlisten to it.
  307. // So go ahead and remove it from bookkeeping.
  308. _limboTargetsByKey.erase(limboKey);
  309. _limboResolutionsByTarget.erase(targetID);
  310. // TODO(dimond): Retry on transient errors?
  311. // It's a limbo doc. Create a synthetic event saying it was deleted. This is kind of a hack.
  312. // Ideally, we would have a method in the local store to purge a document. However, it would
  313. // be tricky to keep all of the local store's invariants with another method.
  314. FSTDeletedDocument *doc =
  315. [FSTDeletedDocument documentWithKey:limboKey version:SnapshotVersion::None()];
  316. DocumentKeySet limboDocuments = DocumentKeySet{doc.key};
  317. FSTRemoteEvent *event = [[FSTRemoteEvent alloc] initWithSnapshotVersion:SnapshotVersion::None()
  318. targetChanges:{}
  319. targetMismatches:{}
  320. documentUpdates:{
  321. { limboKey, doc }
  322. }
  323. limboDocuments:std::move(limboDocuments)];
  324. [self applyRemoteEvent:event];
  325. } else {
  326. FSTQueryView *queryView = self.queryViewsByTarget[@(targetID)];
  327. HARD_ASSERT(queryView, "Unknown targetId: %s", targetID);
  328. [self.localStore releaseQuery:queryView.query];
  329. [self removeAndCleanupQuery:queryView];
  330. [self.delegate handleError:error forQuery:queryView.query];
  331. }
  332. }
  333. - (void)applySuccessfulWriteWithResult:(FSTMutationBatchResult *)batchResult {
  334. [self assertDelegateExistsForSelector:_cmd];
  335. // The local store may or may not be able to apply the write result and raise events immediately
  336. // (depending on whether the watcher is caught up), so we raise user callbacks first so that they
  337. // consistently happen before listen events.
  338. [self processUserCallbacksForBatchID:batchResult.batch.batchID error:nil];
  339. FSTMaybeDocumentDictionary *changes = [self.localStore acknowledgeBatchWithResult:batchResult];
  340. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  341. }
  342. - (void)rejectFailedWriteWithBatchID:(FSTBatchID)batchID error:(NSError *)error {
  343. [self assertDelegateExistsForSelector:_cmd];
  344. // The local store may or may not be able to apply the write result and raise events immediately
  345. // (depending on whether the watcher is caught up), so we raise user callbacks first so that they
  346. // consistently happen before listen events.
  347. [self processUserCallbacksForBatchID:batchID error:error];
  348. FSTMaybeDocumentDictionary *changes = [self.localStore rejectBatchID:batchID];
  349. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  350. }
  351. - (void)processUserCallbacksForBatchID:(FSTBatchID)batchID error:(NSError *_Nullable)error {
  352. NSMutableDictionary<NSNumber *, FSTVoidErrorBlock> *completionBlocks =
  353. _mutationCompletionBlocks[_currentUser];
  354. // NOTE: Mutations restored from persistence won't have completion blocks, so it's okay for
  355. // this (or the completion below) to be nil.
  356. if (completionBlocks) {
  357. NSNumber *boxedBatchID = @(batchID);
  358. FSTVoidErrorBlock completion = completionBlocks[boxedBatchID];
  359. if (completion) {
  360. completion(error);
  361. [completionBlocks removeObjectForKey:boxedBatchID];
  362. }
  363. }
  364. }
  365. - (void)assertDelegateExistsForSelector:(SEL)methodSelector {
  366. HARD_ASSERT(self.delegate, "Tried to call '%s' before delegate was registered.",
  367. NSStringFromSelector(methodSelector));
  368. }
  369. - (void)removeAndCleanupQuery:(FSTQueryView *)queryView {
  370. [self.queryViewsByQuery removeObjectForKey:queryView.query];
  371. [self.queryViewsByTarget removeObjectForKey:@(queryView.targetID)];
  372. DocumentKeySet limboKeys = [self.limboDocumentRefs referencedKeysForID:queryView.targetID];
  373. [self.limboDocumentRefs removeReferencesForID:queryView.targetID];
  374. for (const DocumentKey &key : limboKeys) {
  375. if (![self.limboDocumentRefs containsKey:key]) {
  376. // We removed the last reference for this key.
  377. [self removeLimboTargetForKey:key];
  378. }
  379. }
  380. }
  381. /**
  382. * Computes a new snapshot from the changes and calls the registered callback with the new snapshot.
  383. */
  384. - (void)emitNewSnapshotsWithChanges:(FSTMaybeDocumentDictionary *)changes
  385. remoteEvent:(FSTRemoteEvent *_Nullable)remoteEvent {
  386. NSMutableArray<FSTViewSnapshot *> *newSnapshots = [NSMutableArray array];
  387. NSMutableArray<FSTLocalViewChanges *> *documentChangesInAllViews = [NSMutableArray array];
  388. [self.queryViewsByQuery
  389. enumerateKeysAndObjectsUsingBlock:^(FSTQuery *query, FSTQueryView *queryView, BOOL *stop) {
  390. FSTView *view = queryView.view;
  391. FSTViewDocumentChanges *viewDocChanges = [view computeChangesWithDocuments:changes];
  392. if (viewDocChanges.needsRefill) {
  393. // The query has a limit and some docs were removed/updated, so we need to re-run the
  394. // query against the local store to make sure we didn't lose any good docs that had been
  395. // past the limit.
  396. FSTDocumentDictionary *docs = [self.localStore executeQuery:queryView.query];
  397. viewDocChanges = [view computeChangesWithDocuments:docs previousChanges:viewDocChanges];
  398. }
  399. FSTTargetChange *_Nullable targetChange = nil;
  400. if (remoteEvent) {
  401. auto it = remoteEvent.targetChanges.find(queryView.targetID);
  402. if (it != remoteEvent.targetChanges.end()) {
  403. targetChange = it->second;
  404. }
  405. }
  406. FSTViewChange *viewChange =
  407. [queryView.view applyChangesToDocuments:viewDocChanges targetChange:targetChange];
  408. [self updateTrackedLimboDocumentsWithChanges:viewChange.limboChanges
  409. targetID:queryView.targetID];
  410. if (viewChange.snapshot) {
  411. [newSnapshots addObject:viewChange.snapshot];
  412. FSTLocalViewChanges *docChanges =
  413. [FSTLocalViewChanges changesForViewSnapshot:viewChange.snapshot
  414. withTargetID:queryView.targetID];
  415. [documentChangesInAllViews addObject:docChanges];
  416. }
  417. }];
  418. [self.delegate handleViewSnapshots:newSnapshots];
  419. [self.localStore notifyLocalViewChanges:documentChangesInAllViews];
  420. }
  421. /** Updates the limbo document state for the given targetID. */
  422. - (void)updateTrackedLimboDocumentsWithChanges:(NSArray<FSTLimboDocumentChange *> *)limboChanges
  423. targetID:(FSTTargetID)targetID {
  424. for (FSTLimboDocumentChange *limboChange in limboChanges) {
  425. switch (limboChange.type) {
  426. case FSTLimboDocumentChangeTypeAdded:
  427. [self.limboDocumentRefs addReferenceToKey:limboChange.key forID:targetID];
  428. [self trackLimboChange:limboChange];
  429. break;
  430. case FSTLimboDocumentChangeTypeRemoved:
  431. LOG_DEBUG("Document no longer in limbo: %s", limboChange.key.ToString());
  432. [self.limboDocumentRefs removeReferenceToKey:limboChange.key forID:targetID];
  433. if (![self.limboDocumentRefs containsKey:limboChange.key]) {
  434. // We removed the last reference for this key
  435. [self removeLimboTargetForKey:limboChange.key];
  436. }
  437. break;
  438. default:
  439. HARD_FAIL("Unknown limbo change type: %s", limboChange.type);
  440. }
  441. }
  442. }
  443. - (void)trackLimboChange:(FSTLimboDocumentChange *)limboChange {
  444. DocumentKey key{limboChange.key};
  445. if (_limboTargetsByKey.find(key) == _limboTargetsByKey.end()) {
  446. LOG_DEBUG("New document in limbo: %s", key.ToString());
  447. TargetId limboTargetID = _targetIdGenerator.NextId();
  448. FSTQuery *query = [FSTQuery queryWithPath:key.path()];
  449. FSTQueryData *queryData = [[FSTQueryData alloc] initWithQuery:query
  450. targetID:limboTargetID
  451. listenSequenceNumber:kIrrelevantSequenceNumber
  452. purpose:FSTQueryPurposeLimboResolution];
  453. _limboResolutionsByTarget.emplace(limboTargetID, LimboResolution{key});
  454. [self.remoteStore listenToTargetWithQueryData:queryData];
  455. _limboTargetsByKey[key] = limboTargetID;
  456. }
  457. }
  458. - (void)removeLimboTargetForKey:(const DocumentKey &)key {
  459. const auto iter = _limboTargetsByKey.find(key);
  460. if (iter == _limboTargetsByKey.end()) {
  461. // This target already got removed, because the query failed.
  462. return;
  463. }
  464. TargetId limboTargetID = iter->second;
  465. [self.remoteStore stopListeningToTargetID:limboTargetID];
  466. _limboTargetsByKey.erase(key);
  467. _limboResolutionsByTarget.erase(limboTargetID);
  468. }
  469. // Used for testing
  470. - (std::map<DocumentKey, TargetId>)currentLimboDocuments {
  471. // Return defensive copy
  472. return _limboTargetsByKey;
  473. }
  474. - (void)userDidChange:(const User &)user {
  475. _currentUser = user;
  476. // Notify local store and emit any resulting events from swapping out the mutation queue.
  477. FSTMaybeDocumentDictionary *changes = [self.localStore userDidChange:user];
  478. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  479. // Notify remote store so it can restart its streams.
  480. [self.remoteStore userDidChange:user];
  481. }
  482. - (firebase::firestore::model::DocumentKeySet)remoteKeysForTarget:(FSTBoxedTargetID *)targetId {
  483. const auto iter = _limboResolutionsByTarget.find([targetId intValue]);
  484. if (iter != _limboResolutionsByTarget.end() && iter->second.document_received) {
  485. return DocumentKeySet{iter->second.key};
  486. } else {
  487. FSTQueryView *queryView = self.queryViewsByTarget[targetId];
  488. return queryView ? queryView.view.syncedDocuments : DocumentKeySet{};
  489. }
  490. }
  491. @end
  492. NS_ASSUME_NONNULL_END