FSTFirestoreClient.mm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. #import <future>
  18. #import "Firestore/Source/Core/FSTEventManager.h"
  19. #import "Firestore/Source/Core/FSTSyncEngine.h"
  20. #import "Firestore/Source/Core/FSTTransaction.h"
  21. #import "Firestore/Source/Local/FSTEagerGarbageCollector.h"
  22. #import "Firestore/Source/Local/FSTLevelDB.h"
  23. #import "Firestore/Source/Local/FSTLocalSerializer.h"
  24. #import "Firestore/Source/Local/FSTLocalStore.h"
  25. #import "Firestore/Source/Local/FSTMemoryPersistence.h"
  26. #import "Firestore/Source/Local/FSTNoOpGarbageCollector.h"
  27. #import "Firestore/Source/Remote/FSTDatastore.h"
  28. #import "Firestore/Source/Remote/FSTRemoteStore.h"
  29. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  30. #import "Firestore/Source/Util/FSTAssert.h"
  31. #import "Firestore/Source/Util/FSTClasses.h"
  32. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  33. #import "Firestore/Source/Util/FSTLogger.h"
  34. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  35. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  36. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  37. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  38. namespace util = firebase::firestore::util;
  39. using firebase::firestore::auth::CredentialsProvider;
  40. using firebase::firestore::auth::User;
  41. using firebase::firestore::core::DatabaseInfo;
  42. using firebase::firestore::model::DatabaseId;
  43. NS_ASSUME_NONNULL_BEGIN
  44. @interface FSTFirestoreClient () {
  45. DatabaseInfo _databaseInfo;
  46. }
  47. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  48. usePersistence:(BOOL)usePersistence
  49. credentialsProvider:
  50. (CredentialsProvider *)credentialsProvider // no passing ownership
  51. userDispatchQueue:(FSTDispatchQueue *)userDispatchQueue
  52. workerDispatchQueue:(FSTDispatchQueue *)queue NS_DESIGNATED_INITIALIZER;
  53. @property(nonatomic, assign, readonly) const DatabaseInfo *databaseInfo;
  54. @property(nonatomic, strong, readonly) FSTEventManager *eventManager;
  55. @property(nonatomic, strong, readonly) id<FSTPersistence> persistence;
  56. @property(nonatomic, strong, readonly) FSTSyncEngine *syncEngine;
  57. @property(nonatomic, strong, readonly) FSTRemoteStore *remoteStore;
  58. @property(nonatomic, strong, readonly) FSTLocalStore *localStore;
  59. /**
  60. * Dispatch queue responsible for all of our internal processing. When we get incoming work from
  61. * the user (via public API) or the network (incoming GRPC messages), we should always dispatch
  62. * onto this queue. This ensures our internal data structures are never accessed from multiple
  63. * threads simultaneously.
  64. */
  65. @property(nonatomic, strong, readonly) FSTDispatchQueue *workerDispatchQueue;
  66. // Does not own the CredentialsProvider instance.
  67. @property(nonatomic, assign, readonly) CredentialsProvider *credentialsProvider;
  68. @end
  69. @implementation FSTFirestoreClient
  70. + (instancetype)clientWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  71. usePersistence:(BOOL)usePersistence
  72. credentialsProvider:
  73. (CredentialsProvider *)credentialsProvider // no passing ownership
  74. userDispatchQueue:(FSTDispatchQueue *)userDispatchQueue
  75. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue {
  76. return [[FSTFirestoreClient alloc] initWithDatabaseInfo:databaseInfo
  77. usePersistence:usePersistence
  78. credentialsProvider:credentialsProvider
  79. userDispatchQueue:userDispatchQueue
  80. workerDispatchQueue:workerDispatchQueue];
  81. }
  82. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  83. usePersistence:(BOOL)usePersistence
  84. credentialsProvider:
  85. (CredentialsProvider *)credentialsProvider // no passing ownership
  86. userDispatchQueue:(FSTDispatchQueue *)userDispatchQueue
  87. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue {
  88. if (self = [super init]) {
  89. _databaseInfo = databaseInfo;
  90. _credentialsProvider = credentialsProvider;
  91. _userDispatchQueue = userDispatchQueue;
  92. _workerDispatchQueue = workerDispatchQueue;
  93. auto userPromise = std::make_shared<std::promise<User>>();
  94. __weak typeof(self) weakSelf = self;
  95. auto userChangeListener = [initialized = false, userPromise, weakSelf,
  96. workerDispatchQueue](User user) mutable {
  97. typeof(self) strongSelf = weakSelf;
  98. if (!strongSelf) return;
  99. if (!initialized) {
  100. initialized = true;
  101. userPromise->set_value(user);
  102. } else {
  103. [workerDispatchQueue dispatchAsync:^{
  104. [strongSelf userDidChange:user];
  105. }];
  106. }
  107. };
  108. _credentialsProvider->SetUserChangeListener(userChangeListener);
  109. // Defer initialization until we get the current user from the userChangeListener. This is
  110. // guaranteed to be synchronously dispatched onto our worker queue, so we will be initialized
  111. // before any subsequently queued work runs.
  112. [_workerDispatchQueue dispatchAsync:^{
  113. User user = userPromise->get_future().get();
  114. [self initializeWithUser:user usePersistence:usePersistence];
  115. }];
  116. }
  117. return self;
  118. }
  119. - (void)initializeWithUser:(const User &)user usePersistence:(BOOL)usePersistence {
  120. // Do all of our initialization on our own dispatch queue.
  121. [self.workerDispatchQueue verifyIsCurrentQueue];
  122. // Note: The initialization work must all be synchronous (we can't dispatch more work) since
  123. // external write/listen operations could get queued to run before that subsequent work
  124. // completes.
  125. id<FSTGarbageCollector> garbageCollector;
  126. if (usePersistence) {
  127. // TODO(http://b/33384523): For now we just disable garbage collection when persistence is
  128. // enabled.
  129. garbageCollector = [[FSTNoOpGarbageCollector alloc] init];
  130. NSString *dir = [FSTLevelDB storageDirectoryForDatabaseInfo:*self.databaseInfo
  131. documentsDirectory:[FSTLevelDB documentsDirectory]];
  132. FSTSerializerBeta *remoteSerializer =
  133. [[FSTSerializerBeta alloc] initWithDatabaseID:&self.databaseInfo->database_id()];
  134. FSTLocalSerializer *serializer =
  135. [[FSTLocalSerializer alloc] initWithRemoteSerializer:remoteSerializer];
  136. _persistence = [[FSTLevelDB alloc] initWithDirectory:dir serializer:serializer];
  137. } else {
  138. garbageCollector = [[FSTEagerGarbageCollector alloc] init];
  139. _persistence = [FSTMemoryPersistence persistence];
  140. }
  141. NSError *error;
  142. if (![_persistence start:&error]) {
  143. // If local storage fails to start then just throw up our hands: the error is unrecoverable.
  144. // There's nothing an end-user can do and nearly all failures indicate the developer is doing
  145. // something grossly wrong so we should stop them cold in their tracks with a failure they
  146. // can't ignore.
  147. [NSException raise:NSInternalInconsistencyException format:@"Failed to open DB: %@", error];
  148. }
  149. _localStore = [[FSTLocalStore alloc] initWithPersistence:_persistence
  150. garbageCollector:garbageCollector
  151. initialUser:user];
  152. FSTDatastore *datastore = [FSTDatastore datastoreWithDatabase:self.databaseInfo
  153. workerDispatchQueue:self.workerDispatchQueue
  154. credentials:_credentialsProvider];
  155. _remoteStore = [[FSTRemoteStore alloc] initWithLocalStore:_localStore
  156. datastore:datastore
  157. workerDispatchQueue:self.workerDispatchQueue];
  158. _syncEngine = [[FSTSyncEngine alloc] initWithLocalStore:_localStore
  159. remoteStore:_remoteStore
  160. initialUser:user];
  161. _eventManager = [FSTEventManager eventManagerWithSyncEngine:_syncEngine];
  162. // Setup wiring for remote store.
  163. _remoteStore.syncEngine = _syncEngine;
  164. _remoteStore.onlineStateDelegate = self;
  165. // NOTE: RemoteStore depends on LocalStore (for persisting stream tokens, refilling mutation
  166. // queue, etc.) so must be started after LocalStore.
  167. [_localStore start];
  168. [_remoteStore start];
  169. }
  170. - (void)userDidChange:(const User &)user {
  171. [self.workerDispatchQueue verifyIsCurrentQueue];
  172. FSTLog(@"User Changed: %s", user.uid().c_str());
  173. [self.syncEngine userDidChange:user];
  174. }
  175. - (void)applyChangedOnlineState:(FSTOnlineState)onlineState {
  176. [self.syncEngine applyChangedOnlineState:onlineState];
  177. [self.eventManager applyChangedOnlineState:onlineState];
  178. }
  179. - (void)disableNetworkWithCompletion:(nullable FSTVoidErrorBlock)completion {
  180. [self.workerDispatchQueue dispatchAsync:^{
  181. [self.remoteStore disableNetwork];
  182. if (completion) {
  183. [self.userDispatchQueue dispatchAsync:^{
  184. completion(nil);
  185. }];
  186. }
  187. }];
  188. }
  189. - (void)enableNetworkWithCompletion:(nullable FSTVoidErrorBlock)completion {
  190. [self.workerDispatchQueue dispatchAsync:^{
  191. [self.remoteStore enableNetwork];
  192. if (completion) {
  193. [self.userDispatchQueue dispatchAsync:^{
  194. completion(nil);
  195. }];
  196. }
  197. }];
  198. }
  199. - (void)shutdownWithCompletion:(nullable FSTVoidErrorBlock)completion {
  200. [self.workerDispatchQueue dispatchAsync:^{
  201. self->_credentialsProvider->SetUserChangeListener(nullptr);
  202. [self.remoteStore shutdown];
  203. [self.localStore shutdown];
  204. [self.persistence shutdown];
  205. if (completion) {
  206. [self.userDispatchQueue dispatchAsync:^{
  207. completion(nil);
  208. }];
  209. }
  210. }];
  211. }
  212. - (FSTQueryListener *)listenToQuery:(FSTQuery *)query
  213. options:(FSTListenOptions *)options
  214. viewSnapshotHandler:(FSTViewSnapshotHandler)viewSnapshotHandler {
  215. FSTQueryListener *listener = [[FSTQueryListener alloc] initWithQuery:query
  216. options:options
  217. viewSnapshotHandler:viewSnapshotHandler];
  218. [self.workerDispatchQueue dispatchAsync:^{
  219. [self.eventManager addListener:listener];
  220. }];
  221. return listener;
  222. }
  223. - (void)removeListener:(FSTQueryListener *)listener {
  224. [self.workerDispatchQueue dispatchAsync:^{
  225. [self.eventManager removeListener:listener];
  226. }];
  227. }
  228. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations
  229. completion:(nullable FSTVoidErrorBlock)completion {
  230. [self.workerDispatchQueue dispatchAsync:^{
  231. if (mutations.count == 0) {
  232. if (completion) {
  233. [self.userDispatchQueue dispatchAsync:^{
  234. completion(nil);
  235. }];
  236. }
  237. } else {
  238. [self.syncEngine writeMutations:mutations
  239. completion:^(NSError *error) {
  240. // Dispatch the result back onto the user dispatch queue.
  241. if (completion) {
  242. [self.userDispatchQueue dispatchAsync:^{
  243. completion(error);
  244. }];
  245. }
  246. }];
  247. }
  248. }];
  249. };
  250. - (void)transactionWithRetries:(int)retries
  251. updateBlock:(FSTTransactionBlock)updateBlock
  252. completion:(FSTVoidIDErrorBlock)completion {
  253. [self.workerDispatchQueue dispatchAsync:^{
  254. [self.syncEngine transactionWithRetries:retries
  255. workerDispatchQueue:self.workerDispatchQueue
  256. updateBlock:updateBlock
  257. completion:^(id _Nullable result, NSError *_Nullable error) {
  258. // Dispatch the result back onto the user dispatch queue.
  259. if (completion) {
  260. [self.userDispatchQueue dispatchAsync:^{
  261. completion(result, error);
  262. }];
  263. }
  264. }];
  265. }];
  266. }
  267. - (const DatabaseInfo *)databaseInfo {
  268. return &_databaseInfo;
  269. }
  270. - (const DatabaseId *)databaseID {
  271. return &_databaseInfo.database_id();
  272. }
  273. @end
  274. NS_ASSUME_NONNULL_END