FIRFirestore.mm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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/FIRLogger.h>
  20. #import <FirebaseCore/FIROptions.h>
  21. #include <memory>
  22. #include <utility>
  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/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/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/string_apple.h"
  41. #include "absl/memory/memory.h"
  42. namespace util = firebase::firestore::util;
  43. using firebase::firestore::auth::CredentialsProvider;
  44. using firebase::firestore::auth::FirebaseCredentialsProvider;
  45. using firebase::firestore::core::DatabaseInfo;
  46. using firebase::firestore::model::DatabaseId;
  47. using firebase::firestore::model::ResourcePath;
  48. NS_ASSUME_NONNULL_BEGIN
  49. extern "C" NSString *const FIRFirestoreErrorDomain = @"FIRFirestoreErrorDomain";
  50. @interface FIRFirestore () {
  51. /** The actual owned DatabaseId instance is allocated in FIRFirestore. */
  52. DatabaseId _databaseID;
  53. std::unique_ptr<CredentialsProvider> _credentialsProvider;
  54. }
  55. @property(nonatomic, strong) NSString *persistenceKey;
  56. @property(nonatomic, strong) FSTDispatchQueue *workerDispatchQueue;
  57. // Note that `client` is updated after initialization, but marking this readwrite would generate an
  58. // incorrect setter (since we make the assignment to `client` inside an `@synchronized` block.
  59. @property(nonatomic, strong, readonly) FSTFirestoreClient *client;
  60. @property(nonatomic, strong, readonly) FSTUserDataConverter *dataConverter;
  61. @end
  62. @implementation FIRFirestore {
  63. // All guarded by @synchronized(self)
  64. FIRFirestoreSettings *_settings;
  65. FSTFirestoreClient *_client;
  66. }
  67. + (NSMutableDictionary<NSString *, FIRFirestore *> *)instances {
  68. static dispatch_once_t token = 0;
  69. static NSMutableDictionary<NSString *, FIRFirestore *> *instances;
  70. dispatch_once(&token, ^{
  71. instances = [NSMutableDictionary dictionary];
  72. });
  73. return instances;
  74. }
  75. + (void)initialize {
  76. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  77. [center addObserverForName:kFIRAppDeleteNotification
  78. object:nil
  79. queue:nil
  80. usingBlock:^(NSNotification *_Nonnull note) {
  81. NSString *appName = note.userInfo[kFIRAppNameKey];
  82. if (appName == nil) return;
  83. NSMutableDictionary *instances = [self instances];
  84. @synchronized(instances) {
  85. // Since the key for instances isn't just the app name, iterate over all the
  86. // keys to get the one(s) we have to delete. There could be multiple in case
  87. // the user calls firestoreForApp:database:.
  88. NSMutableArray *keysToDelete = [[NSMutableArray alloc] init];
  89. NSString *keyPrefix = [NSString stringWithFormat:@"%@|", appName];
  90. for (NSString *key in instances.allKeys) {
  91. if ([key hasPrefix:keyPrefix]) {
  92. [keysToDelete addObject:key];
  93. }
  94. }
  95. // Loop through the keys found and delete them from the stored instances.
  96. for (NSString *key in keysToDelete) {
  97. [instances removeObjectForKey:key];
  98. }
  99. }
  100. }];
  101. }
  102. + (instancetype)firestore {
  103. FIRApp *app = [FIRApp defaultApp];
  104. if (!app) {
  105. FSTThrowInvalidUsage(@"FIRAppNotConfiguredException",
  106. @"Failed to get FirebaseApp instance. Please call FirebaseApp.configure() "
  107. @"before using Firestore");
  108. }
  109. return [self firestoreForApp:app database:util::WrapNSStringNoCopy(DatabaseId::kDefault)];
  110. }
  111. + (instancetype)firestoreForApp:(FIRApp *)app {
  112. return [self firestoreForApp:app database:util::WrapNSStringNoCopy(DatabaseId::kDefault)];
  113. }
  114. // TODO(b/62410906): make this public
  115. + (instancetype)firestoreForApp:(FIRApp *)app database:(NSString *)database {
  116. if (!app) {
  117. FSTThrowInvalidArgument(
  118. @"FirebaseApp instance may not be nil. Use FirebaseApp.app() if you'd "
  119. "like to use the default FirebaseApp instance.");
  120. }
  121. if (!database) {
  122. FSTThrowInvalidArgument(
  123. @"database identifier may not be nil. Use '%s' if you want the default "
  124. "database",
  125. DatabaseId::kDefault);
  126. }
  127. // Note: If the key format changes, please change the code that detects FIRApps being deleted
  128. // contained in +initialize. It checks for the app's name followed by a | character.
  129. NSString *key = [NSString stringWithFormat:@"%@|%@", app.name, database];
  130. NSMutableDictionary<NSString *, FIRFirestore *> *instances = self.instances;
  131. @synchronized(instances) {
  132. FIRFirestore *firestore = instances[key];
  133. if (!firestore) {
  134. NSString *projectID = app.options.projectID;
  135. FSTAssert(projectID, @"FirebaseOptions.projectID cannot be nil.");
  136. FSTDispatchQueue *workerDispatchQueue = [FSTDispatchQueue
  137. queueWith:dispatch_queue_create("com.google.firebase.firestore", DISPATCH_QUEUE_SERIAL)];
  138. std::unique_ptr<CredentialsProvider> credentials_provider =
  139. absl::make_unique<FirebaseCredentialsProvider>(app);
  140. NSString *persistenceKey = app.name;
  141. firestore = [[FIRFirestore alloc] initWithProjectID:util::MakeStringView(projectID)
  142. database:util::MakeStringView(database)
  143. persistenceKey:persistenceKey
  144. credentialsProvider:std::move(credentials_provider)
  145. workerDispatchQueue:workerDispatchQueue
  146. firebaseApp:app];
  147. instances[key] = firestore;
  148. }
  149. return firestore;
  150. }
  151. }
  152. - (instancetype)initWithProjectID:(const absl::string_view)projectID
  153. database:(const absl::string_view)database
  154. persistenceKey:(NSString *)persistenceKey
  155. credentialsProvider:(std::unique_ptr<CredentialsProvider>)credentialsProvider
  156. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  157. firebaseApp:(FIRApp *)app {
  158. if (self = [super init]) {
  159. _databaseID = DatabaseId(projectID, database);
  160. FSTPreConverterBlock block = ^id _Nullable(id _Nullable input) {
  161. if ([input isKindOfClass:[FIRDocumentReference class]]) {
  162. FIRDocumentReference *documentReference = (FIRDocumentReference *)input;
  163. return [[FSTDocumentKeyReference alloc] initWithKey:documentReference.key
  164. databaseID:documentReference.firestore.databaseID];
  165. } else {
  166. return input;
  167. }
  168. };
  169. _dataConverter =
  170. [[FSTUserDataConverter alloc] initWithDatabaseID:&_databaseID preConverter:block];
  171. _persistenceKey = persistenceKey;
  172. _credentialsProvider = std::move(credentialsProvider);
  173. _workerDispatchQueue = workerDispatchQueue;
  174. _app = app;
  175. _settings = [[FIRFirestoreSettings alloc] init];
  176. }
  177. return self;
  178. }
  179. - (FIRFirestoreSettings *)settings {
  180. @synchronized(self) {
  181. // Disallow mutation of our internal settings
  182. return [_settings copy];
  183. }
  184. }
  185. - (void)setSettings:(FIRFirestoreSettings *)settings {
  186. @synchronized(self) {
  187. // As a special exception, don't throw if the same settings are passed repeatedly. This should
  188. // make it more friendly to create a Firestore instance.
  189. if (_client && ![_settings isEqual:settings]) {
  190. FSTThrowInvalidUsage(@"FIRIllegalStateException",
  191. @"Firestore instance has already been started and its settings can no "
  192. "longer be changed. You can only set settings before calling any "
  193. "other methods on a Firestore instance.");
  194. }
  195. _settings = [settings copy];
  196. }
  197. }
  198. /**
  199. * Ensures that the FirestoreClient is configured and returns it.
  200. */
  201. - (FSTFirestoreClient *)client {
  202. [self ensureClientConfigured];
  203. return _client;
  204. }
  205. - (void)ensureClientConfigured {
  206. @synchronized(self) {
  207. if (!_client) {
  208. // These values are validated elsewhere; this is just double-checking:
  209. FSTAssert(_settings.host, @"FirestoreSettings.host cannot be nil.");
  210. FSTAssert(_settings.dispatchQueue, @"FirestoreSettings.dispatchQueue cannot be nil.");
  211. if (!_settings.timestampsInSnapshotsEnabled) {
  212. FSTWarn(
  213. @"The behavior for system Date objects stored in Firestore is going to change "
  214. "AND YOUR APP MAY BREAK.\n"
  215. "To hide this warning and ensure your app does not break, you need to add "
  216. "the following code to your app before calling any other Cloud Firestore methods:\n"
  217. "\n"
  218. "let db = Firestore.firestore()\n"
  219. "let settings = db.settings\n"
  220. "settings.areTimestampsInSnapshotsEnabled = true\n"
  221. "db.settings = settings\n"
  222. "\n"
  223. "With this change, timestamps stored in Cloud Firestore will be read back as "
  224. "Firebase Timestamp objects instead of as system Date objects. So you will "
  225. "also need to update code expecting a Date to instead expect a Timestamp. "
  226. "For example:\n"
  227. "\n"
  228. "// old:\n"
  229. "let date: Date = documentSnapshot.get(\"created_at\") as! Date\n"
  230. "// new:\n"
  231. "let timestamp: Timestamp = documentSnapshot.get(\"created_at\") as! Timestamp\n"
  232. "let date: Date = timestamp.dateValue()\n"
  233. "\n"
  234. "Please audit all existing usages of Date when you enable the new behavior. In a "
  235. "future release, the behavior will be changed to the new behavior, so if you do not "
  236. "follow these steps, YOUR APP MAY BREAK.");
  237. }
  238. const DatabaseInfo database_info(*self.databaseID, util::MakeStringView(_persistenceKey),
  239. util::MakeStringView(_settings.host), _settings.sslEnabled);
  240. FSTDispatchQueue *userDispatchQueue = [FSTDispatchQueue queueWith:_settings.dispatchQueue];
  241. _client = [FSTFirestoreClient clientWithDatabaseInfo:database_info
  242. usePersistence:_settings.persistenceEnabled
  243. credentialsProvider:_credentialsProvider.get()
  244. userDispatchQueue:userDispatchQueue
  245. workerDispatchQueue:_workerDispatchQueue];
  246. }
  247. }
  248. }
  249. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  250. if (!collectionPath) {
  251. FSTThrowInvalidArgument(@"Collection path cannot be nil.");
  252. }
  253. [self ensureClientConfigured];
  254. const ResourcePath path = ResourcePath::FromString(util::MakeStringView(collectionPath));
  255. return [FIRCollectionReference referenceWithPath:path firestore:self];
  256. }
  257. - (FIRDocumentReference *)documentWithPath:(NSString *)documentPath {
  258. if (!documentPath) {
  259. FSTThrowInvalidArgument(@"Document path cannot be nil.");
  260. }
  261. [self ensureClientConfigured];
  262. const ResourcePath path = ResourcePath::FromString(util::MakeStringView(documentPath));
  263. return [FIRDocumentReference referenceWithPath:path firestore:self];
  264. }
  265. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **))updateBlock
  266. dispatchQueue:(dispatch_queue_t)queue
  267. completion:
  268. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  269. // We wrap the function they provide in order to use internal implementation classes for
  270. // FSTTransaction, and to run the user callback block on the proper queue.
  271. if (!updateBlock) {
  272. FSTThrowInvalidArgument(@"Transaction block cannot be nil.");
  273. } else if (!completion) {
  274. FSTThrowInvalidArgument(@"Transaction completion block cannot be nil.");
  275. }
  276. FSTTransactionBlock wrappedUpdate =
  277. ^(FSTTransaction *internalTransaction,
  278. void (^internalCompletion)(id _Nullable, NSError *_Nullable)) {
  279. FIRTransaction *transaction =
  280. [FIRTransaction transactionWithFSTTransaction:internalTransaction firestore:self];
  281. dispatch_async(queue, ^{
  282. NSError *_Nullable error = nil;
  283. id _Nullable result = updateBlock(transaction, &error);
  284. if (error) {
  285. // Force the result to be nil in the case of an error, in case the user set both.
  286. result = nil;
  287. }
  288. internalCompletion(result, error);
  289. });
  290. };
  291. [self.client transactionWithRetries:5 updateBlock:wrappedUpdate completion:completion];
  292. }
  293. - (FIRWriteBatch *)batch {
  294. [self ensureClientConfigured];
  295. return [FIRWriteBatch writeBatchWithFirestore:self];
  296. }
  297. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **error))updateBlock
  298. completion:
  299. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  300. static dispatch_queue_t transactionDispatchQueue;
  301. static dispatch_once_t onceToken;
  302. dispatch_once(&onceToken, ^{
  303. transactionDispatchQueue = dispatch_queue_create("com.google.firebase.firestore.transaction",
  304. DISPATCH_QUEUE_CONCURRENT);
  305. });
  306. [self runTransactionWithBlock:updateBlock
  307. dispatchQueue:transactionDispatchQueue
  308. completion:completion];
  309. }
  310. - (void)shutdownWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  311. FSTFirestoreClient *client;
  312. @synchronized(self) {
  313. client = _client;
  314. _client = nil;
  315. }
  316. if (!client) {
  317. // We should be dispatching the callback on the user dispatch queue but if the client is nil
  318. // here that queue was never created.
  319. completion(nil);
  320. } else {
  321. [client shutdownWithCompletion:completion];
  322. }
  323. }
  324. + (BOOL)isLoggingEnabled {
  325. return FIRIsLoggableLevel(FIRLoggerLevelDebug, NO);
  326. }
  327. + (void)enableLogging:(BOOL)logging {
  328. FIRSetLoggerLevel(logging ? FIRLoggerLevelDebug : FIRLoggerLevelNotice);
  329. }
  330. - (void)enableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  331. [self ensureClientConfigured];
  332. [self.client enableNetworkWithCompletion:completion];
  333. }
  334. - (void)disableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable))completion {
  335. [self ensureClientConfigured];
  336. [self.client disableNetworkWithCompletion:completion];
  337. }
  338. - (const DatabaseId *)databaseID {
  339. return &_databaseID;
  340. }
  341. @end
  342. NS_ASSUME_NONNULL_END