FSTDatastore.mm 15 KB

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