FIRFirestore.mm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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(
  130. @"FirebaseApp instance may not be nil. Use FirebaseApp.app() if you'd "
  131. "like to use the default FirebaseApp instance.");
  132. }
  133. if (!database) {
  134. FSTThrowInvalidArgument(
  135. @"database identifier may not be nil. Use '%s' if you want the default "
  136. "database",
  137. DatabaseId::kDefault);
  138. }
  139. id<FSTFirestoreMultiDBProvider> provider =
  140. FIR_COMPONENT(FSTFirestoreMultiDBProvider, app.container);
  141. return [provider firestoreForDatabase:database];
  142. }
  143. - (instancetype)initWithProjectID:(std::string)projectID
  144. database:(std::string)database
  145. persistenceKey:(NSString *)persistenceKey
  146. credentialsProvider:(std::unique_ptr<CredentialsProvider>)credentialsProvider
  147. workerQueue:(std::unique_ptr<AsyncQueue>)workerQueue
  148. firebaseApp:(FIRApp *)app {
  149. if (self = [super init]) {
  150. _databaseID = DatabaseId{std::move(projectID), std::move(database)};
  151. FSTPreConverterBlock block = ^id _Nullable(id _Nullable input) {
  152. if ([input isKindOfClass:[FIRDocumentReference class]]) {
  153. FIRDocumentReference *documentReference = (FIRDocumentReference *)input;
  154. return [[FSTDocumentKeyReference alloc] initWithKey:documentReference.key
  155. databaseID:documentReference.firestore.databaseID];
  156. } else {
  157. return input;
  158. }
  159. };
  160. _dataConverter =
  161. [[FSTUserDataConverter alloc] initWithDatabaseID:&_databaseID preConverter:block];
  162. _persistenceKey = persistenceKey;
  163. _credentialsProvider = std::move(credentialsProvider);
  164. _workerQueue = std::move(workerQueue);
  165. _app = app;
  166. _settings = [[FIRFirestoreSettings alloc] init];
  167. }
  168. return self;
  169. }
  170. - (FIRFirestoreSettings *)settings {
  171. @synchronized(self) {
  172. // Disallow mutation of our internal settings
  173. return [_settings copy];
  174. }
  175. }
  176. - (void)setSettings:(FIRFirestoreSettings *)settings {
  177. @synchronized(self) {
  178. // As a special exception, don't throw if the same settings are passed repeatedly. This should
  179. // make it more friendly to create a Firestore instance.
  180. if (_client && ![_settings isEqual:settings]) {
  181. FSTThrowInvalidUsage(@"FIRIllegalStateException",
  182. @"Firestore instance has already been started and its settings can no "
  183. "longer be changed. You can only set settings before calling any "
  184. "other methods on a Firestore instance.");
  185. }
  186. _settings = [settings copy];
  187. }
  188. }
  189. /**
  190. * Ensures that the FirestoreClient is configured and returns it.
  191. */
  192. - (FSTFirestoreClient *)client {
  193. [self ensureClientConfigured];
  194. return _client;
  195. }
  196. - (void)ensureClientConfigured {
  197. @synchronized(self) {
  198. if (!_client) {
  199. // These values are validated elsewhere; this is just double-checking:
  200. HARD_ASSERT(_settings.host, "FirestoreSettings.host cannot be nil.");
  201. HARD_ASSERT(_settings.dispatchQueue, "FirestoreSettings.dispatchQueue cannot be nil.");
  202. if (!_settings.timestampsInSnapshotsEnabled) {
  203. LOG_WARN(
  204. "The behavior for system Date objects stored in Firestore is going to change "
  205. "AND YOUR APP MAY BREAK.\n"
  206. "To hide this warning and ensure your app does not break, you need to add "
  207. "the following code to your app before calling any other Cloud Firestore methods:\n"
  208. "\n"
  209. "let db = Firestore.firestore()\n"
  210. "let settings = db.settings\n"
  211. "settings.areTimestampsInSnapshotsEnabled = true\n"
  212. "db.settings = settings\n"
  213. "\n"
  214. "With this change, timestamps stored in Cloud Firestore will be read back as "
  215. "Firebase Timestamp objects instead of as system Date objects. So you will "
  216. "also need to update code expecting a Date to instead expect a Timestamp. "
  217. "For example:\n"
  218. "\n"
  219. "// old:\n"
  220. "let date: Date = documentSnapshot.get(\"created_at\") as! Date\n"
  221. "// new:\n"
  222. "let timestamp: Timestamp = documentSnapshot.get(\"created_at\") as! Timestamp\n"
  223. "let date: Date = timestamp.dateValue()\n"
  224. "\n"
  225. "Please audit all existing usages of Date when you enable the new behavior. In a "
  226. "future release, the behavior will be changed to the new behavior, so if you do not "
  227. "follow these steps, YOUR APP MAY BREAK.");
  228. }
  229. const DatabaseInfo database_info(*self.databaseID, util::MakeString(_persistenceKey),
  230. util::MakeString(_settings.host), _settings.sslEnabled);
  231. std::unique_ptr<Executor> userExecutor =
  232. absl::make_unique<ExecutorLibdispatch>(_settings.dispatchQueue);
  233. HARD_ASSERT(_workerQueue, "Expected non-null _workerQueue");
  234. _client = [FSTFirestoreClient clientWithDatabaseInfo:database_info
  235. settings:_settings
  236. credentialsProvider:_credentialsProvider.get()
  237. userExecutor:std::move(userExecutor)
  238. workerQueue:std::move(_workerQueue)];
  239. }
  240. }
  241. }
  242. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  243. if (!collectionPath) {
  244. FSTThrowInvalidArgument(@"Collection path cannot be nil.");
  245. }
  246. if ([collectionPath containsString:@"//"]) {
  247. FSTThrowInvalidArgument(@"Invalid path (%@). Paths must not contain // in them.",
  248. collectionPath);
  249. }
  250. [self ensureClientConfigured];
  251. const ResourcePath path = ResourcePath::FromString(util::MakeString(collectionPath));
  252. return [FIRCollectionReference referenceWithPath:path firestore:self];
  253. }
  254. - (FIRDocumentReference *)documentWithPath:(NSString *)documentPath {
  255. if (!documentPath) {
  256. FSTThrowInvalidArgument(@"Document path cannot be nil.");
  257. }
  258. if ([documentPath containsString:@"//"]) {
  259. FSTThrowInvalidArgument(@"Invalid path (%@). Paths must not contain // in them.", documentPath);
  260. }
  261. [self ensureClientConfigured];
  262. const ResourcePath path = ResourcePath::FromString(util::MakeString(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. if (!_client) {
  312. if (completion) {
  313. // We should be dispatching the callback on the user dispatch queue but if the client is nil
  314. // here that queue was never created.
  315. completion(nil);
  316. }
  317. } else {
  318. [_client shutdownWithCompletion:completion];
  319. }
  320. }
  321. + (BOOL)isLoggingEnabled {
  322. return FIRIsLoggableLevel(FIRLoggerLevelDebug, NO);
  323. }
  324. + (void)enableLogging:(BOOL)logging {
  325. FIRSetLoggerLevel(logging ? FIRLoggerLevelDebug : FIRLoggerLevelNotice);
  326. }
  327. - (void)enableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  328. [self ensureClientConfigured];
  329. [self.client enableNetworkWithCompletion:completion];
  330. }
  331. - (void)disableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable))completion {
  332. [self ensureClientConfigured];
  333. [self.client disableNetworkWithCompletion:completion];
  334. }
  335. - (const DatabaseId *)databaseID {
  336. return &_databaseID;
  337. }
  338. @end
  339. NS_ASSUME_NONNULL_END