FSTFirestoreClient.mm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. bool initialized = false;
  115. __weak __typeof__(self) weakSelf = self;
  116. auto credentialChangeListener = [initialized, userPromise, weakSelf,
  117. workerDispatchQueue](User user) mutable {
  118. __typeof__(self) strongSelf = weakSelf;
  119. if (!strongSelf) return;
  120. if (!initialized) {
  121. initialized = true;
  122. userPromise->set_value(user);
  123. } else {
  124. [workerDispatchQueue dispatchAsync:^{
  125. [strongSelf credentialDidChangeWithUser:user];
  126. }];
  127. }
  128. };
  129. _credentialsProvider->SetCredentialChangeListener(credentialChangeListener);
  130. // Defer initialization until we get the current user from the credentialChangeListener. This is
  131. // guaranteed to be synchronously dispatched onto our worker queue, so we will be initialized
  132. // before any subsequently queued work runs.
  133. [_workerDispatchQueue dispatchAsync:^{
  134. User user = userPromise->get_future().get();
  135. [self initializeWithUser:user usePersistence:usePersistence];
  136. }];
  137. }
  138. return self;
  139. }
  140. - (void)initializeWithUser:(const User &)user usePersistence:(BOOL)usePersistence {
  141. // Do all of our initialization on our own dispatch queue.
  142. [self.workerDispatchQueue verifyIsCurrentQueue];
  143. LOG_DEBUG("Initializing. Current user: %s", user.uid());
  144. // Note: The initialization work must all be synchronous (we can't dispatch more work) since
  145. // external write/listen operations could get queued to run before that subsequent work
  146. // completes.
  147. if (usePersistence) {
  148. Path dir = [FSTLevelDB storageDirectoryForDatabaseInfo:*self.databaseInfo
  149. documentsDirectory:[FSTLevelDB documentsDirectory]];
  150. FSTSerializerBeta *remoteSerializer =
  151. [[FSTSerializerBeta alloc] initWithDatabaseID:&self.databaseInfo->database_id()];
  152. FSTLocalSerializer *serializer =
  153. [[FSTLocalSerializer alloc] initWithRemoteSerializer:remoteSerializer];
  154. _persistence = [[FSTLevelDB alloc] initWithDirectory:std::move(dir) serializer:serializer];
  155. } else {
  156. _persistence = [FSTMemoryPersistence persistenceWithEagerGC];
  157. }
  158. Status status = [_persistence start];
  159. if (!status.ok()) {
  160. // If local storage fails to start then just throw up our hands: the error is unrecoverable.
  161. // There's nothing an end-user can do and nearly all failures indicate the developer is doing
  162. // something grossly wrong so we should stop them cold in their tracks with a failure they
  163. // can't ignore.
  164. [NSException raise:NSInternalInconsistencyException
  165. format:@"Failed to open DB: %s", status.ToString().c_str()];
  166. }
  167. _localStore = [[FSTLocalStore alloc] initWithPersistence:_persistence initialUser:user];
  168. FSTDatastore *datastore = [FSTDatastore datastoreWithDatabase:self.databaseInfo
  169. workerDispatchQueue:self.workerDispatchQueue
  170. credentials:_credentialsProvider];
  171. _remoteStore = [[FSTRemoteStore alloc] initWithLocalStore:_localStore
  172. datastore:datastore
  173. workerDispatchQueue:self.workerDispatchQueue];
  174. _syncEngine = [[FSTSyncEngine alloc] initWithLocalStore:_localStore
  175. remoteStore:_remoteStore
  176. initialUser:user];
  177. _eventManager = [FSTEventManager eventManagerWithSyncEngine:_syncEngine];
  178. // Setup wiring for remote store.
  179. _remoteStore.syncEngine = _syncEngine;
  180. _remoteStore.onlineStateDelegate = self;
  181. // NOTE: RemoteStore depends on LocalStore (for persisting stream tokens, refilling mutation
  182. // queue, etc.) so must be started after LocalStore.
  183. [_localStore start];
  184. [_remoteStore start];
  185. }
  186. - (void)credentialDidChangeWithUser:(const User &)user {
  187. [self.workerDispatchQueue verifyIsCurrentQueue];
  188. LOG_DEBUG("Credential Changed. Current user: %s", user.uid());
  189. [self.syncEngine credentialDidChangeWithUser:user];
  190. }
  191. - (void)applyChangedOnlineState:(OnlineState)onlineState {
  192. [self.syncEngine applyChangedOnlineState:onlineState];
  193. [self.eventManager applyChangedOnlineState:onlineState];
  194. }
  195. - (void)disableNetworkWithCompletion:(nullable FSTVoidErrorBlock)completion {
  196. [self.workerDispatchQueue dispatchAsync:^{
  197. [self.remoteStore disableNetwork];
  198. if (completion) {
  199. self->_userExecutor->Execute([=] { completion(nil); });
  200. }
  201. }];
  202. }
  203. - (void)enableNetworkWithCompletion:(nullable FSTVoidErrorBlock)completion {
  204. [self.workerDispatchQueue dispatchAsync:^{
  205. [self.remoteStore enableNetwork];
  206. if (completion) {
  207. self->_userExecutor->Execute([=] { completion(nil); });
  208. }
  209. }];
  210. }
  211. - (void)shutdownWithCompletion:(nullable FSTVoidErrorBlock)completion {
  212. [self.workerDispatchQueue dispatchAsync:^{
  213. self->_credentialsProvider->SetCredentialChangeListener(nullptr);
  214. [self.remoteStore shutdown];
  215. [self.persistence shutdown];
  216. if (completion) {
  217. self->_userExecutor->Execute([=] { completion(nil); });
  218. }
  219. }];
  220. }
  221. - (FSTQueryListener *)listenToQuery:(FSTQuery *)query
  222. options:(FSTListenOptions *)options
  223. viewSnapshotHandler:(FSTViewSnapshotHandler)viewSnapshotHandler {
  224. FSTQueryListener *listener = [[FSTQueryListener alloc] initWithQuery:query
  225. options:options
  226. viewSnapshotHandler:viewSnapshotHandler];
  227. [self.workerDispatchQueue dispatchAsync:^{
  228. [self.eventManager addListener:listener];
  229. }];
  230. return listener;
  231. }
  232. - (void)removeListener:(FSTQueryListener *)listener {
  233. [self.workerDispatchQueue dispatchAsync:^{
  234. [self.eventManager removeListener:listener];
  235. }];
  236. }
  237. - (void)getDocumentFromLocalCache:(FIRDocumentReference *)doc
  238. completion:(void (^)(FIRDocumentSnapshot *_Nullable document,
  239. NSError *_Nullable error))completion {
  240. [self.workerDispatchQueue dispatchAsync:^{
  241. FSTMaybeDocument *maybeDoc = [self.localStore readDocument:doc.key];
  242. FIRDocumentSnapshot *_Nullable result = nil;
  243. NSError *_Nullable error = nil;
  244. if (maybeDoc) {
  245. FSTDocument *_Nullable document =
  246. ([maybeDoc isKindOfClass:[FSTDocument class]]) ? (FSTDocument *)maybeDoc : nil;
  247. result = [FIRDocumentSnapshot snapshotWithFirestore:doc.firestore
  248. documentKey:doc.key
  249. document:document
  250. fromCache:YES];
  251. } else {
  252. error = [NSError errorWithDomain:FIRFirestoreErrorDomain
  253. code:FIRFirestoreErrorCodeUnavailable
  254. userInfo:@{
  255. NSLocalizedDescriptionKey :
  256. @"Failed to get document from cache. (However, this document "
  257. @"may exist on the server. Run again without setting source to "
  258. @"FIRFirestoreSourceCache to attempt to retrieve the document "
  259. @"from the server.)",
  260. }];
  261. }
  262. if (completion) {
  263. self->_userExecutor->Execute([=] { completion(result, error); });
  264. }
  265. }];
  266. }
  267. - (void)getDocumentsFromLocalCache:(FIRQuery *)query
  268. completion:(void (^)(FIRQuerySnapshot *_Nullable query,
  269. NSError *_Nullable error))completion {
  270. [self.workerDispatchQueue dispatchAsync:^{
  271. FSTDocumentDictionary *docs = [self.localStore executeQuery:query.query];
  272. FSTView *view = [[FSTView alloc] initWithQuery:query.query remoteDocuments:DocumentKeySet{}];
  273. FSTViewDocumentChanges *viewDocChanges = [view computeChangesWithDocuments:docs];
  274. FSTViewChange *viewChange = [view applyChangesToDocuments:viewDocChanges];
  275. HARD_ASSERT(viewChange.limboChanges.count == 0,
  276. "View returned limbo documents during local-only query execution.");
  277. FSTViewSnapshot *snapshot = viewChange.snapshot;
  278. FIRSnapshotMetadata *metadata =
  279. [FIRSnapshotMetadata snapshotMetadataWithPendingWrites:snapshot.hasPendingWrites
  280. fromCache:snapshot.fromCache];
  281. FIRQuerySnapshot *result = [FIRQuerySnapshot snapshotWithFirestore:query.firestore
  282. originalQuery:query.query
  283. snapshot:snapshot
  284. metadata:metadata];
  285. if (completion) {
  286. self->_userExecutor->Execute([=] { completion(result, nil); });
  287. }
  288. }];
  289. }
  290. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations
  291. completion:(nullable FSTVoidErrorBlock)completion {
  292. [self.workerDispatchQueue dispatchAsync:^{
  293. if (mutations.count == 0) {
  294. if (completion) {
  295. self->_userExecutor->Execute([=] { completion(nil); });
  296. }
  297. } else {
  298. [self.syncEngine writeMutations:mutations
  299. completion:^(NSError *error) {
  300. // Dispatch the result back onto the user dispatch queue.
  301. if (completion) {
  302. self->_userExecutor->Execute([=] { completion(error); });
  303. }
  304. }];
  305. }
  306. }];
  307. };
  308. - (void)transactionWithRetries:(int)retries
  309. updateBlock:(FSTTransactionBlock)updateBlock
  310. completion:(FSTVoidIDErrorBlock)completion {
  311. [self.workerDispatchQueue dispatchAsync:^{
  312. [self.syncEngine
  313. transactionWithRetries:retries
  314. workerDispatchQueue:self.workerDispatchQueue
  315. updateBlock:updateBlock
  316. completion:^(id _Nullable result, NSError *_Nullable error) {
  317. // Dispatch the result back onto the user dispatch queue.
  318. if (completion) {
  319. self->_userExecutor->Execute([=] { completion(result, error); });
  320. }
  321. }];
  322. }];
  323. }
  324. - (const DatabaseInfo *)databaseInfo {
  325. return &_databaseInfo;
  326. }
  327. - (const DatabaseId *)databaseID {
  328. return &_databaseInfo.database_id();
  329. }
  330. @end
  331. NS_ASSUME_NONNULL_END