FSTFirestoreClient.m 12 KB

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