FIRFirestore.mm 11 KB

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