FSTSyncEngine.mm 26 KB

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