FSTFirestoreClient.mm 16 KB

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