FSTDatastore.mm 16 KB

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