FPRNanoPbUtils.m 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. // Copyright 2021 Google LLC
  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 "FirebasePerformance/Sources/FPRNanoPbUtils.h"
  15. #ifdef TARGET_HAS_MOBILE_CONNECTIVITY
  16. #import <CoreTelephony/CTCarrier.h>
  17. #import <CoreTelephony/CTTelephonyNetworkInfo.h>
  18. #endif
  19. #import <SystemConfiguration/SystemConfiguration.h>
  20. #import "FirebasePerformance/Sources/Common/FPRConstants.h"
  21. #import "FirebasePerformance/Sources/FIRPerformance+Internal.h"
  22. #import "FirebasePerformance/Sources/FPRDataUtils.h"
  23. #import "FirebasePerformance/Sources/Public/FirebasePerformance/FIRPerformance.h"
  24. #import "FirebasePerformance/Sources/Timer/FIRTrace+Internal.h"
  25. #import "FirebasePerformance/Sources/Timer/FIRTrace+Private.h"
  26. #import "FirebasePerformance/Sources/Gauges/CPU/FPRCPUGaugeData.h"
  27. #import "FirebasePerformance/Sources/Gauges/Memory/FPRMemoryGaugeData.h"
  28. #define BYTES_TO_KB(x) (x / 1024)
  29. static firebase_perf_v1_NetworkRequestMetric_HttpMethod FPRHTTPMethodForString(
  30. NSString *methodString);
  31. static firebase_perf_v1_NetworkConnectionInfo_NetworkType FPRNetworkConnectionInfoNetworkType(void);
  32. #ifdef TARGET_HAS_MOBILE_CONNECTIVITY
  33. static firebase_perf_v1_NetworkConnectionInfo_MobileSubtype FPRCellularNetworkType(void);
  34. #endif
  35. NSArray<FPRSessionDetails *> *FPRMakeFirstSessionVerbose(NSArray<FPRSessionDetails *> *sessions);
  36. #pragma mark - Nanopb creation utilities
  37. /** Converts the network method string to a value defined in the enum
  38. * firebase_perf_v1_NetworkRequestMetric_HttpMethod.
  39. * @return Enum value of the method string. If there is no mapping value defined for the method
  40. * firebase_perf_v1_NetworkRequestMetric_HttpMethod_HTTP_METHOD_UNKNOWN is returned.
  41. */
  42. static firebase_perf_v1_NetworkRequestMetric_HttpMethod FPRHTTPMethodForString(
  43. NSString *methodString) {
  44. static NSDictionary<NSString *, NSNumber *> *HTTPToFPRNetworkTraceMethod;
  45. static dispatch_once_t onceToken = 0;
  46. dispatch_once(&onceToken, ^{
  47. HTTPToFPRNetworkTraceMethod = @{
  48. @"GET" : @(firebase_perf_v1_NetworkRequestMetric_HttpMethod_GET),
  49. @"POST" : @(firebase_perf_v1_NetworkRequestMetric_HttpMethod_POST),
  50. @"PUT" : @(firebase_perf_v1_NetworkRequestMetric_HttpMethod_PUT),
  51. @"DELETE" : @(firebase_perf_v1_NetworkRequestMetric_HttpMethod_DELETE),
  52. @"HEAD" : @(firebase_perf_v1_NetworkRequestMetric_HttpMethod_HEAD),
  53. @"PATCH" : @(firebase_perf_v1_NetworkRequestMetric_HttpMethod_PATCH),
  54. @"OPTIONS" : @(firebase_perf_v1_NetworkRequestMetric_HttpMethod_OPTIONS),
  55. @"TRACE" : @(firebase_perf_v1_NetworkRequestMetric_HttpMethod_TRACE),
  56. @"CONNECT" : @(firebase_perf_v1_NetworkRequestMetric_HttpMethod_CONNECT),
  57. };
  58. });
  59. NSNumber *HTTPMethod = HTTPToFPRNetworkTraceMethod[methodString];
  60. if (HTTPMethod == nil) {
  61. return firebase_perf_v1_NetworkRequestMetric_HttpMethod_HTTP_METHOD_UNKNOWN;
  62. }
  63. return HTTPMethod.intValue;
  64. }
  65. /** Get the current network connection type in firebase_perf_v1_NetworkConnectionInfo_NetworkType
  66. * format.
  67. * @return Current network connection type.
  68. */
  69. static firebase_perf_v1_NetworkConnectionInfo_NetworkType FPRNetworkConnectionInfoNetworkType() {
  70. firebase_perf_v1_NetworkConnectionInfo_NetworkType networkType =
  71. firebase_perf_v1_NetworkConnectionInfo_NetworkType_NONE;
  72. static SCNetworkReachabilityRef reachabilityRef = 0;
  73. static dispatch_once_t onceToken;
  74. dispatch_once(&onceToken, ^{
  75. reachabilityRef = SCNetworkReachabilityCreateWithName(kCFAllocatorSystemDefault, "google.com");
  76. });
  77. SCNetworkReachabilityFlags reachabilityFlags = 0;
  78. SCNetworkReachabilityGetFlags(reachabilityRef, &reachabilityFlags);
  79. // Parse the network flags to set the network type.
  80. if (reachabilityFlags & kSCNetworkReachabilityFlagsReachable) {
  81. if (reachabilityFlags & kSCNetworkReachabilityFlagsIsWWAN) {
  82. networkType = firebase_perf_v1_NetworkConnectionInfo_NetworkType_MOBILE;
  83. } else {
  84. networkType = firebase_perf_v1_NetworkConnectionInfo_NetworkType_WIFI;
  85. }
  86. }
  87. return networkType;
  88. }
  89. #ifdef TARGET_HAS_MOBILE_CONNECTIVITY
  90. /** Get the current cellular network connection type in
  91. * firebase_perf_v1_NetworkConnectionInfo_MobileSubtype format.
  92. * @return Current cellular network connection type.
  93. */
  94. static firebase_perf_v1_NetworkConnectionInfo_MobileSubtype FPRCellularNetworkType() {
  95. static NSDictionary<NSString *, NSNumber *> *cellularNetworkToMobileSubtype;
  96. static dispatch_once_t onceToken = 0;
  97. dispatch_once(&onceToken, ^{
  98. cellularNetworkToMobileSubtype = @{
  99. CTRadioAccessTechnologyGPRS : @(firebase_perf_v1_NetworkConnectionInfo_MobileSubtype_GPRS),
  100. CTRadioAccessTechnologyEdge : @(firebase_perf_v1_NetworkConnectionInfo_MobileSubtype_EDGE),
  101. CTRadioAccessTechnologyWCDMA : @(firebase_perf_v1_NetworkConnectionInfo_MobileSubtype_CDMA),
  102. CTRadioAccessTechnologyHSDPA : @(firebase_perf_v1_NetworkConnectionInfo_MobileSubtype_HSDPA),
  103. CTRadioAccessTechnologyHSUPA : @(firebase_perf_v1_NetworkConnectionInfo_MobileSubtype_HSUPA),
  104. CTRadioAccessTechnologyCDMA1x : @(firebase_perf_v1_NetworkConnectionInfo_MobileSubtype_CDMA),
  105. CTRadioAccessTechnologyCDMAEVDORev0 :
  106. @(firebase_perf_v1_NetworkConnectionInfo_MobileSubtype_EVDO_0),
  107. CTRadioAccessTechnologyCDMAEVDORevA :
  108. @(firebase_perf_v1_NetworkConnectionInfo_MobileSubtype_EVDO_A),
  109. CTRadioAccessTechnologyCDMAEVDORevB :
  110. @(firebase_perf_v1_NetworkConnectionInfo_MobileSubtype_EVDO_B),
  111. CTRadioAccessTechnologyeHRPD : @(firebase_perf_v1_NetworkConnectionInfo_MobileSubtype_EHRPD),
  112. CTRadioAccessTechnologyLTE : @(firebase_perf_v1_NetworkConnectionInfo_MobileSubtype_LTE)
  113. };
  114. });
  115. NSString *networkString = FPRNetworkInfo().currentRadioAccessTechnology;
  116. NSNumber *cellularNetworkType = cellularNetworkToMobileSubtype[networkString];
  117. return cellularNetworkType.intValue;
  118. }
  119. #endif
  120. #pragma mark - Nanopb decode and encode helper methods
  121. pb_bytes_array_t *FPREncodeData(NSData *data) {
  122. pb_bytes_array_t *pbBytesArray = calloc(1, PB_BYTES_ARRAY_T_ALLOCSIZE(data.length));
  123. if (pbBytesArray != NULL) {
  124. [data getBytes:pbBytesArray->bytes length:data.length];
  125. pbBytesArray->size = (pb_size_t)data.length;
  126. }
  127. return pbBytesArray;
  128. }
  129. pb_bytes_array_t *FPREncodeString(NSString *string) {
  130. NSData *stringBytes = [string dataUsingEncoding:NSUTF8StringEncoding];
  131. return FPREncodeData(stringBytes);
  132. }
  133. StringToStringMap *_Nullable FPREncodeStringToStringMap(NSDictionary *_Nullable dict) {
  134. StringToStringMap *map = calloc(dict.count, sizeof(StringToStringMap));
  135. __block NSUInteger index = 0;
  136. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop) {
  137. map[index].key = FPREncodeString(key);
  138. map[index].value = FPREncodeString(value);
  139. index++;
  140. }];
  141. return map;
  142. }
  143. StringToNumberMap *_Nullable FPREncodeStringToNumberMap(NSDictionary *_Nullable dict) {
  144. StringToNumberMap *map = calloc(dict.count, sizeof(StringToNumberMap));
  145. __block NSUInteger index = 0;
  146. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSNumber *value, BOOL *stop) {
  147. map[index].key = FPREncodeString(key);
  148. map[index].value = [value longLongValue];
  149. map[index].has_value = true;
  150. index++;
  151. }];
  152. return map;
  153. }
  154. firebase_perf_v1_PerfSession *FPREncodePerfSessions(NSArray<FPRSessionDetails *> *sessions,
  155. NSInteger count) {
  156. firebase_perf_v1_PerfSession *perfSessions = calloc(count, sizeof(firebase_perf_v1_PerfSession));
  157. __block NSUInteger perfSessionIndex = 0;
  158. [sessions enumerateObjectsUsingBlock:^(FPRSessionDetails *_Nonnull session, NSUInteger index,
  159. BOOL *_Nonnull stop) {
  160. perfSessions[perfSessionIndex].session_id = FPREncodeString(session.sessionId);
  161. perfSessions[perfSessionIndex].session_verbosity_count = 0;
  162. if ((session.options & FPRSessionOptionsEvents) ||
  163. (session.options & FPRSessionOptionsGauges)) {
  164. perfSessions[perfSessionIndex].session_verbosity_count = 1;
  165. perfSessions[perfSessionIndex].session_verbosity =
  166. calloc(perfSessions[perfSessionIndex].session_verbosity_count,
  167. sizeof(firebase_perf_v1_SessionVerbosity));
  168. perfSessions[perfSessionIndex].session_verbosity[0] =
  169. firebase_perf_v1_SessionVerbosity_GAUGES_AND_SYSTEM_EVENTS;
  170. }
  171. perfSessionIndex++;
  172. }];
  173. return perfSessions;
  174. }
  175. #pragma mark - Public methods
  176. firebase_perf_v1_PerfMetric FPRGetPerfMetricMessage(NSString *appID) {
  177. firebase_perf_v1_PerfMetric perfMetricMessage = firebase_perf_v1_PerfMetric_init_default;
  178. FPRSetApplicationInfo(&perfMetricMessage, FPRGetApplicationInfoMessage());
  179. perfMetricMessage.application_info.google_app_id = FPREncodeString(appID);
  180. return perfMetricMessage;
  181. }
  182. firebase_perf_v1_ApplicationInfo FPRGetApplicationInfoMessage() {
  183. firebase_perf_v1_ApplicationInfo appInfoMessage = firebase_perf_v1_ApplicationInfo_init_default;
  184. firebase_perf_v1_IosApplicationInfo iosAppInfo = firebase_perf_v1_IosApplicationInfo_init_default;
  185. NSBundle *mainBundle = [NSBundle mainBundle];
  186. iosAppInfo.bundle_short_version =
  187. FPREncodeString([mainBundle infoDictionary][@"CFBundleShortVersionString"]);
  188. iosAppInfo.sdk_version = FPREncodeString([NSString stringWithUTF8String:kFPRSDKVersion]);
  189. iosAppInfo.network_connection_info.network_type = FPRNetworkConnectionInfoNetworkType();
  190. iosAppInfo.has_network_connection_info = true;
  191. iosAppInfo.network_connection_info.has_network_type = true;
  192. #ifdef TARGET_HAS_MOBILE_CONNECTIVITY
  193. CTTelephonyNetworkInfo *networkInfo = FPRNetworkInfo();
  194. CTCarrier *provider = networkInfo.subscriberCellularProvider;
  195. NSString *mccMnc = FPRValidatedMccMnc(provider.mobileCountryCode, provider.mobileNetworkCode);
  196. if (mccMnc) {
  197. iosAppInfo.mcc_mnc = FPREncodeString(mccMnc);
  198. }
  199. if (iosAppInfo.network_connection_info.network_type ==
  200. firebase_perf_v1_NetworkConnectionInfo_NetworkType_MOBILE) {
  201. iosAppInfo.network_connection_info.mobile_subtype = FPRCellularNetworkType();
  202. iosAppInfo.network_connection_info.has_mobile_subtype = true;
  203. }
  204. #endif
  205. appInfoMessage.ios_app_info = iosAppInfo;
  206. appInfoMessage.has_ios_app_info = true;
  207. NSDictionary<NSString *, NSString *> *attributes =
  208. [[FIRPerformance sharedInstance].attributes mutableCopy];
  209. appInfoMessage.custom_attributes_count = (pb_size_t)attributes.count;
  210. appInfoMessage.custom_attributes =
  211. (firebase_perf_v1_ApplicationInfo_CustomAttributesEntry *)FPREncodeStringToStringMap(
  212. attributes);
  213. return appInfoMessage;
  214. }
  215. firebase_perf_v1_TraceMetric FPRGetTraceMetric(FIRTrace *trace) {
  216. firebase_perf_v1_TraceMetric traceMetric = firebase_perf_v1_TraceMetric_init_default;
  217. traceMetric.name = FPREncodeString(trace.name);
  218. // Set if the trace is an internally created trace.
  219. traceMetric.is_auto = trace.isInternal;
  220. traceMetric.has_is_auto = true;
  221. // Convert the trace duration from seconds to microseconds.
  222. traceMetric.duration_us = trace.totalTraceTimeInterval * USEC_PER_SEC;
  223. traceMetric.has_duration_us = true;
  224. // Convert the start time from seconds to microseconds.
  225. traceMetric.client_start_time_us = trace.startTimeSinceEpoch * USEC_PER_SEC;
  226. traceMetric.has_client_start_time_us = true;
  227. // Filling counters
  228. NSDictionary<NSString *, NSNumber *> *counters = trace.counters;
  229. traceMetric.counters_count = (pb_size_t)counters.count;
  230. traceMetric.counters =
  231. (firebase_perf_v1_TraceMetric_CountersEntry *)FPREncodeStringToNumberMap(counters);
  232. // Filling custom attributes
  233. NSDictionary<NSString *, NSString *> *attributes = [trace.attributes mutableCopy];
  234. traceMetric.custom_attributes_count = (pb_size_t)attributes.count;
  235. traceMetric.custom_attributes =
  236. (firebase_perf_v1_TraceMetric_CustomAttributesEntry *)FPREncodeStringToStringMap(attributes);
  237. // Filling session details
  238. NSArray<FPRSessionDetails *> *orderedSessions = FPRMakeFirstSessionVerbose(trace.sessions);
  239. traceMetric.perf_sessions_count = (pb_size_t)[orderedSessions count];
  240. traceMetric.perf_sessions =
  241. FPREncodePerfSessions(orderedSessions, traceMetric.perf_sessions_count);
  242. return traceMetric;
  243. }
  244. firebase_perf_v1_NetworkRequestMetric FPRGetNetworkRequestMetric(FPRNetworkTrace *trace) {
  245. firebase_perf_v1_NetworkRequestMetric networkMetric =
  246. firebase_perf_v1_NetworkRequestMetric_init_default;
  247. networkMetric.url = FPREncodeString(trace.trimmedURLString);
  248. networkMetric.http_method = FPRHTTPMethodForString(trace.URLRequest.HTTPMethod);
  249. networkMetric.has_http_method = true;
  250. // Convert the start time from seconds to microseconds.
  251. networkMetric.client_start_time_us = trace.startTimeSinceEpoch * USEC_PER_SEC;
  252. networkMetric.has_client_start_time_us = true;
  253. networkMetric.request_payload_bytes = trace.requestSize;
  254. networkMetric.has_request_payload_bytes = true;
  255. networkMetric.response_payload_bytes = trace.responseSize;
  256. networkMetric.has_response_payload_bytes = true;
  257. networkMetric.http_response_code = trace.responseCode;
  258. networkMetric.has_http_response_code = true;
  259. networkMetric.response_content_type = FPREncodeString(trace.responseContentType);
  260. if (trace.responseError) {
  261. networkMetric.network_client_error_reason =
  262. firebase_perf_v1_NetworkRequestMetric_NetworkClientErrorReason_GENERIC_CLIENT_ERROR;
  263. networkMetric.has_network_client_error_reason = true;
  264. }
  265. NSTimeInterval requestTimeUs =
  266. USEC_PER_SEC *
  267. [trace timeIntervalBetweenCheckpointState:FPRNetworkTraceCheckpointStateInitiated
  268. andState:FPRNetworkTraceCheckpointStateRequestCompleted];
  269. if (requestTimeUs > 0) {
  270. networkMetric.time_to_request_completed_us = requestTimeUs;
  271. networkMetric.has_time_to_request_completed_us = true;
  272. }
  273. NSTimeInterval responseIntiationTimeUs =
  274. USEC_PER_SEC *
  275. [trace timeIntervalBetweenCheckpointState:FPRNetworkTraceCheckpointStateInitiated
  276. andState:FPRNetworkTraceCheckpointStateResponseReceived];
  277. if (responseIntiationTimeUs > 0) {
  278. networkMetric.time_to_response_initiated_us = responseIntiationTimeUs;
  279. networkMetric.has_time_to_response_initiated_us = true;
  280. }
  281. NSTimeInterval responseCompletedUs =
  282. USEC_PER_SEC *
  283. [trace timeIntervalBetweenCheckpointState:FPRNetworkTraceCheckpointStateInitiated
  284. andState:FPRNetworkTraceCheckpointStateResponseCompleted];
  285. if (responseCompletedUs > 0) {
  286. networkMetric.time_to_response_completed_us = responseCompletedUs;
  287. networkMetric.has_time_to_response_completed_us = true;
  288. }
  289. // Filling custom attributes
  290. NSDictionary<NSString *, NSString *> *attributes = [trace.attributes mutableCopy];
  291. networkMetric.custom_attributes_count = (pb_size_t)attributes.count;
  292. networkMetric.custom_attributes =
  293. (firebase_perf_v1_NetworkRequestMetric_CustomAttributesEntry *)FPREncodeStringToStringMap(
  294. attributes);
  295. // Filling session details
  296. NSArray<FPRSessionDetails *> *orderedSessions = FPRMakeFirstSessionVerbose(trace.sessions);
  297. networkMetric.perf_sessions_count = (pb_size_t)[orderedSessions count];
  298. networkMetric.perf_sessions =
  299. FPREncodePerfSessions(orderedSessions, networkMetric.perf_sessions_count);
  300. return networkMetric;
  301. }
  302. firebase_perf_v1_GaugeMetric FPRGetGaugeMetric(NSArray *gaugeData, NSString *sessionId) {
  303. firebase_perf_v1_GaugeMetric gaugeMetric = firebase_perf_v1_GaugeMetric_init_default;
  304. gaugeMetric.session_id = FPREncodeString(sessionId);
  305. __block NSInteger cpuReadingsCount = 0;
  306. __block NSInteger memoryReadingsCount = 0;
  307. firebase_perf_v1_CpuMetricReading *cpuReadings =
  308. calloc([gaugeData count], sizeof(firebase_perf_v1_CpuMetricReading));
  309. firebase_perf_v1_IosMemoryReading *memoryReadings =
  310. calloc([gaugeData count], sizeof(firebase_perf_v1_IosMemoryReading));
  311. [gaugeData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  312. if ([obj isKindOfClass:[FPRCPUGaugeData class]]) {
  313. FPRCPUGaugeData *gaugeData = (FPRCPUGaugeData *)obj;
  314. cpuReadings[cpuReadingsCount].client_time_us =
  315. gaugeData.collectionTime.timeIntervalSince1970 * USEC_PER_SEC;
  316. cpuReadings[cpuReadingsCount].has_client_time_us = true;
  317. cpuReadings[cpuReadingsCount].system_time_us = gaugeData.systemTime;
  318. cpuReadings[cpuReadingsCount].has_system_time_us = true;
  319. cpuReadings[cpuReadingsCount].user_time_us = gaugeData.userTime;
  320. cpuReadings[cpuReadingsCount].has_user_time_us = true;
  321. cpuReadingsCount++;
  322. }
  323. if ([obj isKindOfClass:[FPRMemoryGaugeData class]]) {
  324. FPRMemoryGaugeData *gaugeData = (FPRMemoryGaugeData *)obj;
  325. memoryReadings[memoryReadingsCount].client_time_us =
  326. gaugeData.collectionTime.timeIntervalSince1970 * USEC_PER_SEC;
  327. memoryReadings[memoryReadingsCount].has_client_time_us = true;
  328. memoryReadings[memoryReadingsCount].used_app_heap_memory_kb =
  329. (int32_t)BYTES_TO_KB(gaugeData.heapUsed);
  330. memoryReadings[memoryReadingsCount].has_used_app_heap_memory_kb = true;
  331. memoryReadings[memoryReadingsCount].free_app_heap_memory_kb =
  332. (int32_t)BYTES_TO_KB(gaugeData.heapAvailable);
  333. memoryReadings[memoryReadingsCount].has_free_app_heap_memory_kb = true;
  334. memoryReadingsCount++;
  335. }
  336. }];
  337. cpuReadings = realloc(cpuReadings, cpuReadingsCount * sizeof(firebase_perf_v1_CpuMetricReading));
  338. memoryReadings =
  339. realloc(memoryReadings, memoryReadingsCount * sizeof(firebase_perf_v1_IosMemoryReading));
  340. gaugeMetric.cpu_metric_readings = cpuReadings;
  341. gaugeMetric.cpu_metric_readings_count = (pb_size_t)cpuReadingsCount;
  342. gaugeMetric.ios_memory_readings = memoryReadings;
  343. gaugeMetric.ios_memory_readings_count = (pb_size_t)memoryReadingsCount;
  344. return gaugeMetric;
  345. }
  346. firebase_perf_v1_ApplicationProcessState FPRApplicationProcessState(FPRTraceState state) {
  347. firebase_perf_v1_ApplicationProcessState processState =
  348. firebase_perf_v1_ApplicationProcessState_APPLICATION_PROCESS_STATE_UNKNOWN;
  349. switch (state) {
  350. case FPRTraceStateForegroundOnly:
  351. processState = firebase_perf_v1_ApplicationProcessState_FOREGROUND;
  352. break;
  353. case FPRTraceStateBackgroundOnly:
  354. processState = firebase_perf_v1_ApplicationProcessState_BACKGROUND;
  355. break;
  356. case FPRTraceStateBackgroundAndForeground:
  357. processState = firebase_perf_v1_ApplicationProcessState_FOREGROUND_BACKGROUND;
  358. break;
  359. default:
  360. break;
  361. }
  362. return processState;
  363. }
  364. #ifdef TARGET_HAS_MOBILE_CONNECTIVITY
  365. CTTelephonyNetworkInfo *FPRNetworkInfo() {
  366. static CTTelephonyNetworkInfo *networkInfo;
  367. static dispatch_once_t onceToken;
  368. dispatch_once(&onceToken, ^{
  369. networkInfo = [[CTTelephonyNetworkInfo alloc] init];
  370. });
  371. return networkInfo;
  372. }
  373. #endif
  374. /** Reorders the list of sessions to make sure the first session is verbose if at least one session
  375. * in the list is verbose.
  376. * @return Ordered list of sessions.
  377. */
  378. NSArray<FPRSessionDetails *> *FPRMakeFirstSessionVerbose(NSArray<FPRSessionDetails *> *sessions) {
  379. NSMutableArray<FPRSessionDetails *> *orderedSessions =
  380. [[NSMutableArray<FPRSessionDetails *> alloc] initWithArray:sessions];
  381. NSInteger firstVerboseSessionIndex = -1;
  382. for (int i = 0; i < [sessions count]; i++) {
  383. if ([sessions[i] isVerbose]) {
  384. firstVerboseSessionIndex = i;
  385. break;
  386. }
  387. }
  388. if (firstVerboseSessionIndex > 0) {
  389. FPRSessionDetails *verboseSession = orderedSessions[firstVerboseSessionIndex];
  390. [orderedSessions removeObjectAtIndex:firstVerboseSessionIndex];
  391. [orderedSessions insertObject:verboseSession atIndex:0];
  392. }
  393. return [orderedSessions copy];
  394. }
  395. #pragma mark - Nanopb struct fields populating helper methods
  396. void FPRSetApplicationInfo(firebase_perf_v1_PerfMetric *perfMetric,
  397. firebase_perf_v1_ApplicationInfo appInfo) {
  398. perfMetric->application_info = appInfo;
  399. perfMetric->has_application_info = true;
  400. }
  401. void FPRSetTraceMetric(firebase_perf_v1_PerfMetric *perfMetric,
  402. firebase_perf_v1_TraceMetric traceMetric) {
  403. perfMetric->trace_metric = traceMetric;
  404. perfMetric->has_trace_metric = true;
  405. }
  406. void FPRSetNetworkRequestMetric(firebase_perf_v1_PerfMetric *perfMetric,
  407. firebase_perf_v1_NetworkRequestMetric networkMetric) {
  408. perfMetric->network_request_metric = networkMetric;
  409. perfMetric->has_network_request_metric = true;
  410. }
  411. void FPRSetGaugeMetric(firebase_perf_v1_PerfMetric *perfMetric,
  412. firebase_perf_v1_GaugeMetric gaugeMetric) {
  413. perfMetric->gauge_metric = gaugeMetric;
  414. perfMetric->has_gauge_metric = true;
  415. }
  416. void FPRSetApplicationProcessState(firebase_perf_v1_PerfMetric *perfMetric,
  417. firebase_perf_v1_ApplicationProcessState state) {
  418. perfMetric->application_info.application_process_state = state;
  419. perfMetric->application_info.has_application_process_state = true;
  420. }