FIRIAMClearcutHttpRequestSender.m 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. /*
  2. * Copyright 2018 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 <TargetConditionals.h>
  17. #if TARGET_OS_IOS || TARGET_OS_TV || (defined(TARGET_OS_VISION) && TARGET_OS_VISION)
  18. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  19. #import "FirebaseInAppMessaging/Sources/Analytics/FIRIAMClearcutHttpRequestSender.h"
  20. #import "FirebaseInAppMessaging/Sources/Analytics/FIRIAMClearcutLogStorage.h"
  21. #import "FirebaseInAppMessaging/Sources/FIRCore+InAppMessaging.h"
  22. #import "FirebaseInAppMessaging/Sources/Private/Analytics/FIRIAMClientInfoFetcher.h"
  23. #import "FirebaseInAppMessaging/Sources/Private/Util/FIRIAMTimeFetcher.h"
  24. @interface FIRIAMClearcutHttpRequestSender ()
  25. @property(readonly, copy, nonatomic) NSString *serverHostName;
  26. @property(readwrite, nonatomic) id<FIRIAMTimeFetcher> timeFetcher;
  27. @property(readonly, copy, nonatomic) NSString *osMajorVersion;
  28. @end
  29. @implementation FIRIAMClearcutHttpRequestSender
  30. - (instancetype)initWithClearcutHost:(NSString *)serverHost
  31. usingTimeFetcher:(id<FIRIAMTimeFetcher>)timeFetcher
  32. withOSMajorVersion:(NSString *)osMajorVersion {
  33. if (self = [super init]) {
  34. _serverHostName = [serverHost copy];
  35. _timeFetcher = timeFetcher;
  36. _osMajorVersion = [osMajorVersion copy];
  37. }
  38. return self;
  39. }
  40. - (void)updateRequestBodyWithClearcutEnvelopeFields:(NSMutableDictionary *)bodyDict {
  41. bodyDict[@"client_info"] = @{
  42. @"client_type" : @15, // 15 is the enum value for IOS_FIREBASE client
  43. @"ios_client_info" : @{@"os_major_version" : self.osMajorVersion ?: @""}
  44. };
  45. bodyDict[@"log_source"] = @"FIREBASE_INAPPMESSAGING";
  46. NSTimeInterval nowInMs = [self.timeFetcher currentTimestampInSeconds] * 1000;
  47. bodyDict[@"request_time_ms"] = @((long)nowInMs);
  48. }
  49. - (NSArray<NSDictionary *> *)constructLogEventsArrayLogRecords:
  50. (NSArray<FIRIAMClearcutLogRecord *> *)logRecords {
  51. NSMutableArray<NSDictionary *> *logEvents = [[NSMutableArray alloc] init];
  52. for (id next in logRecords) {
  53. FIRIAMClearcutLogRecord *logRecord = (FIRIAMClearcutLogRecord *)next;
  54. [logEvents addObject:@{
  55. @"event_time_ms" : @((long)logRecord.eventTimestampInSeconds * 1000),
  56. @"source_extension_json" : logRecord.eventExtensionJsonString ?: @""
  57. }];
  58. }
  59. return [logEvents copy];
  60. }
  61. // @return nil if error happened in constructing the body
  62. - (NSDictionary *)constructRequestBodyWithRetryRecords:
  63. (NSArray<FIRIAMClearcutLogRecord *> *)logRecords {
  64. NSMutableDictionary *body = [[NSMutableDictionary alloc] init];
  65. [self updateRequestBodyWithClearcutEnvelopeFields:body];
  66. body[@"log_event"] = [self constructLogEventsArrayLogRecords:logRecords];
  67. return [body copy];
  68. }
  69. // a helper method for dealing with the response received from
  70. // executing NSURLSessionDataTask. Triggers the completion callback accordingly
  71. - (void)handleClearcutAPICallResponseWithData:(NSData *)data
  72. response:(NSURLResponse *)response
  73. error:(NSError *)error
  74. completion:
  75. (nonnull void (^)(BOOL success,
  76. BOOL shouldRetryLogs,
  77. int64_t waitTimeInMills))completion {
  78. if (error) {
  79. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM250003",
  80. @"Internal error: encountered error in uploading clearcut message"
  81. ":%@",
  82. error);
  83. completion(NO, YES, 0);
  84. return;
  85. }
  86. if (![response isKindOfClass:[NSHTTPURLResponse class]]) {
  87. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM250008",
  88. @"Received non http response from sending "
  89. "clearcut requests %@",
  90. response);
  91. completion(NO, YES, 0);
  92. return;
  93. }
  94. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  95. if (httpResponse.statusCode == 200) {
  96. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM250004",
  97. @"Sending clearcut logging request was successful");
  98. NSError *errorJson = nil;
  99. NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data
  100. options:kNilOptions
  101. error:&errorJson];
  102. int64_t waitTimeFromClearcutServer = 0;
  103. if (!errorJson && responseDict[@"next_request_wait_millis"]) {
  104. waitTimeFromClearcutServer = [responseDict[@"next_request_wait_millis"] longLongValue];
  105. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM250007",
  106. @"Wait time from clearcut server response is %d seconds",
  107. (int)waitTimeFromClearcutServer / 1000);
  108. }
  109. completion(YES, NO, waitTimeFromClearcutServer);
  110. } else if (httpResponse.statusCode == 400) {
  111. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM250012",
  112. @"Seeing 400 status code in response and we are discarding this log"
  113. @"record");
  114. // 400 means bad request data and it won't be successful with retries. So
  115. // we give up on these log records
  116. completion(NO, NO, 0);
  117. } else {
  118. // May need to handle 401 errors if we do authentication in the future
  119. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM250005",
  120. @"Other http status code seen in clearcut request response %d",
  121. (int)httpResponse.statusCode);
  122. // can be retried
  123. completion(NO, YES, 0);
  124. }
  125. }
  126. - (void)sendClearcutHttpRequestForLogs:(NSArray<FIRIAMClearcutLogRecord *> *)logs
  127. withCompletion:(nonnull void (^)(BOOL success,
  128. BOOL shouldRetryLogs,
  129. int64_t waitTimeInMills))completion {
  130. NSDictionary *requestBody = [self constructRequestBodyWithRetryRecords:logs];
  131. if (!requestBody) {
  132. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM250014",
  133. @"Not able to construct request body for clearcut request, giving up");
  134. completion(NO, NO, 0);
  135. } else {
  136. // sending the log via a http request
  137. NSURLSession *URLSession = [NSURLSession sharedSession];
  138. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  139. [request setHTTPMethod:@"POST"];
  140. [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  141. [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
  142. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM250001",
  143. @"Request body dictionary is %@ for clearcut logging request", requestBody);
  144. NSError *error;
  145. NSData *requestBodyData = [NSJSONSerialization dataWithJSONObject:requestBody
  146. options:0
  147. error:&error];
  148. if (error) {
  149. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM250011",
  150. @"Error in creating request body json for clearcut requests:%@", error);
  151. completion(NO, NO, 0);
  152. return;
  153. }
  154. NSString *requestURLString =
  155. [NSString stringWithFormat:@"https://%@/log?format=json_proto", self.serverHostName];
  156. [request setURL:[NSURL URLWithString:requestURLString]];
  157. [request setHTTPBody:requestBodyData];
  158. NSURLSessionDataTask *clearCutLogDataTask =
  159. [URLSession dataTaskWithRequest:request
  160. completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  161. [self handleClearcutAPICallResponseWithData:data
  162. response:response
  163. error:error
  164. completion:completion];
  165. }];
  166. if (clearCutLogDataTask == nil) {
  167. NSString *errorDesc = @"Internal error: NSURLSessionDataTask failed to be created due to "
  168. "possibly incorrect parameters";
  169. FIRLogWarning(kFIRLoggerInAppMessaging, @"I-IAM250005", @"%@", errorDesc);
  170. completion(NO, NO, 0);
  171. } else {
  172. [clearCutLogDataTask resume];
  173. FIRLogDebug(kFIRLoggerInAppMessaging, @"I-IAM250002",
  174. @"Making a restful api for sending clearcut logging data with "
  175. "a NSURLSessionDataTask request as %@",
  176. clearCutLogDataTask.currentRequest);
  177. }
  178. }
  179. }
  180. @end
  181. #endif // TARGET_OS_IOS || TARGET_OS_TV || (defined(TARGET_OS_VISION) && TARGET_OS_VISION)