FIRFirestore.mm 16 KB

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