FSTFirestoreClient.mm 18 KB

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