FSTDatastore.mm 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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 "Firestore/Source/Remote/FSTDatastore.h"
  17. #include <map>
  18. #include <memory>
  19. #include <vector>
  20. #import "FIRFirestoreErrors.h"
  21. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  22. #import "Firestore/Source/API/FIRFirestoreVersion.h"
  23. #import "Firestore/Source/Local/FSTLocalStore.h"
  24. #import "Firestore/Source/Model/FSTDocument.h"
  25. #import "Firestore/Source/Model/FSTMutation.h"
  26. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  27. #import "Firestore/Source/Remote/FSTStream.h"
  28. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  29. #include "Firestore/core/src/firebase/firestore/auth/token.h"
  30. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  31. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  32. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  33. #include "Firestore/core/src/firebase/firestore/util/async_queue.h"
  34. #include "Firestore/core/src/firebase/firestore/util/error_apple.h"
  35. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  36. #include "Firestore/core/src/firebase/firestore/util/log.h"
  37. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  38. #include "absl/memory/memory.h"
  39. #include "grpcpp/support/status_code_enum.h"
  40. namespace util = firebase::firestore::util;
  41. using firebase::firestore::auth::CredentialsProvider;
  42. using firebase::firestore::auth::Token;
  43. using firebase::firestore::core::DatabaseInfo;
  44. using firebase::firestore::model::DocumentKey;
  45. using firebase::firestore::model::DatabaseId;
  46. using firebase::firestore::remote::Datastore;
  47. using firebase::firestore::remote::GrpcConnection;
  48. using firebase::firestore::remote::WatchStream;
  49. using firebase::firestore::remote::WriteStream;
  50. using util::AsyncQueue;
  51. NS_ASSUME_NONNULL_BEGIN
  52. // TODO(varconst): this is the only leftover from the dependency on gRPC
  53. // Objective-C client (where this constant is declared in `GRPCCall.h`). Remove
  54. // this once error handling is fully translated to C++.
  55. NSString *const kGRPCErrorDomain = @"io.grpc";
  56. #pragma mark - FSTDatastore
  57. @interface FSTDatastore ()
  58. /**
  59. * An object for getting an auth token before each request. Does not own the CredentialsProvider
  60. * instance.
  61. */
  62. @property(nonatomic, assign, readonly) CredentialsProvider *credentials;
  63. @property(nonatomic, strong, readonly) FSTSerializerBeta *serializer;
  64. @end
  65. @implementation FSTDatastore {
  66. AsyncQueue *_workerQueue;
  67. std::shared_ptr<Datastore> _datastore;
  68. }
  69. + (instancetype)datastoreWithDatabase:(const DatabaseInfo *)databaseInfo
  70. workerQueue:(AsyncQueue *)workerQueue
  71. credentials:(CredentialsProvider *)credentials {
  72. return [[FSTDatastore alloc] initWithDatabaseInfo:databaseInfo
  73. workerQueue:workerQueue
  74. credentials:credentials];
  75. }
  76. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo *)databaseInfo
  77. workerQueue:(AsyncQueue *)workerQueue
  78. credentials:(CredentialsProvider *)credentials {
  79. if (self = [super init]) {
  80. _databaseInfo = databaseInfo;
  81. _workerQueue = workerQueue;
  82. _credentials = credentials;
  83. _serializer = [[FSTSerializerBeta alloc] initWithDatabaseID:&databaseInfo->database_id()];
  84. _datastore =
  85. std::make_shared<Datastore>(*_databaseInfo, _workerQueue, _credentials, _serializer);
  86. _datastore->Start();
  87. if (!databaseInfo->ssl_enabled()) {
  88. GrpcConnection::UseInsecureChannel(databaseInfo->host());
  89. }
  90. }
  91. return self;
  92. }
  93. - (void)shutdown {
  94. _datastore->Shutdown();
  95. }
  96. - (NSString *)description {
  97. return [NSString stringWithFormat:@"<FSTDatastore: <DatabaseInfo: database_id:%s host:%s>>",
  98. self.databaseInfo->database_id().database_id().c_str(),
  99. self.databaseInfo->host().c_str()];
  100. }
  101. /**
  102. * Converts the error to an error within the domain FIRFirestoreErrorDomain.
  103. */
  104. + (NSError *)firestoreErrorForError:(NSError *)error {
  105. if (!error) {
  106. return error;
  107. } else if ([error.domain isEqualToString:FIRFirestoreErrorDomain]) {
  108. return error;
  109. } else if ([error.domain isEqualToString:kGRPCErrorDomain]) {
  110. HARD_ASSERT(error.code >= grpc::CANCELLED && error.code <= grpc::UNAUTHENTICATED,
  111. "Unknown GRPC error code: %s", error.code);
  112. return
  113. [NSError errorWithDomain:FIRFirestoreErrorDomain code:error.code userInfo:error.userInfo];
  114. } else {
  115. return [NSError errorWithDomain:FIRFirestoreErrorDomain
  116. code:FIRFirestoreErrorCodeUnknown
  117. userInfo:@{NSUnderlyingErrorKey : error}];
  118. }
  119. }
  120. + (BOOL)isAbortedError:(NSError *)error {
  121. HARD_ASSERT([error.domain isEqualToString:FIRFirestoreErrorDomain],
  122. "isAbortedError: only works with errors emitted by FSTDatastore.");
  123. return error.code == FIRFirestoreErrorCodeAborted;
  124. }
  125. + (BOOL)isPermanentWriteError:(NSError *)error {
  126. HARD_ASSERT([error.domain isEqualToString:FIRFirestoreErrorDomain],
  127. "isPerminanteWriteError: only works with errors emitted by FSTDatastore.");
  128. switch (error.code) {
  129. case FIRFirestoreErrorCodeCancelled:
  130. case FIRFirestoreErrorCodeUnknown:
  131. case FIRFirestoreErrorCodeDeadlineExceeded:
  132. case FIRFirestoreErrorCodeResourceExhausted:
  133. case FIRFirestoreErrorCodeInternal:
  134. case FIRFirestoreErrorCodeUnavailable:
  135. // Unauthenticated means something went wrong with our token and we need to retry with new
  136. // credentials which will happen automatically.
  137. case FIRFirestoreErrorCodeUnauthenticated:
  138. return NO;
  139. case FIRFirestoreErrorCodeInvalidArgument:
  140. case FIRFirestoreErrorCodeNotFound:
  141. case FIRFirestoreErrorCodeAlreadyExists:
  142. case FIRFirestoreErrorCodePermissionDenied:
  143. case FIRFirestoreErrorCodeFailedPrecondition:
  144. case FIRFirestoreErrorCodeAborted:
  145. // Aborted might be retried in some scenarios, but that is dependant on
  146. // the context and should handled individually by the calling code.
  147. // See https://cloud.google.com/apis/design/errors
  148. case FIRFirestoreErrorCodeOutOfRange:
  149. case FIRFirestoreErrorCodeUnimplemented:
  150. case FIRFirestoreErrorCodeDataLoss:
  151. return YES;
  152. default:
  153. return YES;
  154. }
  155. }
  156. - (void)commitMutations:(NSArray<FSTMutation *> *)mutations
  157. completion:(FSTVoidErrorBlock)completion {
  158. _datastore->CommitMutations(mutations, completion);
  159. }
  160. - (void)lookupDocuments:(const std::vector<DocumentKey> &)keys
  161. completion:(FSTVoidMaybeDocumentArrayErrorBlock)completion {
  162. _datastore->LookupDocuments(keys, completion);
  163. }
  164. - (std::shared_ptr<WatchStream>)createWatchStreamWithDelegate:(id)delegate {
  165. return _datastore->CreateWatchStream(delegate);
  166. }
  167. - (std::shared_ptr<WriteStream>)createWriteStreamWithDelegate:(id)delegate {
  168. return _datastore->CreateWriteStream(delegate);
  169. }
  170. @end
  171. NS_ASSUME_NONNULL_END