FIRFirestore.mm 15 KB

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