FSTFirestoreClient.mm 16 KB

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