FSTLocalStore.mm 22 KB

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