FIRFirestore.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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)initWithProjectID:(std::string)projectID
  88. database:(std::string)database
  89. persistenceKey:(std::string)persistenceKey
  90. credentialsProvider:(std::unique_ptr<CredentialsProvider>)credentialsProvider
  91. workerQueue:(std::unique_ptr<AsyncQueue>)workerQueue
  92. firebaseApp:(FIRApp *)app {
  93. if (self = [super init]) {
  94. _firestore = std::make_shared<Firestore>(
  95. std::move(projectID), std::move(database), std::move(persistenceKey),
  96. std::move(credentialsProvider), std::move(workerQueue), (__bridge void *)self);
  97. _app = app;
  98. FSTPreConverterBlock block = ^id _Nullable(id _Nullable input) {
  99. if ([input isKindOfClass:[FIRDocumentReference class]]) {
  100. FIRDocumentReference *documentReference = (FIRDocumentReference *)input;
  101. return [[FSTDocumentKeyReference alloc] initWithKey:documentReference.key
  102. databaseID:documentReference.firestore.databaseID];
  103. } else {
  104. return input;
  105. }
  106. };
  107. _dataConverter = [[FSTUserDataConverter alloc] initWithDatabaseID:&_firestore->database_id()
  108. preConverter:block];
  109. // Use the property setter so the default settings get plumbed into _firestoreClient.
  110. self.settings = [[FIRFirestoreSettings alloc] init];
  111. }
  112. return self;
  113. }
  114. - (FIRFirestoreSettings *)settings {
  115. // Disallow mutation of our internal settings
  116. return [_settings copy];
  117. }
  118. - (void)setSettings:(FIRFirestoreSettings *)settings {
  119. if (![settings isEqual:_settings]) {
  120. _settings = settings;
  121. _firestore->set_settings([settings internalSettings]);
  122. std::unique_ptr<util::Executor> user_executor =
  123. absl::make_unique<util::ExecutorLibdispatch>(settings.dispatchQueue);
  124. _firestore->set_user_executor(std::move(user_executor));
  125. }
  126. }
  127. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  128. if (!collectionPath) {
  129. ThrowInvalidArgument("Collection path cannot be nil.");
  130. }
  131. if ([collectionPath containsString:@"//"]) {
  132. ThrowInvalidArgument("Invalid path (%s). Paths must not contain // in them.", collectionPath);
  133. }
  134. return _firestore->GetCollection(util::MakeString(collectionPath));
  135. }
  136. - (FIRDocumentReference *)documentWithPath:(NSString *)documentPath {
  137. if (!documentPath) {
  138. ThrowInvalidArgument("Document path cannot be nil.");
  139. }
  140. if ([documentPath containsString:@"//"]) {
  141. ThrowInvalidArgument("Invalid path (%s). Paths must not contain // in them.", documentPath);
  142. }
  143. DocumentReference documentReference = _firestore->GetDocument(util::MakeString(documentPath));
  144. return [[FIRDocumentReference alloc] initWithReference:std::move(documentReference)];
  145. }
  146. - (FIRQuery *)collectionGroupWithID:(NSString *)collectionID {
  147. if (!collectionID) {
  148. ThrowInvalidArgument("Collection ID cannot be nil.");
  149. }
  150. if ([collectionID containsString:@"/"]) {
  151. ThrowInvalidArgument("Invalid collection ID (%s). Collection IDs must not contain / in them.",
  152. collectionID);
  153. }
  154. return _firestore->GetCollectionGroup(collectionID);
  155. }
  156. - (FIRWriteBatch *)batch {
  157. return [FIRWriteBatch writeBatchWithDataConverter:self.dataConverter
  158. writeBatch:_firestore->GetBatch()];
  159. }
  160. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **))updateBlock
  161. dispatchQueue:(dispatch_queue_t)queue
  162. completion:
  163. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  164. if (!updateBlock) {
  165. ThrowInvalidArgument("Transaction block cannot be nil.");
  166. }
  167. if (!completion) {
  168. ThrowInvalidArgument("Transaction completion block cannot be nil.");
  169. }
  170. // Wrap the user-supplied updateBlock in a core C++ compatible callback. Wrap the result of the
  171. // updateBlock invocation up in an absl::any for tunneling through the internals of the system.
  172. auto internalUpdateBlock = [self, updateBlock, queue](
  173. std::shared_ptr<core::Transaction> internalTransaction,
  174. core::TransactionResultCallback internalCallback) {
  175. FIRTransaction *transaction =
  176. [FIRTransaction transactionWithInternalTransaction:std::move(internalTransaction)
  177. firestore:self];
  178. dispatch_async(queue, ^{
  179. NSError *_Nullable error = nil;
  180. id _Nullable result = updateBlock(transaction, &error);
  181. // If the user set an error, disregard the result.
  182. if (error) {
  183. internalCallback(util::Status::FromNSError(error));
  184. } else {
  185. internalCallback(absl::make_any<id>(result));
  186. }
  187. });
  188. };
  189. // Unpacks the absl::any value and calls the user completion handler.
  190. //
  191. // PORTING NOTE: Other platforms where the user return value is internally representable don't
  192. // need this wrapper.
  193. auto objcTranslator = [completion](util::StatusOr<absl::any> maybeValue) {
  194. if (!maybeValue.ok()) {
  195. completion(nil, util::MakeNSError(maybeValue.status()));
  196. return;
  197. }
  198. absl::any value = std::move(maybeValue).ValueOrDie();
  199. completion(absl::any_cast<id>(value), nil);
  200. };
  201. _firestore->RunTransaction(std::move(internalUpdateBlock), std::move(objcTranslator));
  202. }
  203. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **error))updateBlock
  204. completion:
  205. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  206. static dispatch_queue_t transactionDispatchQueue;
  207. static dispatch_once_t onceToken;
  208. dispatch_once(&onceToken, ^{
  209. transactionDispatchQueue = dispatch_queue_create("com.google.firebase.firestore.transaction",
  210. DISPATCH_QUEUE_CONCURRENT);
  211. });
  212. [self runTransactionWithBlock:updateBlock
  213. dispatchQueue:transactionDispatchQueue
  214. completion:completion];
  215. }
  216. + (void)enableLogging:(BOOL)logging {
  217. util::LogSetLevel(logging ? util::kLogLevelDebug : util::kLogLevelNotice);
  218. }
  219. - (void)enableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  220. _firestore->EnableNetwork(util::MakeCallback(completion));
  221. }
  222. - (void)disableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable))completion {
  223. _firestore->DisableNetwork(util::MakeCallback(completion));
  224. }
  225. @end
  226. @implementation FIRFirestore (Internal)
  227. - (std::shared_ptr<Firestore>)wrapped {
  228. return _firestore;
  229. }
  230. - (AsyncQueue *)workerQueue {
  231. return _firestore->worker_queue();
  232. }
  233. - (const DatabaseId *)databaseID {
  234. return &_firestore->database_id();
  235. }
  236. + (BOOL)isLoggingEnabled {
  237. return util::LogIsLoggable(util::kLogLevelDebug);
  238. }
  239. + (FIRFirestore *)recoverFromFirestore:(std::shared_ptr<Firestore>)firestore {
  240. return (__bridge FIRFirestore *)firestore->extension();
  241. }
  242. - (void)shutdownWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  243. _firestore->Shutdown(util::MakeCallback(completion));
  244. }
  245. @end
  246. NS_ASSUME_NONNULL_END