FPRNanoPbUtils.m 22 KB

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