FSTFirestoreClient.mm 18 KB

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