FIRFirestore.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. #include <memory>
  18. #include <string>
  19. #include <utility>
  20. #import "FIRFirestoreSettings+Internal.h"
  21. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  22. #import "Firestore/Source/API/FIRCollectionReference+Internal.h"
  23. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  24. #import "Firestore/Source/API/FIRListenerRegistration+Internal.h"
  25. #import "Firestore/Source/API/FIRQuery+Internal.h"
  26. #import "Firestore/Source/API/FIRTransaction+Internal.h"
  27. #import "Firestore/Source/API/FIRWriteBatch+Internal.h"
  28. #import "Firestore/Source/API/FSTFirestoreComponent.h"
  29. #import "Firestore/Source/API/FSTUserDataConverter.h"
  30. #include "Firestore/core/src/api/collection_reference.h"
  31. #include "Firestore/core/src/api/document_reference.h"
  32. #include "Firestore/core/src/api/firestore.h"
  33. #include "Firestore/core/src/api/write_batch.h"
  34. #include "Firestore/core/src/auth/credentials_provider.h"
  35. #include "Firestore/core/src/core/database_info.h"
  36. #include "Firestore/core/src/core/event_listener.h"
  37. #include "Firestore/core/src/core/transaction.h"
  38. #include "Firestore/core/src/model/database_id.h"
  39. #include "Firestore/core/src/util/async_queue.h"
  40. #include "Firestore/core/src/util/config.h"
  41. #include "Firestore/core/src/util/empty.h"
  42. #include "Firestore/core/src/util/error_apple.h"
  43. #include "Firestore/core/src/util/exception.h"
  44. #include "Firestore/core/src/util/exception_apple.h"
  45. #include "Firestore/core/src/util/executor_libdispatch.h"
  46. #include "Firestore/core/src/util/hard_assert.h"
  47. #include "Firestore/core/src/util/log.h"
  48. #include "Firestore/core/src/util/status.h"
  49. #include "Firestore/core/src/util/statusor.h"
  50. #include "Firestore/core/src/util/string_apple.h"
  51. namespace util = firebase::firestore::util;
  52. using firebase::firestore::api::DocumentReference;
  53. using firebase::firestore::api::Firestore;
  54. using firebase::firestore::api::ListenerRegistration;
  55. using firebase::firestore::auth::CredentialsProvider;
  56. using firebase::firestore::core::EventListener;
  57. using firebase::firestore::model::DatabaseId;
  58. using firebase::firestore::util::AsyncQueue;
  59. using firebase::firestore::util::Empty;
  60. using firebase::firestore::util::MakeCallback;
  61. using firebase::firestore::util::MakeNSError;
  62. using firebase::firestore::util::MakeNSString;
  63. using firebase::firestore::util::MakeString;
  64. using firebase::firestore::util::ObjcThrowHandler;
  65. using firebase::firestore::util::SetThrowHandler;
  66. using firebase::firestore::util::Status;
  67. using firebase::firestore::util::StatusOr;
  68. using firebase::firestore::util::ThrowIllegalState;
  69. using firebase::firestore::util::ThrowInvalidArgument;
  70. using UserUpdateBlock = id _Nullable (^)(FIRTransaction *, NSError **);
  71. using UserTransactionCompletion = void (^)(id _Nullable, NSError *_Nullable);
  72. NS_ASSUME_NONNULL_BEGIN
  73. #pragma mark - FIRFirestore
  74. @interface FIRFirestore ()
  75. @property(nonatomic, strong, readonly) FSTUserDataConverter *dataConverter;
  76. @end
  77. @implementation FIRFirestore {
  78. std::shared_ptr<Firestore> _firestore;
  79. FIRFirestoreSettings *_settings;
  80. __weak id<FSTFirestoreInstanceRegistry> _registry;
  81. }
  82. + (void)initialize {
  83. if (self == [FIRFirestore class]) {
  84. SetThrowHandler(ObjcThrowHandler);
  85. Firestore::SetClientLanguage("gl-objc/");
  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. #if HAVE_LIBDISPATCH
  151. std::unique_ptr<util::Executor> user_executor =
  152. absl::make_unique<util::ExecutorLibdispatch>(settings.dispatchQueue);
  153. #else
  154. // It's possible to build without libdispatch on macOS for testing purposes.
  155. // In this case, avoid breaking the build.
  156. std::unique_ptr<util::Executor> user_executor =
  157. util::Executor::CreateSerial("com.google.firebase.firestore.user");
  158. #endif // HAVE_LIBDISPATCH
  159. _firestore->set_user_executor(std::move(user_executor));
  160. }
  161. }
  162. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  163. if (!collectionPath) {
  164. ThrowInvalidArgument("Collection path cannot be nil.");
  165. }
  166. if ([collectionPath containsString:@"//"]) {
  167. ThrowInvalidArgument("Invalid path (%s). Paths must not contain // in them.", collectionPath);
  168. }
  169. return [[FIRCollectionReference alloc]
  170. initWithReference:_firestore->GetCollection(MakeString(collectionPath))];
  171. }
  172. - (FIRDocumentReference *)documentWithPath:(NSString *)documentPath {
  173. if (!documentPath) {
  174. ThrowInvalidArgument("Document path cannot be nil.");
  175. }
  176. if ([documentPath containsString:@"//"]) {
  177. ThrowInvalidArgument("Invalid path (%s). Paths must not contain // in them.", documentPath);
  178. }
  179. DocumentReference documentReference = _firestore->GetDocument(MakeString(documentPath));
  180. return [[FIRDocumentReference alloc] initWithReference:std::move(documentReference)];
  181. }
  182. - (FIRQuery *)collectionGroupWithID:(NSString *)collectionID {
  183. if (!collectionID) {
  184. ThrowInvalidArgument("Collection ID cannot be nil.");
  185. }
  186. if ([collectionID containsString:@"/"]) {
  187. ThrowInvalidArgument("Invalid collection ID (%s). Collection IDs must not contain / in them.",
  188. collectionID);
  189. }
  190. auto query = _firestore->GetCollectionGroup(MakeString(collectionID));
  191. return [[FIRQuery alloc] initWithQuery:std::move(query) firestore:_firestore];
  192. }
  193. - (FIRWriteBatch *)batch {
  194. return [FIRWriteBatch writeBatchWithDataConverter:self.dataConverter
  195. writeBatch:_firestore->GetBatch()];
  196. }
  197. - (void)runTransactionWithBlock:(UserUpdateBlock)updateBlock
  198. dispatchQueue:(dispatch_queue_t)queue
  199. completion:(UserTransactionCompletion)completion {
  200. if (!updateBlock) {
  201. ThrowInvalidArgument("Transaction block cannot be nil.");
  202. }
  203. if (!completion) {
  204. ThrowInvalidArgument("Transaction completion block cannot be nil.");
  205. }
  206. class TransactionResult {
  207. public:
  208. TransactionResult(FIRFirestore *firestore,
  209. UserUpdateBlock update_block,
  210. dispatch_queue_t queue,
  211. UserTransactionCompletion completion)
  212. : firestore_(firestore),
  213. user_update_block_(update_block),
  214. queue_(queue),
  215. user_completion_(completion) {
  216. }
  217. void RunUpdateBlock(std::shared_ptr<core::Transaction> internalTransaction,
  218. core::TransactionResultCallback internalCallback) {
  219. dispatch_async(queue_, ^{
  220. auto transaction = [FIRTransaction transactionWithInternalTransaction:internalTransaction
  221. firestore:firestore_];
  222. NSError *_Nullable error = nil;
  223. user_result_ = user_update_block_(transaction, &error);
  224. // If the user set an error, disregard the result.
  225. if (error) {
  226. // If the error is a user error, set flag to not retry the transaction.
  227. if (error.domain != FIRFirestoreErrorDomain) {
  228. internalTransaction->MarkPermanentlyFailed();
  229. }
  230. internalCallback(Status::FromNSError(error));
  231. } else {
  232. internalCallback(Status::OK());
  233. }
  234. });
  235. }
  236. void HandleFinalStatus(const Status &status) {
  237. if (!status.ok()) {
  238. user_completion_(nil, MakeNSError(status));
  239. return;
  240. }
  241. user_completion_(user_result_, nil);
  242. }
  243. private:
  244. FIRFirestore *firestore_;
  245. UserUpdateBlock user_update_block_;
  246. dispatch_queue_t queue_;
  247. UserTransactionCompletion user_completion_;
  248. id _Nullable user_result_;
  249. };
  250. auto result_capture = std::make_shared<TransactionResult>(self, updateBlock, queue, completion);
  251. // Wrap the user-supplied updateBlock in a core C++ compatible callback. Wrap the result of the
  252. // updateBlock invocation up in a TransactionResult for tunneling through the internals of the
  253. // system.
  254. auto internalUpdateBlock = [result_capture](
  255. std::shared_ptr<core::Transaction> internalTransaction,
  256. core::TransactionResultCallback internalCallback) {
  257. result_capture->RunUpdateBlock(internalTransaction, internalCallback);
  258. };
  259. // Unpacks the TransactionResult value and calls the user completion handler.
  260. //
  261. // PORTING NOTE: Other platforms where the user return value is internally representable don't
  262. // need this wrapper.
  263. auto objcTranslator = [result_capture](const Status &status) {
  264. result_capture->HandleFinalStatus(status);
  265. };
  266. _firestore->RunTransaction(std::move(internalUpdateBlock), std::move(objcTranslator));
  267. }
  268. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **error))updateBlock
  269. completion:
  270. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  271. static dispatch_queue_t transactionDispatchQueue;
  272. static dispatch_once_t onceToken;
  273. dispatch_once(&onceToken, ^{
  274. transactionDispatchQueue = dispatch_queue_create("com.google.firebase.firestore.transaction",
  275. DISPATCH_QUEUE_CONCURRENT);
  276. });
  277. [self runTransactionWithBlock:updateBlock
  278. dispatchQueue:transactionDispatchQueue
  279. completion:completion];
  280. }
  281. + (void)enableLogging:(BOOL)logging {
  282. util::LogSetLevel(logging ? util::kLogLevelDebug : util::kLogLevelNotice);
  283. }
  284. - (void)enableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  285. _firestore->EnableNetwork(MakeCallback(completion));
  286. }
  287. - (void)disableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable))completion {
  288. _firestore->DisableNetwork(MakeCallback(completion));
  289. }
  290. - (void)clearPersistenceWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  291. _firestore->ClearPersistence(MakeCallback(completion));
  292. }
  293. - (void)waitForPendingWritesWithCompletion:(void (^)(NSError *_Nullable error))completion {
  294. _firestore->WaitForPendingWrites(MakeCallback(completion));
  295. }
  296. - (void)terminateWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  297. id<FSTFirestoreInstanceRegistry> strongRegistry = _registry;
  298. if (strongRegistry) {
  299. [strongRegistry
  300. removeInstanceWithDatabase:MakeNSString(_firestore->database_id().database_id())];
  301. }
  302. [self terminateInternalWithCompletion:completion];
  303. }
  304. - (id<FIRListenerRegistration>)addSnapshotsInSyncListener:(void (^)(void))listener {
  305. std::unique_ptr<core::EventListener<Empty>> eventListener =
  306. core::EventListener<Empty>::Create([listener](const StatusOr<Empty> &) { listener(); });
  307. std::unique_ptr<ListenerRegistration> result =
  308. _firestore->AddSnapshotsInSyncListener(std::move(eventListener));
  309. return [[FSTListenerRegistration alloc] initWithRegistration:std::move(result)];
  310. }
  311. @end
  312. @implementation FIRFirestore (Internal)
  313. - (std::shared_ptr<Firestore>)wrapped {
  314. return _firestore;
  315. }
  316. - (const std::shared_ptr<util::AsyncQueue> &)workerQueue {
  317. return _firestore->worker_queue();
  318. }
  319. - (const DatabaseId &)databaseID {
  320. return _firestore->database_id();
  321. }
  322. + (FIRFirestore *)recoverFromFirestore:(std::shared_ptr<Firestore>)firestore {
  323. return (__bridge FIRFirestore *)firestore->extension();
  324. }
  325. - (void)terminateInternalWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  326. _firestore->Terminate(MakeCallback(completion));
  327. }
  328. @end
  329. NS_ASSUME_NONNULL_END