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/FIRAppInternal.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. 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. + (void)initialize {
  69. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  70. [center addObserverForName:kFIRAppDeleteNotification
  71. object:nil
  72. queue:nil
  73. usingBlock:^(NSNotification *_Nonnull note) {
  74. NSString *appName = note.userInfo[kFIRAppNameKey];
  75. if (appName == nil) return;
  76. NSMutableDictionary *instances = [self instances];
  77. @synchronized(instances) {
  78. // Since the key for instances isn't just the app name, iterate over all the
  79. // keys to get the one(s) we have to delete. There could be multiple in case
  80. // the user calls firestoreForApp:database:.
  81. NSMutableArray *keysToDelete = [[NSMutableArray alloc] init];
  82. NSString *keyPrefix = [NSString stringWithFormat:@"%@|", appName];
  83. for (NSString *key in instances.allKeys) {
  84. if ([key hasPrefix:keyPrefix]) {
  85. [keysToDelete addObject:key];
  86. }
  87. }
  88. // Loop through the keys found and delete them from the stored instances.
  89. for (NSString *key in keysToDelete) {
  90. [instances removeObjectForKey:key];
  91. }
  92. }
  93. }];
  94. }
  95. + (instancetype)firestore {
  96. FIRApp *app = [FIRApp defaultApp];
  97. if (!app) {
  98. FSTThrowInvalidUsage(@"FIRAppNotConfiguredException",
  99. @"Failed to get FirebaseApp instance. Please call FirebaseApp.configure() "
  100. @"before using Firestore");
  101. }
  102. return [self firestoreForApp:app database:util::WrapNSStringNoCopy(DatabaseId::kDefault)];
  103. }
  104. + (instancetype)firestoreForApp:(FIRApp *)app {
  105. return [self firestoreForApp:app database:util::WrapNSStringNoCopy(DatabaseId::kDefault)];
  106. }
  107. // TODO(b/62410906): make this public
  108. + (instancetype)firestoreForApp:(FIRApp *)app database:(NSString *)database {
  109. if (!app) {
  110. FSTThrowInvalidArgument(
  111. @"FirebaseApp instance may not be nil. Use FirebaseApp.app() if you'd "
  112. "like to use the default FirebaseApp instance.");
  113. }
  114. if (!database) {
  115. FSTThrowInvalidArgument(
  116. @"database identifier may not be nil. Use '%@' if you want the default "
  117. "database",
  118. util::WrapNSStringNoCopy(DatabaseId::kDefault));
  119. }
  120. // Note: If the key format changes, please change the code that detects FIRApps being deleted
  121. // contained in +initialize. It checks for the app's name followed by a | character.
  122. NSString *key = [NSString stringWithFormat:@"%@|%@", app.name, database];
  123. NSMutableDictionary<NSString *, FIRFirestore *> *instances = self.instances;
  124. @synchronized(instances) {
  125. FIRFirestore *firestore = instances[key];
  126. if (!firestore) {
  127. NSString *projectID = app.options.projectID;
  128. FSTAssert(projectID, @"FirebaseOptions.projectID cannot be nil.");
  129. FSTDispatchQueue *workerDispatchQueue = [FSTDispatchQueue
  130. queueWith:dispatch_queue_create("com.google.firebase.firestore", DISPATCH_QUEUE_SERIAL)];
  131. id<FSTCredentialsProvider> credentialsProvider;
  132. credentialsProvider = [[FSTFirebaseCredentialsProvider alloc] initWithApp:app];
  133. NSString *persistenceKey = app.name;
  134. firestore = [[FIRFirestore alloc] initWithProjectID:util::MakeStringView(projectID)
  135. database:util::MakeStringView(database)
  136. persistenceKey:persistenceKey
  137. credentialsProvider:credentialsProvider
  138. workerDispatchQueue:workerDispatchQueue
  139. firebaseApp:app];
  140. instances[key] = firestore;
  141. }
  142. return firestore;
  143. }
  144. }
  145. - (instancetype)initWithProjectID:(const absl::string_view)projectID
  146. database:(const absl::string_view)database
  147. persistenceKey:(NSString *)persistenceKey
  148. credentialsProvider:(id<FSTCredentialsProvider>)credentialsProvider
  149. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  150. firebaseApp:(FIRApp *)app {
  151. if (self = [super init]) {
  152. _databaseID = DatabaseId(projectID, 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 =
  163. [[FSTUserDataConverter alloc] initWithDatabaseID:&_databaseID preConverter:block];
  164. _persistenceKey = persistenceKey;
  165. _credentialsProvider = credentialsProvider;
  166. _workerDispatchQueue = workerDispatchQueue;
  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. FSTAssert(_settings.host, @"FirestoreSettings.host cannot be nil.");
  203. FSTAssert(_settings.dispatchQueue, @"FirestoreSettings.dispatchQueue cannot be nil.");
  204. const DatabaseInfo database_info(*self.databaseID, util::MakeStringView(_persistenceKey),
  205. util::MakeStringView(_settings.host), _settings.sslEnabled);
  206. FSTDispatchQueue *userDispatchQueue = [FSTDispatchQueue queueWith:_settings.dispatchQueue];
  207. _client = [FSTFirestoreClient clientWithDatabaseInfo:database_info
  208. usePersistence:_settings.persistenceEnabled
  209. credentialsProvider:_credentialsProvider
  210. userDispatchQueue:userDispatchQueue
  211. workerDispatchQueue:_workerDispatchQueue];
  212. }
  213. }
  214. }
  215. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  216. if (!collectionPath) {
  217. FSTThrowInvalidArgument(@"Collection path cannot be nil.");
  218. }
  219. [self ensureClientConfigured];
  220. FSTResourcePath *path = [FSTResourcePath pathWithString:collectionPath];
  221. return [FIRCollectionReference referenceWithPath:path firestore:self];
  222. }
  223. - (FIRDocumentReference *)documentWithPath:(NSString *)documentPath {
  224. if (!documentPath) {
  225. FSTThrowInvalidArgument(@"Document path cannot be nil.");
  226. }
  227. [self ensureClientConfigured];
  228. FSTResourcePath *path = [FSTResourcePath pathWithString:documentPath];
  229. return [FIRDocumentReference referenceWithPath:path firestore:self];
  230. }
  231. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **))updateBlock
  232. dispatchQueue:(dispatch_queue_t)queue
  233. completion:
  234. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  235. // We wrap the function they provide in order to use internal implementation classes for
  236. // FSTTransaction, and to run the user callback block on the proper queue.
  237. if (!updateBlock) {
  238. FSTThrowInvalidArgument(@"Transaction block cannot be nil.");
  239. } else if (!completion) {
  240. FSTThrowInvalidArgument(@"Transaction completion block cannot be nil.");
  241. }
  242. FSTTransactionBlock wrappedUpdate =
  243. ^(FSTTransaction *internalTransaction,
  244. void (^internalCompletion)(id _Nullable, NSError *_Nullable)) {
  245. FIRTransaction *transaction =
  246. [FIRTransaction transactionWithFSTTransaction:internalTransaction firestore:self];
  247. dispatch_async(queue, ^{
  248. NSError *_Nullable error = nil;
  249. id _Nullable result = updateBlock(transaction, &error);
  250. if (error) {
  251. // Force the result to be nil in the case of an error, in case the user set both.
  252. result = nil;
  253. }
  254. internalCompletion(result, error);
  255. });
  256. };
  257. [self.client transactionWithRetries:5 updateBlock:wrappedUpdate completion:completion];
  258. }
  259. - (FIRWriteBatch *)batch {
  260. [self ensureClientConfigured];
  261. return [FIRWriteBatch writeBatchWithFirestore:self];
  262. }
  263. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **error))updateBlock
  264. completion:
  265. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  266. static dispatch_queue_t transactionDispatchQueue;
  267. static dispatch_once_t onceToken;
  268. dispatch_once(&onceToken, ^{
  269. transactionDispatchQueue = dispatch_queue_create("com.google.firebase.firestore.transaction",
  270. DISPATCH_QUEUE_CONCURRENT);
  271. });
  272. [self runTransactionWithBlock:updateBlock
  273. dispatchQueue:transactionDispatchQueue
  274. completion:completion];
  275. }
  276. - (void)shutdownWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  277. FSTFirestoreClient *client;
  278. @synchronized(self) {
  279. client = _client;
  280. _client = nil;
  281. }
  282. if (!client) {
  283. // We should be dispatching the callback on the user dispatch queue but if the client is nil
  284. // here that queue was never created.
  285. completion(nil);
  286. } else {
  287. [client shutdownWithCompletion:completion];
  288. }
  289. }
  290. + (BOOL)isLoggingEnabled {
  291. return FIRIsLoggableLevel(FIRLoggerLevelDebug, NO);
  292. }
  293. + (void)enableLogging:(BOOL)logging {
  294. FIRSetLoggerLevel(logging ? FIRLoggerLevelDebug : FIRLoggerLevelNotice);
  295. }
  296. - (void)enableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  297. [self ensureClientConfigured];
  298. [self.client enableNetworkWithCompletion:completion];
  299. }
  300. - (void)disableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable))completion {
  301. [self ensureClientConfigured];
  302. [self.client disableNetworkWithCompletion:completion];
  303. }
  304. - (const DatabaseId *)databaseID {
  305. return &_databaseID;
  306. }
  307. @end
  308. NS_ASSUME_NONNULL_END