FSTLocalStore.m 23 KB

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