FPRNanoPbUtils.m 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 =
  165. calloc(perfSessions[perfSessionIndex].session_verbosity_count,
  166. sizeof(firebase_perf_v1_SessionVerbosity));
  167. perfSessions[perfSessionIndex].session_verbosity[0] =
  168. firebase_perf_v1_SessionVerbosity_GAUGES_AND_SYSTEM_EVENTS;
  169. perfSessions[perfSessionIndex].session_verbosity_count = 1;
  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 subtraces
  233. traceMetric.subtraces_count = (pb_size_t)[trace.stages count];
  234. firebase_perf_v1_TraceMetric *subtraces =
  235. calloc(traceMetric.subtraces_count, sizeof(firebase_perf_v1_TraceMetric));
  236. __block NSUInteger subtraceIndex = 0;
  237. [trace.stages
  238. enumerateObjectsUsingBlock:^(FIRTrace *_Nonnull stage, NSUInteger idx, BOOL *_Nonnull stop) {
  239. subtraces[subtraceIndex] = FPRGetTraceMetric(stage);
  240. subtraceIndex++;
  241. }];
  242. traceMetric.subtraces = subtraces;
  243. // Filling custom attributes
  244. NSDictionary<NSString *, NSString *> *attributes = [trace.attributes mutableCopy];
  245. traceMetric.custom_attributes_count = (pb_size_t)attributes.count;
  246. traceMetric.custom_attributes =
  247. (firebase_perf_v1_TraceMetric_CustomAttributesEntry *)FPREncodeStringToStringMap(attributes);
  248. // Filling session details
  249. NSArray<FPRSessionDetails *> *orderedSessions = FPRMakeFirstSessionVerbose(trace.sessions);
  250. traceMetric.perf_sessions_count = (pb_size_t)[orderedSessions count];
  251. traceMetric.perf_sessions =
  252. FPREncodePerfSessions(orderedSessions, traceMetric.perf_sessions_count);
  253. return traceMetric;
  254. }
  255. firebase_perf_v1_NetworkRequestMetric FPRGetNetworkRequestMetric(FPRNetworkTrace *trace) {
  256. firebase_perf_v1_NetworkRequestMetric networkMetric =
  257. firebase_perf_v1_NetworkRequestMetric_init_default;
  258. networkMetric.url = FPREncodeString(trace.trimmedURLString);
  259. networkMetric.http_method = FPRHTTPMethodForString(trace.URLRequest.HTTPMethod);
  260. networkMetric.has_http_method = true;
  261. // Convert the start time from seconds to microseconds.
  262. networkMetric.client_start_time_us = trace.startTimeSinceEpoch * USEC_PER_SEC;
  263. networkMetric.has_client_start_time_us = true;
  264. networkMetric.request_payload_bytes = trace.requestSize;
  265. networkMetric.has_request_payload_bytes = true;
  266. networkMetric.response_payload_bytes = trace.responseSize;
  267. networkMetric.has_response_payload_bytes = true;
  268. networkMetric.http_response_code = trace.responseCode;
  269. networkMetric.has_http_response_code = true;
  270. networkMetric.response_content_type = FPREncodeString(trace.responseContentType);
  271. if (trace.responseError) {
  272. networkMetric.network_client_error_reason =
  273. firebase_perf_v1_NetworkRequestMetric_NetworkClientErrorReason_GENERIC_CLIENT_ERROR;
  274. networkMetric.has_network_client_error_reason = true;
  275. }
  276. NSTimeInterval requestTimeUs =
  277. USEC_PER_SEC *
  278. [trace timeIntervalBetweenCheckpointState:FPRNetworkTraceCheckpointStateInitiated
  279. andState:FPRNetworkTraceCheckpointStateRequestCompleted];
  280. if (requestTimeUs > 0) {
  281. networkMetric.time_to_request_completed_us = requestTimeUs;
  282. networkMetric.has_time_to_request_completed_us = true;
  283. }
  284. NSTimeInterval responseIntiationTimeUs =
  285. USEC_PER_SEC *
  286. [trace timeIntervalBetweenCheckpointState:FPRNetworkTraceCheckpointStateInitiated
  287. andState:FPRNetworkTraceCheckpointStateResponseReceived];
  288. if (responseIntiationTimeUs > 0) {
  289. networkMetric.time_to_response_initiated_us = responseIntiationTimeUs;
  290. networkMetric.has_time_to_response_initiated_us = true;
  291. }
  292. NSTimeInterval responseCompletedUs =
  293. USEC_PER_SEC *
  294. [trace timeIntervalBetweenCheckpointState:FPRNetworkTraceCheckpointStateInitiated
  295. andState:FPRNetworkTraceCheckpointStateResponseCompleted];
  296. if (responseCompletedUs > 0) {
  297. networkMetric.time_to_response_completed_us = responseCompletedUs;
  298. networkMetric.has_time_to_response_completed_us = true;
  299. }
  300. // Filling custom attributes
  301. NSDictionary<NSString *, NSString *> *attributes = [trace.attributes mutableCopy];
  302. networkMetric.custom_attributes_count = (pb_size_t)attributes.count;
  303. networkMetric.custom_attributes =
  304. (firebase_perf_v1_NetworkRequestMetric_CustomAttributesEntry *)FPREncodeStringToStringMap(
  305. attributes);
  306. // Filling session details
  307. NSArray<FPRSessionDetails *> *orderedSessions = FPRMakeFirstSessionVerbose(trace.sessions);
  308. networkMetric.perf_sessions_count = (pb_size_t)[orderedSessions count];
  309. networkMetric.perf_sessions =
  310. FPREncodePerfSessions(orderedSessions, networkMetric.perf_sessions_count);
  311. return networkMetric;
  312. }
  313. firebase_perf_v1_GaugeMetric FPRGetGaugeMetric(NSArray *gaugeData, NSString *sessionId) {
  314. firebase_perf_v1_GaugeMetric gaugeMetric = firebase_perf_v1_GaugeMetric_init_default;
  315. gaugeMetric.session_id = FPREncodeString(sessionId);
  316. __block NSInteger cpuReadingsCount = 0;
  317. __block NSInteger memoryReadingsCount = 0;
  318. firebase_perf_v1_CpuMetricReading *cpuReadings =
  319. calloc([gaugeData count], sizeof(firebase_perf_v1_CpuMetricReading));
  320. firebase_perf_v1_IosMemoryReading *memoryReadings =
  321. calloc([gaugeData count], sizeof(firebase_perf_v1_IosMemoryReading));
  322. [gaugeData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  323. if ([obj isKindOfClass:[FPRCPUGaugeData class]]) {
  324. FPRCPUGaugeData *gaugeData = (FPRCPUGaugeData *)obj;
  325. cpuReadings[cpuReadingsCount].client_time_us =
  326. gaugeData.collectionTime.timeIntervalSince1970 * USEC_PER_SEC;
  327. cpuReadings[cpuReadingsCount].has_client_time_us = true;
  328. cpuReadings[cpuReadingsCount].system_time_us = gaugeData.systemTime;
  329. cpuReadings[cpuReadingsCount].has_system_time_us = true;
  330. cpuReadings[cpuReadingsCount].user_time_us = gaugeData.userTime;
  331. cpuReadings[cpuReadingsCount].has_user_time_us = true;
  332. cpuReadingsCount++;
  333. }
  334. if ([obj isKindOfClass:[FPRMemoryGaugeData class]]) {
  335. FPRMemoryGaugeData *gaugeData = (FPRMemoryGaugeData *)obj;
  336. memoryReadings[memoryReadingsCount].client_time_us =
  337. gaugeData.collectionTime.timeIntervalSince1970 * USEC_PER_SEC;
  338. memoryReadings[memoryReadingsCount].has_client_time_us = true;
  339. memoryReadings[memoryReadingsCount].used_app_heap_memory_kb =
  340. (int32_t)BYTES_TO_KB(gaugeData.heapUsed);
  341. memoryReadings[memoryReadingsCount].has_used_app_heap_memory_kb = true;
  342. memoryReadings[memoryReadingsCount].free_app_heap_memory_kb =
  343. (int32_t)BYTES_TO_KB(gaugeData.heapAvailable);
  344. memoryReadings[memoryReadingsCount].has_free_app_heap_memory_kb = true;
  345. memoryReadingsCount++;
  346. }
  347. }];
  348. cpuReadings = realloc(cpuReadings, cpuReadingsCount * sizeof(firebase_perf_v1_CpuMetricReading));
  349. memoryReadings =
  350. realloc(memoryReadings, memoryReadingsCount * sizeof(firebase_perf_v1_IosMemoryReading));
  351. gaugeMetric.cpu_metric_readings = cpuReadings;
  352. gaugeMetric.cpu_metric_readings_count = (pb_size_t)cpuReadingsCount;
  353. gaugeMetric.ios_memory_readings = memoryReadings;
  354. gaugeMetric.ios_memory_readings_count = (pb_size_t)memoryReadingsCount;
  355. return gaugeMetric;
  356. }
  357. firebase_perf_v1_ApplicationProcessState FPRApplicationProcessState(FPRTraceState state) {
  358. firebase_perf_v1_ApplicationProcessState processState =
  359. firebase_perf_v1_ApplicationProcessState_APPLICATION_PROCESS_STATE_UNKNOWN;
  360. switch (state) {
  361. case FPRTraceStateForegroundOnly:
  362. processState = firebase_perf_v1_ApplicationProcessState_FOREGROUND;
  363. break;
  364. case FPRTraceStateBackgroundOnly:
  365. processState = firebase_perf_v1_ApplicationProcessState_BACKGROUND;
  366. break;
  367. case FPRTraceStateBackgroundAndForeground:
  368. processState = firebase_perf_v1_ApplicationProcessState_FOREGROUND_BACKGROUND;
  369. break;
  370. default:
  371. break;
  372. }
  373. return processState;
  374. }
  375. #ifdef TARGET_HAS_MOBILE_CONNECTIVITY
  376. CTTelephonyNetworkInfo *FPRNetworkInfo() {
  377. static CTTelephonyNetworkInfo *networkInfo;
  378. static dispatch_once_t onceToken;
  379. dispatch_once(&onceToken, ^{
  380. networkInfo = [[CTTelephonyNetworkInfo alloc] init];
  381. });
  382. return networkInfo;
  383. }
  384. #endif
  385. /** Reorders the list of sessions to make sure the first session is verbose if at least one session
  386. * in the list is verbose.
  387. * @return Ordered list of sessions.
  388. */
  389. NSArray<FPRSessionDetails *> *FPRMakeFirstSessionVerbose(NSArray<FPRSessionDetails *> *sessions) {
  390. NSMutableArray<FPRSessionDetails *> *orderedSessions =
  391. [[NSMutableArray<FPRSessionDetails *> alloc] initWithArray:sessions];
  392. NSInteger firstVerboseSessionIndex = -1;
  393. for (int i = 0; i < [sessions count]; i++) {
  394. if ([sessions[i] isVerbose]) {
  395. firstVerboseSessionIndex = i;
  396. break;
  397. }
  398. }
  399. if (firstVerboseSessionIndex > 0) {
  400. FPRSessionDetails *verboseSession = orderedSessions[firstVerboseSessionIndex];
  401. [orderedSessions removeObjectAtIndex:firstVerboseSessionIndex];
  402. [orderedSessions insertObject:verboseSession atIndex:0];
  403. }
  404. return [orderedSessions copy];
  405. }
  406. #pragma mark - Nanopb struct fields populating helper methods
  407. void FPRSetApplicationInfo(firebase_perf_v1_PerfMetric *perfMetric,
  408. firebase_perf_v1_ApplicationInfo appInfo) {
  409. perfMetric->application_info = appInfo;
  410. perfMetric->has_application_info = true;
  411. }
  412. void FPRSetTraceMetric(firebase_perf_v1_PerfMetric *perfMetric,
  413. firebase_perf_v1_TraceMetric traceMetric) {
  414. perfMetric->trace_metric = traceMetric;
  415. perfMetric->has_trace_metric = true;
  416. }
  417. void FPRSetNetworkRequestMetric(firebase_perf_v1_PerfMetric *perfMetric,
  418. firebase_perf_v1_NetworkRequestMetric networkMetric) {
  419. perfMetric->network_request_metric = networkMetric;
  420. perfMetric->has_network_request_metric = true;
  421. }
  422. void FPRSetGaugeMetric(firebase_perf_v1_PerfMetric *perfMetric,
  423. firebase_perf_v1_GaugeMetric gaugeMetric) {
  424. perfMetric->gauge_metric = gaugeMetric;
  425. perfMetric->has_gauge_metric = true;
  426. }
  427. void FPRSetApplicationProcessState(firebase_perf_v1_PerfMetric *perfMetric,
  428. firebase_perf_v1_ApplicationProcessState state) {
  429. perfMetric->application_info.application_process_state = state;
  430. perfMetric->application_info.has_application_process_state = true;
  431. }