FIRFunctions.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. // Copyright 2017 Google
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "FIRFunctions.h"
  15. #import "FIRFunctions+Internal.h"
  16. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  17. #import "Interop/Auth/Public/FIRAuthInterop.h"
  18. #import "FIRError.h"
  19. #import "FIRHTTPSCallable+Internal.h"
  20. #import "FIRHTTPSCallable.h"
  21. #import "FUNContext.h"
  22. #import "FUNError.h"
  23. #import "FUNSerializer.h"
  24. #import "FUNUsageValidation.h"
  25. #import <GTMSessionFetcher/GTMSessionFetcherService.h>
  26. // The following two macros supply the incantation so that the C
  27. // preprocessor does not try to parse the version as a floating
  28. // point number. See
  29. // https://www.guyrutenberg.com/2008/12/20/expanding-macros-into-string-constants-in-c/
  30. #define STR(x) STR_EXPAND(x)
  31. #define STR_EXPAND(x) #x
  32. NS_ASSUME_NONNULL_BEGIN
  33. NSString *const kFUNInstanceIDTokenHeader = @"Firebase-Instance-ID-Token";
  34. NSString *const kFUNDefaultRegion = @"us-central1";
  35. /// Empty protocol to register Functions as a component with Core.
  36. @protocol FIRFunctionsInstanceProvider
  37. @end
  38. @interface FIRFunctions () <FIRLibrary, FIRFunctionsInstanceProvider> {
  39. // The network client to use for http requests.
  40. GTMSessionFetcherService *_fetcherService;
  41. // The projectID to use for all function references.
  42. NSString *_projectID;
  43. // The region to use for all function references.
  44. NSString *_region;
  45. // A serializer to encode/decode data and return values.
  46. FUNSerializer *_serializer;
  47. // A factory for getting the metadata to include with function calls.
  48. FUNContextProvider *_contextProvider;
  49. // For testing only. If this is set, functions will be called against it instead of Firebase.
  50. NSString *_emulatorOrigin;
  51. }
  52. // Re-declare this initializer here in order to attribute it as the designated initializer.
  53. - (instancetype)initWithProjectID:(NSString *)projectID
  54. region:(NSString *)region
  55. auth:(nullable id<FIRAuthInterop>)auth NS_DESIGNATED_INITIALIZER;
  56. @end
  57. @implementation FIRFunctions
  58. + (void)load {
  59. NSString *version = [NSString stringWithUTF8String:(const char *const)STR(FIRFunctions_VERSION)];
  60. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self withName:@"fire-fun" withVersion:version];
  61. }
  62. + (NSArray<FIRComponent *> *)componentsToRegister {
  63. FIRComponentCreationBlock creationBlock =
  64. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  65. *isCacheable = YES;
  66. return [self functionsForApp:container.app];
  67. };
  68. FIRDependency *auth = [FIRDependency dependencyWithProtocol:@protocol(FIRAuthInterop)
  69. isRequired:NO];
  70. FIRComponent *internalProvider =
  71. [FIRComponent componentWithProtocol:@protocol(FIRFunctionsInstanceProvider)
  72. instantiationTiming:FIRInstantiationTimingLazy
  73. dependencies:@[ auth ]
  74. creationBlock:creationBlock];
  75. return @[ internalProvider ];
  76. }
  77. + (instancetype)functions {
  78. return [[self alloc] initWithApp:[FIRApp defaultApp] region:kFUNDefaultRegion];
  79. }
  80. + (instancetype)functionsForApp:(FIRApp *)app {
  81. return [[self alloc] initWithApp:app region:kFUNDefaultRegion];
  82. }
  83. + (instancetype)functionsForRegion:(NSString *)region {
  84. return [[self alloc] initWithApp:[FIRApp defaultApp] region:region];
  85. }
  86. + (instancetype)functionsForApp:(FIRApp *)app region:(NSString *)region {
  87. return [[self alloc] initWithApp:app region:region];
  88. }
  89. - (instancetype)initWithApp:(FIRApp *)app region:(NSString *)region {
  90. return [self initWithProjectID:app.options.projectID
  91. region:region
  92. auth:FIR_COMPONENT(FIRAuthInterop, app.container)];
  93. }
  94. - (instancetype)initWithProjectID:(NSString *)projectID
  95. region:(NSString *)region
  96. auth:(nullable id<FIRAuthInterop>)auth {
  97. self = [super init];
  98. if (self) {
  99. if (!region) {
  100. FUNThrowInvalidArgument(@"FIRFunctions region cannot be nil.");
  101. }
  102. _fetcherService = [[GTMSessionFetcherService alloc] init];
  103. _projectID = [projectID copy];
  104. _region = [region copy];
  105. _serializer = [[FUNSerializer alloc] init];
  106. _contextProvider = [[FUNContextProvider alloc] initWithAuth:auth];
  107. _emulatorOrigin = nil;
  108. }
  109. return self;
  110. }
  111. - (void)useLocalhost {
  112. [self useFunctionsEmulatorOrigin:@"http://localhost:5005"];
  113. }
  114. - (void)useFunctionsEmulatorOrigin:(NSString *)origin {
  115. _emulatorOrigin = origin;
  116. }
  117. - (NSString *)URLWithName:(NSString *)name {
  118. if (!name) {
  119. FUNThrowInvalidArgument(@"FIRFunctions function name cannot be nil.");
  120. }
  121. if (!_projectID) {
  122. FUNThrowInvalidArgument(@"FIRFunctions app projectID cannot be nil.");
  123. }
  124. if (_emulatorOrigin) {
  125. return [NSString stringWithFormat:@"%@/%@/%@/%@", _emulatorOrigin, _projectID, _region, name];
  126. }
  127. return
  128. [NSString stringWithFormat:@"https://%@-%@.cloudfunctions.net/%@", _region, _projectID, name];
  129. }
  130. - (void)callFunction:(NSString *)name
  131. withObject:(nullable id)data
  132. timeout:(NSTimeInterval)timeout
  133. completion:(void (^)(FIRHTTPSCallableResult *_Nullable result,
  134. NSError *_Nullable error))completion {
  135. [_contextProvider getContext:^(FUNContext *_Nullable context, NSError *_Nullable error) {
  136. if (error) {
  137. if (completion) {
  138. completion(nil, error);
  139. }
  140. return;
  141. }
  142. return [self callFunction:name
  143. withObject:data
  144. timeout:timeout
  145. context:context
  146. completion:completion];
  147. }];
  148. }
  149. - (void)callFunction:(NSString *)name
  150. withObject:(nullable id)data
  151. timeout:(NSTimeInterval)timeout
  152. context:(FUNContext *)context
  153. completion:(void (^)(FIRHTTPSCallableResult *_Nullable result,
  154. NSError *_Nullable error))completion {
  155. NSURL *url = [NSURL URLWithString:[self URLWithName:name]];
  156. NSURLRequest *request = [NSURLRequest requestWithURL:url
  157. cachePolicy:NSURLRequestUseProtocolCachePolicy
  158. timeoutInterval:timeout];
  159. GTMSessionFetcher *fetcher = [_fetcherService fetcherWithRequest:request];
  160. NSMutableDictionary *body = [NSMutableDictionary dictionary];
  161. // Encode the data in the body.
  162. if (!data) {
  163. data = [NSNull null];
  164. }
  165. id encoded = [_serializer encode:data];
  166. if (!encoded) {
  167. FUNThrowInvalidArgument(@"FIRFunctions data encoded as nil. This should not happen.");
  168. }
  169. body[@"data"] = encoded;
  170. NSError *error = nil;
  171. NSData *payload = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
  172. if (error) {
  173. if (completion) {
  174. dispatch_async(dispatch_get_main_queue(), ^{
  175. completion(nil, error);
  176. });
  177. }
  178. return;
  179. }
  180. fetcher.bodyData = payload;
  181. // Set the headers.
  182. [fetcher setRequestValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  183. if (context.authToken) {
  184. NSString *value = [NSString stringWithFormat:@"Bearer %@", context.authToken];
  185. [fetcher setRequestValue:value forHTTPHeaderField:@"Authorization"];
  186. }
  187. if (context.instanceIDToken) {
  188. [fetcher setRequestValue:context.instanceIDToken forHTTPHeaderField:kFUNInstanceIDTokenHeader];
  189. }
  190. // Override normal security rules if this is a local test.
  191. if (_emulatorOrigin) {
  192. fetcher.allowLocalhostRequest = YES;
  193. fetcher.allowedInsecureSchemes = @[ @"http" ];
  194. }
  195. FUNSerializer *serializer = _serializer;
  196. [fetcher beginFetchWithCompletionHandler:^(NSData *_Nullable data, NSError *_Nullable error) {
  197. // If there was an HTTP error, convert it to our own error domain.
  198. if (error) {
  199. if ([error.domain isEqualToString:kGTMSessionFetcherStatusDomain]) {
  200. error = FUNErrorForResponse(error.code, data, serializer);
  201. }
  202. if ([error.domain isEqualToString:NSURLErrorDomain]) {
  203. if (error.code == NSURLErrorTimedOut) {
  204. error = FUNErrorForCode(FIRFunctionsErrorCodeDeadlineExceeded);
  205. }
  206. }
  207. } else {
  208. // If there wasn't an HTTP error, see if there was an error in the body.
  209. error = FUNErrorForResponse(200, data, serializer);
  210. }
  211. // If there was an error, report it to the user and stop.
  212. if (error) {
  213. if (completion) {
  214. completion(nil, error);
  215. }
  216. return;
  217. }
  218. id responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  219. if (error) {
  220. if (completion) {
  221. completion(nil, error);
  222. }
  223. return;
  224. }
  225. if (![responseJSON isKindOfClass:[NSDictionary class]]) {
  226. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : @"Response was not a dictionary."};
  227. error = [NSError errorWithDomain:FIRFunctionsErrorDomain
  228. code:FIRFunctionsErrorCodeInternal
  229. userInfo:userInfo];
  230. if (completion) {
  231. completion(nil, error);
  232. }
  233. return;
  234. }
  235. id dataJSON = responseJSON[@"data"];
  236. // TODO(klimt): Allow "result" instead of "data" for now, for backwards compatibility.
  237. if (!dataJSON) {
  238. dataJSON = responseJSON[@"result"];
  239. }
  240. if (!dataJSON) {
  241. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : @"Response is missing data field."};
  242. error = [NSError errorWithDomain:FIRFunctionsErrorDomain
  243. code:FIRFunctionsErrorCodeInternal
  244. userInfo:userInfo];
  245. if (completion) {
  246. completion(nil, error);
  247. }
  248. return;
  249. }
  250. id resultData = [serializer decode:dataJSON error:&error];
  251. if (error) {
  252. if (completion) {
  253. completion(nil, error);
  254. }
  255. return;
  256. }
  257. id result = [[FIRHTTPSCallableResult alloc] initWithData:resultData];
  258. if (completion) {
  259. // If there's no result field, this will return nil, which is fine.
  260. completion(result, nil);
  261. }
  262. }];
  263. }
  264. - (FIRHTTPSCallable *)HTTPSCallableWithName:(NSString *)name {
  265. return [[FIRHTTPSCallable alloc] initWithFunctions:self name:name];
  266. }
  267. @end
  268. NS_ASSUME_NONNULL_END