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/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/FSTDatastore.h"
  41. #import "Firestore/Source/Remote/FSTRemoteStore.h"
  42. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  43. #import "Firestore/Source/Util/FSTClasses.h"
  44. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  45. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  46. #include "Firestore/core/src/firebase/firestore/model/database_id.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::OnlineState;
  59. using firebase::firestore::util::Path;
  60. using firebase::firestore::util::Status;
  61. using firebase::firestore::util::AsyncQueue;
  62. using firebase::firestore::util::DelayedOperation;
  63. using firebase::firestore::util::Executor;
  64. using firebase::firestore::util::TimerId;
  65. NS_ASSUME_NONNULL_BEGIN
  66. /** How long we wait to try running LRU GC after SDK initialization. */
  67. static const std::chrono::milliseconds FSTLruGcInitialDelay = std::chrono::minutes(1);
  68. /** Minimum amount of time between GC checks, after the first one. */
  69. static const std::chrono::milliseconds FSTLruGcRegularDelay = std::chrono::minutes(5);
  70. @interface FSTFirestoreClient () {
  71. DatabaseInfo _databaseInfo;
  72. }
  73. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  74. settings:(FIRFirestoreSettings *)settings
  75. credentialsProvider:
  76. (CredentialsProvider *)credentialsProvider // no passing ownership
  77. userExecutor:(std::unique_ptr<Executor>)userExecutor
  78. workerQueue:(std::unique_ptr<AsyncQueue>)queue NS_DESIGNATED_INITIALIZER;
  79. @property(nonatomic, assign, readonly) const DatabaseInfo *databaseInfo;
  80. @property(nonatomic, strong, readonly) FSTEventManager *eventManager;
  81. @property(nonatomic, strong, readonly) id<FSTPersistence> persistence;
  82. @property(nonatomic, strong, readonly) FSTSyncEngine *syncEngine;
  83. @property(nonatomic, strong, readonly) FSTRemoteStore *remoteStore;
  84. @property(nonatomic, strong, readonly) FSTLocalStore *localStore;
  85. // Does not own the CredentialsProvider instance.
  86. @property(nonatomic, assign, readonly) CredentialsProvider *credentialsProvider;
  87. @end
  88. @implementation FSTFirestoreClient {
  89. /**
  90. * Async queue responsible for all of our internal processing. When we get incoming work from
  91. * the user (via public API) or the network (incoming gRPC messages), we should always dispatch
  92. * onto this queue. This ensures our internal data structures are never accessed from multiple
  93. * threads simultaneously.
  94. */
  95. std::unique_ptr<AsyncQueue> _workerQueue;
  96. std::unique_ptr<Executor> _userExecutor;
  97. std::chrono::milliseconds _initialGcDelay;
  98. std::chrono::milliseconds _regularGcDelay;
  99. BOOL _gcHasRun;
  100. _Nullable id<FSTLRUDelegate> _lruDelegate;
  101. DelayedOperation _lruCallback;
  102. }
  103. - (Executor *)userExecutor {
  104. return _userExecutor.get();
  105. }
  106. - (AsyncQueue *)workerQueue {
  107. return _workerQueue.get();
  108. }
  109. + (instancetype)clientWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  110. settings:(FIRFirestoreSettings *)settings
  111. credentialsProvider:
  112. (CredentialsProvider *)credentialsProvider // no passing ownership
  113. userExecutor:(std::unique_ptr<Executor>)userExecutor
  114. workerQueue:(std::unique_ptr<AsyncQueue>)workerQueue {
  115. return [[FSTFirestoreClient alloc] initWithDatabaseInfo:databaseInfo
  116. settings:settings
  117. credentialsProvider:credentialsProvider
  118. userExecutor:std::move(userExecutor)
  119. workerQueue:std::move(workerQueue)];
  120. }
  121. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  122. settings:(FIRFirestoreSettings *)settings
  123. credentialsProvider:
  124. (CredentialsProvider *)credentialsProvider // no passing ownership
  125. userExecutor:(std::unique_ptr<Executor>)userExecutor
  126. workerQueue:(std::unique_ptr<AsyncQueue>)workerQueue {
  127. if (self = [super init]) {
  128. _databaseInfo = databaseInfo;
  129. _credentialsProvider = credentialsProvider;
  130. _userExecutor = std::move(userExecutor);
  131. _workerQueue = std::move(workerQueue);
  132. _gcHasRun = NO;
  133. _initialGcDelay = FSTLruGcInitialDelay;
  134. _regularGcDelay = FSTLruGcRegularDelay;
  135. auto userPromise = std::make_shared<std::promise<User>>();
  136. bool initialized = false;
  137. __weak __typeof__(self) weakSelf = self;
  138. auto credentialChangeListener = [initialized, userPromise, weakSelf](User user) mutable {
  139. __typeof__(self) strongSelf = weakSelf;
  140. if (!strongSelf) return;
  141. if (!initialized) {
  142. initialized = true;
  143. userPromise->set_value(user);
  144. } else {
  145. strongSelf->_workerQueue->Enqueue(
  146. [strongSelf, user] { [strongSelf credentialDidChangeWithUser:user]; });
  147. }
  148. };
  149. _credentialsProvider->SetCredentialChangeListener(credentialChangeListener);
  150. // Defer initialization until we get the current user from the credentialChangeListener. This is
  151. // guaranteed to be synchronously dispatched onto our worker queue, so we will be initialized
  152. // before any subsequently queued work runs.
  153. _workerQueue->Enqueue([self, userPromise, settings] {
  154. User user = userPromise->get_future().get();
  155. [self initializeWithUser:user settings:settings];
  156. });
  157. }
  158. return self;
  159. }
  160. - (void)initializeWithUser:(const User &)user settings:(FIRFirestoreSettings *)settings {
  161. // Do all of our initialization on our own dispatch queue.
  162. _workerQueue->VerifyIsCurrentQueue();
  163. LOG_DEBUG("Initializing. Current user: %s", user.uid());
  164. // Note: The initialization work must all be synchronous (we can't dispatch more work) since
  165. // external write/listen operations could get queued to run before that subsequent work
  166. // completes.
  167. if (settings.isPersistenceEnabled) {
  168. Path dir = [FSTLevelDB storageDirectoryForDatabaseInfo:*self.databaseInfo
  169. documentsDirectory:[FSTLevelDB documentsDirectory]];
  170. FSTSerializerBeta *remoteSerializer =
  171. [[FSTSerializerBeta alloc] initWithDatabaseID:&self.databaseInfo->database_id()];
  172. FSTLocalSerializer *serializer =
  173. [[FSTLocalSerializer alloc] initWithRemoteSerializer:remoteSerializer];
  174. FSTLevelDB *ldb =
  175. [[FSTLevelDB alloc] initWithDirectory:std::move(dir)
  176. serializer:serializer
  177. lruParams:LruParams::WithCacheSize(settings.cacheSizeBytes)];
  178. _lruDelegate = ldb.referenceDelegate;
  179. _persistence = ldb;
  180. [self scheduleLruGarbageCollection];
  181. } else {
  182. _persistence = [FSTMemoryPersistence persistenceWithEagerGC];
  183. }
  184. Status status = [_persistence start];
  185. if (!status.ok()) {
  186. // If local storage fails to start then just throw up our hands: the error is unrecoverable.
  187. // There's nothing an end-user can do and nearly all failures indicate the developer is doing
  188. // something grossly wrong so we should stop them cold in their tracks with a failure they
  189. // can't ignore.
  190. [NSException raise:NSInternalInconsistencyException
  191. format:@"Failed to open DB: %s", status.ToString().c_str()];
  192. }
  193. _localStore = [[FSTLocalStore alloc] initWithPersistence:_persistence initialUser:user];
  194. FSTDatastore *datastore = [FSTDatastore datastoreWithDatabase:self.databaseInfo
  195. workerQueue:_workerQueue.get()
  196. credentials:_credentialsProvider];
  197. _remoteStore = [[FSTRemoteStore alloc] initWithLocalStore:_localStore
  198. datastore:datastore
  199. workerQueue:_workerQueue.get()];
  200. _syncEngine = [[FSTSyncEngine alloc] initWithLocalStore:_localStore
  201. remoteStore:_remoteStore
  202. initialUser:user];
  203. _eventManager = [FSTEventManager eventManagerWithSyncEngine:_syncEngine];
  204. // Setup wiring for remote store.
  205. _remoteStore.syncEngine = _syncEngine;
  206. _remoteStore.onlineStateDelegate = self;
  207. // NOTE: RemoteStore depends on LocalStore (for persisting stream tokens, refilling mutation
  208. // queue, etc.) so must be started after LocalStore.
  209. [_localStore start];
  210. [_remoteStore start];
  211. }
  212. /**
  213. * Schedules a callback to try running LRU garbage collection. Reschedules itself after the GC has
  214. * run.
  215. */
  216. - (void)scheduleLruGarbageCollection {
  217. std::chrono::milliseconds delay = _gcHasRun ? _regularGcDelay : _initialGcDelay;
  218. _lruCallback = _workerQueue->EnqueueAfterDelay(delay, TimerId::GarbageCollectionDelay, [self]() {
  219. [self->_localStore collectGarbage:self->_lruDelegate.gc];
  220. self->_gcHasRun = YES;
  221. [self scheduleLruGarbageCollection];
  222. });
  223. }
  224. - (void)credentialDidChangeWithUser:(const User &)user {
  225. _workerQueue->VerifyIsCurrentQueue();
  226. LOG_DEBUG("Credential Changed. Current user: %s", user.uid());
  227. [self.syncEngine credentialDidChangeWithUser:user];
  228. }
  229. - (void)applyChangedOnlineState:(OnlineState)onlineState {
  230. [self.syncEngine applyChangedOnlineState:onlineState];
  231. }
  232. - (void)disableNetworkWithCompletion:(nullable FSTVoidErrorBlock)completion {
  233. _workerQueue->Enqueue([self, completion] {
  234. [self.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. [self.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. [self.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. FSTDocumentDictionary *docs = [self.localStore executeQuery:query.query];
  315. FSTView *view = [[FSTView alloc] initWithQuery:query.query remoteDocuments:DocumentKeySet{}];
  316. FSTViewDocumentChanges *viewDocChanges = [view computeChangesWithDocuments:docs];
  317. FSTViewChange *viewChange = [view applyChangesToDocuments:viewDocChanges];
  318. HARD_ASSERT(viewChange.limboChanges.count == 0,
  319. "View returned limbo documents during local-only query execution.");
  320. FSTViewSnapshot *snapshot = viewChange.snapshot;
  321. FIRSnapshotMetadata *metadata =
  322. [FIRSnapshotMetadata snapshotMetadataWithPendingWrites:snapshot.hasPendingWrites
  323. fromCache:snapshot.fromCache];
  324. FIRQuerySnapshot *result = [FIRQuerySnapshot snapshotWithFirestore:query.firestore
  325. originalQuery:query.query
  326. snapshot:snapshot
  327. metadata:metadata];
  328. if (completion) {
  329. self->_userExecutor->Execute([=] { completion(result, nil); });
  330. }
  331. });
  332. }
  333. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations
  334. completion:(nullable FSTVoidErrorBlock)completion {
  335. _workerQueue->Enqueue([self, mutations, completion] {
  336. if (mutations.count == 0) {
  337. if (completion) {
  338. self->_userExecutor->Execute([=] { completion(nil); });
  339. }
  340. } else {
  341. [self.syncEngine writeMutations:mutations
  342. completion:^(NSError *error) {
  343. // Dispatch the result back onto the user dispatch queue.
  344. if (completion) {
  345. self->_userExecutor->Execute([=] { completion(error); });
  346. }
  347. }];
  348. }
  349. });
  350. };
  351. - (void)transactionWithRetries:(int)retries
  352. updateBlock:(FSTTransactionBlock)updateBlock
  353. completion:(FSTVoidIDErrorBlock)completion {
  354. _workerQueue->Enqueue([self, retries, updateBlock, completion] {
  355. [self.syncEngine
  356. transactionWithRetries:retries
  357. workerQueue:_workerQueue.get()
  358. updateBlock:updateBlock
  359. completion:^(id _Nullable result, NSError *_Nullable error) {
  360. // Dispatch the result back onto the user dispatch queue.
  361. if (completion) {
  362. self->_userExecutor->Execute([=] { completion(result, error); });
  363. }
  364. }];
  365. });
  366. }
  367. - (const DatabaseInfo *)databaseInfo {
  368. return &_databaseInfo;
  369. }
  370. - (const DatabaseId *)databaseID {
  371. return &_databaseInfo.database_id();
  372. }
  373. @end
  374. NS_ASSUME_NONNULL_END