FIRFirestore.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 "FIRFirestore.h"
  17. #import <FirebaseCore/FIRApp.h>
  18. #import <FirebaseCore/FIRLogger.h>
  19. #import <FirebaseCore/FIROptions.h>
  20. #import "FIRFirestoreSettings.h"
  21. #import "Firestore/Source/API/FIRCollectionReference+Internal.h"
  22. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  23. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  24. #import "Firestore/Source/API/FIRTransaction+Internal.h"
  25. #import "Firestore/Source/API/FIRWriteBatch+Internal.h"
  26. #import "Firestore/Source/API/FSTUserDataConverter.h"
  27. #import "Firestore/Source/Auth/FSTCredentialsProvider.h"
  28. #import "Firestore/Source/Core/FSTFirestoreClient.h"
  29. #import "Firestore/Source/Model/FSTDocumentKey.h"
  30. #import "Firestore/Source/Model/FSTPath.h"
  31. #import "Firestore/Source/Util/FSTAssert.h"
  32. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  33. #import "Firestore/Source/Util/FSTLogger.h"
  34. #import "Firestore/Source/Util/FSTUsageValidation.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::core::DatabaseInfo;
  40. using firebase::firestore::model::DatabaseId;
  41. NS_ASSUME_NONNULL_BEGIN
  42. extern "C" NSString *const FIRFirestoreErrorDomain = @"FIRFirestoreErrorDomain";
  43. @interface FIRFirestore () {
  44. /** The actual owned DatabaseId instance is allocated in FIRFirestore. */
  45. firebase::firestore::model::DatabaseId _databaseID;
  46. }
  47. @property(nonatomic, strong) NSString *persistenceKey;
  48. @property(nonatomic, strong) id<FSTCredentialsProvider> credentialsProvider;
  49. @property(nonatomic, strong) FSTDispatchQueue *workerDispatchQueue;
  50. // Note that `client` is updated after initialization, but marking this readwrite would generate an
  51. // incorrect setter (since we make the assignment to `client` inside an `@synchronized` block.
  52. @property(nonatomic, strong, readonly) FSTFirestoreClient *client;
  53. @property(nonatomic, strong, readonly) FSTUserDataConverter *dataConverter;
  54. @end
  55. @implementation FIRFirestore {
  56. // All guarded by @synchronized(self)
  57. FIRFirestoreSettings *_settings;
  58. FSTFirestoreClient *_client;
  59. }
  60. + (NSMutableDictionary<NSString *, FIRFirestore *> *)instances {
  61. static dispatch_once_t token = 0;
  62. static NSMutableDictionary<NSString *, FIRFirestore *> *instances;
  63. dispatch_once(&token, ^{
  64. instances = [NSMutableDictionary dictionary];
  65. });
  66. return instances;
  67. }
  68. + (instancetype)firestore {
  69. FIRApp *app = [FIRApp defaultApp];
  70. if (!app) {
  71. FSTThrowInvalidUsage(@"FIRAppNotConfiguredException",
  72. @"Failed to get FirebaseApp instance. Please call FirebaseApp.configure() "
  73. @"before using Firestore");
  74. }
  75. return
  76. [self firestoreForApp:app database:util::WrapNSStringNoCopy(DatabaseId::kDefaultDatabaseId)];
  77. }
  78. + (instancetype)firestoreForApp:(FIRApp *)app {
  79. return
  80. [self firestoreForApp:app database:util::WrapNSStringNoCopy(DatabaseId::kDefaultDatabaseId)];
  81. }
  82. // TODO(b/62410906): make this public
  83. + (instancetype)firestoreForApp:(FIRApp *)app database:(NSString *)database {
  84. if (!app) {
  85. FSTThrowInvalidArgument(
  86. @"FirebaseApp instance may not be nil. Use FirebaseApp.app() if you'd "
  87. "like to use the default FirebaseApp instance.");
  88. }
  89. if (!database) {
  90. FSTThrowInvalidArgument(
  91. @"database identifier may not be nil. Use '%@' if you want the default "
  92. "database",
  93. util::WrapNSStringNoCopy(DatabaseId::kDefaultDatabaseId));
  94. }
  95. NSString *key = [NSString stringWithFormat:@"%@|%@", app.name, database];
  96. NSMutableDictionary<NSString *, FIRFirestore *> *instances = self.instances;
  97. @synchronized(instances) {
  98. FIRFirestore *firestore = instances[key];
  99. if (!firestore) {
  100. NSString *projectID = app.options.projectID;
  101. FSTAssert(projectID, @"FirebaseOptions.projectID cannot be nil.");
  102. FSTDispatchQueue *workerDispatchQueue = [FSTDispatchQueue
  103. queueWith:dispatch_queue_create("com.google.firebase.firestore", DISPATCH_QUEUE_SERIAL)];
  104. id<FSTCredentialsProvider> credentialsProvider;
  105. credentialsProvider = [[FSTFirebaseCredentialsProvider alloc] initWithApp:app];
  106. NSString *persistenceKey = app.name;
  107. firestore = [[FIRFirestore alloc] initWithProjectID:projectID
  108. database:database
  109. persistenceKey:persistenceKey
  110. credentialsProvider:credentialsProvider
  111. workerDispatchQueue:workerDispatchQueue
  112. firebaseApp:app];
  113. instances[key] = firestore;
  114. }
  115. return firestore;
  116. }
  117. }
  118. - (instancetype)initWithProjectID:(NSString *)projectID
  119. database:(NSString *)database
  120. persistenceKey:(NSString *)persistenceKey
  121. credentialsProvider:(id<FSTCredentialsProvider>)credentialsProvider
  122. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  123. firebaseApp:(FIRApp *)app {
  124. if (self = [super init]) {
  125. _databaseID = DatabaseId(util::MakeStringView(projectID), util::MakeStringView(database));
  126. FSTPreConverterBlock block = ^id _Nullable(id _Nullable input) {
  127. if ([input isKindOfClass:[FIRDocumentReference class]]) {
  128. FIRDocumentReference *documentReference = (FIRDocumentReference *)input;
  129. return [[FSTDocumentKeyReference alloc] initWithKey:documentReference.key
  130. databaseID:documentReference.firestore.databaseID];
  131. } else {
  132. return input;
  133. }
  134. };
  135. _dataConverter =
  136. [[FSTUserDataConverter alloc] initWithDatabaseID:&_databaseID preConverter:block];
  137. _persistenceKey = persistenceKey;
  138. _credentialsProvider = credentialsProvider;
  139. _workerDispatchQueue = workerDispatchQueue;
  140. _app = app;
  141. _settings = [[FIRFirestoreSettings alloc] init];
  142. }
  143. return self;
  144. }
  145. - (FIRFirestoreSettings *)settings {
  146. @synchronized(self) {
  147. // Disallow mutation of our internal settings
  148. return [_settings copy];
  149. }
  150. }
  151. - (void)setSettings:(FIRFirestoreSettings *)settings {
  152. @synchronized(self) {
  153. // As a special exception, don't throw if the same settings are passed repeatedly. This should
  154. // make it more friendly to create a Firestore instance.
  155. if (_client && ![_settings isEqual:settings]) {
  156. FSTThrowInvalidUsage(@"FIRIllegalStateException",
  157. @"Firestore instance has already been started and its settings can no "
  158. "longer be changed. You can only set settings before calling any "
  159. "other methods on a Firestore instance.");
  160. }
  161. _settings = [settings copy];
  162. }
  163. }
  164. /**
  165. * Ensures that the FirestoreClient is configured and returns it.
  166. */
  167. - (FSTFirestoreClient *)client {
  168. [self ensureClientConfigured];
  169. return _client;
  170. }
  171. - (void)ensureClientConfigured {
  172. @synchronized(self) {
  173. if (!_client) {
  174. // These values are validated elsewhere; this is just double-checking:
  175. FSTAssert(_settings.host, @"FirestoreSettings.host cannot be nil.");
  176. FSTAssert(_settings.dispatchQueue, @"FirestoreSettings.dispatchQueue cannot be nil.");
  177. const DatabaseInfo database_info(*self.databaseID, util::MakeStringView(_persistenceKey),
  178. util::MakeStringView(_settings.host), _settings.sslEnabled);
  179. FSTDispatchQueue *userDispatchQueue = [FSTDispatchQueue queueWith:_settings.dispatchQueue];
  180. _client = [FSTFirestoreClient clientWithDatabaseInfo:database_info
  181. usePersistence:_settings.persistenceEnabled
  182. credentialsProvider:_credentialsProvider
  183. userDispatchQueue:userDispatchQueue
  184. workerDispatchQueue:_workerDispatchQueue];
  185. }
  186. }
  187. }
  188. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  189. if (!collectionPath) {
  190. FSTThrowInvalidArgument(@"Collection path cannot be nil.");
  191. }
  192. [self ensureClientConfigured];
  193. FSTResourcePath *path = [FSTResourcePath pathWithString:collectionPath];
  194. return [FIRCollectionReference referenceWithPath:path firestore:self];
  195. }
  196. - (FIRDocumentReference *)documentWithPath:(NSString *)documentPath {
  197. if (!documentPath) {
  198. FSTThrowInvalidArgument(@"Document path cannot be nil.");
  199. }
  200. [self ensureClientConfigured];
  201. FSTResourcePath *path = [FSTResourcePath pathWithString:documentPath];
  202. return [FIRDocumentReference referenceWithPath:path firestore:self];
  203. }
  204. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **))updateBlock
  205. dispatchQueue:(dispatch_queue_t)queue
  206. completion:
  207. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  208. // We wrap the function they provide in order to use internal implementation classes for
  209. // FSTTransaction, and to run the user callback block on the proper queue.
  210. if (!updateBlock) {
  211. FSTThrowInvalidArgument(@"Transaction block cannot be nil.");
  212. } else if (!completion) {
  213. FSTThrowInvalidArgument(@"Transaction completion block cannot be nil.");
  214. }
  215. FSTTransactionBlock wrappedUpdate =
  216. ^(FSTTransaction *internalTransaction,
  217. void (^internalCompletion)(id _Nullable, NSError *_Nullable)) {
  218. FIRTransaction *transaction =
  219. [FIRTransaction transactionWithFSTTransaction:internalTransaction firestore:self];
  220. dispatch_async(queue, ^{
  221. NSError *_Nullable error = nil;
  222. id _Nullable result = updateBlock(transaction, &error);
  223. if (error) {
  224. // Force the result to be nil in the case of an error, in case the user set both.
  225. result = nil;
  226. }
  227. internalCompletion(result, error);
  228. });
  229. };
  230. [self.client transactionWithRetries:5 updateBlock:wrappedUpdate completion:completion];
  231. }
  232. - (FIRWriteBatch *)batch {
  233. [self ensureClientConfigured];
  234. return [FIRWriteBatch writeBatchWithFirestore:self];
  235. }
  236. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **error))updateBlock
  237. completion:
  238. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  239. static dispatch_queue_t transactionDispatchQueue;
  240. static dispatch_once_t onceToken;
  241. dispatch_once(&onceToken, ^{
  242. transactionDispatchQueue = dispatch_queue_create("com.google.firebase.firestore.transaction",
  243. DISPATCH_QUEUE_CONCURRENT);
  244. });
  245. [self runTransactionWithBlock:updateBlock
  246. dispatchQueue:transactionDispatchQueue
  247. completion:completion];
  248. }
  249. - (void)shutdownWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  250. FSTFirestoreClient *client;
  251. @synchronized(self) {
  252. client = _client;
  253. _client = nil;
  254. }
  255. if (!client) {
  256. // We should be dispatching the callback on the user dispatch queue but if the client is nil
  257. // here that queue was never created.
  258. completion(nil);
  259. } else {
  260. [client shutdownWithCompletion:completion];
  261. }
  262. }
  263. + (BOOL)isLoggingEnabled {
  264. return FIRIsLoggableLevel(FIRLoggerLevelDebug, NO);
  265. }
  266. + (void)enableLogging:(BOOL)logging {
  267. FIRSetLoggerLevel(logging ? FIRLoggerLevelDebug : FIRLoggerLevelNotice);
  268. }
  269. - (void)enableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  270. [self ensureClientConfigured];
  271. [self.client enableNetworkWithCompletion:completion];
  272. }
  273. - (void)disableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable))completion {
  274. [self ensureClientConfigured];
  275. [self.client disableNetworkWithCompletion:completion];
  276. }
  277. - (const DatabaseId *)databaseID {
  278. return &_databaseID;
  279. }
  280. @end
  281. NS_ASSUME_NONNULL_END