FSTDatastore.mm 15 KB

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