FSTFirestoreClient.mm 12 KB

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