FSTFirestoreClient.mm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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/FSTTransaction.h"
  32. #import "Firestore/Source/Core/FSTView.h"
  33. #import "Firestore/Source/Local/FSTLRUGarbageCollector.h"
  34. #import "Firestore/Source/Local/FSTLevelDB.h"
  35. #import "Firestore/Source/Local/FSTLocalSerializer.h"
  36. #import "Firestore/Source/Local/FSTLocalStore.h"
  37. #import "Firestore/Source/Local/FSTMemoryPersistence.h"
  38. #import "Firestore/Source/Model/FSTDocument.h"
  39. #import "Firestore/Source/Model/FSTDocumentSet.h"
  40. #import "Firestore/Source/Remote/FSTRemoteStore.h"
  41. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  42. #import "Firestore/Source/Util/FSTClasses.h"
  43. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  44. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  45. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  46. #include "Firestore/core/src/firebase/firestore/remote/datastore.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. 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::util::Path;
  63. using firebase::firestore::util::Status;
  64. using firebase::firestore::util::AsyncQueue;
  65. using firebase::firestore::util::DelayedOperation;
  66. using firebase::firestore::util::Executor;
  67. using firebase::firestore::util::TimerId;
  68. NS_ASSUME_NONNULL_BEGIN
  69. /** How long we wait to try running LRU GC after SDK initialization. */
  70. static const std::chrono::milliseconds FSTLruGcInitialDelay = std::chrono::minutes(1);
  71. /** Minimum amount of time between GC checks, after the first one. */
  72. static const std::chrono::milliseconds FSTLruGcRegularDelay = std::chrono::minutes(5);
  73. @interface FSTFirestoreClient () {
  74. DatabaseInfo _databaseInfo;
  75. }
  76. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  77. settings:(FIRFirestoreSettings *)settings
  78. credentialsProvider:
  79. (CredentialsProvider *)credentialsProvider // no passing ownership
  80. userExecutor:(std::unique_ptr<Executor>)userExecutor
  81. workerQueue:(std::unique_ptr<AsyncQueue>)queue NS_DESIGNATED_INITIALIZER;
  82. @property(nonatomic, assign, readonly) const DatabaseInfo *databaseInfo;
  83. @property(nonatomic, strong, readonly) FSTEventManager *eventManager;
  84. @property(nonatomic, strong, readonly) id<FSTPersistence> persistence;
  85. @property(nonatomic, strong, readonly) FSTSyncEngine *syncEngine;
  86. @property(nonatomic, strong, readonly) FSTRemoteStore *remoteStore;
  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<Executor> _userExecutor;
  100. std::chrono::milliseconds _initialGcDelay;
  101. std::chrono::milliseconds _regularGcDelay;
  102. BOOL _gcHasRun;
  103. _Nullable id<FSTLRUDelegate> _lruDelegate;
  104. DelayedOperation _lruCallback;
  105. }
  106. - (Executor *)userExecutor {
  107. return _userExecutor.get();
  108. }
  109. - (AsyncQueue *)workerQueue {
  110. return _workerQueue.get();
  111. }
  112. + (instancetype)clientWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  113. settings:(FIRFirestoreSettings *)settings
  114. credentialsProvider:
  115. (CredentialsProvider *)credentialsProvider // no passing ownership
  116. userExecutor:(std::unique_ptr<Executor>)userExecutor
  117. workerQueue:(std::unique_ptr<AsyncQueue>)workerQueue {
  118. return [[FSTFirestoreClient alloc] initWithDatabaseInfo:databaseInfo
  119. settings:settings
  120. credentialsProvider:credentialsProvider
  121. userExecutor:std::move(userExecutor)
  122. workerQueue:std::move(workerQueue)];
  123. }
  124. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  125. settings:(FIRFirestoreSettings *)settings
  126. credentialsProvider:
  127. (CredentialsProvider *)credentialsProvider // no passing ownership
  128. userExecutor:(std::unique_ptr<Executor>)userExecutor
  129. workerQueue:(std::unique_ptr<AsyncQueue>)workerQueue {
  130. if (self = [super init]) {
  131. _databaseInfo = databaseInfo;
  132. _credentialsProvider = credentialsProvider;
  133. _userExecutor = std::move(userExecutor);
  134. _workerQueue = std::move(workerQueue);
  135. _gcHasRun = NO;
  136. _initialGcDelay = FSTLruGcInitialDelay;
  137. _regularGcDelay = FSTLruGcRegularDelay;
  138. auto userPromise = std::make_shared<std::promise<User>>();
  139. bool initialized = false;
  140. __weak __typeof__(self) weakSelf = self;
  141. auto credentialChangeListener = [initialized, userPromise, weakSelf](User user) mutable {
  142. __typeof__(self) strongSelf = weakSelf;
  143. if (!strongSelf) return;
  144. if (!initialized) {
  145. initialized = true;
  146. userPromise->set_value(user);
  147. } else {
  148. strongSelf->_workerQueue->Enqueue(
  149. [strongSelf, user] { [strongSelf credentialDidChangeWithUser:user]; });
  150. }
  151. };
  152. _credentialsProvider->SetCredentialChangeListener(credentialChangeListener);
  153. // Defer initialization until we get the current user from the credentialChangeListener. This is
  154. // guaranteed to be synchronously dispatched onto our worker queue, so we will be initialized
  155. // before any subsequently queued work runs.
  156. _workerQueue->Enqueue([self, userPromise, settings] {
  157. User user = userPromise->get_future().get();
  158. [self initializeWithUser:user settings:settings];
  159. });
  160. }
  161. return self;
  162. }
  163. - (void)initializeWithUser:(const User &)user settings:(FIRFirestoreSettings *)settings {
  164. // Do all of our initialization on our own dispatch queue.
  165. _workerQueue->VerifyIsCurrentQueue();
  166. LOG_DEBUG("Initializing. Current user: %s", user.uid());
  167. // Note: The initialization work must all be synchronous (we can't dispatch more work) since
  168. // external write/listen operations could get queued to run before that subsequent work
  169. // completes.
  170. if (settings.isPersistenceEnabled) {
  171. Path dir = [FSTLevelDB storageDirectoryForDatabaseInfo:*self.databaseInfo
  172. documentsDirectory:[FSTLevelDB documentsDirectory]];
  173. FSTSerializerBeta *remoteSerializer =
  174. [[FSTSerializerBeta alloc] initWithDatabaseID:&self.databaseInfo->database_id()];
  175. FSTLocalSerializer *serializer =
  176. [[FSTLocalSerializer alloc] initWithRemoteSerializer:remoteSerializer];
  177. FSTLevelDB *ldb;
  178. Status levelDbStatus =
  179. [FSTLevelDB dbWithDirectory:std::move(dir)
  180. serializer:serializer
  181. lruParams:LruParams::WithCacheSize(settings.cacheSizeBytes)
  182. ptr:&ldb];
  183. if (!levelDbStatus.ok()) {
  184. // If leveldb fails to start then just throw up our hands: the error is unrecoverable.
  185. // There's nothing an end-user can do and nearly all failures indicate the developer is doing
  186. // something grossly wrong so we should stop them cold in their tracks with a failure they
  187. // can't ignore.
  188. [NSException raise:NSInternalInconsistencyException
  189. format:@"Failed to open DB: %s", levelDbStatus.ToString().c_str()];
  190. }
  191. _lruDelegate = ldb.referenceDelegate;
  192. _persistence = ldb;
  193. [self scheduleLruGarbageCollection];
  194. } else {
  195. _persistence = [FSTMemoryPersistence persistenceWithEagerGC];
  196. }
  197. _localStore = [[FSTLocalStore alloc] initWithPersistence:_persistence initialUser:user];
  198. auto datastore =
  199. std::make_shared<Datastore>(*self.databaseInfo, _workerQueue.get(), _credentialsProvider);
  200. _remoteStore = [[FSTRemoteStore alloc] initWithLocalStore:_localStore
  201. datastore:std::move(datastore)
  202. workerQueue:_workerQueue.get()];
  203. _syncEngine = [[FSTSyncEngine alloc] initWithLocalStore:_localStore
  204. remoteStore:_remoteStore
  205. initialUser:user];
  206. _eventManager = [FSTEventManager eventManagerWithSyncEngine:_syncEngine];
  207. // Setup wiring for remote store.
  208. _remoteStore.syncEngine = _syncEngine;
  209. _remoteStore.onlineStateDelegate = self;
  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)applyChangedOnlineState:(OnlineState)onlineState {
  233. [self.syncEngine applyChangedOnlineState:onlineState];
  234. }
  235. - (void)disableNetworkWithCompletion:(nullable FSTVoidErrorBlock)completion {
  236. _workerQueue->Enqueue([self, completion] {
  237. [self.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. [self.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. [self.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:(FSTViewSnapshotHandler)viewSnapshotHandler {
  268. FSTQueryListener *listener = [[FSTQueryListener alloc] initWithQuery:query
  269. options:options
  270. viewSnapshotHandler:viewSnapshotHandler];
  271. _workerQueue->Enqueue([self, listener] { [self.eventManager addListener:listener]; });
  272. return listener;
  273. }
  274. - (void)removeListener:(FSTQueryListener *)listener {
  275. _workerQueue->Enqueue([self, listener] { [self.eventManager removeListener:listener]; });
  276. }
  277. - (void)getDocumentFromLocalCache:(FIRDocumentReference *)doc
  278. completion:(void (^)(FIRDocumentSnapshot *_Nullable document,
  279. NSError *_Nullable error))completion {
  280. _workerQueue->Enqueue([self, doc, completion] {
  281. FSTMaybeDocument *maybeDoc = [self.localStore readDocument:doc.key];
  282. FIRDocumentSnapshot *_Nullable result = nil;
  283. NSError *_Nullable error = nil;
  284. if ([maybeDoc isKindOfClass:[FSTDocument class]]) {
  285. FSTDocument *document = (FSTDocument *)maybeDoc;
  286. result = [FIRDocumentSnapshot snapshotWithFirestore:doc.firestore
  287. documentKey:doc.key
  288. document:document
  289. fromCache:YES
  290. hasPendingWrites:document.hasLocalMutations];
  291. } else if ([maybeDoc isKindOfClass:[FSTDeletedDocument class]]) {
  292. result = [FIRDocumentSnapshot snapshotWithFirestore:doc.firestore
  293. documentKey:doc.key
  294. document:nil
  295. fromCache:YES
  296. hasPendingWrites:NO];
  297. } else {
  298. error = [NSError errorWithDomain:FIRFirestoreErrorDomain
  299. code:FIRFirestoreErrorCodeUnavailable
  300. userInfo:@{
  301. NSLocalizedDescriptionKey :
  302. @"Failed to get document from cache. (However, this document "
  303. @"may exist on the server. Run again without setting source to "
  304. @"FIRFirestoreSourceCache to attempt to retrieve the document "
  305. @"from the server.)",
  306. }];
  307. }
  308. if (completion) {
  309. self->_userExecutor->Execute([=] { completion(result, error); });
  310. }
  311. });
  312. }
  313. - (void)getDocumentsFromLocalCache:(FIRQuery *)query
  314. completion:(void (^)(FIRQuerySnapshot *_Nullable query,
  315. NSError *_Nullable error))completion {
  316. _workerQueue->Enqueue([self, query, completion] {
  317. DocumentMap docs = [self.localStore executeQuery:query.query];
  318. FSTView *view = [[FSTView alloc] initWithQuery:query.query remoteDocuments:DocumentKeySet{}];
  319. FSTViewDocumentChanges *viewDocChanges =
  320. [view computeChangesWithDocuments:docs.underlying_map()];
  321. FSTViewChange *viewChange = [view applyChangesToDocuments:viewDocChanges];
  322. HARD_ASSERT(viewChange.limboChanges.count == 0,
  323. "View returned limbo documents during local-only query execution.");
  324. FSTViewSnapshot *snapshot = viewChange.snapshot;
  325. FIRSnapshotMetadata *metadata =
  326. [FIRSnapshotMetadata snapshotMetadataWithPendingWrites:snapshot.hasPendingWrites
  327. fromCache:snapshot.fromCache];
  328. FIRQuerySnapshot *result = [FIRQuerySnapshot snapshotWithFirestore:query.firestore
  329. originalQuery:query.query
  330. snapshot:snapshot
  331. metadata:metadata];
  332. if (completion) {
  333. self->_userExecutor->Execute([=] { completion(result, nil); });
  334. }
  335. });
  336. }
  337. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations
  338. completion:(nullable FSTVoidErrorBlock)completion {
  339. _workerQueue->Enqueue([self, mutations, completion] {
  340. if (mutations.count == 0) {
  341. if (completion) {
  342. self->_userExecutor->Execute([=] { completion(nil); });
  343. }
  344. } else {
  345. [self.syncEngine writeMutations: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