FSTLocalStore.mm 22 KB

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