FIRFirestore.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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+Internal.h"
  17. #import <FirebaseCore/FIRApp.h>
  18. #import <FirebaseCore/FIRAppInternal.h>
  19. #import <FirebaseCore/FIRComponentContainer.h>
  20. #import <FirebaseCore/FIROptions.h>
  21. #include <memory>
  22. #include <string>
  23. #include <utility>
  24. #import "FIRFirestoreSettings+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/FSTFirestoreComponent.h"
  30. #import "Firestore/Source/API/FSTUserDataConverter.h"
  31. #include "Firestore/core/src/firebase/firestore/api/firestore.h"
  32. #include "Firestore/core/src/firebase/firestore/api/input_validation.h"
  33. #include "Firestore/core/src/firebase/firestore/api/write_batch.h"
  34. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  35. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  36. #include "Firestore/core/src/firebase/firestore/core/transaction.h"
  37. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  38. #include "Firestore/core/src/firebase/firestore/util/async_queue.h"
  39. #include "Firestore/core/src/firebase/firestore/util/error_apple.h"
  40. #include "Firestore/core/src/firebase/firestore/util/executor_libdispatch.h"
  41. #include "Firestore/core/src/firebase/firestore/util/log.h"
  42. #include "Firestore/core/src/firebase/firestore/util/status.h"
  43. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  44. namespace util = firebase::firestore::util;
  45. using firebase::firestore::api::DocumentReference;
  46. using firebase::firestore::api::Firestore;
  47. using firebase::firestore::api::ThrowIllegalState;
  48. using firebase::firestore::api::ThrowInvalidArgument;
  49. using firebase::firestore::auth::CredentialsProvider;
  50. using firebase::firestore::model::DatabaseId;
  51. using firebase::firestore::util::AsyncQueue;
  52. NS_ASSUME_NONNULL_BEGIN
  53. #pragma mark - FIRFirestore
  54. @interface FIRFirestore ()
  55. @property(nonatomic, strong, readonly) FSTUserDataConverter *dataConverter;
  56. @end
  57. @implementation FIRFirestore {
  58. std::shared_ptr<Firestore> _firestore;
  59. FIRFirestoreSettings *_settings;
  60. }
  61. + (instancetype)firestore {
  62. FIRApp *app = [FIRApp defaultApp];
  63. if (!app) {
  64. ThrowIllegalState("Failed to get FirebaseApp instance. Please call FirebaseApp.configure() "
  65. "before using Firestore");
  66. }
  67. return [self firestoreForApp:app database:util::WrapNSString(DatabaseId::kDefault)];
  68. }
  69. + (instancetype)firestoreForApp:(FIRApp *)app {
  70. return [self firestoreForApp:app database:util::WrapNSString(DatabaseId::kDefault)];
  71. }
  72. // TODO(b/62410906): make this public
  73. + (instancetype)firestoreForApp:(FIRApp *)app database:(NSString *)database {
  74. if (!app) {
  75. ThrowInvalidArgument("FirebaseApp instance may not be nil. Use FirebaseApp.app() if you'd like "
  76. "to use the default FirebaseApp instance.");
  77. }
  78. if (!database) {
  79. ThrowInvalidArgument("Database identifier may not be nil. Use '%s' if you want the default "
  80. "database",
  81. DatabaseId::kDefault);
  82. }
  83. id<FSTFirestoreMultiDBProvider> provider =
  84. FIR_COMPONENT(FSTFirestoreMultiDBProvider, app.container);
  85. return [provider firestoreForDatabase:database];
  86. }
  87. - (instancetype)initWithDatabaseID:(model::DatabaseId)databaseID
  88. persistenceKey:(std::string)persistenceKey
  89. credentialsProvider:(std::unique_ptr<CredentialsProvider>)credentialsProvider
  90. workerQueue:(std::shared_ptr<AsyncQueue>)workerQueue
  91. firebaseApp:(FIRApp *)app {
  92. if (self = [super init]) {
  93. _firestore = std::make_shared<Firestore>(std::move(databaseID), std::move(persistenceKey),
  94. std::move(credentialsProvider), std::move(workerQueue),
  95. (__bridge void *)self);
  96. _app = app;
  97. FSTPreConverterBlock block = ^id _Nullable(id _Nullable input) {
  98. if ([input isKindOfClass:[FIRDocumentReference class]]) {
  99. FIRDocumentReference *documentReference = (FIRDocumentReference *)input;
  100. return [[FSTDocumentKeyReference alloc] initWithKey:documentReference.key
  101. databaseID:documentReference.firestore.databaseID];
  102. } else {
  103. return input;
  104. }
  105. };
  106. _dataConverter = [[FSTUserDataConverter alloc] initWithDatabaseID:_firestore->database_id()
  107. preConverter:block];
  108. // Use the property setter so the default settings get plumbed into _firestoreClient.
  109. self.settings = [[FIRFirestoreSettings alloc] init];
  110. }
  111. return self;
  112. }
  113. - (FIRFirestoreSettings *)settings {
  114. // Disallow mutation of our internal settings
  115. return [_settings copy];
  116. }
  117. - (void)setSettings:(FIRFirestoreSettings *)settings {
  118. if (![settings isEqual:_settings]) {
  119. _settings = settings;
  120. _firestore->set_settings([settings internalSettings]);
  121. std::unique_ptr<util::Executor> user_executor =
  122. absl::make_unique<util::ExecutorLibdispatch>(settings.dispatchQueue);
  123. _firestore->set_user_executor(std::move(user_executor));
  124. }
  125. }
  126. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  127. if (!collectionPath) {
  128. ThrowInvalidArgument("Collection path cannot be nil.");
  129. }
  130. if ([collectionPath containsString:@"//"]) {
  131. ThrowInvalidArgument("Invalid path (%s). Paths must not contain // in them.", collectionPath);
  132. }
  133. return _firestore->GetCollection(util::MakeString(collectionPath));
  134. }
  135. - (FIRDocumentReference *)documentWithPath:(NSString *)documentPath {
  136. if (!documentPath) {
  137. ThrowInvalidArgument("Document path cannot be nil.");
  138. }
  139. if ([documentPath containsString:@"//"]) {
  140. ThrowInvalidArgument("Invalid path (%s). Paths must not contain // in them.", documentPath);
  141. }
  142. DocumentReference documentReference = _firestore->GetDocument(util::MakeString(documentPath));
  143. return [[FIRDocumentReference alloc] initWithReference:std::move(documentReference)];
  144. }
  145. - (FIRQuery *)collectionGroupWithID:(NSString *)collectionID {
  146. if (!collectionID) {
  147. ThrowInvalidArgument("Collection ID cannot be nil.");
  148. }
  149. if ([collectionID containsString:@"/"]) {
  150. ThrowInvalidArgument("Invalid collection ID (%s). Collection IDs must not contain / in them.",
  151. collectionID);
  152. }
  153. return _firestore->GetCollectionGroup(collectionID);
  154. }
  155. - (FIRWriteBatch *)batch {
  156. return [FIRWriteBatch writeBatchWithDataConverter:self.dataConverter
  157. writeBatch:_firestore->GetBatch()];
  158. }
  159. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **))updateBlock
  160. dispatchQueue:(dispatch_queue_t)queue
  161. completion:
  162. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  163. if (!updateBlock) {
  164. ThrowInvalidArgument("Transaction block cannot be nil.");
  165. }
  166. if (!completion) {
  167. ThrowInvalidArgument("Transaction completion block cannot be nil.");
  168. }
  169. // Wrap the user-supplied updateBlock in a core C++ compatible callback. Wrap the result of the
  170. // updateBlock invocation up in an absl::any for tunneling through the internals of the system.
  171. auto internalUpdateBlock = [self, updateBlock, queue](
  172. std::shared_ptr<core::Transaction> internalTransaction,
  173. core::TransactionResultCallback internalCallback) {
  174. FIRTransaction *transaction =
  175. [FIRTransaction transactionWithInternalTransaction:std::move(internalTransaction)
  176. firestore:self];
  177. dispatch_async(queue, ^{
  178. NSError *_Nullable error = nil;
  179. id _Nullable result = updateBlock(transaction, &error);
  180. // If the user set an error, disregard the result.
  181. if (error) {
  182. internalCallback(util::Status::FromNSError(error));
  183. } else {
  184. internalCallback(absl::make_any<id>(result));
  185. }
  186. });
  187. };
  188. // Unpacks the absl::any value and calls the user completion handler.
  189. //
  190. // PORTING NOTE: Other platforms where the user return value is internally representable don't
  191. // need this wrapper.
  192. auto objcTranslator = [completion](util::StatusOr<absl::any> maybeValue) {
  193. if (!maybeValue.ok()) {
  194. completion(nil, util::MakeNSError(maybeValue.status()));
  195. return;
  196. }
  197. absl::any value = std::move(maybeValue).ValueOrDie();
  198. completion(absl::any_cast<id>(value), nil);
  199. };
  200. _firestore->RunTransaction(std::move(internalUpdateBlock), std::move(objcTranslator));
  201. }
  202. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **error))updateBlock
  203. completion:
  204. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  205. static dispatch_queue_t transactionDispatchQueue;
  206. static dispatch_once_t onceToken;
  207. dispatch_once(&onceToken, ^{
  208. transactionDispatchQueue = dispatch_queue_create("com.google.firebase.firestore.transaction",
  209. DISPATCH_QUEUE_CONCURRENT);
  210. });
  211. [self runTransactionWithBlock:updateBlock
  212. dispatchQueue:transactionDispatchQueue
  213. completion:completion];
  214. }
  215. + (void)enableLogging:(BOOL)logging {
  216. util::LogSetLevel(logging ? util::kLogLevelDebug : util::kLogLevelNotice);
  217. }
  218. - (void)enableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  219. _firestore->EnableNetwork(util::MakeCallback(completion));
  220. }
  221. - (void)disableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable))completion {
  222. _firestore->DisableNetwork(util::MakeCallback(completion));
  223. }
  224. @end
  225. @implementation FIRFirestore (Internal)
  226. - (std::shared_ptr<Firestore>)wrapped {
  227. return _firestore;
  228. }
  229. - (const std::shared_ptr<util::AsyncQueue> &)workerQueue {
  230. return _firestore->worker_queue();
  231. }
  232. - (const DatabaseId &)databaseID {
  233. return _firestore->database_id();
  234. }
  235. + (BOOL)isLoggingEnabled {
  236. return util::LogIsLoggable(util::kLogLevelDebug);
  237. }
  238. - (void)clearPersistenceWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  239. _firestore->ClearPersistence(util::MakeCallback(completion));
  240. }
  241. + (FIRFirestore *)recoverFromFirestore:(std::shared_ptr<Firestore>)firestore {
  242. return (__bridge FIRFirestore *)firestore->extension();
  243. }
  244. - (void)shutdownWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  245. _firestore->Shutdown(util::MakeCallback(completion));
  246. }
  247. @end
  248. NS_ASSUME_NONNULL_END