FIRFirestore.mm 15 KB

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