FSTSyncEngine.mm 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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. FSTQuery *query = queryView.query;
  332. [self.localStore releaseQuery:query];
  333. [self removeAndCleanupQuery:queryView];
  334. if ([self errorIsInteresting:error]) {
  335. LOG_WARN("Listen for query at %s failed: %s", query.path.CanonicalString(),
  336. error.localizedDescription);
  337. }
  338. [self.delegate handleError:error forQuery:query];
  339. }
  340. }
  341. - (void)applySuccessfulWriteWithResult:(FSTMutationBatchResult *)batchResult {
  342. [self assertDelegateExistsForSelector:_cmd];
  343. // The local store may or may not be able to apply the write result and raise events immediately
  344. // (depending on whether the watcher is caught up), so we raise user callbacks first so that they
  345. // consistently happen before listen events.
  346. [self processUserCallbacksForBatchID:batchResult.batch.batchID error:nil];
  347. FSTMaybeDocumentDictionary *changes = [self.localStore acknowledgeBatchWithResult:batchResult];
  348. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  349. }
  350. - (void)rejectFailedWriteWithBatchID:(BatchId)batchID error:(NSError *)error {
  351. [self assertDelegateExistsForSelector:_cmd];
  352. FSTMaybeDocumentDictionary *changes = [self.localStore rejectBatchID:batchID];
  353. if (!changes.isEmpty && [self errorIsInteresting:error]) {
  354. LOG_WARN("Write at %s failed: %s", changes.minKey.path.CanonicalString(),
  355. error.localizedDescription);
  356. }
  357. // The local store may or may not be able to apply the write result and raise events immediately
  358. // (depending on whether the watcher is caught up), so we raise user callbacks first so that they
  359. // consistently happen before listen events.
  360. [self processUserCallbacksForBatchID:batchID error:error];
  361. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  362. }
  363. - (void)processUserCallbacksForBatchID:(BatchId)batchID error:(NSError *_Nullable)error {
  364. NSMutableDictionary<NSNumber *, FSTVoidErrorBlock> *completionBlocks =
  365. _mutationCompletionBlocks[_currentUser];
  366. // NOTE: Mutations restored from persistence won't have completion blocks, so it's okay for
  367. // this (or the completion below) to be nil.
  368. if (completionBlocks) {
  369. NSNumber *boxedBatchID = @(batchID);
  370. FSTVoidErrorBlock completion = completionBlocks[boxedBatchID];
  371. if (completion) {
  372. completion(error);
  373. [completionBlocks removeObjectForKey:boxedBatchID];
  374. }
  375. }
  376. }
  377. - (void)assertDelegateExistsForSelector:(SEL)methodSelector {
  378. HARD_ASSERT(self.delegate, "Tried to call '%s' before delegate was registered.",
  379. NSStringFromSelector(methodSelector));
  380. }
  381. - (void)removeAndCleanupQuery:(FSTQueryView *)queryView {
  382. [self.queryViewsByQuery removeObjectForKey:queryView.query];
  383. [self.queryViewsByTarget removeObjectForKey:@(queryView.targetID)];
  384. DocumentKeySet limboKeys = [self.limboDocumentRefs referencedKeysForID:queryView.targetID];
  385. [self.limboDocumentRefs removeReferencesForID:queryView.targetID];
  386. for (const DocumentKey &key : limboKeys) {
  387. if (![self.limboDocumentRefs containsKey:key]) {
  388. // We removed the last reference for this key.
  389. [self removeLimboTargetForKey:key];
  390. }
  391. }
  392. }
  393. /**
  394. * Computes a new snapshot from the changes and calls the registered callback with the new snapshot.
  395. */
  396. - (void)emitNewSnapshotsWithChanges:(FSTMaybeDocumentDictionary *)changes
  397. remoteEvent:(FSTRemoteEvent *_Nullable)remoteEvent {
  398. NSMutableArray<FSTViewSnapshot *> *newSnapshots = [NSMutableArray array];
  399. NSMutableArray<FSTLocalViewChanges *> *documentChangesInAllViews = [NSMutableArray array];
  400. [self.queryViewsByQuery
  401. enumerateKeysAndObjectsUsingBlock:^(FSTQuery *query, FSTQueryView *queryView, BOOL *stop) {
  402. FSTView *view = queryView.view;
  403. FSTViewDocumentChanges *viewDocChanges = [view computeChangesWithDocuments:changes];
  404. if (viewDocChanges.needsRefill) {
  405. // The query has a limit and some docs were removed/updated, so we need to re-run the
  406. // query against the local store to make sure we didn't lose any good docs that had been
  407. // past the limit.
  408. FSTDocumentDictionary *docs = [self.localStore executeQuery:queryView.query];
  409. viewDocChanges = [view computeChangesWithDocuments:docs previousChanges:viewDocChanges];
  410. }
  411. FSTTargetChange *_Nullable targetChange = nil;
  412. if (remoteEvent) {
  413. auto it = remoteEvent.targetChanges.find(queryView.targetID);
  414. if (it != remoteEvent.targetChanges.end()) {
  415. targetChange = it->second;
  416. }
  417. }
  418. FSTViewChange *viewChange =
  419. [queryView.view applyChangesToDocuments:viewDocChanges targetChange:targetChange];
  420. [self updateTrackedLimboDocumentsWithChanges:viewChange.limboChanges
  421. targetID:queryView.targetID];
  422. if (viewChange.snapshot) {
  423. [newSnapshots addObject:viewChange.snapshot];
  424. FSTLocalViewChanges *docChanges =
  425. [FSTLocalViewChanges changesForViewSnapshot:viewChange.snapshot
  426. withTargetID:queryView.targetID];
  427. [documentChangesInAllViews addObject:docChanges];
  428. }
  429. }];
  430. [self.delegate handleViewSnapshots:newSnapshots];
  431. [self.localStore notifyLocalViewChanges:documentChangesInAllViews];
  432. }
  433. /** Updates the limbo document state for the given targetID. */
  434. - (void)updateTrackedLimboDocumentsWithChanges:(NSArray<FSTLimboDocumentChange *> *)limboChanges
  435. targetID:(TargetId)targetID {
  436. for (FSTLimboDocumentChange *limboChange in limboChanges) {
  437. switch (limboChange.type) {
  438. case FSTLimboDocumentChangeTypeAdded:
  439. [self.limboDocumentRefs addReferenceToKey:limboChange.key forID:targetID];
  440. [self trackLimboChange:limboChange];
  441. break;
  442. case FSTLimboDocumentChangeTypeRemoved:
  443. LOG_DEBUG("Document no longer in limbo: %s", limboChange.key.ToString());
  444. [self.limboDocumentRefs removeReferenceToKey:limboChange.key forID:targetID];
  445. if (![self.limboDocumentRefs containsKey:limboChange.key]) {
  446. // We removed the last reference for this key
  447. [self removeLimboTargetForKey:limboChange.key];
  448. }
  449. break;
  450. default:
  451. HARD_FAIL("Unknown limbo change type: %s", limboChange.type);
  452. }
  453. }
  454. }
  455. - (void)trackLimboChange:(FSTLimboDocumentChange *)limboChange {
  456. DocumentKey key{limboChange.key};
  457. if (_limboTargetsByKey.find(key) == _limboTargetsByKey.end()) {
  458. LOG_DEBUG("New document in limbo: %s", key.ToString());
  459. TargetId limboTargetID = _targetIdGenerator.NextId();
  460. FSTQuery *query = [FSTQuery queryWithPath:key.path()];
  461. FSTQueryData *queryData = [[FSTQueryData alloc] initWithQuery:query
  462. targetID:limboTargetID
  463. listenSequenceNumber:kIrrelevantSequenceNumber
  464. purpose:FSTQueryPurposeLimboResolution];
  465. _limboResolutionsByTarget.emplace(limboTargetID, LimboResolution{key});
  466. [self.remoteStore listenToTargetWithQueryData:queryData];
  467. _limboTargetsByKey[key] = limboTargetID;
  468. }
  469. }
  470. - (void)removeLimboTargetForKey:(const DocumentKey &)key {
  471. const auto iter = _limboTargetsByKey.find(key);
  472. if (iter == _limboTargetsByKey.end()) {
  473. // This target already got removed, because the query failed.
  474. return;
  475. }
  476. TargetId limboTargetID = iter->second;
  477. [self.remoteStore stopListeningToTargetID:limboTargetID];
  478. _limboTargetsByKey.erase(key);
  479. _limboResolutionsByTarget.erase(limboTargetID);
  480. }
  481. // Used for testing
  482. - (std::map<DocumentKey, TargetId>)currentLimboDocuments {
  483. // Return defensive copy
  484. return _limboTargetsByKey;
  485. }
  486. - (void)credentialDidChangeWithUser:(const firebase::firestore::auth::User &)user {
  487. BOOL userChanged = (_currentUser != user);
  488. _currentUser = user;
  489. if (userChanged) {
  490. // Notify local store and emit any resulting events from swapping out the mutation queue.
  491. FSTMaybeDocumentDictionary *changes = [self.localStore userDidChange:user];
  492. [self emitNewSnapshotsWithChanges:changes remoteEvent:nil];
  493. }
  494. // Notify remote store so it can restart its streams.
  495. [self.remoteStore credentialDidChange];
  496. }
  497. - (firebase::firestore::model::DocumentKeySet)remoteKeysForTarget:(FSTBoxedTargetID *)targetId {
  498. const auto iter = _limboResolutionsByTarget.find([targetId intValue]);
  499. if (iter != _limboResolutionsByTarget.end() && iter->second.document_received) {
  500. return DocumentKeySet{iter->second.key};
  501. } else {
  502. FSTQueryView *queryView = self.queryViewsByTarget[targetId];
  503. return queryView ? queryView.view.syncedDocuments : DocumentKeySet{};
  504. }
  505. }
  506. /**
  507. * Decides if the error likely represents a developer mistake such as forgetting to create an index
  508. * or permission denied. Used to decide whether an error is worth automatically logging as a
  509. * warning.
  510. */
  511. - (BOOL)errorIsInteresting:(NSError *)error {
  512. if (error.domain == FIRFirestoreErrorDomain) {
  513. if (error.code == FIRFirestoreErrorCodeFailedPrecondition &&
  514. [error.localizedDescription containsString:@"requires an index"]) {
  515. return YES;
  516. } else if (error.code == FIRFirestoreErrorCodePermissionDenied) {
  517. return YES;
  518. }
  519. }
  520. return NO;
  521. }
  522. @end
  523. NS_ASSUME_NONNULL_END