FSTLocalStore.mm 23 KB

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