FSTLocalStore.mm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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/Local/FSTLocalStore.h"
  17. #include <set>
  18. #import "FIRTimestamp.h"
  19. #import "Firestore/Source/Core/FSTListenSequence.h"
  20. #import "Firestore/Source/Core/FSTQuery.h"
  21. #import "Firestore/Source/Local/FSTGarbageCollector.h"
  22. #import "Firestore/Source/Local/FSTLocalDocumentsView.h"
  23. #import "Firestore/Source/Local/FSTLocalViewChanges.h"
  24. #import "Firestore/Source/Local/FSTLocalWriteResult.h"
  25. #import "Firestore/Source/Local/FSTMutationQueue.h"
  26. #import "Firestore/Source/Local/FSTPersistence.h"
  27. #import "Firestore/Source/Local/FSTQueryCache.h"
  28. #import "Firestore/Source/Local/FSTQueryData.h"
  29. #import "Firestore/Source/Local/FSTReferenceSet.h"
  30. #import "Firestore/Source/Local/FSTRemoteDocumentCache.h"
  31. #import "Firestore/Source/Model/FSTDocument.h"
  32. #import "Firestore/Source/Model/FSTDocumentDictionary.h"
  33. #import "Firestore/Source/Model/FSTMutation.h"
  34. #import "Firestore/Source/Model/FSTMutationBatch.h"
  35. #import "Firestore/Source/Remote/FSTRemoteEvent.h"
  36. #import "Firestore/Source/Util/FSTAssert.h"
  37. #import "Firestore/Source/Util/FSTLogger.h"
  38. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  39. #include "Firestore/core/src/firebase/firestore/core/target_id_generator.h"
  40. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  41. #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
  42. using firebase::firestore::auth::User;
  43. using firebase::firestore::core::TargetIdGenerator;
  44. using firebase::firestore::model::DocumentKey;
  45. using firebase::firestore::model::SnapshotVersion;
  46. using firebase::firestore::model::DocumentKeySet;
  47. using firebase::firestore::model::DocumentVersionMap;
  48. NS_ASSUME_NONNULL_BEGIN
  49. @interface FSTLocalStore ()
  50. /** Manages our in-memory or durable persistence. */
  51. @property(nonatomic, strong, readonly) id<FSTPersistence> persistence;
  52. /** The set of all mutations that have been sent but not yet been applied to the backend. */
  53. @property(nonatomic, strong) id<FSTMutationQueue> mutationQueue;
  54. /** The set of all cached remote documents. */
  55. @property(nonatomic, strong) id<FSTRemoteDocumentCache> remoteDocumentCache;
  56. /** The "local" view of all documents (layering mutationQueue on top of remoteDocumentCache). */
  57. @property(nonatomic, strong) FSTLocalDocumentsView *localDocuments;
  58. /** The set of document references maintained by any local views. */
  59. @property(nonatomic, strong) FSTReferenceSet *localViewReferences;
  60. /**
  61. * The garbage collector collects documents that should no longer be cached (e.g. if they are no
  62. * longer retained by the above reference sets and the garbage collector is performing eager
  63. * collection).
  64. */
  65. @property(nonatomic, strong) id<FSTGarbageCollector> garbageCollector;
  66. /** Maps a query to the data about that query. */
  67. @property(nonatomic, strong) id<FSTQueryCache> queryCache;
  68. /** Maps a targetID to data about its query. */
  69. @property(nonatomic, strong) NSMutableDictionary<NSNumber *, FSTQueryData *> *targetIDs;
  70. @property(nonatomic, strong) FSTListenSequence *listenSequence;
  71. /**
  72. * A heldBatchResult is a mutation batch result (from a write acknowledgement) that arrived before
  73. * the watch stream got notified of a snapshot that includes the write.  So we "hold" it until
  74. * the watch stream catches up. It ensures that the local write remains visible (latency
  75. * compensation) and doesn't temporarily appear reverted because the watch stream is slower than
  76. * the write stream and so wasn't reflecting it.
  77. *
  78. * NOTE: Eventually we want to move this functionality into the remote store.
  79. */
  80. @property(nonatomic, strong) NSMutableArray<FSTMutationBatchResult *> *heldBatchResults;
  81. @end
  82. @implementation FSTLocalStore {
  83. /** Used to generate targetIDs for queries tracked locally. */
  84. TargetIdGenerator _targetIDGenerator;
  85. }
  86. - (instancetype)initWithPersistence:(id<FSTPersistence>)persistence
  87. garbageCollector:(id<FSTGarbageCollector>)garbageCollector
  88. initialUser:(const User &)initialUser {
  89. if (self = [super init]) {
  90. _persistence = persistence;
  91. _mutationQueue = [persistence mutationQueueForUser:initialUser];
  92. _remoteDocumentCache = [persistence remoteDocumentCache];
  93. _queryCache = [persistence queryCache];
  94. _localDocuments = [FSTLocalDocumentsView viewWithRemoteDocumentCache:_remoteDocumentCache
  95. mutationQueue:_mutationQueue];
  96. _localViewReferences = [[FSTReferenceSet alloc] init];
  97. [_persistence.referenceDelegate addInMemoryPins:_localViewReferences];
  98. _garbageCollector = garbageCollector;
  99. [_garbageCollector addGarbageSource:_queryCache];
  100. [_garbageCollector addGarbageSource:_localViewReferences];
  101. [_garbageCollector addGarbageSource:_mutationQueue];
  102. _targetIDs = [NSMutableDictionary dictionary];
  103. _heldBatchResults = [NSMutableArray array];
  104. _targetIDGenerator = TargetIdGenerator::LocalStoreTargetIdGenerator(0);
  105. }
  106. return self;
  107. }
  108. - (void)start {
  109. [self startMutationQueue];
  110. [self startQueryCache];
  111. }
  112. - (void)startMutationQueue {
  113. self.persistence.run("Start MutationQueue", [&]() {
  114. [self.mutationQueue start];
  115. // If we have any leftover mutation batch results from a prior run, just drop them.
  116. // TODO(http://b/33446471): We probably need to repopulate heldBatchResults or similar instead,
  117. // but that is not straightforward since we're not persisting the write ack versions.
  118. [self.heldBatchResults removeAllObjects];
  119. // TODO(mikelehen): This is the only usage of getAllMutationBatchesThroughBatchId:. Consider
  120. // removing it in favor of a getAcknowledgedBatches method.
  121. FSTBatchID highestAck = [self.mutationQueue highestAcknowledgedBatchID];
  122. if (highestAck != kFSTBatchIDUnknown) {
  123. NSArray<FSTMutationBatch *> *batches =
  124. [self.mutationQueue allMutationBatchesThroughBatchID:highestAck];
  125. if (batches.count > 0) {
  126. // NOTE: This could be more efficient if we had a removeBatchesThroughBatchID, but this set
  127. // should be very small and this code should go away eventually.
  128. [self.mutationQueue removeMutationBatches:batches];
  129. }
  130. }
  131. });
  132. }
  133. - (void)startQueryCache {
  134. [self.queryCache start];
  135. FSTTargetID targetID = [self.queryCache highestTargetID];
  136. _targetIDGenerator = TargetIdGenerator::LocalStoreTargetIdGenerator(targetID);
  137. FSTListenSequenceNumber sequenceNumber = [self.queryCache highestListenSequenceNumber];
  138. self.listenSequence = [[FSTListenSequence alloc] initStartingAfter:sequenceNumber];
  139. }
  140. - (FSTMaybeDocumentDictionary *)userDidChange:(const User &)user {
  141. // Swap out the mutation queue, grabbing the pending mutation batches before and after.
  142. NSArray<FSTMutationBatch *> *oldBatches = self.persistence.run(
  143. "OldBatches",
  144. [&]() -> NSArray<FSTMutationBatch *> * { return [self.mutationQueue allMutationBatches]; });
  145. [self.garbageCollector removeGarbageSource:self.mutationQueue];
  146. self.mutationQueue = [self.persistence mutationQueueForUser:user];
  147. [self.garbageCollector addGarbageSource:self.mutationQueue];
  148. [self startMutationQueue];
  149. return self.persistence.run("NewBatches", [&]() -> FSTMaybeDocumentDictionary * {
  150. NSArray<FSTMutationBatch *> *newBatches = [self.mutationQueue allMutationBatches];
  151. // Recreate our LocalDocumentsView using the new MutationQueue.
  152. self.localDocuments =
  153. [FSTLocalDocumentsView viewWithRemoteDocumentCache:self.remoteDocumentCache
  154. mutationQueue:self.mutationQueue];
  155. // Union the old/new changed keys.
  156. DocumentKeySet changedKeys;
  157. for (NSArray<FSTMutationBatch *> *batches in @[ oldBatches, newBatches ]) {
  158. for (FSTMutationBatch *batch in batches) {
  159. for (FSTMutation *mutation in batch.mutations) {
  160. changedKeys = changedKeys.insert(mutation.key);
  161. }
  162. }
  163. }
  164. // Return the set of all (potentially) changed documents as the result of the user change.
  165. return [self.localDocuments documentsForKeys:changedKeys];
  166. });
  167. }
  168. - (FSTLocalWriteResult *)locallyWriteMutations:(NSArray<FSTMutation *> *)mutations {
  169. return self.persistence.run("Locally write mutations", [&]() -> FSTLocalWriteResult * {
  170. FIRTimestamp *localWriteTime = [FIRTimestamp timestamp];
  171. FSTMutationBatch *batch =
  172. [self.mutationQueue addMutationBatchWithWriteTime:localWriteTime mutations:mutations];
  173. DocumentKeySet keys = [batch keys];
  174. FSTMaybeDocumentDictionary *changedDocuments = [self.localDocuments documentsForKeys:keys];
  175. return [FSTLocalWriteResult resultForBatchID:batch.batchID changes:changedDocuments];
  176. });
  177. }
  178. - (FSTMaybeDocumentDictionary *)acknowledgeBatchWithResult:(FSTMutationBatchResult *)batchResult {
  179. return self.persistence.run("Acknowledge batch", [&]() -> FSTMaybeDocumentDictionary * {
  180. id<FSTMutationQueue> mutationQueue = self.mutationQueue;
  181. [mutationQueue acknowledgeBatch:batchResult.batch streamToken:batchResult.streamToken];
  182. DocumentKeySet affected;
  183. if ([self shouldHoldBatchResultWithVersion:batchResult.commitVersion]) {
  184. [self.heldBatchResults addObject:batchResult];
  185. } else {
  186. affected = [self releaseBatchResults:@[ batchResult ]];
  187. }
  188. [self.mutationQueue performConsistencyCheck];
  189. return [self.localDocuments documentsForKeys:affected];
  190. });
  191. }
  192. - (FSTMaybeDocumentDictionary *)rejectBatchID:(FSTBatchID)batchID {
  193. return self.persistence.run("Reject batch", [&]() -> FSTMaybeDocumentDictionary * {
  194. FSTMutationBatch *toReject = [self.mutationQueue lookupMutationBatch:batchID];
  195. FSTAssert(toReject, @"Attempt to reject nonexistent batch!");
  196. FSTBatchID lastAcked = [self.mutationQueue highestAcknowledgedBatchID];
  197. FSTAssert(batchID > lastAcked, @"Acknowledged batches can't be rejected.");
  198. DocumentKeySet affected = [self removeMutationBatch:toReject];
  199. [self.mutationQueue performConsistencyCheck];
  200. return [self.localDocuments documentsForKeys:affected];
  201. });
  202. }
  203. - (nullable NSData *)lastStreamToken {
  204. return [self.mutationQueue lastStreamToken];
  205. }
  206. - (void)setLastStreamToken:(nullable NSData *)streamToken {
  207. self.persistence.run("Set stream token",
  208. [&]() { [self.mutationQueue setLastStreamToken:streamToken]; });
  209. }
  210. - (const SnapshotVersion &)lastRemoteSnapshotVersion {
  211. return [self.queryCache lastRemoteSnapshotVersion];
  212. }
  213. - (FSTMaybeDocumentDictionary *)applyRemoteEvent:(FSTRemoteEvent *)remoteEvent {
  214. return self.persistence.run("Apply remote event", [&]() -> FSTMaybeDocumentDictionary * {
  215. // TODO(gsoltis): move the sequence number into the reference delegate.
  216. FSTListenSequenceNumber sequenceNumber = [self.listenSequence next];
  217. id<FSTQueryCache> queryCache = self.queryCache;
  218. [remoteEvent.targetChanges enumerateKeysAndObjectsUsingBlock:^(
  219. NSNumber *targetIDNumber, FSTTargetChange *change, BOOL *stop) {
  220. FSTTargetID targetID = targetIDNumber.intValue;
  221. // Do not ref/unref unassigned targetIDs - it may lead to leaks.
  222. FSTQueryData *queryData = self.targetIDs[targetIDNumber];
  223. if (!queryData) {
  224. return;
  225. }
  226. // Update the resume token if the change includes one. Don't clear any preexisting value.
  227. // Bump the sequence number as well, so that documents being removed now are ordered later
  228. // than documents that were previously removed from this target.
  229. NSData *resumeToken = change.resumeToken;
  230. if (resumeToken.length > 0) {
  231. queryData = [queryData queryDataByReplacingSnapshotVersion:change.snapshotVersion
  232. resumeToken:resumeToken
  233. sequenceNumber:sequenceNumber];
  234. self.targetIDs[targetIDNumber] = queryData;
  235. [self.queryCache updateQueryData:queryData];
  236. }
  237. FSTTargetMapping *mapping = change.mapping;
  238. if (mapping) {
  239. // First make sure that all references are deleted.
  240. if ([mapping isKindOfClass:[FSTResetMapping class]]) {
  241. FSTResetMapping *reset = (FSTResetMapping *)mapping;
  242. [queryCache removeMatchingKeysForTargetID:targetID];
  243. [queryCache addMatchingKeys:reset.documents forTargetID:targetID];
  244. } else if ([mapping isKindOfClass:[FSTUpdateMapping class]]) {
  245. FSTUpdateMapping *update = (FSTUpdateMapping *)mapping;
  246. [queryCache removeMatchingKeys:update.removedDocuments forTargetID:targetID];
  247. [queryCache addMatchingKeys:update.addedDocuments forTargetID:targetID];
  248. } else {
  249. FSTFail(@"Unknown mapping type: %@", mapping);
  250. }
  251. }
  252. }];
  253. // TODO(klimt): This could probably be an NSMutableDictionary.
  254. DocumentKeySet changedDocKeys;
  255. const DocumentKeySet &limboDocuments = remoteEvent.limboDocumentChanges;
  256. for (const auto &kv : remoteEvent.documentUpdates) {
  257. const DocumentKey &key = kv.first;
  258. FSTMaybeDocument *doc = kv.second;
  259. changedDocKeys = changedDocKeys.insert(key);
  260. FSTMaybeDocument *existingDoc = [self.remoteDocumentCache entryForKey:key];
  261. // Make sure we don't apply an old document version to the remote cache, though we
  262. // make an exception for SnapshotVersion::None() which can happen for manufactured
  263. // events (e.g. in the case of a limbo document resolution failing).
  264. if (!existingDoc || SnapshotVersion{doc.version} == SnapshotVersion::None() ||
  265. SnapshotVersion{doc.version} >= SnapshotVersion{existingDoc.version}) {
  266. [self.remoteDocumentCache addEntry:doc];
  267. } else {
  268. FSTLog(
  269. @"FSTLocalStore Ignoring outdated watch update for %s. "
  270. "Current version: %s Watch version: %s",
  271. key.ToString().c_str(), existingDoc.version.timestamp().ToString().c_str(),
  272. doc.version.timestamp().ToString().c_str());
  273. }
  274. // The document might be garbage because it was unreferenced by everything.
  275. // Make sure to mark it as garbage if it is...
  276. [self.garbageCollector addPotentialGarbageKey:key];
  277. if (limboDocuments.contains(key)) {
  278. [self.persistence.referenceDelegate limboDocumentUpdated:key];
  279. }
  280. }
  281. // HACK: The only reason we allow omitting snapshot version is so we can synthesize remote
  282. // events when we get permission denied errors while trying to resolve the state of a locally
  283. // cached document that is in limbo.
  284. const SnapshotVersion &lastRemoteVersion = [self.queryCache lastRemoteSnapshotVersion];
  285. const SnapshotVersion &remoteVersion = remoteEvent.snapshotVersion;
  286. if (remoteVersion != SnapshotVersion::None()) {
  287. FSTAssert(remoteVersion >= lastRemoteVersion,
  288. @"Watch stream reverted to previous snapshot?? (%s < %s)",
  289. remoteVersion.timestamp().ToString().c_str(),
  290. lastRemoteVersion.timestamp().ToString().c_str());
  291. [self.queryCache setLastRemoteSnapshotVersion:remoteVersion];
  292. }
  293. DocumentKeySet releasedWriteKeys = [self releaseHeldBatchResults];
  294. // Union the two key sets.
  295. DocumentKeySet keysToRecalc = changedDocKeys;
  296. for (const DocumentKey &key : releasedWriteKeys) {
  297. keysToRecalc = keysToRecalc.insert(key);
  298. }
  299. return [self.localDocuments documentsForKeys:keysToRecalc];
  300. });
  301. }
  302. - (void)notifyLocalViewChanges:(NSArray<FSTLocalViewChanges *> *)viewChanges {
  303. self.persistence.run("NotifyLocalViewChanges", [&]() {
  304. FSTReferenceSet *localViewReferences = self.localViewReferences;
  305. for (FSTLocalViewChanges *view in viewChanges) {
  306. FSTQueryData *queryData = [self.queryCache queryDataForQuery:view.query];
  307. FSTAssert(queryData, @"Local view changes contain unallocated query.");
  308. FSTTargetID targetID = queryData.targetID;
  309. for (const DocumentKey &key : view.removedKeys) {
  310. [self->_persistence.referenceDelegate removeReference:key target:targetID];
  311. }
  312. [localViewReferences addReferencesToKeys:view.addedKeys forID:targetID];
  313. [localViewReferences removeReferencesToKeys:view.removedKeys forID:targetID];
  314. }
  315. });
  316. }
  317. - (nullable FSTMutationBatch *)nextMutationBatchAfterBatchID:(FSTBatchID)batchID {
  318. FSTMutationBatch *result =
  319. self.persistence.run("NextMutationBatchAfterBatchID", [&]() -> FSTMutationBatch * {
  320. return [self.mutationQueue nextMutationBatchAfterBatchID:batchID];
  321. });
  322. return result;
  323. }
  324. - (nullable FSTMaybeDocument *)readDocument:(const DocumentKey &)key {
  325. return self.persistence.run("ReadDocument", [&]() -> FSTMaybeDocument *_Nullable {
  326. return [self.localDocuments documentForKey:key];
  327. });
  328. }
  329. - (FSTQueryData *)allocateQuery:(FSTQuery *)query {
  330. FSTQueryData *queryData = self.persistence.run("Allocate query", [&]() -> FSTQueryData * {
  331. FSTQueryData *cached = [self.queryCache queryDataForQuery:query];
  332. // TODO(mcg): freshen last accessed date if cached exists?
  333. if (!cached) {
  334. cached = [[FSTQueryData alloc] initWithQuery:query
  335. targetID:_targetIDGenerator.NextId()
  336. listenSequenceNumber:[self.listenSequence next]
  337. purpose:FSTQueryPurposeListen];
  338. [self.queryCache addQueryData:cached];
  339. }
  340. return cached;
  341. });
  342. // Sanity check to ensure that even when resuming a query it's not currently active.
  343. FSTBoxedTargetID *boxedTargetID = @(queryData.targetID);
  344. FSTAssert(!self.targetIDs[boxedTargetID], @"Tried to allocate an already allocated query: %@",
  345. query);
  346. self.targetIDs[boxedTargetID] = queryData;
  347. return queryData;
  348. }
  349. - (void)releaseQuery:(FSTQuery *)query {
  350. self.persistence.run("Release query", [&]() {
  351. FSTQueryData *queryData = [self.queryCache queryDataForQuery:query];
  352. FSTAssert(queryData, @"Tried to release nonexistent query: %@", query);
  353. [self.localViewReferences removeReferencesForID:queryData.targetID];
  354. if (self.garbageCollector.isEager) {
  355. [self.queryCache removeQueryData:queryData];
  356. }
  357. [self.persistence.referenceDelegate removeTarget:queryData];
  358. [self.targetIDs removeObjectForKey:@(queryData.targetID)];
  359. // If this was the last watch target, then we won't get any more watch snapshots, so we should
  360. // release any held batch results.
  361. if ([self.targetIDs count] == 0) {
  362. [self releaseHeldBatchResults];
  363. }
  364. });
  365. }
  366. - (FSTDocumentDictionary *)executeQuery:(FSTQuery *)query {
  367. return self.persistence.run("ExecuteQuery", [&]() -> FSTDocumentDictionary * {
  368. return [self.localDocuments documentsMatchingQuery:query];
  369. });
  370. }
  371. - (DocumentKeySet)remoteDocumentKeysForTarget:(FSTTargetID)targetID {
  372. return self.persistence.run("RemoteDocumentKeysForTarget", [&]() -> DocumentKeySet {
  373. return [self.queryCache matchingKeysForTargetID:targetID];
  374. });
  375. }
  376. - (void)collectGarbage {
  377. self.persistence.run("Garbage Collection", [&]() {
  378. // Call collectGarbage regardless of whether isGCEnabled so the referenceSet doesn't continue to
  379. // accumulate the garbage keys.
  380. std::set<DocumentKey> garbage = [self.garbageCollector collectGarbage];
  381. if (garbage.size() > 0) {
  382. for (const DocumentKey &key : garbage) {
  383. [self.remoteDocumentCache removeEntryForKey:key];
  384. }
  385. }
  386. });
  387. }
  388. /**
  389. * Releases all the held mutation batches up to the current remote version received, and
  390. * applies their mutations to the docs in the remote documents cache.
  391. *
  392. * @return the set of keys of docs that were modified by those writes.
  393. */
  394. - (DocumentKeySet)releaseHeldBatchResults {
  395. NSMutableArray<FSTMutationBatchResult *> *toRelease = [NSMutableArray array];
  396. for (FSTMutationBatchResult *batchResult in self.heldBatchResults) {
  397. if (![self isRemoteUpToVersion:batchResult.commitVersion]) {
  398. break;
  399. }
  400. [toRelease addObject:batchResult];
  401. }
  402. if (toRelease.count == 0) {
  403. return DocumentKeySet{};
  404. } else {
  405. [self.heldBatchResults removeObjectsInRange:NSMakeRange(0, toRelease.count)];
  406. return [self releaseBatchResults:toRelease];
  407. }
  408. }
  409. - (BOOL)isRemoteUpToVersion:(const SnapshotVersion &)version {
  410. // If there are no watch targets, then we won't get remote snapshots, and are always "up-to-date."
  411. return version <= self.queryCache.lastRemoteSnapshotVersion || self.targetIDs.count == 0;
  412. }
  413. - (BOOL)shouldHoldBatchResultWithVersion:(const SnapshotVersion &)version {
  414. // Check if watcher isn't up to date or prior results are already held.
  415. return ![self isRemoteUpToVersion:version] || self.heldBatchResults.count > 0;
  416. }
  417. - (DocumentKeySet)releaseBatchResults:(NSArray<FSTMutationBatchResult *> *)batchResults {
  418. NSMutableArray<FSTMutationBatch *> *batches = [NSMutableArray array];
  419. for (FSTMutationBatchResult *batchResult in batchResults) {
  420. [self applyBatchResult:batchResult];
  421. [batches addObject:batchResult.batch];
  422. }
  423. return [self removeMutationBatches:batches];
  424. }
  425. - (DocumentKeySet)removeMutationBatch:(FSTMutationBatch *)batch {
  426. return [self removeMutationBatches:@[ batch ]];
  427. }
  428. /** Removes all the mutation batches named in the given array. */
  429. - (DocumentKeySet)removeMutationBatches:(NSArray<FSTMutationBatch *> *)batches {
  430. DocumentKeySet affectedDocs;
  431. for (FSTMutationBatch *batch in batches) {
  432. for (FSTMutation *mutation in batch.mutations) {
  433. const DocumentKey &key = mutation.key;
  434. affectedDocs = affectedDocs.insert(key);
  435. }
  436. }
  437. [self.mutationQueue removeMutationBatches:batches];
  438. return affectedDocs;
  439. }
  440. - (void)applyBatchResult:(FSTMutationBatchResult *)batchResult {
  441. FSTMutationBatch *batch = batchResult.batch;
  442. DocumentKeySet docKeys = batch.keys;
  443. const DocumentVersionMap &versions = batchResult.docVersions;
  444. for (const DocumentKey &docKey : docKeys) {
  445. FSTMaybeDocument *_Nullable remoteDoc = [self.remoteDocumentCache entryForKey:docKey];
  446. FSTMaybeDocument *_Nullable doc = remoteDoc;
  447. auto ackVersionIter = versions.find(docKey);
  448. FSTAssert(ackVersionIter != versions.end(),
  449. @"docVersions should contain every doc in the write.");
  450. const SnapshotVersion &ackVersion = ackVersionIter->second;
  451. if (!doc || doc.version < ackVersion) {
  452. doc = [batch applyTo:doc documentKey:docKey mutationBatchResult:batchResult];
  453. if (!doc) {
  454. FSTAssert(!remoteDoc, @"Mutation batch %@ applied to document %@ resulted in nil.", batch,
  455. remoteDoc);
  456. } else {
  457. [self.remoteDocumentCache addEntry:doc];
  458. }
  459. }
  460. }
  461. }
  462. @end
  463. NS_ASSUME_NONNULL_END