FIRFunctions.m 11 KB

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