FIRFirestore.mm 12 KB

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