FSTFirestoreClient.mm 16 KB

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