FIRFirestore.mm 14 KB

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