FIRFirestore.mm 14 KB

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