FSTSyncEngine.mm 24 KB

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