2017-10-03 08:55:22 -07:00
|
|
|
/*
|
|
|
|
|
* Copyright 2017 Google
|
|
|
|
|
*
|
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
|
*
|
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
*
|
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
|
* limitations under the License.
|
|
|
|
|
*/
|
|
|
|
|
|
2017-11-16 20:52:01 -08:00
|
|
|
#import "Firestore/Source/Local/FSTLocalStore.h"
|
2017-10-03 08:55:22 -07:00
|
|
|
|
2019-03-22 13:46:48 -07:00
|
|
|
#include <memory>
|
2018-04-09 11:54:39 -07:00
|
|
|
#include <set>
|
2019-01-24 17:01:31 -05:00
|
|
|
#include <unordered_map>
|
2018-12-10 11:57:08 -08:00
|
|
|
#include <utility>
|
2019-01-29 16:01:59 -08:00
|
|
|
#include <vector>
|
2018-04-09 11:54:39 -07:00
|
|
|
|
2018-02-20 17:33:57 -05:00
|
|
|
#import "FIRTimestamp.h"
|
2017-11-16 20:52:01 -08:00
|
|
|
#import "Firestore/Source/Core/FSTQuery.h"
|
2018-11-26 14:33:28 -08:00
|
|
|
#import "Firestore/Source/Local/FSTLRUGarbageCollector.h"
|
2017-11-16 20:52:01 -08:00
|
|
|
#import "Firestore/Source/Local/FSTLocalViewChanges.h"
|
|
|
|
|
#import "Firestore/Source/Local/FSTLocalWriteResult.h"
|
|
|
|
|
#import "Firestore/Source/Local/FSTPersistence.h"
|
|
|
|
|
#import "Firestore/Source/Local/FSTQueryData.h"
|
|
|
|
|
#import "Firestore/Source/Model/FSTDocument.h"
|
|
|
|
|
#import "Firestore/Source/Model/FSTMutation.h"
|
|
|
|
|
#import "Firestore/Source/Model/FSTMutationBatch.h"
|
2017-10-03 08:55:22 -07:00
|
|
|
|
2018-02-15 17:23:08 -05:00
|
|
|
#include "Firestore/core/src/firebase/firestore/auth/user.h"
|
2018-01-25 18:39:46 -05:00
|
|
|
#include "Firestore/core/src/firebase/firestore/core/target_id_generator.h"
|
2018-12-10 11:57:08 -08:00
|
|
|
#include "Firestore/core/src/firebase/firestore/immutable/sorted_set.h"
|
2019-03-22 13:46:48 -07:00
|
|
|
#include "Firestore/core/src/firebase/firestore/local/local_documents_view.h"
|
2019-01-29 16:01:59 -08:00
|
|
|
#include "Firestore/core/src/firebase/firestore/local/mutation_queue.h"
|
2018-12-21 22:08:34 -08:00
|
|
|
#include "Firestore/core/src/firebase/firestore/local/query_cache.h"
|
2018-12-21 21:03:13 -08:00
|
|
|
#include "Firestore/core/src/firebase/firestore/local/reference_set.h"
|
2018-12-18 13:24:35 -08:00
|
|
|
#include "Firestore/core/src/firebase/firestore/local/remote_document_cache.h"
|
2019-03-22 13:46:48 -07:00
|
|
|
#include "Firestore/core/src/firebase/firestore/model/document_key_set.h"
|
|
|
|
|
#include "Firestore/core/src/firebase/firestore/model/document_map.h"
|
2018-04-25 14:05:36 -04:00
|
|
|
#include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
|
2019-01-29 15:10:18 -05:00
|
|
|
#include "Firestore/core/src/firebase/firestore/remote/remote_event.h"
|
2018-05-24 11:00:23 -07:00
|
|
|
#include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
|
2018-05-23 07:00:05 -07:00
|
|
|
#include "Firestore/core/src/firebase/firestore/util/log.h"
|
2019-03-22 13:46:48 -07:00
|
|
|
#include "absl/memory/memory.h"
|
2018-01-25 18:39:46 -05:00
|
|
|
|
2018-02-15 17:23:08 -05:00
|
|
|
using firebase::firestore::auth::User;
|
2018-02-06 13:51:11 -05:00
|
|
|
using firebase::firestore::core::TargetIdGenerator;
|
2019-03-22 13:46:48 -07:00
|
|
|
using firebase::firestore::local::LocalDocumentsView;
|
2018-11-26 14:33:28 -08:00
|
|
|
using firebase::firestore::local::LruResults;
|
2019-01-29 16:01:59 -08:00
|
|
|
using firebase::firestore::local::MutationQueue;
|
2018-12-21 22:08:34 -08:00
|
|
|
using firebase::firestore::local::QueryCache;
|
2018-12-21 21:03:13 -08:00
|
|
|
using firebase::firestore::local::ReferenceSet;
|
2018-12-18 13:24:35 -08:00
|
|
|
using firebase::firestore::local::RemoteDocumentCache;
|
2018-08-16 10:44:26 -07:00
|
|
|
using firebase::firestore::model::BatchId;
|
2018-03-24 11:06:32 -04:00
|
|
|
using firebase::firestore::model::DocumentKey;
|
2018-05-05 08:10:51 -07:00
|
|
|
using firebase::firestore::model::DocumentKeySet;
|
2018-12-10 11:57:08 -08:00
|
|
|
using firebase::firestore::model::DocumentMap;
|
2018-05-05 09:00:53 -07:00
|
|
|
using firebase::firestore::model::DocumentVersionMap;
|
2019-03-06 14:51:30 -08:00
|
|
|
using firebase::firestore::model::FieldMask;
|
|
|
|
|
using firebase::firestore::model::FieldPath;
|
2018-12-10 11:57:08 -08:00
|
|
|
using firebase::firestore::model::MaybeDocumentMap;
|
2018-08-16 14:02:03 -07:00
|
|
|
using firebase::firestore::model::ListenSequenceNumber;
|
2019-03-06 14:51:30 -08:00
|
|
|
using firebase::firestore::model::Precondition;
|
2018-08-15 15:56:45 -07:00
|
|
|
using firebase::firestore::model::SnapshotVersion;
|
|
|
|
|
using firebase::firestore::model::TargetId;
|
2019-01-29 18:55:25 -05:00
|
|
|
using firebase::firestore::remote::RemoteEvent;
|
2019-01-29 15:10:18 -05:00
|
|
|
using firebase::firestore::remote::TargetChange;
|
2018-02-06 13:51:11 -05:00
|
|
|
|
2017-10-03 08:55:22 -07:00
|
|
|
NS_ASSUME_NONNULL_BEGIN
|
|
|
|
|
|
2018-08-15 17:24:20 -07:00
|
|
|
/**
|
|
|
|
|
* The maximum time to leave a resume token buffered without writing it out. This value is
|
|
|
|
|
* arbitrary: it's long enough to avoid several writes (possibly indefinitely if updates come more
|
|
|
|
|
* frequently than this) but short enough that restarting after crashing will still have a pretty
|
|
|
|
|
* recent resume token.
|
|
|
|
|
*/
|
|
|
|
|
static const int64_t kResumeTokenMaxAgeSeconds = 5 * 60; // 5 minutes
|
|
|
|
|
|
2017-10-03 08:55:22 -07:00
|
|
|
@interface FSTLocalStore ()
|
|
|
|
|
|
|
|
|
|
/** Manages our in-memory or durable persistence. */
|
|
|
|
|
@property(nonatomic, strong, readonly) id<FSTPersistence> persistence;
|
|
|
|
|
|
|
|
|
|
/** Maps a query to the data about that query. */
|
2018-12-21 22:08:34 -08:00
|
|
|
@property(nonatomic) QueryCache *queryCache;
|
2017-10-03 08:55:22 -07:00
|
|
|
|
|
|
|
|
@end
|
|
|
|
|
|
2018-01-25 18:39:46 -05:00
|
|
|
@implementation FSTLocalStore {
|
|
|
|
|
/** Used to generate targetIDs for queries tracked locally. */
|
2018-02-06 13:51:11 -05:00
|
|
|
TargetIdGenerator _targetIDGenerator;
|
2018-12-18 13:24:35 -08:00
|
|
|
/** The set of all cached remote documents. */
|
|
|
|
|
RemoteDocumentCache *_remoteDocumentCache;
|
2018-12-21 22:08:34 -08:00
|
|
|
QueryCache *_queryCache;
|
2019-01-29 16:01:59 -08:00
|
|
|
/** The set of all mutations that have been sent but not yet been applied to the backend. */
|
|
|
|
|
MutationQueue *_mutationQueue;
|
2018-12-21 21:03:13 -08:00
|
|
|
|
2019-03-22 13:46:48 -07:00
|
|
|
/** The "local" view of all documents (layering mutationQueue on top of remoteDocumentCache). */
|
|
|
|
|
std::unique_ptr<LocalDocumentsView> _localDocuments;
|
|
|
|
|
|
2018-12-21 21:03:13 -08:00
|
|
|
/** The set of document references maintained by any local views. */
|
|
|
|
|
ReferenceSet _localViewReferences;
|
2019-01-24 17:01:31 -05:00
|
|
|
|
|
|
|
|
/** Maps a targetID to data about its query. */
|
|
|
|
|
std::unordered_map<TargetId, FSTQueryData *> _targetIDs;
|
2018-01-25 18:39:46 -05:00
|
|
|
}
|
2017-10-03 08:55:22 -07:00
|
|
|
|
|
|
|
|
- (instancetype)initWithPersistence:(id<FSTPersistence>)persistence
|
2018-02-15 17:23:08 -05:00
|
|
|
initialUser:(const User &)initialUser {
|
2017-10-03 08:55:22 -07:00
|
|
|
if (self = [super init]) {
|
|
|
|
|
_persistence = persistence;
|
|
|
|
|
_mutationQueue = [persistence mutationQueueForUser:initialUser];
|
|
|
|
|
_remoteDocumentCache = [persistence remoteDocumentCache];
|
|
|
|
|
_queryCache = [persistence queryCache];
|
2019-03-22 13:46:48 -07:00
|
|
|
_localDocuments = absl::make_unique<LocalDocumentsView>(_remoteDocumentCache, _mutationQueue,
|
|
|
|
|
[_persistence indexManager]);
|
2018-12-21 21:03:13 -08:00
|
|
|
[_persistence.referenceDelegate addInMemoryPins:&_localViewReferences];
|
2017-10-03 08:55:22 -07:00
|
|
|
|
2018-11-07 11:22:01 -08:00
|
|
|
_targetIDGenerator = TargetIdGenerator::QueryCacheTargetIdGenerator(0);
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
return self;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
- (void)start {
|
|
|
|
|
[self startMutationQueue];
|
2018-12-21 22:08:34 -08:00
|
|
|
TargetId targetID = _queryCache->highest_target_id();
|
2018-11-07 11:22:01 -08:00
|
|
|
_targetIDGenerator = TargetIdGenerator::QueryCacheTargetIdGenerator(targetID);
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
- (void)startMutationQueue {
|
2019-01-29 16:01:59 -08:00
|
|
|
self.persistence.run("Start MutationQueue", [&]() { _mutationQueue->Start(); });
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2018-12-10 11:57:08 -08:00
|
|
|
- (MaybeDocumentMap)userDidChange:(const User &)user {
|
2017-10-03 08:55:22 -07:00
|
|
|
// Swap out the mutation queue, grabbing the pending mutation batches before and after.
|
2019-01-29 16:01:59 -08:00
|
|
|
std::vector<FSTMutationBatch *> oldBatches = self.persistence.run(
|
2018-03-30 10:18:25 -07:00
|
|
|
"OldBatches",
|
2019-01-29 16:01:59 -08:00
|
|
|
[&]() -> std::vector<FSTMutationBatch *> { return _mutationQueue->AllMutationBatches(); });
|
2017-10-03 08:55:22 -07:00
|
|
|
|
2019-01-29 16:01:59 -08:00
|
|
|
// The old one has a reference to the mutation queue, so nil it out first.
|
2019-03-22 13:46:48 -07:00
|
|
|
_localDocuments.reset();
|
2019-01-29 16:01:59 -08:00
|
|
|
_mutationQueue = [self.persistence mutationQueueForUser:user];
|
2017-10-03 08:55:22 -07:00
|
|
|
|
|
|
|
|
[self startMutationQueue];
|
|
|
|
|
|
2018-12-10 11:57:08 -08:00
|
|
|
return self.persistence.run("NewBatches", [&]() -> MaybeDocumentMap {
|
2019-01-29 16:01:59 -08:00
|
|
|
std::vector<FSTMutationBatch *> newBatches = _mutationQueue->AllMutationBatches();
|
2017-10-03 08:55:22 -07:00
|
|
|
|
2018-03-30 10:18:25 -07:00
|
|
|
// Recreate our LocalDocumentsView using the new MutationQueue.
|
2019-03-22 13:46:48 -07:00
|
|
|
_localDocuments = absl::make_unique<LocalDocumentsView>(_remoteDocumentCache, _mutationQueue,
|
|
|
|
|
[_persistence indexManager]);
|
2017-10-03 08:55:22 -07:00
|
|
|
|
2018-03-30 10:18:25 -07:00
|
|
|
// Union the old/new changed keys.
|
2018-05-05 08:10:51 -07:00
|
|
|
DocumentKeySet changedKeys;
|
2019-01-29 16:01:59 -08:00
|
|
|
for (const std::vector<FSTMutationBatch *> &batches : {oldBatches, newBatches}) {
|
|
|
|
|
for (FSTMutationBatch *batch : batches) {
|
2019-02-07 22:03:17 -05:00
|
|
|
for (FSTMutation *mutation : [batch mutations]) {
|
2018-05-05 08:10:51 -07:00
|
|
|
changedKeys = changedKeys.insert(mutation.key);
|
2018-03-30 10:18:25 -07:00
|
|
|
}
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-30 10:18:25 -07:00
|
|
|
// Return the set of all (potentially) changed documents as the result of the user change.
|
2019-03-22 13:46:48 -07:00
|
|
|
return _localDocuments->GetDocuments(changedKeys);
|
2018-03-30 10:18:25 -07:00
|
|
|
});
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2019-02-07 22:03:17 -05:00
|
|
|
- (FSTLocalWriteResult *)locallyWriteMutations:(std::vector<FSTMutation *> &&)mutations {
|
2019-03-06 14:51:30 -08:00
|
|
|
FIRTimestamp *localWriteTime = [FIRTimestamp timestamp];
|
|
|
|
|
DocumentKeySet keys;
|
|
|
|
|
for (FSTMutation *mutation : mutations) {
|
|
|
|
|
keys = keys.insert(mutation.key);
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-30 10:18:25 -07:00
|
|
|
return self.persistence.run("Locally write mutations", [&]() -> FSTLocalWriteResult * {
|
2019-03-06 14:51:30 -08:00
|
|
|
// Load and apply all existing mutations. This lets us compute the current base state for
|
|
|
|
|
// all non-idempotent transforms before applying any additional user-provided writes.
|
2019-03-22 13:46:48 -07:00
|
|
|
MaybeDocumentMap existingDocuments = _localDocuments->GetDocuments(keys);
|
2019-03-06 14:51:30 -08:00
|
|
|
|
|
|
|
|
// For non-idempotent mutations (such as `FieldValue.increment()`), we record the base
|
|
|
|
|
// state in a separate patch mutation. This is later used to guarantee consistent values
|
|
|
|
|
// and prevents flicker even if the backend sends us an update that already includes our
|
|
|
|
|
// transform.
|
|
|
|
|
std::vector<FSTMutation *> baseMutations;
|
|
|
|
|
for (FSTMutation *mutation : mutations) {
|
|
|
|
|
if (mutation.idempotent) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Theoretically, we should only include non-idempotent fields in this field mask as this mask
|
|
|
|
|
// is used to prevent flicker for non-idempotent transforms by providing consistent base
|
|
|
|
|
// values. By including the fields for all DocumentTransforms, we incorrectly prevent rebasing
|
|
|
|
|
// of idempotent transforms (such as `arrayUnion()`) when any non-idempotent transforms are
|
|
|
|
|
// present.
|
|
|
|
|
// TODO(mrschmidt): Expose a method that only returns the a field mask for non-idempotent
|
|
|
|
|
// transforms
|
|
|
|
|
const FieldMask *fieldMask = [mutation fieldMask];
|
|
|
|
|
if (fieldMask) {
|
|
|
|
|
// `documentsForKeys` is guaranteed to return a (nullable) entry for every document key.
|
|
|
|
|
FSTMaybeDocument *maybeDocument = existingDocuments.find(mutation.key)->second;
|
|
|
|
|
FSTObjectValue *baseValues =
|
|
|
|
|
[maybeDocument isKindOfClass:[FSTDocument class]]
|
|
|
|
|
? [((FSTDocument *)maybeDocument).data objectByApplyingFieldMask:*fieldMask]
|
|
|
|
|
: [FSTObjectValue objectValue];
|
|
|
|
|
// NOTE: The base state should only be applied if there's some existing document to
|
|
|
|
|
// override, so use a Precondition of exists=true
|
|
|
|
|
baseMutations.push_back([[FSTPatchMutation alloc] initWithKey:mutation.key
|
|
|
|
|
fieldMask:*fieldMask
|
|
|
|
|
value:baseValues
|
|
|
|
|
precondition:Precondition::Exists(true)]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
FSTMutationBatch *batch = _mutationQueue->AddMutationBatch(
|
|
|
|
|
localWriteTime, std::move(baseMutations), std::move(mutations));
|
|
|
|
|
MaybeDocumentMap changedDocuments = [batch applyToLocalDocumentSet:existingDocuments];
|
2018-12-10 11:57:08 -08:00
|
|
|
return [FSTLocalWriteResult resultForBatchID:batch.batchID changes:std::move(changedDocuments)];
|
2018-03-30 10:18:25 -07:00
|
|
|
});
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2018-12-10 11:57:08 -08:00
|
|
|
- (MaybeDocumentMap)acknowledgeBatchWithResult:(FSTMutationBatchResult *)batchResult {
|
|
|
|
|
return self.persistence.run("Acknowledge batch", [&]() -> MaybeDocumentMap {
|
2018-11-01 09:44:30 -07:00
|
|
|
FSTMutationBatch *batch = batchResult.batch;
|
2019-01-29 16:01:59 -08:00
|
|
|
_mutationQueue->AcknowledgeBatch(batch, batchResult.streamToken);
|
2018-11-01 09:44:30 -07:00
|
|
|
[self applyBatchResult:batchResult];
|
2019-01-29 16:01:59 -08:00
|
|
|
_mutationQueue->PerformConsistencyCheck();
|
2017-10-03 08:55:22 -07:00
|
|
|
|
2019-03-22 13:46:48 -07:00
|
|
|
return _localDocuments->GetDocuments(batch.keys);
|
2018-03-30 10:18:25 -07:00
|
|
|
});
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2018-12-10 11:57:08 -08:00
|
|
|
- (MaybeDocumentMap)rejectBatchID:(BatchId)batchID {
|
|
|
|
|
return self.persistence.run("Reject batch", [&]() -> MaybeDocumentMap {
|
2019-01-29 16:01:59 -08:00
|
|
|
FSTMutationBatch *toReject = _mutationQueue->LookupMutationBatch(batchID);
|
2018-05-24 11:00:23 -07:00
|
|
|
HARD_ASSERT(toReject, "Attempt to reject nonexistent batch!");
|
2017-10-03 08:55:22 -07:00
|
|
|
|
2019-01-29 16:01:59 -08:00
|
|
|
_mutationQueue->RemoveMutationBatch(toReject);
|
|
|
|
|
_mutationQueue->PerformConsistencyCheck();
|
2017-10-03 08:55:22 -07:00
|
|
|
|
2019-03-22 13:46:48 -07:00
|
|
|
return _localDocuments->GetDocuments(toReject.keys);
|
2018-03-30 10:18:25 -07:00
|
|
|
});
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
- (nullable NSData *)lastStreamToken {
|
2019-01-29 16:01:59 -08:00
|
|
|
return _mutationQueue->GetLastStreamToken();
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
- (void)setLastStreamToken:(nullable NSData *)streamToken {
|
2018-03-30 10:18:25 -07:00
|
|
|
self.persistence.run("Set stream token",
|
2019-01-29 16:01:59 -08:00
|
|
|
[&]() { _mutationQueue->SetLastStreamToken(streamToken); });
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2018-04-25 14:05:36 -04:00
|
|
|
- (const SnapshotVersion &)lastRemoteSnapshotVersion {
|
2018-12-21 22:08:34 -08:00
|
|
|
return self.queryCache->GetLastRemoteSnapshotVersion();
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2019-01-29 18:55:25 -05:00
|
|
|
- (MaybeDocumentMap)applyRemoteEvent:(const RemoteEvent &)remoteEvent {
|
2018-12-10 11:57:08 -08:00
|
|
|
return self.persistence.run("Apply remote event", [&]() -> MaybeDocumentMap {
|
2018-05-08 10:49:54 -07:00
|
|
|
// TODO(gsoltis): move the sequence number into the reference delegate.
|
2018-08-16 14:02:03 -07:00
|
|
|
ListenSequenceNumber sequenceNumber = self.persistence.currentSequenceNumber;
|
2017-10-03 08:55:22 -07:00
|
|
|
|
2018-07-19 07:15:47 -07:00
|
|
|
DocumentKeySet authoritativeUpdates;
|
2019-01-29 18:55:25 -05:00
|
|
|
for (const auto &entry : remoteEvent.target_changes()) {
|
2018-08-15 15:56:45 -07:00
|
|
|
TargetId targetID = entry.first;
|
2019-01-29 15:10:18 -05:00
|
|
|
const TargetChange &change = entry.second;
|
2017-10-03 08:55:22 -07:00
|
|
|
|
2018-03-30 10:18:25 -07:00
|
|
|
// Do not ref/unref unassigned targetIDs - it may lead to leaks.
|
2019-01-24 17:01:31 -05:00
|
|
|
auto found = _targetIDs.find(targetID);
|
|
|
|
|
if (found == _targetIDs.end()) {
|
2018-06-12 10:58:35 -07:00
|
|
|
continue;
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
2019-01-24 17:01:31 -05:00
|
|
|
FSTQueryData *queryData = found->second;
|
2018-03-30 10:18:25 -07:00
|
|
|
|
2018-07-19 07:15:47 -07:00
|
|
|
// When a global snapshot contains updates (either add or modify) we can completely trust
|
|
|
|
|
// these updates as authoritative and blindly apply them to our cache (as a defensive measure
|
|
|
|
|
// to promote self-healing in the unfortunate case that our cache is ever somehow corrupted /
|
|
|
|
|
// out-of-sync).
|
|
|
|
|
//
|
|
|
|
|
// If the document is only updated while removing it from a target then watch isn't obligated
|
|
|
|
|
// to send the absolute latest version: it can send the first version that caused the document
|
|
|
|
|
// not to match.
|
2019-01-29 15:10:18 -05:00
|
|
|
for (const DocumentKey &key : change.added_documents()) {
|
2018-07-19 07:15:47 -07:00
|
|
|
authoritativeUpdates = authoritativeUpdates.insert(key);
|
|
|
|
|
}
|
2019-01-29 15:10:18 -05:00
|
|
|
for (const DocumentKey &key : change.modified_documents()) {
|
2018-07-19 07:15:47 -07:00
|
|
|
authoritativeUpdates = authoritativeUpdates.insert(key);
|
|
|
|
|
}
|
|
|
|
|
|
2019-01-29 15:10:18 -05:00
|
|
|
_queryCache->RemoveMatchingKeys(change.removed_documents(), targetID);
|
|
|
|
|
_queryCache->AddMatchingKeys(change.added_documents(), targetID);
|
2018-06-12 10:58:35 -07:00
|
|
|
|
2018-05-03 12:11:39 -07:00
|
|
|
// Update the resume token if the change includes one. Don't clear any preexisting value.
|
|
|
|
|
// Bump the sequence number as well, so that documents being removed now are ordered later
|
|
|
|
|
// than documents that were previously removed from this target.
|
2019-01-29 15:10:18 -05:00
|
|
|
NSData *resumeToken = change.resume_token();
|
2018-05-03 12:11:39 -07:00
|
|
|
if (resumeToken.length > 0) {
|
2018-08-15 17:24:20 -07:00
|
|
|
FSTQueryData *oldQueryData = queryData;
|
2019-01-29 18:55:25 -05:00
|
|
|
queryData = [queryData queryDataByReplacingSnapshotVersion:remoteEvent.snapshot_version()
|
2018-05-03 12:11:39 -07:00
|
|
|
resumeToken:resumeToken
|
|
|
|
|
sequenceNumber:sequenceNumber];
|
2019-01-24 17:01:31 -05:00
|
|
|
_targetIDs[targetID] = queryData;
|
2018-08-15 17:24:20 -07:00
|
|
|
|
|
|
|
|
if ([self shouldPersistQueryData:queryData oldQueryData:oldQueryData change:change]) {
|
2018-12-21 22:08:34 -08:00
|
|
|
_queryCache->UpdateTarget(queryData);
|
2018-08-15 17:24:20 -07:00
|
|
|
}
|
2018-05-03 12:11:39 -07:00
|
|
|
}
|
2018-06-12 10:58:35 -07:00
|
|
|
}
|
2018-03-30 10:18:25 -07:00
|
|
|
|
2018-12-10 14:39:22 -08:00
|
|
|
MaybeDocumentMap changedDocs;
|
2019-01-29 18:55:25 -05:00
|
|
|
const DocumentKeySet &limboDocuments = remoteEvent.limbo_document_changes();
|
2018-12-10 14:39:22 -08:00
|
|
|
DocumentKeySet updatedKeys;
|
2019-01-29 18:55:25 -05:00
|
|
|
for (const auto &kv : remoteEvent.document_updates()) {
|
2018-12-10 14:39:22 -08:00
|
|
|
updatedKeys = updatedKeys.insert(kv.first);
|
|
|
|
|
}
|
|
|
|
|
// Each loop iteration only affects its "own" doc, so it's safe to get all the remote
|
|
|
|
|
// documents in advance in a single call.
|
2018-12-18 13:24:35 -08:00
|
|
|
MaybeDocumentMap existingDocs = _remoteDocumentCache->GetAll(updatedKeys);
|
2018-12-10 14:39:22 -08:00
|
|
|
|
2019-01-29 18:55:25 -05:00
|
|
|
for (const auto &kv : remoteEvent.document_updates()) {
|
2018-03-30 10:18:25 -07:00
|
|
|
const DocumentKey &key = kv.first;
|
|
|
|
|
FSTMaybeDocument *doc = kv.second;
|
2018-12-10 14:39:22 -08:00
|
|
|
FSTMaybeDocument *existingDoc = nil;
|
|
|
|
|
auto foundExisting = existingDocs.find(key);
|
|
|
|
|
if (foundExisting != existingDocs.end()) {
|
|
|
|
|
existingDoc = foundExisting->second;
|
|
|
|
|
}
|
2018-07-19 07:15:47 -07:00
|
|
|
|
|
|
|
|
// If a document update isn't authoritative, make sure we don't apply an old document version
|
|
|
|
|
// to the remote cache. We make an exception for SnapshotVersion.MIN which can happen for
|
|
|
|
|
// manufactured events (e.g. in the case of a limbo document resolution failing).
|
|
|
|
|
if (!existingDoc || doc.version == SnapshotVersion::None() ||
|
2018-11-01 09:44:30 -07:00
|
|
|
(authoritativeUpdates.contains(doc.key) && !existingDoc.hasPendingWrites) ||
|
|
|
|
|
doc.version >= existingDoc.version) {
|
2018-12-18 13:24:35 -08:00
|
|
|
_remoteDocumentCache->Add(doc);
|
2018-12-10 14:39:22 -08:00
|
|
|
changedDocs = changedDocs.insert(key, doc);
|
2018-03-30 10:18:25 -07:00
|
|
|
} else {
|
2019-01-02 09:27:31 -08:00
|
|
|
LOG_DEBUG("FSTLocalStore Ignoring outdated watch update for %s. "
|
|
|
|
|
"Current version: %s Watch version: %s",
|
|
|
|
|
key.ToString(), existingDoc.version.timestamp().ToString(),
|
|
|
|
|
doc.version.timestamp().ToString());
|
2018-03-30 10:18:25 -07:00
|
|
|
}
|
|
|
|
|
|
2018-07-27 13:58:11 -07:00
|
|
|
// If this was a limbo resolution, make sure we mark when it was accessed.
|
2018-05-08 10:49:54 -07:00
|
|
|
if (limboDocuments.contains(key)) {
|
|
|
|
|
[self.persistence.referenceDelegate limboDocumentUpdated:key];
|
|
|
|
|
}
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2018-03-30 10:18:25 -07:00
|
|
|
// HACK: The only reason we allow omitting snapshot version is so we can synthesize remote
|
|
|
|
|
// events when we get permission denied errors while trying to resolve the state of a locally
|
|
|
|
|
// cached document that is in limbo.
|
2018-12-21 22:08:34 -08:00
|
|
|
const SnapshotVersion &lastRemoteVersion = _queryCache->GetLastRemoteSnapshotVersion();
|
2019-01-29 18:55:25 -05:00
|
|
|
const SnapshotVersion &remoteVersion = remoteEvent.snapshot_version();
|
2018-04-25 14:05:36 -04:00
|
|
|
if (remoteVersion != SnapshotVersion::None()) {
|
2018-05-24 11:00:23 -07:00
|
|
|
HARD_ASSERT(remoteVersion >= lastRemoteVersion,
|
|
|
|
|
"Watch stream reverted to previous snapshot?? (%s < %s)",
|
|
|
|
|
remoteVersion.timestamp().ToString(), lastRemoteVersion.timestamp().ToString());
|
2018-12-21 22:08:34 -08:00
|
|
|
_queryCache->SetLastRemoteSnapshotVersion(remoteVersion);
|
2018-03-24 11:06:32 -04:00
|
|
|
}
|
2017-10-03 08:55:22 -07:00
|
|
|
|
2019-03-22 13:46:48 -07:00
|
|
|
return _localDocuments->GetLocalViewOfDocuments(changedDocs);
|
2018-03-30 10:18:25 -07:00
|
|
|
});
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2018-08-15 17:24:20 -07:00
|
|
|
/**
|
|
|
|
|
* Returns YES if the newQueryData should be persisted during an update of an active target.
|
|
|
|
|
* QueryData should always be persisted when a target is being released and should not call this
|
|
|
|
|
* function.
|
|
|
|
|
*
|
|
|
|
|
* While the target is active, QueryData updates can be omitted when nothing about the target has
|
|
|
|
|
* changed except metadata like the resume token or snapshot version. Occasionally it's worth the
|
|
|
|
|
* extra write to prevent these values from getting too stale after a crash, but this doesn't have
|
|
|
|
|
* to be too frequent.
|
|
|
|
|
*/
|
|
|
|
|
- (BOOL)shouldPersistQueryData:(FSTQueryData *)newQueryData
|
|
|
|
|
oldQueryData:(FSTQueryData *)oldQueryData
|
2019-01-29 15:10:18 -05:00
|
|
|
change:(const TargetChange &)change {
|
2018-08-15 17:24:20 -07:00
|
|
|
// Avoid clearing any existing value
|
|
|
|
|
if (newQueryData.resumeToken.length == 0) return NO;
|
|
|
|
|
|
|
|
|
|
// Any resume token is interesting if there isn't one already.
|
|
|
|
|
if (oldQueryData.resumeToken.length == 0) return YES;
|
|
|
|
|
|
|
|
|
|
// Don't allow resume token changes to be buffered indefinitely. This allows us to be reasonably
|
|
|
|
|
// up-to-date after a crash and avoids needing to loop over all active queries on shutdown.
|
|
|
|
|
// Especially in the browser we may not get time to do anything interesting while the current
|
|
|
|
|
// tab is closing.
|
|
|
|
|
int64_t newSeconds = newQueryData.snapshotVersion.timestamp().seconds();
|
|
|
|
|
int64_t oldSeconds = oldQueryData.snapshotVersion.timestamp().seconds();
|
|
|
|
|
int64_t timeDelta = newSeconds - oldSeconds;
|
|
|
|
|
if (timeDelta >= kResumeTokenMaxAgeSeconds) return YES;
|
|
|
|
|
|
|
|
|
|
// Otherwise if the only thing that has changed about a target is its resume token then it's not
|
|
|
|
|
// worth persisting. Note that the RemoteStore keeps an in-memory view of the currently active
|
|
|
|
|
// targets which includes the current resume token, so stream failure or user changes will still
|
|
|
|
|
// use an up-to-date resume token regardless of what we do here.
|
2019-01-29 15:10:18 -05:00
|
|
|
size_t changes = change.added_documents().size() + change.modified_documents().size() +
|
|
|
|
|
change.removed_documents().size();
|
2018-08-15 17:24:20 -07:00
|
|
|
return changes > 0;
|
|
|
|
|
}
|
|
|
|
|
|
2017-10-03 08:55:22 -07:00
|
|
|
- (void)notifyLocalViewChanges:(NSArray<FSTLocalViewChanges *> *)viewChanges {
|
2018-03-30 10:18:25 -07:00
|
|
|
self.persistence.run("NotifyLocalViewChanges", [&]() {
|
2018-07-31 10:19:57 -07:00
|
|
|
for (FSTLocalViewChanges *viewChange in viewChanges) {
|
|
|
|
|
for (const DocumentKey &key : viewChange.removedKeys) {
|
2018-07-27 13:58:11 -07:00
|
|
|
[self->_persistence.referenceDelegate removeReference:key];
|
2018-05-08 10:49:54 -07:00
|
|
|
}
|
2018-12-21 21:03:13 -08:00
|
|
|
_localViewReferences.AddReferences(viewChange.addedKeys, viewChange.targetID);
|
|
|
|
|
_localViewReferences.AddReferences(viewChange.removedKeys, viewChange.targetID);
|
2018-03-30 10:18:25 -07:00
|
|
|
}
|
|
|
|
|
});
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2018-08-16 10:44:26 -07:00
|
|
|
- (nullable FSTMutationBatch *)nextMutationBatchAfterBatchID:(BatchId)batchID {
|
2018-03-30 10:18:25 -07:00
|
|
|
FSTMutationBatch *result =
|
|
|
|
|
self.persistence.run("NextMutationBatchAfterBatchID", [&]() -> FSTMutationBatch * {
|
2019-01-29 16:01:59 -08:00
|
|
|
return _mutationQueue->NextMutationBatchAfterBatchId(batchID);
|
2018-03-30 10:18:25 -07:00
|
|
|
});
|
2018-03-26 11:57:34 -07:00
|
|
|
return result;
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2018-03-23 17:52:01 -04:00
|
|
|
- (nullable FSTMaybeDocument *)readDocument:(const DocumentKey &)key {
|
2018-03-30 10:18:25 -07:00
|
|
|
return self.persistence.run("ReadDocument", [&]() -> FSTMaybeDocument *_Nullable {
|
2019-03-22 13:46:48 -07:00
|
|
|
return _localDocuments->GetDocument(key);
|
2018-03-30 10:18:25 -07:00
|
|
|
});
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
- (FSTQueryData *)allocateQuery:(FSTQuery *)query {
|
2018-03-30 10:18:25 -07:00
|
|
|
FSTQueryData *queryData = self.persistence.run("Allocate query", [&]() -> FSTQueryData * {
|
2018-12-21 22:08:34 -08:00
|
|
|
FSTQueryData *cached = _queryCache->GetTarget(query);
|
2018-03-30 10:18:25 -07:00
|
|
|
// TODO(mcg): freshen last accessed date if cached exists?
|
|
|
|
|
if (!cached) {
|
|
|
|
|
cached = [[FSTQueryData alloc] initWithQuery:query
|
|
|
|
|
targetID:_targetIDGenerator.NextId()
|
2018-07-27 13:58:11 -07:00
|
|
|
listenSequenceNumber:self.persistence.currentSequenceNumber
|
2018-03-30 10:18:25 -07:00
|
|
|
purpose:FSTQueryPurposeListen];
|
2018-12-21 22:08:34 -08:00
|
|
|
_queryCache->AddTarget(cached);
|
2018-03-30 10:18:25 -07:00
|
|
|
}
|
|
|
|
|
return cached;
|
|
|
|
|
});
|
2017-10-03 08:55:22 -07:00
|
|
|
// Sanity check to ensure that even when resuming a query it's not currently active.
|
2019-01-24 17:01:31 -05:00
|
|
|
TargetId targetID = queryData.targetID;
|
|
|
|
|
HARD_ASSERT(_targetIDs.find(targetID) == _targetIDs.end(),
|
|
|
|
|
"Tried to allocate an already allocated query: %s", query);
|
|
|
|
|
_targetIDs[targetID] = queryData;
|
2018-03-30 10:18:25 -07:00
|
|
|
return queryData;
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
- (void)releaseQuery:(FSTQuery *)query {
|
2018-03-30 10:18:25 -07:00
|
|
|
self.persistence.run("Release query", [&]() {
|
2018-12-21 22:08:34 -08:00
|
|
|
FSTQueryData *queryData = _queryCache->GetTarget(query);
|
2018-05-24 11:00:23 -07:00
|
|
|
HARD_ASSERT(queryData, "Tried to release nonexistent query: %s", query);
|
2017-10-03 08:55:22 -07:00
|
|
|
|
2018-08-15 17:24:20 -07:00
|
|
|
TargetId targetID = queryData.targetID;
|
|
|
|
|
|
2019-01-24 17:01:31 -05:00
|
|
|
auto found = _targetIDs.find(targetID);
|
2019-05-17 09:01:35 -04:00
|
|
|
if (found != _targetIDs.end()) {
|
|
|
|
|
FSTQueryData *cachedQueryData = found->second;
|
|
|
|
|
|
|
|
|
|
if (cachedQueryData.snapshotVersion > queryData.snapshotVersion) {
|
|
|
|
|
// If we've been avoiding persisting the resumeToken (see shouldPersistQueryData for
|
|
|
|
|
// conditions and rationale) we need to persist the token now because there will no
|
|
|
|
|
// longer be an in-memory version to fall back on.
|
|
|
|
|
queryData = cachedQueryData;
|
|
|
|
|
_queryCache->UpdateTarget(queryData);
|
|
|
|
|
}
|
2018-08-15 17:24:20 -07:00
|
|
|
}
|
|
|
|
|
|
2018-11-01 09:44:30 -07:00
|
|
|
// References for documents sent via Watch are automatically removed when we delete a
|
|
|
|
|
// query's target data from the reference delegate. Since this does not remove references
|
|
|
|
|
// for locally mutated documents, we have to remove the target associations for these
|
|
|
|
|
// documents manually.
|
2018-12-21 21:03:13 -08:00
|
|
|
DocumentKeySet removed = _localViewReferences.RemoveReferences(targetID);
|
2018-11-01 09:44:30 -07:00
|
|
|
for (const DocumentKey &key : removed) {
|
|
|
|
|
[self.persistence.referenceDelegate removeReference:key];
|
|
|
|
|
}
|
2019-01-24 17:01:31 -05:00
|
|
|
_targetIDs.erase(targetID);
|
2018-05-08 10:49:54 -07:00
|
|
|
[self.persistence.referenceDelegate removeTarget:queryData];
|
2018-03-30 10:18:25 -07:00
|
|
|
});
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2018-12-10 11:57:08 -08:00
|
|
|
- (DocumentMap)executeQuery:(FSTQuery *)query {
|
|
|
|
|
return self.persistence.run("ExecuteQuery", [&]() -> DocumentMap {
|
2019-03-22 13:46:48 -07:00
|
|
|
return _localDocuments->GetDocumentsMatchingQuery(query);
|
2018-03-30 10:18:25 -07:00
|
|
|
});
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2018-08-15 15:56:45 -07:00
|
|
|
- (DocumentKeySet)remoteDocumentKeysForTarget:(TargetId)targetID {
|
2018-05-05 08:10:51 -07:00
|
|
|
return self.persistence.run("RemoteDocumentKeysForTarget", [&]() -> DocumentKeySet {
|
2018-12-21 22:08:34 -08:00
|
|
|
return _queryCache->GetMatchingKeys(targetID);
|
2018-03-30 10:18:25 -07:00
|
|
|
});
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2018-04-02 16:01:03 -07:00
|
|
|
- (void)applyBatchResult:(FSTMutationBatchResult *)batchResult {
|
2017-10-03 08:55:22 -07:00
|
|
|
FSTMutationBatch *batch = batchResult.batch;
|
2018-05-05 08:10:51 -07:00
|
|
|
DocumentKeySet docKeys = batch.keys;
|
2018-05-05 09:00:53 -07:00
|
|
|
const DocumentVersionMap &versions = batchResult.docVersions;
|
2018-05-05 08:10:51 -07:00
|
|
|
for (const DocumentKey &docKey : docKeys) {
|
2018-12-18 13:24:35 -08:00
|
|
|
FSTMaybeDocument *_Nullable remoteDoc = _remoteDocumentCache->Get(docKey);
|
2017-10-03 08:55:22 -07:00
|
|
|
FSTMaybeDocument *_Nullable doc = remoteDoc;
|
2018-05-05 09:00:53 -07:00
|
|
|
|
|
|
|
|
auto ackVersionIter = versions.find(docKey);
|
2018-05-24 11:00:23 -07:00
|
|
|
HARD_ASSERT(ackVersionIter != versions.end(),
|
|
|
|
|
"docVersions should contain every doc in the write.");
|
2018-05-05 09:00:53 -07:00
|
|
|
const SnapshotVersion &ackVersion = ackVersionIter->second;
|
|
|
|
|
if (!doc || doc.version < ackVersion) {
|
2018-10-17 14:49:40 -07:00
|
|
|
doc = [batch applyToRemoteDocument:doc documentKey:docKey mutationBatchResult:batchResult];
|
2017-10-03 08:55:22 -07:00
|
|
|
if (!doc) {
|
2018-05-24 11:00:23 -07:00
|
|
|
HARD_ASSERT(!remoteDoc, "Mutation batch %s applied to document %s resulted in nil.", batch,
|
|
|
|
|
remoteDoc);
|
2017-10-03 08:55:22 -07:00
|
|
|
} else {
|
2018-12-18 13:24:35 -08:00
|
|
|
_remoteDocumentCache->Add(doc);
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
}
|
2018-05-05 08:10:51 -07:00
|
|
|
}
|
2018-11-01 09:44:30 -07:00
|
|
|
|
2019-01-29 16:01:59 -08:00
|
|
|
_mutationQueue->RemoveMutationBatch(batch);
|
2017-10-03 08:55:22 -07:00
|
|
|
}
|
|
|
|
|
|
2018-11-26 14:33:28 -08:00
|
|
|
- (LruResults)collectGarbage:(FSTLRUGarbageCollector *)garbageCollector {
|
|
|
|
|
return self.persistence.run("Collect garbage", [&]() -> LruResults {
|
|
|
|
|
return [garbageCollector collectWithLiveTargets:_targetIDs];
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2017-10-03 08:55:22 -07:00
|
|
|
@end
|
|
|
|
|
|
|
|
|
|
NS_ASSUME_NONNULL_END
|