FSTFirestoreClient.mm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. }
  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 isKindOfClass:[FSTDocument class]]) {
  244. FSTDocument *document = (FSTDocument *)maybeDoc;
  245. result = [FIRDocumentSnapshot snapshotWithFirestore:doc.firestore
  246. documentKey:doc.key
  247. document:document
  248. fromCache:YES
  249. hasPendingWrites:document.hasLocalMutations];
  250. } else if ([maybeDoc isKindOfClass:[FSTDeletedDocument class]]) {
  251. result = [FIRDocumentSnapshot snapshotWithFirestore:doc.firestore
  252. documentKey:doc.key
  253. document:nil
  254. fromCache:YES
  255. hasPendingWrites:NO];
  256. } else {
  257. error = [NSError errorWithDomain:FIRFirestoreErrorDomain
  258. code:FIRFirestoreErrorCodeUnavailable
  259. userInfo:@{
  260. NSLocalizedDescriptionKey :
  261. @"Failed to get document from cache. (However, this document "
  262. @"may exist on the server. Run again without setting source to "
  263. @"FIRFirestoreSourceCache to attempt to retrieve the document "
  264. @"from the server.)",
  265. }];
  266. }
  267. if (completion) {
  268. self->_userExecutor->Execute([=] { completion(result, error); });
  269. }
  270. }];
  271. }
  272. - (void)getDocumentsFromLocalCache:(FIRQuery *)query
  273. completion:(void (^)(FIRQuerySnapshot *_Nullable query,
  274. NSError *_Nullable error))completion {
  275. [self.workerDispatchQueue dispatchAsync:^{
  276. FSTDocumentDictionary *docs = [self.localStore executeQuery:query.query];
  277. FSTView *view = [[FSTView alloc] initWithQuery:query.query remoteDocuments:DocumentKeySet{}];
  278. FSTViewDocumentChanges *viewDocChanges = [view computeChangesWithDocuments:docs];
  279. FSTViewChange *viewChange = [view applyChangesToDocuments:viewDocChanges];
  280. HARD_ASSERT(viewChange.limboChanges.count == 0,
  281. "View returned limbo documents during local-only query execution.");
  282. FSTViewSnapshot *snapshot = viewChange.snapshot;
  283. FIRSnapshotMetadata *metadata =
  284. [FIRSnapshotMetadata snapshotMetadataWithPendingWrites:snapshot.hasPendingWrites
  285. fromCache:snapshot.fromCache];
  286. FIRQuerySnapshot *result = [FIRQuerySnapshot snapshotWithFirestore:query.firestore
  287. originalQuery:query.query
  288. snapshot:snapshot
  289. metadata:metadata];
  290. if (completion) {
  291. self->_userExecutor->Execute([=] { completion(result, nil); });
  292. }
  293. }];
  294. }
  295. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations
  296. completion:(nullable FSTVoidErrorBlock)completion {
  297. [self.workerDispatchQueue dispatchAsync:^{
  298. if (mutations.count == 0) {
  299. if (completion) {
  300. self->_userExecutor->Execute([=] { completion(nil); });
  301. }
  302. } else {
  303. [self.syncEngine writeMutations:mutations
  304. completion:^(NSError *error) {
  305. // Dispatch the result back onto the user dispatch queue.
  306. if (completion) {
  307. self->_userExecutor->Execute([=] { completion(error); });
  308. }
  309. }];
  310. }
  311. }];
  312. };
  313. - (void)transactionWithRetries:(int)retries
  314. updateBlock:(FSTTransactionBlock)updateBlock
  315. completion:(FSTVoidIDErrorBlock)completion {
  316. [self.workerDispatchQueue dispatchAsync:^{
  317. [self.syncEngine
  318. transactionWithRetries:retries
  319. workerDispatchQueue:self.workerDispatchQueue
  320. updateBlock:updateBlock
  321. completion:^(id _Nullable result, NSError *_Nullable error) {
  322. // Dispatch the result back onto the user dispatch queue.
  323. if (completion) {
  324. self->_userExecutor->Execute([=] { completion(result, error); });
  325. }
  326. }];
  327. }];
  328. }
  329. - (const DatabaseInfo *)databaseInfo {
  330. return &_databaseInfo;
  331. }
  332. - (const DatabaseId *)databaseID {
  333. return &_databaseInfo.database_id();
  334. }
  335. @end
  336. NS_ASSUME_NONNULL_END