FSTFirestoreClient.mm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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/Core/FSTFirestoreClient.h"
  17. #include <chrono> // NOLINT(build/c++11)
  18. #include <future> // NOLINT(build/c++11)
  19. #include <memory>
  20. #include <utility>
  21. #import "FIRFirestoreErrors.h"
  22. #import "FIRFirestoreSettings.h"
  23. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  24. #import "Firestore/Source/API/FIRDocumentSnapshot+Internal.h"
  25. #import "Firestore/Source/API/FIRQuery+Internal.h"
  26. #import "Firestore/Source/API/FIRQuerySnapshot+Internal.h"
  27. #import "Firestore/Source/API/FIRSnapshotMetadata+Internal.h"
  28. #import "Firestore/Source/Core/FSTEventManager.h"
  29. #import "Firestore/Source/Core/FSTQuery.h"
  30. #import "Firestore/Source/Core/FSTSyncEngine.h"
  31. #import "Firestore/Source/Core/FSTView.h"
  32. #import "Firestore/Source/Local/FSTLRUGarbageCollector.h"
  33. #import "Firestore/Source/Local/FSTLevelDB.h"
  34. #import "Firestore/Source/Local/FSTLocalSerializer.h"
  35. #import "Firestore/Source/Local/FSTLocalStore.h"
  36. #import "Firestore/Source/Local/FSTMemoryPersistence.h"
  37. #import "Firestore/Source/Model/FSTDocument.h"
  38. #import "Firestore/Source/Model/FSTDocumentSet.h"
  39. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  40. #import "Firestore/Source/Util/FSTClasses.h"
  41. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  42. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  43. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  44. #include "Firestore/core/src/firebase/firestore/remote/datastore.h"
  45. #include "Firestore/core/src/firebase/firestore/remote/remote_store.h"
  46. #include "Firestore/core/src/firebase/firestore/util/async_queue.h"
  47. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  48. #include "Firestore/core/src/firebase/firestore/util/log.h"
  49. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  50. #include "absl/memory/memory.h"
  51. namespace util = firebase::firestore::util;
  52. using firebase::firestore::api::DocumentReference;
  53. using firebase::firestore::auth::CredentialsProvider;
  54. using firebase::firestore::auth::User;
  55. using firebase::firestore::core::DatabaseInfo;
  56. using firebase::firestore::core::ViewSnapshot;
  57. using firebase::firestore::core::ViewSnapshotHandler;
  58. using firebase::firestore::local::LruParams;
  59. using firebase::firestore::model::DatabaseId;
  60. using firebase::firestore::model::DocumentKeySet;
  61. using firebase::firestore::model::DocumentMap;
  62. using firebase::firestore::model::MaybeDocumentMap;
  63. using firebase::firestore::model::OnlineState;
  64. using firebase::firestore::remote::Datastore;
  65. using firebase::firestore::remote::RemoteStore;
  66. using firebase::firestore::util::Path;
  67. using firebase::firestore::util::Status;
  68. using firebase::firestore::util::AsyncQueue;
  69. using firebase::firestore::util::DelayedOperation;
  70. using firebase::firestore::util::Executor;
  71. using firebase::firestore::util::TimerId;
  72. NS_ASSUME_NONNULL_BEGIN
  73. /** How long we wait to try running LRU GC after SDK initialization. */
  74. static const std::chrono::milliseconds FSTLruGcInitialDelay = std::chrono::minutes(1);
  75. /** Minimum amount of time between GC checks, after the first one. */
  76. static const std::chrono::milliseconds FSTLruGcRegularDelay = std::chrono::minutes(5);
  77. @interface FSTFirestoreClient () {
  78. DatabaseInfo _databaseInfo;
  79. }
  80. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  81. settings:(FIRFirestoreSettings *)settings
  82. credentialsProvider:
  83. (CredentialsProvider *)credentialsProvider // no passing ownership
  84. userExecutor:(std::unique_ptr<Executor>)userExecutor
  85. workerQueue:(std::unique_ptr<AsyncQueue>)queue NS_DESIGNATED_INITIALIZER;
  86. @property(nonatomic, assign, readonly) const DatabaseInfo *databaseInfo;
  87. @property(nonatomic, strong, readonly) FSTEventManager *eventManager;
  88. @property(nonatomic, strong, readonly) id<FSTPersistence> persistence;
  89. @property(nonatomic, strong, readonly) FSTSyncEngine *syncEngine;
  90. @property(nonatomic, strong, readonly) FSTLocalStore *localStore;
  91. // Does not own the CredentialsProvider instance.
  92. @property(nonatomic, assign, readonly) CredentialsProvider *credentialsProvider;
  93. @end
  94. @implementation FSTFirestoreClient {
  95. /**
  96. * Async queue responsible for all of our internal processing. When we get incoming work from
  97. * the user (via public API) or the network (incoming gRPC messages), we should always dispatch
  98. * onto this queue. This ensures our internal data structures are never accessed from multiple
  99. * threads simultaneously.
  100. */
  101. std::unique_ptr<AsyncQueue> _workerQueue;
  102. std::unique_ptr<RemoteStore> _remoteStore;
  103. std::unique_ptr<Executor> _userExecutor;
  104. std::chrono::milliseconds _initialGcDelay;
  105. std::chrono::milliseconds _regularGcDelay;
  106. BOOL _gcHasRun;
  107. _Nullable id<FSTLRUDelegate> _lruDelegate;
  108. DelayedOperation _lruCallback;
  109. }
  110. - (Executor *)userExecutor {
  111. return _userExecutor.get();
  112. }
  113. - (AsyncQueue *)workerQueue {
  114. return _workerQueue.get();
  115. }
  116. + (instancetype)clientWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  117. settings:(FIRFirestoreSettings *)settings
  118. credentialsProvider:
  119. (CredentialsProvider *)credentialsProvider // no passing ownership
  120. userExecutor:(std::unique_ptr<Executor>)userExecutor
  121. workerQueue:(std::unique_ptr<AsyncQueue>)workerQueue {
  122. return [[FSTFirestoreClient alloc] initWithDatabaseInfo:databaseInfo
  123. settings:settings
  124. credentialsProvider:credentialsProvider
  125. userExecutor:std::move(userExecutor)
  126. workerQueue:std::move(workerQueue)];
  127. }
  128. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  129. settings:(FIRFirestoreSettings *)settings
  130. credentialsProvider:
  131. (CredentialsProvider *)credentialsProvider // no passing ownership
  132. userExecutor:(std::unique_ptr<Executor>)userExecutor
  133. workerQueue:(std::unique_ptr<AsyncQueue>)workerQueue {
  134. if (self = [super init]) {
  135. _databaseInfo = databaseInfo;
  136. _credentialsProvider = credentialsProvider;
  137. _userExecutor = std::move(userExecutor);
  138. _workerQueue = std::move(workerQueue);
  139. _gcHasRun = NO;
  140. _initialGcDelay = FSTLruGcInitialDelay;
  141. _regularGcDelay = FSTLruGcRegularDelay;
  142. auto userPromise = std::make_shared<std::promise<User>>();
  143. bool initialized = false;
  144. __weak __typeof__(self) weakSelf = self;
  145. auto credentialChangeListener = [initialized, userPromise, weakSelf](User user) mutable {
  146. __typeof__(self) strongSelf = weakSelf;
  147. if (!strongSelf) return;
  148. if (!initialized) {
  149. initialized = true;
  150. userPromise->set_value(user);
  151. } else {
  152. strongSelf->_workerQueue->Enqueue(
  153. [strongSelf, user] { [strongSelf credentialDidChangeWithUser:user]; });
  154. }
  155. };
  156. _credentialsProvider->SetCredentialChangeListener(credentialChangeListener);
  157. // Defer initialization until we get the current user from the credentialChangeListener. This is
  158. // guaranteed to be synchronously dispatched onto our worker queue, so we will be initialized
  159. // before any subsequently queued work runs.
  160. _workerQueue->Enqueue([self, userPromise, settings] {
  161. User user = userPromise->get_future().get();
  162. [self initializeWithUser:user settings:settings];
  163. });
  164. }
  165. return self;
  166. }
  167. - (void)initializeWithUser:(const User &)user settings:(FIRFirestoreSettings *)settings {
  168. // Do all of our initialization on our own dispatch queue.
  169. _workerQueue->VerifyIsCurrentQueue();
  170. LOG_DEBUG("Initializing. Current user: %s", user.uid());
  171. // Note: The initialization work must all be synchronous (we can't dispatch more work) since
  172. // external write/listen operations could get queued to run before that subsequent work
  173. // completes.
  174. if (settings.isPersistenceEnabled) {
  175. Path dir = [FSTLevelDB storageDirectoryForDatabaseInfo:*self.databaseInfo
  176. documentsDirectory:[FSTLevelDB documentsDirectory]];
  177. FSTSerializerBeta *remoteSerializer =
  178. [[FSTSerializerBeta alloc] initWithDatabaseID:&self.databaseInfo->database_id()];
  179. FSTLocalSerializer *serializer =
  180. [[FSTLocalSerializer alloc] initWithRemoteSerializer:remoteSerializer];
  181. FSTLevelDB *ldb;
  182. Status levelDbStatus =
  183. [FSTLevelDB dbWithDirectory:std::move(dir)
  184. serializer:serializer
  185. lruParams:LruParams::WithCacheSize(settings.cacheSizeBytes)
  186. ptr:&ldb];
  187. if (!levelDbStatus.ok()) {
  188. // If leveldb fails to start then just throw up our hands: the error is unrecoverable.
  189. // There's nothing an end-user can do and nearly all failures indicate the developer is doing
  190. // something grossly wrong so we should stop them cold in their tracks with a failure they
  191. // can't ignore.
  192. [NSException raise:NSInternalInconsistencyException
  193. format:@"Failed to open DB: %s", levelDbStatus.ToString().c_str()];
  194. }
  195. _lruDelegate = ldb.referenceDelegate;
  196. _persistence = ldb;
  197. [self scheduleLruGarbageCollection];
  198. } else {
  199. _persistence = [FSTMemoryPersistence persistenceWithEagerGC];
  200. }
  201. _localStore = [[FSTLocalStore alloc] initWithPersistence:_persistence initialUser:user];
  202. auto datastore =
  203. std::make_shared<Datastore>(*self.databaseInfo, _workerQueue.get(), _credentialsProvider);
  204. _remoteStore = absl::make_unique<RemoteStore>(
  205. _localStore, std::move(datastore), _workerQueue.get(),
  206. [self](OnlineState onlineState) { [self.syncEngine applyChangedOnlineState:onlineState]; });
  207. _syncEngine = [[FSTSyncEngine alloc] initWithLocalStore:_localStore
  208. remoteStore:_remoteStore.get()
  209. initialUser:user];
  210. _eventManager = [FSTEventManager eventManagerWithSyncEngine:_syncEngine];
  211. // Setup wiring for remote store.
  212. _remoteStore->set_sync_engine(_syncEngine);
  213. // NOTE: RemoteStore depends on LocalStore (for persisting stream tokens, refilling mutation
  214. // queue, etc.) so must be started after LocalStore.
  215. [_localStore start];
  216. _remoteStore->Start();
  217. }
  218. /**
  219. * Schedules a callback to try running LRU garbage collection. Reschedules itself after the GC has
  220. * run.
  221. */
  222. - (void)scheduleLruGarbageCollection {
  223. std::chrono::milliseconds delay = _gcHasRun ? _regularGcDelay : _initialGcDelay;
  224. _lruCallback = _workerQueue->EnqueueAfterDelay(delay, TimerId::GarbageCollectionDelay, [self]() {
  225. [self->_localStore collectGarbage:self->_lruDelegate.gc];
  226. self->_gcHasRun = YES;
  227. [self scheduleLruGarbageCollection];
  228. });
  229. }
  230. - (void)credentialDidChangeWithUser:(const User &)user {
  231. _workerQueue->VerifyIsCurrentQueue();
  232. LOG_DEBUG("Credential Changed. Current user: %s", user.uid());
  233. [self.syncEngine credentialDidChangeWithUser:user];
  234. }
  235. - (void)disableNetworkWithCompletion:(nullable FSTVoidErrorBlock)completion {
  236. _workerQueue->Enqueue([self, completion] {
  237. _remoteStore->DisableNetwork();
  238. if (completion) {
  239. self->_userExecutor->Execute([=] { completion(nil); });
  240. }
  241. });
  242. }
  243. - (void)enableNetworkWithCompletion:(nullable FSTVoidErrorBlock)completion {
  244. _workerQueue->Enqueue([self, completion] {
  245. _remoteStore->EnableNetwork();
  246. if (completion) {
  247. self->_userExecutor->Execute([=] { completion(nil); });
  248. }
  249. });
  250. }
  251. - (void)shutdownWithCompletion:(nullable FSTVoidErrorBlock)completion {
  252. _workerQueue->Enqueue([self, completion] {
  253. self->_credentialsProvider->SetCredentialChangeListener(nullptr);
  254. // If we've scheduled LRU garbage collection, cancel it.
  255. if (self->_lruCallback) {
  256. self->_lruCallback.Cancel();
  257. }
  258. _remoteStore->Shutdown();
  259. [self.persistence shutdown];
  260. if (completion) {
  261. self->_userExecutor->Execute([=] { completion(nil); });
  262. }
  263. });
  264. }
  265. - (FSTQueryListener *)listenToQuery:(FSTQuery *)query
  266. options:(FSTListenOptions *)options
  267. viewSnapshotHandler:(ViewSnapshotHandler &&)viewSnapshotHandler {
  268. FSTQueryListener *listener =
  269. [[FSTQueryListener alloc] initWithQuery:query
  270. options:options
  271. viewSnapshotHandler:std::move(viewSnapshotHandler)];
  272. _workerQueue->Enqueue([self, listener] { [self.eventManager addListener:listener]; });
  273. return listener;
  274. }
  275. - (void)removeListener:(FSTQueryListener *)listener {
  276. _workerQueue->Enqueue([self, listener] { [self.eventManager removeListener:listener]; });
  277. }
  278. - (void)getDocumentFromLocalCache:(const DocumentReference &)doc
  279. completion:(void (^)(FIRDocumentSnapshot *_Nullable document,
  280. NSError *_Nullable error))completion {
  281. _workerQueue->Enqueue([self, doc, completion] {
  282. FSTMaybeDocument *maybeDoc = [self.localStore readDocument:doc.key()];
  283. FIRDocumentSnapshot *_Nullable result = nil;
  284. NSError *_Nullable error = nil;
  285. if ([maybeDoc isKindOfClass:[FSTDocument class]]) {
  286. FSTDocument *document = (FSTDocument *)maybeDoc;
  287. result = [FIRDocumentSnapshot snapshotWithFirestore:doc.firestore()
  288. documentKey:doc.key()
  289. document:document
  290. fromCache:YES
  291. hasPendingWrites:document.hasLocalMutations];
  292. } else if ([maybeDoc isKindOfClass:[FSTDeletedDocument class]]) {
  293. result = [FIRDocumentSnapshot snapshotWithFirestore:doc.firestore()
  294. documentKey:doc.key()
  295. document:nil
  296. fromCache:YES
  297. hasPendingWrites:NO];
  298. } else {
  299. error = [NSError errorWithDomain:FIRFirestoreErrorDomain
  300. code:FIRFirestoreErrorCodeUnavailable
  301. userInfo:@{
  302. NSLocalizedDescriptionKey :
  303. @"Failed to get document from cache. (However, this document "
  304. @"may exist on the server. Run again without setting source to "
  305. @"FIRFirestoreSourceCache to attempt to retrieve the document "
  306. @"from the server.)",
  307. }];
  308. }
  309. if (completion) {
  310. self->_userExecutor->Execute([=] { completion(result, error); });
  311. }
  312. });
  313. }
  314. - (void)getDocumentsFromLocalCache:(FIRQuery *)query
  315. completion:(void (^)(FIRQuerySnapshot *_Nullable query,
  316. NSError *_Nullable error))completion {
  317. _workerQueue->Enqueue([self, query, completion] {
  318. DocumentMap docs = [self.localStore executeQuery:query.query];
  319. FSTView *view = [[FSTView alloc] initWithQuery:query.query remoteDocuments:DocumentKeySet{}];
  320. FSTViewDocumentChanges *viewDocChanges =
  321. [view computeChangesWithDocuments:docs.underlying_map()];
  322. FSTViewChange *viewChange = [view applyChangesToDocuments:viewDocChanges];
  323. HARD_ASSERT(viewChange.limboChanges.count == 0,
  324. "View returned limbo documents during local-only query execution.");
  325. HARD_ASSERT(viewChange.snapshot.has_value(), "Expected a snapshot");
  326. ViewSnapshot snapshot = std::move(viewChange.snapshot).value();
  327. FIRSnapshotMetadata *metadata =
  328. [FIRSnapshotMetadata snapshotMetadataWithPendingWrites:snapshot.has_pending_writes()
  329. fromCache:snapshot.from_cache()];
  330. FIRQuerySnapshot *result = [FIRQuerySnapshot snapshotWithFirestore:query.firestore
  331. originalQuery:query.query
  332. snapshot:std::move(snapshot)
  333. metadata:metadata];
  334. if (completion) {
  335. self->_userExecutor->Execute([=] { completion(result, nil); });
  336. }
  337. });
  338. }
  339. - (void)writeMutations:(std::vector<FSTMutation *> &&)mutations
  340. completion:(nullable FSTVoidErrorBlock)completion {
  341. // TODO(c++14): move `mutations` into lambda (C++14).
  342. _workerQueue->Enqueue([self, mutations, completion]() mutable {
  343. if (mutations.empty()) {
  344. if (completion) {
  345. self->_userExecutor->Execute([=] { completion(nil); });
  346. }
  347. } else {
  348. [self.syncEngine writeMutations:std::move(mutations)
  349. completion:^(NSError *error) {
  350. // Dispatch the result back onto the user dispatch queue.
  351. if (completion) {
  352. self->_userExecutor->Execute([=] { completion(error); });
  353. }
  354. }];
  355. }
  356. });
  357. };
  358. - (void)transactionWithRetries:(int)retries
  359. updateBlock:(FSTTransactionBlock)updateBlock
  360. completion:(FSTVoidIDErrorBlock)completion {
  361. _workerQueue->Enqueue([self, retries, updateBlock, completion] {
  362. [self.syncEngine
  363. transactionWithRetries:retries
  364. workerQueue:_workerQueue.get()
  365. updateBlock:updateBlock
  366. completion:^(id _Nullable result, NSError *_Nullable error) {
  367. // Dispatch the result back onto the user dispatch queue.
  368. if (completion) {
  369. self->_userExecutor->Execute([=] { completion(result, error); });
  370. }
  371. }];
  372. });
  373. }
  374. - (const DatabaseInfo *)databaseInfo {
  375. return &_databaseInfo;
  376. }
  377. - (const DatabaseId *)databaseID {
  378. return &_databaseInfo.database_id();
  379. }
  380. @end
  381. NS_ASSUME_NONNULL_END