FSTLocalStore.mm 21 KB

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