FIRFirestore.mm 15 KB

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