FIRFirestore.mm 15 KB

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