FIRFirestore.mm 14 KB

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