FIRFirestore.mm 12 KB

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