FIRFunctions.m 11 KB

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