FSTLocalStore.mm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. #include <unordered_map>
  19. #include <utility>
  20. #include <vector>
  21. #import "FIRTimestamp.h"
  22. #import "Firestore/Source/Core/FSTQuery.h"
  23. #import "Firestore/Source/Local/FSTLRUGarbageCollector.h"
  24. #import "Firestore/Source/Local/FSTLocalDocumentsView.h"
  25. #import "Firestore/Source/Local/FSTLocalViewChanges.h"
  26. #import "Firestore/Source/Local/FSTLocalWriteResult.h"
  27. #import "Firestore/Source/Local/FSTPersistence.h"
  28. #import "Firestore/Source/Local/FSTQueryData.h"
  29. #import "Firestore/Source/Model/FSTDocument.h"
  30. #import "Firestore/Source/Model/FSTMutation.h"
  31. #import "Firestore/Source/Model/FSTMutationBatch.h"
  32. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  33. #include "Firestore/core/src/firebase/firestore/core/target_id_generator.h"
  34. #include "Firestore/core/src/firebase/firestore/immutable/sorted_set.h"
  35. #include "Firestore/core/src/firebase/firestore/local/mutation_queue.h"
  36. #include "Firestore/core/src/firebase/firestore/local/query_cache.h"
  37. #include "Firestore/core/src/firebase/firestore/local/reference_set.h"
  38. #include "Firestore/core/src/firebase/firestore/local/remote_document_cache.h"
  39. #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
  40. #include "Firestore/core/src/firebase/firestore/remote/remote_event.h"
  41. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  42. #include "Firestore/core/src/firebase/firestore/util/log.h"
  43. using firebase::firestore::auth::User;
  44. using firebase::firestore::core::TargetIdGenerator;
  45. using firebase::firestore::local::LruResults;
  46. using firebase::firestore::local::MutationQueue;
  47. using firebase::firestore::local::QueryCache;
  48. using firebase::firestore::local::ReferenceSet;
  49. using firebase::firestore::local::RemoteDocumentCache;
  50. using firebase::firestore::model::BatchId;
  51. using firebase::firestore::model::DocumentKey;
  52. using firebase::firestore::model::DocumentKeySet;
  53. using firebase::firestore::model::DocumentMap;
  54. using firebase::firestore::model::DocumentVersionMap;
  55. using firebase::firestore::model::FieldMask;
  56. using firebase::firestore::model::FieldPath;
  57. using firebase::firestore::model::MaybeDocumentMap;
  58. using firebase::firestore::model::ListenSequenceNumber;
  59. using firebase::firestore::model::Precondition;
  60. using firebase::firestore::model::SnapshotVersion;
  61. using firebase::firestore::model::TargetId;
  62. using firebase::firestore::remote::RemoteEvent;
  63. using firebase::firestore::remote::TargetChange;
  64. NS_ASSUME_NONNULL_BEGIN
  65. /**
  66. * The maximum time to leave a resume token buffered without writing it out. This value is
  67. * arbitrary: it's long enough to avoid several writes (possibly indefinitely if updates come more
  68. * frequently than this) but short enough that restarting after crashing will still have a pretty
  69. * recent resume token.
  70. */
  71. static const int64_t kResumeTokenMaxAgeSeconds = 5 * 60; // 5 minutes
  72. @interface FSTLocalStore ()
  73. /** Manages our in-memory or durable persistence. */
  74. @property(nonatomic, strong, readonly) id<FSTPersistence> persistence;
  75. /** The "local" view of all documents (layering mutationQueue on top of remoteDocumentCache). */
  76. @property(nonatomic, nullable, strong) FSTLocalDocumentsView *localDocuments;
  77. /** Maps a query to the data about that query. */
  78. @property(nonatomic) QueryCache *queryCache;
  79. @end
  80. @implementation FSTLocalStore {
  81. /** Used to generate targetIDs for queries tracked locally. */
  82. TargetIdGenerator _targetIDGenerator;
  83. /** The set of all cached remote documents. */
  84. RemoteDocumentCache *_remoteDocumentCache;
  85. QueryCache *_queryCache;
  86. /** The set of all mutations that have been sent but not yet been applied to the backend. */
  87. MutationQueue *_mutationQueue;
  88. /** The set of document references maintained by any local views. */
  89. ReferenceSet _localViewReferences;
  90. /** Maps a targetID to data about its query. */
  91. std::unordered_map<TargetId, FSTQueryData *> _targetIDs;
  92. }
  93. - (instancetype)initWithPersistence:(id<FSTPersistence>)persistence
  94. initialUser:(const User &)initialUser {
  95. if (self = [super init]) {
  96. _persistence = persistence;
  97. _mutationQueue = [persistence mutationQueueForUser:initialUser];
  98. _remoteDocumentCache = [persistence remoteDocumentCache];
  99. _queryCache = [persistence queryCache];
  100. _localDocuments =
  101. [FSTLocalDocumentsView viewWithRemoteDocumentCache:_remoteDocumentCache
  102. mutationQueue:_mutationQueue
  103. indexManager:[persistence indexManager]];
  104. [_persistence.referenceDelegate addInMemoryPins:&_localViewReferences];
  105. _targetIDGenerator = TargetIdGenerator::QueryCacheTargetIdGenerator(0);
  106. }
  107. return self;
  108. }
  109. - (void)start {
  110. [self startMutationQueue];
  111. TargetId targetID = _queryCache->highest_target_id();
  112. _targetIDGenerator = TargetIdGenerator::QueryCacheTargetIdGenerator(targetID);
  113. }
  114. - (void)startMutationQueue {
  115. self.persistence.run("Start MutationQueue", [&]() { _mutationQueue->Start(); });
  116. }
  117. - (MaybeDocumentMap)userDidChange:(const User &)user {
  118. // Swap out the mutation queue, grabbing the pending mutation batches before and after.
  119. std::vector<FSTMutationBatch *> oldBatches = self.persistence.run(
  120. "OldBatches",
  121. [&]() -> std::vector<FSTMutationBatch *> { return _mutationQueue->AllMutationBatches(); });
  122. // The old one has a reference to the mutation queue, so nil it out first.
  123. self.localDocuments = nil;
  124. _mutationQueue = [self.persistence mutationQueueForUser:user];
  125. [self startMutationQueue];
  126. return self.persistence.run("NewBatches", [&]() -> MaybeDocumentMap {
  127. std::vector<FSTMutationBatch *> newBatches = _mutationQueue->AllMutationBatches();
  128. // Recreate our LocalDocumentsView using the new MutationQueue.
  129. self.localDocuments =
  130. [FSTLocalDocumentsView viewWithRemoteDocumentCache:_remoteDocumentCache
  131. mutationQueue:_mutationQueue
  132. indexManager:[_persistence indexManager]];
  133. // Union the old/new changed keys.
  134. DocumentKeySet changedKeys;
  135. for (const std::vector<FSTMutationBatch *> &batches : {oldBatches, newBatches}) {
  136. for (FSTMutationBatch *batch : batches) {
  137. for (FSTMutation *mutation : [batch mutations]) {
  138. changedKeys = changedKeys.insert(mutation.key);
  139. }
  140. }
  141. }
  142. // Return the set of all (potentially) changed documents as the result of the user change.
  143. return [self.localDocuments documentsForKeys:changedKeys];
  144. });
  145. }
  146. - (FSTLocalWriteResult *)locallyWriteMutations:(std::vector<FSTMutation *> &&)mutations {
  147. FIRTimestamp *localWriteTime = [FIRTimestamp timestamp];
  148. DocumentKeySet keys;
  149. for (FSTMutation *mutation : mutations) {
  150. keys = keys.insert(mutation.key);
  151. }
  152. return self.persistence.run("Locally write mutations", [&]() -> FSTLocalWriteResult * {
  153. // Load and apply all existing mutations. This lets us compute the current base state for
  154. // all non-idempotent transforms before applying any additional user-provided writes.
  155. MaybeDocumentMap existingDocuments = [self.localDocuments documentsForKeys:keys];
  156. // For non-idempotent mutations (such as `FieldValue.increment()`), we record the base
  157. // state in a separate patch mutation. This is later used to guarantee consistent values
  158. // and prevents flicker even if the backend sends us an update that already includes our
  159. // transform.
  160. std::vector<FSTMutation *> baseMutations;
  161. for (FSTMutation *mutation : mutations) {
  162. if (mutation.idempotent) {
  163. continue;
  164. }
  165. // Theoretically, we should only include non-idempotent fields in this field mask as this mask
  166. // is used to prevent flicker for non-idempotent transforms by providing consistent base
  167. // values. By including the fields for all DocumentTransforms, we incorrectly prevent rebasing
  168. // of idempotent transforms (such as `arrayUnion()`) when any non-idempotent transforms are
  169. // present.
  170. // TODO(mrschmidt): Expose a method that only returns the a field mask for non-idempotent
  171. // transforms
  172. const FieldMask *fieldMask = [mutation fieldMask];
  173. if (fieldMask) {
  174. // `documentsForKeys` is guaranteed to return a (nullable) entry for every document key.
  175. FSTMaybeDocument *maybeDocument = existingDocuments.find(mutation.key)->second;
  176. FSTObjectValue *baseValues =
  177. [maybeDocument isKindOfClass:[FSTDocument class]]
  178. ? [((FSTDocument *)maybeDocument).data objectByApplyingFieldMask:*fieldMask]
  179. : [FSTObjectValue objectValue];
  180. // NOTE: The base state should only be applied if there's some existing document to
  181. // override, so use a Precondition of exists=true
  182. baseMutations.push_back([[FSTPatchMutation alloc] initWithKey:mutation.key
  183. fieldMask:*fieldMask
  184. value:baseValues
  185. precondition:Precondition::Exists(true)]);
  186. }
  187. }
  188. FSTMutationBatch *batch = _mutationQueue->AddMutationBatch(
  189. localWriteTime, std::move(baseMutations), std::move(mutations));
  190. MaybeDocumentMap changedDocuments = [batch applyToLocalDocumentSet:existingDocuments];
  191. return [FSTLocalWriteResult resultForBatchID:batch.batchID changes:std::move(changedDocuments)];
  192. });
  193. }
  194. - (MaybeDocumentMap)acknowledgeBatchWithResult:(FSTMutationBatchResult *)batchResult {
  195. return self.persistence.run("Acknowledge batch", [&]() -> MaybeDocumentMap {
  196. FSTMutationBatch *batch = batchResult.batch;
  197. _mutationQueue->AcknowledgeBatch(batch, batchResult.streamToken);
  198. [self applyBatchResult:batchResult];
  199. _mutationQueue->PerformConsistencyCheck();
  200. return [self.localDocuments documentsForKeys:batch.keys];
  201. });
  202. }
  203. - (MaybeDocumentMap)rejectBatchID:(BatchId)batchID {
  204. return self.persistence.run("Reject batch", [&]() -> MaybeDocumentMap {
  205. FSTMutationBatch *toReject = _mutationQueue->LookupMutationBatch(batchID);
  206. HARD_ASSERT(toReject, "Attempt to reject nonexistent batch!");
  207. _mutationQueue->RemoveMutationBatch(toReject);
  208. _mutationQueue->PerformConsistencyCheck();
  209. return [self.localDocuments documentsForKeys:toReject.keys];
  210. });
  211. }
  212. - (nullable NSData *)lastStreamToken {
  213. return _mutationQueue->GetLastStreamToken();
  214. }
  215. - (void)setLastStreamToken:(nullable NSData *)streamToken {
  216. self.persistence.run("Set stream token",
  217. [&]() { _mutationQueue->SetLastStreamToken(streamToken); });
  218. }
  219. - (const SnapshotVersion &)lastRemoteSnapshotVersion {
  220. return self.queryCache->GetLastRemoteSnapshotVersion();
  221. }
  222. - (MaybeDocumentMap)applyRemoteEvent:(const RemoteEvent &)remoteEvent {
  223. return self.persistence.run("Apply remote event", [&]() -> MaybeDocumentMap {
  224. // TODO(gsoltis): move the sequence number into the reference delegate.
  225. ListenSequenceNumber sequenceNumber = self.persistence.currentSequenceNumber;
  226. DocumentKeySet authoritativeUpdates;
  227. for (const auto &entry : remoteEvent.target_changes()) {
  228. TargetId targetID = entry.first;
  229. const TargetChange &change = entry.second;
  230. // Do not ref/unref unassigned targetIDs - it may lead to leaks.
  231. auto found = _targetIDs.find(targetID);
  232. if (found == _targetIDs.end()) {
  233. continue;
  234. }
  235. FSTQueryData *queryData = found->second;
  236. // When a global snapshot contains updates (either add or modify) we can completely trust
  237. // these updates as authoritative and blindly apply them to our cache (as a defensive measure
  238. // to promote self-healing in the unfortunate case that our cache is ever somehow corrupted /
  239. // out-of-sync).
  240. //
  241. // If the document is only updated while removing it from a target then watch isn't obligated
  242. // to send the absolute latest version: it can send the first version that caused the document
  243. // not to match.
  244. for (const DocumentKey &key : change.added_documents()) {
  245. authoritativeUpdates = authoritativeUpdates.insert(key);
  246. }
  247. for (const DocumentKey &key : change.modified_documents()) {
  248. authoritativeUpdates = authoritativeUpdates.insert(key);
  249. }
  250. _queryCache->RemoveMatchingKeys(change.removed_documents(), targetID);
  251. _queryCache->AddMatchingKeys(change.added_documents(), targetID);
  252. // Update the resume token if the change includes one. Don't clear any preexisting value.
  253. // Bump the sequence number as well, so that documents being removed now are ordered later
  254. // than documents that were previously removed from this target.
  255. NSData *resumeToken = change.resume_token();
  256. if (resumeToken.length > 0) {
  257. FSTQueryData *oldQueryData = queryData;
  258. queryData = [queryData queryDataByReplacingSnapshotVersion:remoteEvent.snapshot_version()
  259. resumeToken:resumeToken
  260. sequenceNumber:sequenceNumber];
  261. _targetIDs[targetID] = queryData;
  262. if ([self shouldPersistQueryData:queryData oldQueryData:oldQueryData change:change]) {
  263. _queryCache->UpdateTarget(queryData);
  264. }
  265. }
  266. }
  267. MaybeDocumentMap changedDocs;
  268. const DocumentKeySet &limboDocuments = remoteEvent.limbo_document_changes();
  269. DocumentKeySet updatedKeys;
  270. for (const auto &kv : remoteEvent.document_updates()) {
  271. updatedKeys = updatedKeys.insert(kv.first);
  272. }
  273. // Each loop iteration only affects its "own" doc, so it's safe to get all the remote
  274. // documents in advance in a single call.
  275. MaybeDocumentMap existingDocs = _remoteDocumentCache->GetAll(updatedKeys);
  276. for (const auto &kv : remoteEvent.document_updates()) {
  277. const DocumentKey &key = kv.first;
  278. FSTMaybeDocument *doc = kv.second;
  279. FSTMaybeDocument *existingDoc = nil;
  280. auto foundExisting = existingDocs.find(key);
  281. if (foundExisting != existingDocs.end()) {
  282. existingDoc = foundExisting->second;
  283. }
  284. // If a document update isn't authoritative, make sure we don't apply an old document version
  285. // to the remote cache. We make an exception for SnapshotVersion.MIN which can happen for
  286. // manufactured events (e.g. in the case of a limbo document resolution failing).
  287. if (!existingDoc || doc.version == SnapshotVersion::None() ||
  288. (authoritativeUpdates.contains(doc.key) && !existingDoc.hasPendingWrites) ||
  289. doc.version >= existingDoc.version) {
  290. _remoteDocumentCache->Add(doc);
  291. changedDocs = changedDocs.insert(key, doc);
  292. } else {
  293. LOG_DEBUG("FSTLocalStore Ignoring outdated watch update for %s. "
  294. "Current version: %s Watch version: %s",
  295. key.ToString(), existingDoc.version.timestamp().ToString(),
  296. doc.version.timestamp().ToString());
  297. }
  298. // If this was a limbo resolution, make sure we mark when it was accessed.
  299. if (limboDocuments.contains(key)) {
  300. [self.persistence.referenceDelegate limboDocumentUpdated:key];
  301. }
  302. }
  303. // HACK: The only reason we allow omitting snapshot version is so we can synthesize remote
  304. // events when we get permission denied errors while trying to resolve the state of a locally
  305. // cached document that is in limbo.
  306. const SnapshotVersion &lastRemoteVersion = _queryCache->GetLastRemoteSnapshotVersion();
  307. const SnapshotVersion &remoteVersion = remoteEvent.snapshot_version();
  308. if (remoteVersion != SnapshotVersion::None()) {
  309. HARD_ASSERT(remoteVersion >= lastRemoteVersion,
  310. "Watch stream reverted to previous snapshot?? (%s < %s)",
  311. remoteVersion.timestamp().ToString(), lastRemoteVersion.timestamp().ToString());
  312. _queryCache->SetLastRemoteSnapshotVersion(remoteVersion);
  313. }
  314. return [self.localDocuments localViewsForDocuments:changedDocs];
  315. });
  316. }
  317. /**
  318. * Returns YES if the newQueryData should be persisted during an update of an active target.
  319. * QueryData should always be persisted when a target is being released and should not call this
  320. * function.
  321. *
  322. * While the target is active, QueryData updates can be omitted when nothing about the target has
  323. * changed except metadata like the resume token or snapshot version. Occasionally it's worth the
  324. * extra write to prevent these values from getting too stale after a crash, but this doesn't have
  325. * to be too frequent.
  326. */
  327. - (BOOL)shouldPersistQueryData:(FSTQueryData *)newQueryData
  328. oldQueryData:(FSTQueryData *)oldQueryData
  329. change:(const TargetChange &)change {
  330. // Avoid clearing any existing value
  331. if (newQueryData.resumeToken.length == 0) return NO;
  332. // Any resume token is interesting if there isn't one already.
  333. if (oldQueryData.resumeToken.length == 0) return YES;
  334. // Don't allow resume token changes to be buffered indefinitely. This allows us to be reasonably
  335. // up-to-date after a crash and avoids needing to loop over all active queries on shutdown.
  336. // Especially in the browser we may not get time to do anything interesting while the current
  337. // tab is closing.
  338. int64_t newSeconds = newQueryData.snapshotVersion.timestamp().seconds();
  339. int64_t oldSeconds = oldQueryData.snapshotVersion.timestamp().seconds();
  340. int64_t timeDelta = newSeconds - oldSeconds;
  341. if (timeDelta >= kResumeTokenMaxAgeSeconds) return YES;
  342. // Otherwise if the only thing that has changed about a target is its resume token then it's not
  343. // worth persisting. Note that the RemoteStore keeps an in-memory view of the currently active
  344. // targets which includes the current resume token, so stream failure or user changes will still
  345. // use an up-to-date resume token regardless of what we do here.
  346. size_t changes = change.added_documents().size() + change.modified_documents().size() +
  347. change.removed_documents().size();
  348. return changes > 0;
  349. }
  350. - (void)notifyLocalViewChanges:(NSArray<FSTLocalViewChanges *> *)viewChanges {
  351. self.persistence.run("NotifyLocalViewChanges", [&]() {
  352. for (FSTLocalViewChanges *viewChange in viewChanges) {
  353. for (const DocumentKey &key : viewChange.removedKeys) {
  354. [self->_persistence.referenceDelegate removeReference:key];
  355. }
  356. _localViewReferences.AddReferences(viewChange.addedKeys, viewChange.targetID);
  357. _localViewReferences.AddReferences(viewChange.removedKeys, viewChange.targetID);
  358. }
  359. });
  360. }
  361. - (nullable FSTMutationBatch *)nextMutationBatchAfterBatchID:(BatchId)batchID {
  362. FSTMutationBatch *result =
  363. self.persistence.run("NextMutationBatchAfterBatchID", [&]() -> FSTMutationBatch * {
  364. return _mutationQueue->NextMutationBatchAfterBatchId(batchID);
  365. });
  366. return result;
  367. }
  368. - (nullable FSTMaybeDocument *)readDocument:(const DocumentKey &)key {
  369. return self.persistence.run("ReadDocument", [&]() -> FSTMaybeDocument *_Nullable {
  370. return [self.localDocuments documentForKey:key];
  371. });
  372. }
  373. - (FSTQueryData *)allocateQuery:(FSTQuery *)query {
  374. FSTQueryData *queryData = self.persistence.run("Allocate query", [&]() -> FSTQueryData * {
  375. FSTQueryData *cached = _queryCache->GetTarget(query);
  376. // TODO(mcg): freshen last accessed date if cached exists?
  377. if (!cached) {
  378. cached = [[FSTQueryData alloc] initWithQuery:query
  379. targetID:_targetIDGenerator.NextId()
  380. listenSequenceNumber:self.persistence.currentSequenceNumber
  381. purpose:FSTQueryPurposeListen];
  382. _queryCache->AddTarget(cached);
  383. }
  384. return cached;
  385. });
  386. // Sanity check to ensure that even when resuming a query it's not currently active.
  387. TargetId targetID = queryData.targetID;
  388. HARD_ASSERT(_targetIDs.find(targetID) == _targetIDs.end(),
  389. "Tried to allocate an already allocated query: %s", query);
  390. _targetIDs[targetID] = queryData;
  391. return queryData;
  392. }
  393. - (void)releaseQuery:(FSTQuery *)query {
  394. self.persistence.run("Release query", [&]() {
  395. FSTQueryData *queryData = _queryCache->GetTarget(query);
  396. HARD_ASSERT(queryData, "Tried to release nonexistent query: %s", query);
  397. TargetId targetID = queryData.targetID;
  398. auto found = _targetIDs.find(targetID);
  399. FSTQueryData *cachedQueryData = found != _targetIDs.end() ? found->second : nil;
  400. if (cachedQueryData.snapshotVersion > queryData.snapshotVersion) {
  401. // If we've been avoiding persisting the resumeToken (see shouldPersistQueryData for
  402. // conditions and rationale) we need to persist the token now because there will no
  403. // longer be an in-memory version to fall back on.
  404. queryData = cachedQueryData;
  405. _queryCache->UpdateTarget(queryData);
  406. }
  407. // References for documents sent via Watch are automatically removed when we delete a
  408. // query's target data from the reference delegate. Since this does not remove references
  409. // for locally mutated documents, we have to remove the target associations for these
  410. // documents manually.
  411. DocumentKeySet removed = _localViewReferences.RemoveReferences(targetID);
  412. for (const DocumentKey &key : removed) {
  413. [self.persistence.referenceDelegate removeReference:key];
  414. }
  415. _targetIDs.erase(targetID);
  416. [self.persistence.referenceDelegate removeTarget:queryData];
  417. });
  418. }
  419. - (DocumentMap)executeQuery:(FSTQuery *)query {
  420. return self.persistence.run("ExecuteQuery", [&]() -> DocumentMap {
  421. return [self.localDocuments documentsMatchingQuery:query];
  422. });
  423. }
  424. - (DocumentKeySet)remoteDocumentKeysForTarget:(TargetId)targetID {
  425. return self.persistence.run("RemoteDocumentKeysForTarget", [&]() -> DocumentKeySet {
  426. return _queryCache->GetMatchingKeys(targetID);
  427. });
  428. }
  429. - (void)applyBatchResult:(FSTMutationBatchResult *)batchResult {
  430. FSTMutationBatch *batch = batchResult.batch;
  431. DocumentKeySet docKeys = batch.keys;
  432. const DocumentVersionMap &versions = batchResult.docVersions;
  433. for (const DocumentKey &docKey : docKeys) {
  434. FSTMaybeDocument *_Nullable remoteDoc = _remoteDocumentCache->Get(docKey);
  435. FSTMaybeDocument *_Nullable doc = remoteDoc;
  436. auto ackVersionIter = versions.find(docKey);
  437. HARD_ASSERT(ackVersionIter != versions.end(),
  438. "docVersions should contain every doc in the write.");
  439. const SnapshotVersion &ackVersion = ackVersionIter->second;
  440. if (!doc || doc.version < ackVersion) {
  441. doc = [batch applyToRemoteDocument:doc documentKey:docKey mutationBatchResult:batchResult];
  442. if (!doc) {
  443. HARD_ASSERT(!remoteDoc, "Mutation batch %s applied to document %s resulted in nil.", batch,
  444. remoteDoc);
  445. } else {
  446. _remoteDocumentCache->Add(doc);
  447. }
  448. }
  449. }
  450. _mutationQueue->RemoveMutationBatch(batch);
  451. }
  452. - (LruResults)collectGarbage:(FSTLRUGarbageCollector *)garbageCollector {
  453. return self.persistence.run("Collect garbage", [&]() -> LruResults {
  454. return [garbageCollector collectWithLiveTargets:_targetIDs];
  455. });
  456. }
  457. @end
  458. NS_ASSUME_NONNULL_END