FSTSyncEngine.mm 24 KB

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