FSTFirestoreClient.mm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 <future> // NOLINT(build/c++11)
  18. #include <memory>
  19. #include <utility>
  20. #import "FIRFirestoreErrors.h"
  21. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  22. #import "Firestore/Source/API/FIRDocumentSnapshot+Internal.h"
  23. #import "Firestore/Source/API/FIRQuery+Internal.h"
  24. #import "Firestore/Source/API/FIRQuerySnapshot+Internal.h"
  25. #import "Firestore/Source/API/FIRSnapshotMetadata+Internal.h"
  26. #import "Firestore/Source/Core/FSTEventManager.h"
  27. #import "Firestore/Source/Core/FSTQuery.h"
  28. #import "Firestore/Source/Core/FSTSyncEngine.h"
  29. #import "Firestore/Source/Core/FSTTransaction.h"
  30. #import "Firestore/Source/Core/FSTView.h"
  31. #import "Firestore/Source/Local/FSTLevelDB.h"
  32. #import "Firestore/Source/Local/FSTLocalSerializer.h"
  33. #import "Firestore/Source/Local/FSTLocalStore.h"
  34. #import "Firestore/Source/Local/FSTMemoryPersistence.h"
  35. #import "Firestore/Source/Model/FSTDocument.h"
  36. #import "Firestore/Source/Model/FSTDocumentSet.h"
  37. #import "Firestore/Source/Remote/FSTDatastore.h"
  38. #import "Firestore/Source/Remote/FSTRemoteStore.h"
  39. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  40. #import "Firestore/Source/Util/FSTClasses.h"
  41. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  42. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  43. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  44. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  45. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  46. #include "Firestore/core/src/firebase/firestore/util/log.h"
  47. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  48. namespace util = firebase::firestore::util;
  49. using firebase::firestore::auth::CredentialsProvider;
  50. using firebase::firestore::auth::User;
  51. using firebase::firestore::core::DatabaseInfo;
  52. using firebase::firestore::model::DatabaseId;
  53. using firebase::firestore::model::DocumentKeySet;
  54. using firebase::firestore::model::OnlineState;
  55. using firebase::firestore::util::Path;
  56. using firebase::firestore::util::Status;
  57. using firebase::firestore::util::internal::Executor;
  58. NS_ASSUME_NONNULL_BEGIN
  59. @interface FSTFirestoreClient () {
  60. DatabaseInfo _databaseInfo;
  61. }
  62. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  63. usePersistence:(BOOL)usePersistence
  64. credentialsProvider:
  65. (CredentialsProvider *)credentialsProvider // no passing ownership
  66. userExecutor:(std::unique_ptr<Executor>)userExecutor
  67. workerDispatchQueue:(FSTDispatchQueue *)queue NS_DESIGNATED_INITIALIZER;
  68. @property(nonatomic, assign, readonly) const DatabaseInfo *databaseInfo;
  69. @property(nonatomic, strong, readonly) FSTEventManager *eventManager;
  70. @property(nonatomic, strong, readonly) id<FSTPersistence> persistence;
  71. @property(nonatomic, strong, readonly) FSTSyncEngine *syncEngine;
  72. @property(nonatomic, strong, readonly) FSTRemoteStore *remoteStore;
  73. @property(nonatomic, strong, readonly) FSTLocalStore *localStore;
  74. /**
  75. * Dispatch queue responsible for all of our internal processing. When we get incoming work from
  76. * the user (via public API) or the network (incoming GRPC messages), we should always dispatch
  77. * onto this queue. This ensures our internal data structures are never accessed from multiple
  78. * threads simultaneously.
  79. */
  80. @property(nonatomic, strong, readonly) FSTDispatchQueue *workerDispatchQueue;
  81. // Does not own the CredentialsProvider instance.
  82. @property(nonatomic, assign, readonly) CredentialsProvider *credentialsProvider;
  83. @end
  84. @implementation FSTFirestoreClient {
  85. std::unique_ptr<Executor> _userExecutor;
  86. }
  87. - (Executor *)userExecutor {
  88. return _userExecutor.get();
  89. }
  90. + (instancetype)clientWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  91. usePersistence:(BOOL)usePersistence
  92. credentialsProvider:
  93. (CredentialsProvider *)credentialsProvider // no passing ownership
  94. userExecutor:(std::unique_ptr<Executor>)userExecutor
  95. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue {
  96. return [[FSTFirestoreClient alloc] initWithDatabaseInfo:databaseInfo
  97. usePersistence:usePersistence
  98. credentialsProvider:credentialsProvider
  99. userExecutor:std::move(userExecutor)
  100. workerDispatchQueue:workerDispatchQueue];
  101. }
  102. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  103. usePersistence:(BOOL)usePersistence
  104. credentialsProvider:
  105. (CredentialsProvider *)credentialsProvider // no passing ownership
  106. userExecutor:(std::unique_ptr<Executor>)userExecutor
  107. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue {
  108. if (self = [super init]) {
  109. _databaseInfo = databaseInfo;
  110. _credentialsProvider = credentialsProvider;
  111. _userExecutor = std::move(userExecutor);
  112. _workerDispatchQueue = workerDispatchQueue;
  113. auto userPromise = std::make_shared<std::promise<User>>();
  114. __weak typeof(self) weakSelf = self;
  115. auto credentialChangeListener = [initialized = false, userPromise, weakSelf,
  116. workerDispatchQueue](User user) mutable {
  117. typeof(self) strongSelf = weakSelf;
  118. if (!strongSelf) return;
  119. if (!initialized) {
  120. initialized = true;
  121. userPromise->set_value(user);
  122. } else {
  123. [workerDispatchQueue dispatchAsync:^{
  124. [strongSelf credentialDidChangeWithUser:user];
  125. }];
  126. }
  127. };
  128. _credentialsProvider->SetCredentialChangeListener(credentialChangeListener);
  129. // Defer initialization until we get the current user from the credentialChangeListener. This is
  130. // guaranteed to be synchronously dispatched onto our worker queue, so we will be initialized
  131. // before any subsequently queued work runs.
  132. [_workerDispatchQueue dispatchAsync:^{
  133. User user = userPromise->get_future().get();
  134. [self initializeWithUser:user usePersistence:usePersistence];
  135. }];
  136. }
  137. return self;
  138. }
  139. - (void)initializeWithUser:(const User &)user usePersistence:(BOOL)usePersistence {
  140. // Do all of our initialization on our own dispatch queue.
  141. [self.workerDispatchQueue verifyIsCurrentQueue];
  142. LOG_DEBUG("Initializing. Current user: %s", user.uid());
  143. // Note: The initialization work must all be synchronous (we can't dispatch more work) since
  144. // external write/listen operations could get queued to run before that subsequent work
  145. // completes.
  146. if (usePersistence) {
  147. Path dir = [FSTLevelDB storageDirectoryForDatabaseInfo:*self.databaseInfo
  148. documentsDirectory:[FSTLevelDB documentsDirectory]];
  149. FSTSerializerBeta *remoteSerializer =
  150. [[FSTSerializerBeta alloc] initWithDatabaseID:&self.databaseInfo->database_id()];
  151. FSTLocalSerializer *serializer =
  152. [[FSTLocalSerializer alloc] initWithRemoteSerializer:remoteSerializer];
  153. _persistence = [[FSTLevelDB alloc] initWithDirectory:std::move(dir) serializer:serializer];
  154. } else {
  155. _persistence = [FSTMemoryPersistence persistenceWithEagerGC];
  156. }
  157. Status status = [_persistence start];
  158. if (!status.ok()) {
  159. // If local storage fails to start then just throw up our hands: the error is unrecoverable.
  160. // There's nothing an end-user can do and nearly all failures indicate the developer is doing
  161. // something grossly wrong so we should stop them cold in their tracks with a failure they
  162. // can't ignore.
  163. [NSException raise:NSInternalInconsistencyException
  164. format:@"Failed to open DB: %s", status.ToString().c_str()];
  165. }
  166. _localStore = [[FSTLocalStore alloc] initWithPersistence:_persistence initialUser:user];
  167. FSTDatastore *datastore = [FSTDatastore datastoreWithDatabase:self.databaseInfo
  168. workerDispatchQueue:self.workerDispatchQueue
  169. credentials:_credentialsProvider];
  170. _remoteStore = [[FSTRemoteStore alloc] initWithLocalStore:_localStore
  171. datastore:datastore
  172. workerDispatchQueue:self.workerDispatchQueue];
  173. _syncEngine = [[FSTSyncEngine alloc] initWithLocalStore:_localStore
  174. remoteStore:_remoteStore
  175. initialUser:user];
  176. _eventManager = [FSTEventManager eventManagerWithSyncEngine:_syncEngine];
  177. // Setup wiring for remote store.
  178. _remoteStore.syncEngine = _syncEngine;
  179. _remoteStore.onlineStateDelegate = self;
  180. // NOTE: RemoteStore depends on LocalStore (for persisting stream tokens, refilling mutation
  181. // queue, etc.) so must be started after LocalStore.
  182. [_localStore start];
  183. [_remoteStore start];
  184. }
  185. - (void)credentialDidChangeWithUser:(const User &)user {
  186. [self.workerDispatchQueue verifyIsCurrentQueue];
  187. LOG_DEBUG("Credential Changed. Current user: %s", user.uid());
  188. [self.syncEngine credentialDidChangeWithUser:user];
  189. }
  190. - (void)applyChangedOnlineState:(OnlineState)onlineState {
  191. [self.syncEngine applyChangedOnlineState:onlineState];
  192. [self.eventManager applyChangedOnlineState:onlineState];
  193. }
  194. - (void)disableNetworkWithCompletion:(nullable FSTVoidErrorBlock)completion {
  195. [self.workerDispatchQueue dispatchAsync:^{
  196. [self.remoteStore disableNetwork];
  197. if (completion) {
  198. self->_userExecutor->Execute([=] { completion(nil); });
  199. }
  200. }];
  201. }
  202. - (void)enableNetworkWithCompletion:(nullable FSTVoidErrorBlock)completion {
  203. [self.workerDispatchQueue dispatchAsync:^{
  204. [self.remoteStore enableNetwork];
  205. if (completion) {
  206. self->_userExecutor->Execute([=] { completion(nil); });
  207. }
  208. }];
  209. }
  210. - (void)shutdownWithCompletion:(nullable FSTVoidErrorBlock)completion {
  211. [self.workerDispatchQueue dispatchAsync:^{
  212. self->_credentialsProvider->SetCredentialChangeListener(nullptr);
  213. [self.remoteStore shutdown];
  214. [self.persistence shutdown];
  215. if (completion) {
  216. self->_userExecutor->Execute([=] { completion(nil); });
  217. }
  218. }];
  219. }
  220. - (FSTQueryListener *)listenToQuery:(FSTQuery *)query
  221. options:(FSTListenOptions *)options
  222. viewSnapshotHandler:(FSTViewSnapshotHandler)viewSnapshotHandler {
  223. FSTQueryListener *listener = [[FSTQueryListener alloc] initWithQuery:query
  224. options:options
  225. viewSnapshotHandler:viewSnapshotHandler];
  226. [self.workerDispatchQueue dispatchAsync:^{
  227. [self.eventManager addListener:listener];
  228. }];
  229. return listener;
  230. }
  231. - (void)removeListener:(FSTQueryListener *)listener {
  232. [self.workerDispatchQueue dispatchAsync:^{
  233. [self.eventManager removeListener:listener];
  234. }];
  235. }
  236. - (void)getDocumentFromLocalCache:(FIRDocumentReference *)doc
  237. completion:(void (^)(FIRDocumentSnapshot *_Nullable document,
  238. NSError *_Nullable error))completion {
  239. [self.workerDispatchQueue dispatchAsync:^{
  240. FSTMaybeDocument *maybeDoc = [self.localStore readDocument:doc.key];
  241. FIRDocumentSnapshot *_Nullable result = nil;
  242. NSError *_Nullable error = nil;
  243. if (maybeDoc) {
  244. FSTDocument *_Nullable document =
  245. ([maybeDoc isKindOfClass:[FSTDocument class]]) ? (FSTDocument *)maybeDoc : nil;
  246. result = [FIRDocumentSnapshot snapshotWithFirestore:doc.firestore
  247. documentKey:doc.key
  248. document:document
  249. fromCache:YES];
  250. } else {
  251. error = [NSError errorWithDomain:FIRFirestoreErrorDomain
  252. code:FIRFirestoreErrorCodeUnavailable
  253. userInfo:@{
  254. NSLocalizedDescriptionKey :
  255. @"Failed to get document from cache. (However, this document "
  256. @"may exist on the server. Run again without setting source to "
  257. @"FIRFirestoreSourceCache to attempt to retrieve the document "
  258. @"from the server.)",
  259. }];
  260. }
  261. if (completion) {
  262. self->_userExecutor->Execute([=] { completion(result, error); });
  263. }
  264. }];
  265. }
  266. - (void)getDocumentsFromLocalCache:(FIRQuery *)query
  267. completion:(void (^)(FIRQuerySnapshot *_Nullable query,
  268. NSError *_Nullable error))completion {
  269. [self.workerDispatchQueue dispatchAsync:^{
  270. FSTDocumentDictionary *docs = [self.localStore executeQuery:query.query];
  271. FSTView *view = [[FSTView alloc] initWithQuery:query.query remoteDocuments:DocumentKeySet{}];
  272. FSTViewDocumentChanges *viewDocChanges = [view computeChangesWithDocuments:docs];
  273. FSTViewChange *viewChange = [view applyChangesToDocuments:viewDocChanges];
  274. HARD_ASSERT(viewChange.limboChanges.count == 0,
  275. "View returned limbo documents during local-only query execution.");
  276. FSTViewSnapshot *snapshot = viewChange.snapshot;
  277. FIRSnapshotMetadata *metadata =
  278. [FIRSnapshotMetadata snapshotMetadataWithPendingWrites:snapshot.hasPendingWrites
  279. fromCache:snapshot.fromCache];
  280. FIRQuerySnapshot *result = [FIRQuerySnapshot snapshotWithFirestore:query.firestore
  281. originalQuery:query.query
  282. snapshot:snapshot
  283. metadata:metadata];
  284. if (completion) {
  285. self->_userExecutor->Execute([=] { completion(result, nil); });
  286. }
  287. }];
  288. }
  289. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations
  290. completion:(nullable FSTVoidErrorBlock)completion {
  291. [self.workerDispatchQueue dispatchAsync:^{
  292. if (mutations.count == 0) {
  293. if (completion) {
  294. self->_userExecutor->Execute([=] { completion(nil); });
  295. }
  296. } else {
  297. [self.syncEngine writeMutations:mutations
  298. completion:^(NSError *error) {
  299. // Dispatch the result back onto the user dispatch queue.
  300. if (completion) {
  301. self->_userExecutor->Execute([=] { completion(error); });
  302. }
  303. }];
  304. }
  305. }];
  306. };
  307. - (void)transactionWithRetries:(int)retries
  308. updateBlock:(FSTTransactionBlock)updateBlock
  309. completion:(FSTVoidIDErrorBlock)completion {
  310. [self.workerDispatchQueue dispatchAsync:^{
  311. [self.syncEngine
  312. transactionWithRetries:retries
  313. workerDispatchQueue:self.workerDispatchQueue
  314. updateBlock:updateBlock
  315. completion:^(id _Nullable result, NSError *_Nullable error) {
  316. // Dispatch the result back onto the user dispatch queue.
  317. if (completion) {
  318. self->_userExecutor->Execute([=] { completion(result, error); });
  319. }
  320. }];
  321. }];
  322. }
  323. - (const DatabaseInfo *)databaseInfo {
  324. return &_databaseInfo;
  325. }
  326. - (const DatabaseId *)databaseID {
  327. return &_databaseInfo.database_id();
  328. }
  329. @end
  330. NS_ASSUME_NONNULL_END