FIRFirestore.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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/FIRAppInternal.h>
  19. #import <FirebaseCore/FIRComponentContainer.h>
  20. #import <FirebaseCore/FIRLogger.h>
  21. #import <FirebaseCore/FIROptions.h>
  22. #include <memory>
  23. #include <string>
  24. #include <utility>
  25. #import "FIRFirestoreSettings.h"
  26. #import "Firestore/Source/API/FIRCollectionReference+Internal.h"
  27. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  28. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  29. #import "Firestore/Source/API/FIRTransaction+Internal.h"
  30. #import "Firestore/Source/API/FIRWriteBatch+Internal.h"
  31. #import "Firestore/Source/API/FSTFirestoreComponent.h"
  32. #import "Firestore/Source/API/FSTUserDataConverter.h"
  33. #import "Firestore/Source/Core/FSTFirestoreClient.h"
  34. #import "Firestore/Source/Util/FSTUsageValidation.h"
  35. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  36. #include "Firestore/core/src/firebase/firestore/auth/firebase_credentials_provider_apple.h"
  37. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  38. #include "Firestore/core/src/firebase/firestore/core/transaction.h"
  39. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  40. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  41. #include "Firestore/core/src/firebase/firestore/util/async_queue.h"
  42. #include "Firestore/core/src/firebase/firestore/util/executor_libdispatch.h"
  43. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  44. #include "Firestore/core/src/firebase/firestore/util/log.h"
  45. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  46. #include "absl/memory/memory.h"
  47. namespace util = firebase::firestore::util;
  48. using firebase::firestore::auth::CredentialsProvider;
  49. using firebase::firestore::auth::FirebaseCredentialsProvider;
  50. using firebase::firestore::core::DatabaseInfo;
  51. using firebase::firestore::core::Transaction;
  52. using firebase::firestore::model::DatabaseId;
  53. using firebase::firestore::model::ResourcePath;
  54. using util::AsyncQueue;
  55. using util::Executor;
  56. using util::ExecutorLibdispatch;
  57. NS_ASSUME_NONNULL_BEGIN
  58. extern "C" NSString *const FIRFirestoreErrorDomain = @"FIRFirestoreErrorDomain";
  59. #pragma mark - FIRFirestore
  60. @interface FIRFirestore () {
  61. /** The actual owned DatabaseId instance is allocated in FIRFirestore. */
  62. DatabaseId _databaseID;
  63. std::unique_ptr<CredentialsProvider> _credentialsProvider;
  64. }
  65. @property(nonatomic, strong) NSString *persistenceKey;
  66. // Note that `client` is updated after initialization, but marking this readwrite would generate an
  67. // incorrect setter (since we make the assignment to `client` inside an `@synchronized` block.
  68. @property(nonatomic, strong, readonly) FSTFirestoreClient *client;
  69. @property(nonatomic, strong, readonly) FSTUserDataConverter *dataConverter;
  70. @end
  71. @implementation FIRFirestore {
  72. // Ownership will be transferred to `FSTFirestoreClient` as soon as the client is created.
  73. std::unique_ptr<AsyncQueue> _workerQueue;
  74. // All guarded by @synchronized(self)
  75. FIRFirestoreSettings *_settings;
  76. FSTFirestoreClient *_client;
  77. }
  78. - (AsyncQueue *)workerQueue {
  79. return [_client workerQueue];
  80. }
  81. + (NSMutableDictionary<NSString *, FIRFirestore *> *)instances {
  82. static dispatch_once_t token = 0;
  83. static NSMutableDictionary<NSString *, FIRFirestore *> *instances;
  84. dispatch_once(&token, ^{
  85. instances = [NSMutableDictionary dictionary];
  86. });
  87. return instances;
  88. }
  89. + (void)initialize {
  90. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  91. [center addObserverForName:kFIRAppDeleteNotification
  92. object:nil
  93. queue:nil
  94. usingBlock:^(NSNotification *_Nonnull note) {
  95. NSString *appName = note.userInfo[kFIRAppNameKey];
  96. if (appName == nil) return;
  97. NSMutableDictionary *instances = [self instances];
  98. @synchronized(instances) {
  99. // Since the key for instances isn't just the app name, iterate over all the
  100. // keys to get the one(s) we have to delete. There could be multiple in case
  101. // the user calls firestoreForApp:database:.
  102. NSMutableArray *keysToDelete = [[NSMutableArray alloc] init];
  103. NSString *keyPrefix = [NSString stringWithFormat:@"%@|", appName];
  104. for (NSString *key in instances.allKeys) {
  105. if ([key hasPrefix:keyPrefix]) {
  106. [keysToDelete addObject:key];
  107. }
  108. }
  109. // Loop through the keys found and delete them from the stored instances.
  110. for (NSString *key in keysToDelete) {
  111. [instances removeObjectForKey:key];
  112. }
  113. }
  114. }];
  115. }
  116. + (instancetype)firestore {
  117. FIRApp *app = [FIRApp defaultApp];
  118. if (!app) {
  119. FSTThrowInvalidUsage(@"FIRAppNotConfiguredException",
  120. @"Failed to get FirebaseApp instance. Please call FirebaseApp.configure() "
  121. @"before using Firestore");
  122. }
  123. return [self firestoreForApp:app database:util::WrapNSString(DatabaseId::kDefault)];
  124. }
  125. + (instancetype)firestoreForApp:(FIRApp *)app {
  126. return [self firestoreForApp:app database:util::WrapNSString(DatabaseId::kDefault)];
  127. }
  128. // TODO(b/62410906): make this public
  129. + (instancetype)firestoreForApp:(FIRApp *)app database:(NSString *)database {
  130. if (!app) {
  131. FSTThrowInvalidArgument(@"FirebaseApp instance may not be nil. Use FirebaseApp.app() if you'd "
  132. "like to use the default FirebaseApp instance.");
  133. }
  134. if (!database) {
  135. FSTThrowInvalidArgument(@"database identifier may not be nil. Use '%s' if you want the default "
  136. "database",
  137. DatabaseId::kDefault);
  138. }
  139. id<FSTFirestoreMultiDBProvider> provider =
  140. FIR_COMPONENT(FSTFirestoreMultiDBProvider, app.container);
  141. return [provider firestoreForDatabase:database];
  142. }
  143. - (instancetype)initWithProjectID:(std::string)projectID
  144. database:(std::string)database
  145. persistenceKey:(NSString *)persistenceKey
  146. credentialsProvider:(std::unique_ptr<CredentialsProvider>)credentialsProvider
  147. workerQueue:(std::unique_ptr<AsyncQueue>)workerQueue
  148. firebaseApp:(FIRApp *)app {
  149. if (self = [super init]) {
  150. _databaseID = DatabaseId{std::move(projectID), std::move(database)};
  151. FSTPreConverterBlock block = ^id _Nullable(id _Nullable input) {
  152. if ([input isKindOfClass:[FIRDocumentReference class]]) {
  153. FIRDocumentReference *documentReference = (FIRDocumentReference *)input;
  154. return [[FSTDocumentKeyReference alloc] initWithKey:documentReference.key
  155. databaseID:documentReference.firestore.databaseID];
  156. } else {
  157. return input;
  158. }
  159. };
  160. _dataConverter = [[FSTUserDataConverter alloc] initWithDatabaseID:&_databaseID
  161. preConverter:block];
  162. _persistenceKey = persistenceKey;
  163. _credentialsProvider = std::move(credentialsProvider);
  164. _workerQueue = std::move(workerQueue);
  165. _app = app;
  166. _settings = [[FIRFirestoreSettings alloc] init];
  167. }
  168. return self;
  169. }
  170. - (FIRFirestoreSettings *)settings {
  171. @synchronized(self) {
  172. // Disallow mutation of our internal settings
  173. return [_settings copy];
  174. }
  175. }
  176. - (void)setSettings:(FIRFirestoreSettings *)settings {
  177. @synchronized(self) {
  178. // As a special exception, don't throw if the same settings are passed repeatedly. This should
  179. // make it more friendly to create a Firestore instance.
  180. if (_client && ![_settings isEqual:settings]) {
  181. FSTThrowInvalidUsage(@"FIRIllegalStateException",
  182. @"Firestore instance has already been started and its settings can no "
  183. "longer be changed. You can only set settings before calling any "
  184. "other methods on a Firestore instance.");
  185. }
  186. _settings = [settings copy];
  187. }
  188. }
  189. /**
  190. * Ensures that the FirestoreClient is configured and returns it.
  191. */
  192. - (FSTFirestoreClient *)client {
  193. [self ensureClientConfigured];
  194. return _client;
  195. }
  196. - (void)ensureClientConfigured {
  197. @synchronized(self) {
  198. if (!_client) {
  199. // These values are validated elsewhere; this is just double-checking:
  200. HARD_ASSERT(_settings.host, "FirestoreSettings.host cannot be nil.");
  201. HARD_ASSERT(_settings.dispatchQueue, "FirestoreSettings.dispatchQueue cannot be nil.");
  202. const DatabaseInfo database_info(*self.databaseID, util::MakeString(_persistenceKey),
  203. util::MakeString(_settings.host), _settings.sslEnabled);
  204. std::unique_ptr<Executor> userExecutor =
  205. absl::make_unique<ExecutorLibdispatch>(_settings.dispatchQueue);
  206. HARD_ASSERT(_workerQueue, "Expected non-null _workerQueue");
  207. _client = [FSTFirestoreClient clientWithDatabaseInfo:database_info
  208. settings:_settings
  209. credentialsProvider:_credentialsProvider.get()
  210. userExecutor:std::move(userExecutor)
  211. workerQueue:std::move(_workerQueue)];
  212. }
  213. }
  214. }
  215. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  216. if (!collectionPath) {
  217. FSTThrowInvalidArgument(@"Collection path cannot be nil.");
  218. }
  219. if ([collectionPath containsString:@"//"]) {
  220. FSTThrowInvalidArgument(@"Invalid path (%@). Paths must not contain // in them.",
  221. collectionPath);
  222. }
  223. [self ensureClientConfigured];
  224. const ResourcePath path = ResourcePath::FromString(util::MakeString(collectionPath));
  225. return [FIRCollectionReference referenceWithPath:path firestore:self];
  226. }
  227. - (FIRDocumentReference *)documentWithPath:(NSString *)documentPath {
  228. if (!documentPath) {
  229. FSTThrowInvalidArgument(@"Document path cannot be nil.");
  230. }
  231. if ([documentPath containsString:@"//"]) {
  232. FSTThrowInvalidArgument(@"Invalid path (%@). Paths must not contain // in them.", documentPath);
  233. }
  234. [self ensureClientConfigured];
  235. const ResourcePath path = ResourcePath::FromString(util::MakeString(documentPath));
  236. return [FIRDocumentReference referenceWithPath:path firestore:self];
  237. }
  238. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **))updateBlock
  239. dispatchQueue:(dispatch_queue_t)queue
  240. completion:
  241. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  242. // We wrap the function they provide in order to use internal implementation classes for
  243. // ransaction, and to run the user callback block on the proper queue.
  244. if (!updateBlock) {
  245. FSTThrowInvalidArgument(@"Transaction block cannot be nil.");
  246. } else if (!completion) {
  247. FSTThrowInvalidArgument(@"Transaction completion block cannot be nil.");
  248. }
  249. FSTTransactionBlock wrappedUpdate =
  250. ^(std::shared_ptr<Transaction> internalTransaction,
  251. void (^internalCompletion)(id _Nullable, NSError *_Nullable)) {
  252. FIRTransaction *transaction =
  253. [FIRTransaction transactionWithInternalTransaction:std::move(internalTransaction)
  254. firestore:self];
  255. dispatch_async(queue, ^{
  256. NSError *_Nullable error = nil;
  257. id _Nullable result = updateBlock(transaction, &error);
  258. if (error) {
  259. // Force the result to be nil in the case of an error, in case the user set both.
  260. result = nil;
  261. }
  262. internalCompletion(result, error);
  263. });
  264. };
  265. [self.client transactionWithRetries:5 updateBlock:wrappedUpdate completion:completion];
  266. }
  267. - (FIRWriteBatch *)batch {
  268. [self ensureClientConfigured];
  269. return [FIRWriteBatch writeBatchWithFirestore:self];
  270. }
  271. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **error))updateBlock
  272. completion:
  273. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  274. static dispatch_queue_t transactionDispatchQueue;
  275. static dispatch_once_t onceToken;
  276. dispatch_once(&onceToken, ^{
  277. transactionDispatchQueue = dispatch_queue_create("com.google.firebase.firestore.transaction",
  278. DISPATCH_QUEUE_CONCURRENT);
  279. });
  280. [self runTransactionWithBlock:updateBlock
  281. dispatchQueue:transactionDispatchQueue
  282. completion:completion];
  283. }
  284. - (void)shutdownWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  285. if (!_client) {
  286. if (completion) {
  287. // We should be dispatching the callback on the user dispatch queue but if the client is nil
  288. // here that queue was never created.
  289. completion(nil);
  290. }
  291. } else {
  292. [_client shutdownWithCompletion:completion];
  293. }
  294. }
  295. + (BOOL)isLoggingEnabled {
  296. return FIRIsLoggableLevel(FIRLoggerLevelDebug, NO);
  297. }
  298. + (void)enableLogging:(BOOL)logging {
  299. FIRSetLoggerLevel(logging ? FIRLoggerLevelDebug : FIRLoggerLevelNotice);
  300. }
  301. - (void)enableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  302. [self ensureClientConfigured];
  303. [self.client enableNetworkWithCompletion:completion];
  304. }
  305. - (void)disableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable))completion {
  306. [self ensureClientConfigured];
  307. [self.client disableNetworkWithCompletion:completion];
  308. }
  309. - (const DatabaseId *)databaseID {
  310. return &_databaseID;
  311. }
  312. @end
  313. NS_ASSUME_NONNULL_END