FSTDatastore.mm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. #import <GRPCClient/GRPCCall+OAuth2.h>
  18. #import <ProtoRPC/ProtoRPC.h>
  19. #import "FIRFirestoreErrors.h"
  20. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  21. #import "Firestore/Source/API/FIRFirestoreVersion.h"
  22. #import "Firestore/Source/Local/FSTLocalStore.h"
  23. #import "Firestore/Source/Model/FSTDocument.h"
  24. #import "Firestore/Source/Model/FSTDocumentKey.h"
  25. #import "Firestore/Source/Model/FSTMutation.h"
  26. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  27. #import "Firestore/Source/Remote/FSTStream.h"
  28. #import "Firestore/Source/Util/FSTAssert.h"
  29. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  30. #import "Firestore/Source/Util/FSTLogger.h"
  31. #import "Firestore/Protos/objc/google/firestore/v1beta1/Firestore.pbrpc.h"
  32. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  33. #include "Firestore/core/src/firebase/firestore/auth/token.h"
  34. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  35. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  36. #include "Firestore/core/src/firebase/firestore/util/error_apple.h"
  37. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  38. namespace util = firebase::firestore::util;
  39. using firebase::firestore::auth::CredentialsProvider;
  40. using firebase::firestore::auth::Token;
  41. using firebase::firestore::core::DatabaseInfo;
  42. using firebase::firestore::model::DatabaseId;
  43. NS_ASSUME_NONNULL_BEGIN
  44. // GRPC does not publicly declare a means of disabling SSL, which we need for testing. Firestore
  45. // directly exposes an sslEnabled setting so this is required to plumb that through. Note that our
  46. // own tests depend on this working so we'll know if this changes upstream.
  47. @interface GRPCHost
  48. + (nullable instancetype)hostWithAddress:(NSString *)address;
  49. @property(nonatomic, getter=isSecure) BOOL secure;
  50. @end
  51. static NSString *const kXGoogAPIClientHeader = @"x-goog-api-client";
  52. static NSString *const kGoogleCloudResourcePrefix = @"google-cloud-resource-prefix";
  53. /** Function typedef used to create RPCs. */
  54. typedef GRPCProtoCall * (^RPCFactory)(void);
  55. #pragma mark - FSTDatastore
  56. @interface FSTDatastore ()
  57. /** The GRPC service for Firestore. */
  58. @property(nonatomic, strong, readonly) GCFSFirestore *service;
  59. @property(nonatomic, strong, readonly) FSTDispatchQueue *workerDispatchQueue;
  60. /**
  61. * An object for getting an auth token before each request. Does not own the CredentialsProvider
  62. * instance.
  63. */
  64. @property(nonatomic, assign, readonly) CredentialsProvider *credentials;
  65. @property(nonatomic, strong, readonly) FSTSerializerBeta *serializer;
  66. @end
  67. @implementation FSTDatastore
  68. + (instancetype)datastoreWithDatabase:(const DatabaseInfo *)databaseInfo
  69. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  70. credentials:(CredentialsProvider *)credentials {
  71. return [[FSTDatastore alloc] initWithDatabaseInfo:databaseInfo
  72. workerDispatchQueue:workerDispatchQueue
  73. credentials:credentials];
  74. }
  75. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo *)databaseInfo
  76. workerDispatchQueue:(FSTDispatchQueue *)workerDispatchQueue
  77. credentials:(CredentialsProvider *)credentials {
  78. if (self = [super init]) {
  79. _databaseInfo = databaseInfo;
  80. NSString *host = util::WrapNSString(databaseInfo->host());
  81. if (!databaseInfo->ssl_enabled()) {
  82. GRPCHost *hostConfig = [GRPCHost hostWithAddress:host];
  83. hostConfig.secure = NO;
  84. }
  85. _service = [GCFSFirestore serviceWithHost:host];
  86. _workerDispatchQueue = workerDispatchQueue;
  87. _credentials = credentials;
  88. _serializer = [[FSTSerializerBeta alloc] initWithDatabaseID:&databaseInfo->database_id()];
  89. }
  90. return self;
  91. }
  92. - (NSString *)description {
  93. return [NSString stringWithFormat:@"<FSTDatastore: <DatabaseInfo: database_id:%s host:%s>>",
  94. self.databaseInfo->database_id().database_id().c_str(),
  95. self.databaseInfo->host().c_str()];
  96. }
  97. /**
  98. * Converts the error to an error within the domain FIRFirestoreErrorDomain.
  99. */
  100. + (NSError *)firestoreErrorForError:(NSError *)error {
  101. if (!error) {
  102. return error;
  103. } else if ([error.domain isEqualToString:FIRFirestoreErrorDomain]) {
  104. return error;
  105. } else if ([error.domain isEqualToString:kGRPCErrorDomain]) {
  106. FSTAssert(error.code >= GRPCErrorCodeCancelled && error.code <= GRPCErrorCodeUnauthenticated,
  107. @"Unknown GRPC error code: %ld", (long)error.code);
  108. return
  109. [NSError errorWithDomain:FIRFirestoreErrorDomain code:error.code userInfo:error.userInfo];
  110. } else {
  111. return [NSError errorWithDomain:FIRFirestoreErrorDomain
  112. code:FIRFirestoreErrorCodeUnknown
  113. userInfo:@{NSUnderlyingErrorKey : error}];
  114. }
  115. }
  116. + (BOOL)isAbortedError:(NSError *)error {
  117. FSTAssert([error.domain isEqualToString:FIRFirestoreErrorDomain],
  118. @"isAbortedError: only works with errors emitted by FSTDatastore.");
  119. return error.code == FIRFirestoreErrorCodeAborted;
  120. }
  121. + (BOOL)isPermanentWriteError:(NSError *)error {
  122. FSTAssert([error.domain isEqualToString:FIRFirestoreErrorDomain],
  123. @"isPerminanteWriteError: only works with errors emitted by FSTDatastore.");
  124. switch (error.code) {
  125. case FIRFirestoreErrorCodeCancelled:
  126. case FIRFirestoreErrorCodeUnknown:
  127. case FIRFirestoreErrorCodeDeadlineExceeded:
  128. case FIRFirestoreErrorCodeResourceExhausted:
  129. case FIRFirestoreErrorCodeInternal:
  130. case FIRFirestoreErrorCodeUnavailable:
  131. case FIRFirestoreErrorCodeUnauthenticated:
  132. // Unauthenticated means something went wrong with our token and we need
  133. // to retry with new credentials which will happen automatically.
  134. // TODO(b/37325376): Give up after second unauthenticated error.
  135. return NO;
  136. case FIRFirestoreErrorCodeInvalidArgument:
  137. case FIRFirestoreErrorCodeNotFound:
  138. case FIRFirestoreErrorCodeAlreadyExists:
  139. case FIRFirestoreErrorCodePermissionDenied:
  140. case FIRFirestoreErrorCodeFailedPrecondition:
  141. case FIRFirestoreErrorCodeAborted:
  142. // Aborted might be retried in some scenarios, but that is dependant on
  143. // the context and should handled individually by the calling code.
  144. // See https://cloud.google.com/apis/design/errors
  145. case FIRFirestoreErrorCodeOutOfRange:
  146. case FIRFirestoreErrorCodeUnimplemented:
  147. case FIRFirestoreErrorCodeDataLoss:
  148. default:
  149. return YES;
  150. }
  151. }
  152. /** Returns the string to be used as x-goog-api-client header value. */
  153. + (NSString *)googAPIClientHeaderValue {
  154. // TODO(dimond): This should ideally also include the grpc version, however, gRPC defines the
  155. // version as a macro, so it would be hardcoded based on version we have at compile time of
  156. // the Firestore library, rather than the version available at runtime/at compile time by the
  157. // user of the library.
  158. return [NSString stringWithFormat:@"gl-objc/ fire/%s grpc/", FirebaseFirestoreVersionString];
  159. }
  160. /** Returns the string to be used as google-cloud-resource-prefix header value. */
  161. + (NSString *)googleCloudResourcePrefixForDatabaseID:(const DatabaseId *)databaseID {
  162. return [NSString stringWithFormat:@"projects/%s/databases/%s", databaseID->project_id().c_str(),
  163. databaseID->database_id().c_str()];
  164. }
  165. /**
  166. * Takes a dictionary of (HTTP) response headers and returns the set of whitelisted headers
  167. * (for logging purposes).
  168. */
  169. + (NSDictionary<NSString *, NSString *> *)extractWhiteListedHeaders:
  170. (NSDictionary<NSString *, NSString *> *)headers {
  171. NSMutableDictionary<NSString *, NSString *> *whiteListedHeaders =
  172. [NSMutableDictionary dictionary];
  173. NSArray<NSString *> *whiteList = @[
  174. @"date", @"x-google-backends", @"x-google-netmon-label", @"x-google-service",
  175. @"x-google-gfe-request-trace"
  176. ];
  177. [headers
  178. enumerateKeysAndObjectsUsingBlock:^(NSString *headerName, NSString *headerValue, BOOL *stop) {
  179. if ([whiteList containsObject:[headerName lowercaseString]]) {
  180. whiteListedHeaders[headerName] = headerValue;
  181. }
  182. }];
  183. return whiteListedHeaders;
  184. }
  185. /** Logs the (whitelisted) headers returned for an GRPCProtoCall RPC. */
  186. + (void)logHeadersForRPC:(GRPCProtoCall *)rpc RPCName:(NSString *)rpcName {
  187. if ([FIRFirestore isLoggingEnabled]) {
  188. FSTLog(@"RPC %@ returned headers (whitelisted): %@", rpcName,
  189. [FSTDatastore extractWhiteListedHeaders:rpc.responseHeaders]);
  190. }
  191. }
  192. - (void)commitMutations:(NSArray<FSTMutation *> *)mutations
  193. completion:(FSTVoidErrorBlock)completion {
  194. GCFSCommitRequest *request = [GCFSCommitRequest message];
  195. request.database = [self.serializer encodedDatabaseID];
  196. NSMutableArray<GCFSWrite *> *mutationProtos = [NSMutableArray array];
  197. for (FSTMutation *mutation in mutations) {
  198. [mutationProtos addObject:[self.serializer encodedMutation:mutation]];
  199. }
  200. request.writesArray = mutationProtos;
  201. RPCFactory rpcFactory = ^GRPCProtoCall * {
  202. __block GRPCProtoCall *rpc = [self.service
  203. RPCToCommitWithRequest:request
  204. handler:^(GCFSCommitResponse *response, NSError *_Nullable error) {
  205. error = [FSTDatastore firestoreErrorForError:error];
  206. [self.workerDispatchQueue dispatchAsync:^{
  207. FSTLog(@"RPC CommitRequest completed. Error: %@", error);
  208. [FSTDatastore logHeadersForRPC:rpc RPCName:@"CommitRequest"];
  209. completion(error);
  210. }];
  211. }];
  212. return rpc;
  213. };
  214. [self invokeRPCWithFactory:rpcFactory errorHandler:completion];
  215. }
  216. - (void)lookupDocuments:(NSArray<FSTDocumentKey *> *)keys
  217. completion:(FSTVoidMaybeDocumentArrayErrorBlock)completion {
  218. GCFSBatchGetDocumentsRequest *request = [GCFSBatchGetDocumentsRequest message];
  219. request.database = [self.serializer encodedDatabaseID];
  220. for (FSTDocumentKey *key in keys) {
  221. [request.documentsArray addObject:[self.serializer encodedDocumentKey:key]];
  222. }
  223. __block FSTMaybeDocumentDictionary *results =
  224. [FSTMaybeDocumentDictionary maybeDocumentDictionary];
  225. RPCFactory rpcFactory = ^GRPCProtoCall * {
  226. __block GRPCProtoCall *rpc = [self.service
  227. RPCToBatchGetDocumentsWithRequest:request
  228. eventHandler:^(BOOL done,
  229. GCFSBatchGetDocumentsResponse *_Nullable response,
  230. NSError *_Nullable error) {
  231. error = [FSTDatastore firestoreErrorForError:error];
  232. [self.workerDispatchQueue dispatchAsync:^{
  233. if (error) {
  234. FSTLog(@"RPC BatchGetDocuments completed. Error: %@", error);
  235. [FSTDatastore logHeadersForRPC:rpc RPCName:@"BatchGetDocuments"];
  236. completion(nil, error);
  237. return;
  238. }
  239. if (!done) {
  240. // Streaming response, accumulate result
  241. FSTMaybeDocument *doc =
  242. [self.serializer decodedMaybeDocumentFromBatch:response];
  243. results = [results dictionaryBySettingObject:doc forKey:doc.key];
  244. } else {
  245. // Streaming response is done, call completion
  246. FSTLog(@"RPC BatchGetDocuments completed successfully.");
  247. [FSTDatastore logHeadersForRPC:rpc RPCName:@"BatchGetDocuments"];
  248. FSTAssert(!response, @"Got response after done.");
  249. NSMutableArray<FSTMaybeDocument *> *docs =
  250. [NSMutableArray arrayWithCapacity:keys.count];
  251. for (FSTDocumentKey *key in keys) {
  252. [docs addObject:results[key]];
  253. }
  254. completion(docs, nil);
  255. }
  256. }];
  257. }];
  258. return rpc;
  259. };
  260. [self invokeRPCWithFactory:rpcFactory
  261. errorHandler:^(NSError *_Nonnull error) {
  262. error = [FSTDatastore firestoreErrorForError:error];
  263. completion(nil, error);
  264. }];
  265. }
  266. - (void)invokeRPCWithFactory:(GRPCProtoCall * (^)(void))rpcFactory
  267. errorHandler:(FSTVoidErrorBlock)errorHandler {
  268. // TODO(mikelehen): We should force a refresh if the previous RPC failed due to an expired token,
  269. // but I'm not sure how to detect that right now. http://b/32762461
  270. _credentials->GetToken(
  271. /*force_refresh=*/false,
  272. [self, rpcFactory, errorHandler](Token result, const int64_t error_code,
  273. const absl::string_view error_msg) {
  274. NSError *error = util::WrapNSError(error_code, error_msg);
  275. [self.workerDispatchQueue dispatchAsyncAllowingSameQueue:^{
  276. if (error) {
  277. errorHandler(error);
  278. } else {
  279. GRPCProtoCall *rpc = rpcFactory();
  280. [FSTDatastore
  281. prepareHeadersForRPC:rpc
  282. databaseID:&self.databaseInfo->database_id()
  283. token:(result.user().is_authenticated() ? result.token()
  284. : absl::string_view())];
  285. [rpc start];
  286. }
  287. }];
  288. });
  289. }
  290. - (FSTWatchStream *)createWatchStream {
  291. return [[FSTWatchStream alloc] initWithDatabase:_databaseInfo
  292. workerDispatchQueue:_workerDispatchQueue
  293. credentials:_credentials
  294. serializer:_serializer];
  295. }
  296. - (FSTWriteStream *)createWriteStream {
  297. return [[FSTWriteStream alloc] initWithDatabase:_databaseInfo
  298. workerDispatchQueue:_workerDispatchQueue
  299. credentials:_credentials
  300. serializer:_serializer];
  301. }
  302. /** Adds headers to the RPC including any OAuth access token if provided .*/
  303. + (void)prepareHeadersForRPC:(GRPCCall *)rpc
  304. databaseID:(const DatabaseId *)databaseID
  305. token:(const absl::string_view)token {
  306. rpc.oauth2AccessToken = token.data() == nullptr ? nil : util::WrapNSString(token);
  307. rpc.requestHeaders[kXGoogAPIClientHeader] = [FSTDatastore googAPIClientHeaderValue];
  308. // This header is used to improve routing and project isolation by the backend.
  309. rpc.requestHeaders[kGoogleCloudResourcePrefix] =
  310. [FSTDatastore googleCloudResourcePrefixForDatabaseID:databaseID];
  311. }
  312. @end
  313. NS_ASSUME_NONNULL_END