FPRNetworkTrace.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. // Copyright 2020 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/Instrumentation/FPRNetworkTrace.h"
  15. #import "FirebasePerformance/Sources/Instrumentation/FPRNetworkTrace+Private.h"
  16. #import "FirebasePerformance/Sources/AppActivity/FPRSessionManager.h"
  17. #import "FirebasePerformance/Sources/Common/FPRConstants.h"
  18. #import "FirebasePerformance/Sources/Common/FPRDiagnostics.h"
  19. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations.h"
  20. #import "FirebasePerformance/Sources/FPRClient.h"
  21. #import "FirebasePerformance/Sources/FPRConsoleLogger.h"
  22. #import "FirebasePerformance/Sources/FPRDataUtils.h"
  23. #import "FirebasePerformance/Sources/FPRURLFilter.h"
  24. #import "FirebasePerformance/Sources/Gauges/FPRGaugeManager.h"
  25. #import "FirebasePerformance/Sources/ISASwizzler/FPRObjectSwizzler.h"
  26. NSString *const kFPRNetworkTracePropertyName = @"fpr_networkTrace";
  27. @interface FPRNetworkTrace ()
  28. @property(nonatomic, readwrite) NSURLRequest *URLRequest;
  29. @property(nonatomic, readwrite, nullable) NSError *responseError;
  30. /** State to know if the trace has started. */
  31. @property(nonatomic) BOOL traceStarted;
  32. /** State to know if the trace has completed. */
  33. @property(nonatomic) BOOL traceCompleted;
  34. /** Background activity tracker to know the background state of the trace. */
  35. @property(nonatomic) FPRTraceBackgroundActivityTracker *backgroundActivityTracker;
  36. /** Custom attribute managed internally. */
  37. @property(nonatomic) NSMutableDictionary<NSString *, NSString *> *customAttributes;
  38. /** @brief Serial queue to manage the updation of session Ids. */
  39. @property(nonatomic, readwrite) dispatch_queue_t sessionIdSerialQueue;
  40. /**
  41. * Updates the current trace with the current session details.
  42. * @param sessionDetails Updated session details of the currently active session.
  43. */
  44. - (void)updateTraceWithCurrentSession:(FPRSessionDetails *)sessionDetails;
  45. @end
  46. @implementation FPRNetworkTrace {
  47. /**
  48. * @brief Object containing different states of the network request. Stores the information about
  49. * the state of a network request (defined in FPRNetworkTraceCheckpointState) and the time at
  50. * which the event happened.
  51. */
  52. NSMutableDictionary<NSString *, NSNumber *> *_states;
  53. }
  54. - (nullable instancetype)initWithURLRequest:(NSURLRequest *)URLRequest {
  55. if (URLRequest.URL == nil) {
  56. FPRLogError(kFPRNetworkTraceInvalidInputs, @"Invalid URL. URL is nil.");
  57. return nil;
  58. }
  59. // Fail early instead of creating a trace here.
  60. // IMPORTANT: Order is important here. This check needs to be done before looking up on remote
  61. // config. Reference bug: b/141861005.
  62. if (![[FPRURLFilter sharedInstance] shouldInstrumentURL:URLRequest.URL.absoluteString]) {
  63. return nil;
  64. }
  65. BOOL tracingEnabled = [FPRConfigurations sharedInstance].isDataCollectionEnabled;
  66. if (!tracingEnabled) {
  67. FPRLogInfo(kFPRTraceDisabled, @"Trace feature is disabled.");
  68. return nil;
  69. }
  70. BOOL sdkEnabled = [[FPRConfigurations sharedInstance] sdkEnabled];
  71. if (!sdkEnabled) {
  72. FPRLogInfo(kFPRTraceDisabled, @"Dropping event since Performance SDK is disabled.");
  73. return nil;
  74. }
  75. NSString *trimmedURLString = [FPRNetworkTrace stringByTrimmingURLString:URLRequest];
  76. if (!trimmedURLString || trimmedURLString.length <= 0) {
  77. FPRLogWarning(kFPRNetworkTraceURLLengthExceeds, @"URL length outside limits, returning nil.");
  78. return nil;
  79. }
  80. if (![URLRequest.URL.absoluteString isEqualToString:trimmedURLString]) {
  81. FPRLogInfo(kFPRNetworkTraceURLLengthTruncation,
  82. @"URL length exceeds limits, truncating recorded URL - %@.", trimmedURLString);
  83. }
  84. self = [super init];
  85. if (self) {
  86. _URLRequest = URLRequest;
  87. _trimmedURLString = trimmedURLString;
  88. _states = [[NSMutableDictionary<NSString *, NSNumber *> alloc] init];
  89. _hasValidResponseCode = NO;
  90. _customAttributes = [[NSMutableDictionary<NSString *, NSString *> alloc] init];
  91. _syncQueue =
  92. dispatch_queue_create("com.google.perf.networkTrace.metric", DISPATCH_QUEUE_SERIAL);
  93. _sessionIdSerialQueue =
  94. dispatch_queue_create("com.google.perf.sessionIds.networkTrace", DISPATCH_QUEUE_SERIAL);
  95. _activeSessions = [[NSMutableArray<FPRSessionDetails *> alloc] init];
  96. if (![FPRNetworkTrace isCompleteAndValidTrimmedURLString:_trimmedURLString
  97. URLRequest:_URLRequest]) {
  98. return nil;
  99. };
  100. }
  101. return self;
  102. }
  103. - (instancetype)init {
  104. FPRAssert(NO, @"Not a designated initializer.");
  105. return nil;
  106. }
  107. - (void)dealloc {
  108. // Safety net to ensure the notifications are not received anymore.
  109. FPRSessionManager *sessionManager = [FPRSessionManager sharedInstance];
  110. [sessionManager.sessionNotificationCenter removeObserver:self
  111. name:kFPRSessionIdUpdatedNotification
  112. object:sessionManager];
  113. }
  114. - (NSString *)description {
  115. return [NSString stringWithFormat:@"Request: %@", _URLRequest];
  116. }
  117. - (void)sessionChanged:(NSNotification *)notification {
  118. if (self.traceStarted && !self.traceCompleted) {
  119. NSDictionary<NSString *, FPRSessionDetails *> *userInfo = notification.userInfo;
  120. FPRSessionDetails *sessionDetails = [userInfo valueForKey:kFPRSessionIdNotificationKey];
  121. if (sessionDetails) {
  122. [self updateTraceWithCurrentSession:sessionDetails];
  123. }
  124. }
  125. }
  126. - (void)updateTraceWithCurrentSession:(FPRSessionDetails *)sessionDetails {
  127. if (sessionDetails != nil) {
  128. dispatch_sync(self.sessionIdSerialQueue, ^{
  129. [self.activeSessions addObject:sessionDetails];
  130. });
  131. }
  132. }
  133. - (NSArray<FPRSessionDetails *> *)sessions {
  134. __block NSArray<FPRSessionDetails *> *sessionInfos = nil;
  135. dispatch_sync(self.sessionIdSerialQueue, ^{
  136. sessionInfos = [self.activeSessions copy];
  137. });
  138. return sessionInfos;
  139. }
  140. - (NSDictionary<NSString *, NSNumber *> *)checkpointStates {
  141. __block NSDictionary<NSString *, NSNumber *> *copiedStates;
  142. dispatch_sync(self.syncQueue, ^{
  143. copiedStates = [_states copy];
  144. });
  145. return copiedStates;
  146. }
  147. - (void)checkpointState:(FPRNetworkTraceCheckpointState)state {
  148. if (!self.traceCompleted && self.traceStarted) {
  149. NSString *stateKey = @(state).stringValue;
  150. if (stateKey) {
  151. dispatch_sync(self.syncQueue, ^{
  152. NSNumber *existingState = _states[stateKey];
  153. if (existingState == nil) {
  154. double intervalSinceEpoch = [[NSDate date] timeIntervalSince1970];
  155. [_states setObject:@(intervalSinceEpoch) forKey:stateKey];
  156. }
  157. });
  158. } else {
  159. FPRAssert(NO, @"stateKey wasn't created for checkpoint state %ld", (long)state);
  160. }
  161. }
  162. }
  163. - (void)start {
  164. if (!self.traceCompleted) {
  165. [[FPRSessionManager sharedInstance] collectAllGaugesOnce];
  166. self.traceStarted = YES;
  167. self.backgroundActivityTracker = [[FPRTraceBackgroundActivityTracker alloc] init];
  168. [self checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  169. if ([self.URLRequest.HTTPMethod isEqualToString:@"POST"] ||
  170. [self.URLRequest.HTTPMethod isEqualToString:@"PUT"]) {
  171. self.requestSize = self.URLRequest.HTTPBody.length;
  172. }
  173. FPRSessionManager *sessionManager = [FPRSessionManager sharedInstance];
  174. [self updateTraceWithCurrentSession:[sessionManager.sessionDetails copy]];
  175. [sessionManager.sessionNotificationCenter addObserver:self
  176. selector:@selector(sessionChanged:)
  177. name:kFPRSessionIdUpdatedNotification
  178. object:sessionManager];
  179. }
  180. }
  181. - (FPRTraceState)backgroundTraceState {
  182. FPRTraceBackgroundActivityTracker *backgroundActivityTracker = self.backgroundActivityTracker;
  183. if (backgroundActivityTracker) {
  184. return backgroundActivityTracker.traceBackgroundState;
  185. }
  186. return FPRTraceStateUnknown;
  187. }
  188. - (NSTimeInterval)startTimeSinceEpoch {
  189. NSString *stateKey =
  190. [NSString stringWithFormat:@"%lu", (unsigned long)FPRNetworkTraceCheckpointStateInitiated];
  191. __block NSTimeInterval timeSinceEpoch;
  192. dispatch_sync(self.syncQueue, ^{
  193. timeSinceEpoch = [[_states objectForKey:stateKey] doubleValue];
  194. });
  195. return timeSinceEpoch;
  196. }
  197. #pragma mark - Overrides
  198. - (void)setResponseCode:(int32_t)responseCode {
  199. dispatch_sync(self.syncQueue, ^{
  200. _responseCode = responseCode;
  201. });
  202. if (responseCode != 0) {
  203. _hasValidResponseCode = YES;
  204. }
  205. }
  206. #pragma mark - FPRNetworkResponseHandler methods
  207. - (void)didCompleteRequestWithResponse:(NSURLResponse *)response error:(NSError *)error {
  208. if (!self.traceCompleted && self.traceStarted) {
  209. // Extract needed fields for the trace object.
  210. if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
  211. NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
  212. self.responseCode = (int32_t)HTTPResponse.statusCode;
  213. }
  214. self.responseError = error;
  215. self.responseContentType = response.MIMEType;
  216. [self checkpointState:FPRNetworkTraceCheckpointStateResponseCompleted];
  217. // Send the network trace for logging.
  218. [[FPRSessionManager sharedInstance] collectAllGaugesOnce];
  219. [[FPRClient sharedInstance] logNetworkTrace:self];
  220. self.traceCompleted = YES;
  221. }
  222. FPRSessionManager *sessionManager = [FPRSessionManager sharedInstance];
  223. [sessionManager.sessionNotificationCenter removeObserver:self
  224. name:kFPRSessionIdUpdatedNotification
  225. object:sessionManager];
  226. }
  227. - (void)didUploadFileWithURL:(NSURL *)URL {
  228. NSNumber *value = nil;
  229. NSError *error = nil;
  230. if ([URL getResourceValue:&value forKey:NSURLFileSizeKey error:&error]) {
  231. if (error) {
  232. FPRLogNotice(kFPRNetworkTraceFileError, @"Unable to determine the size of file.");
  233. } else {
  234. self.requestSize = value.unsignedIntegerValue;
  235. }
  236. }
  237. }
  238. - (void)didReceiveData:(NSData *)data {
  239. dispatch_sync(self.syncQueue, ^{
  240. self.responseSize = data.length;
  241. });
  242. }
  243. - (void)didReceiveFileURL:(NSURL *)URL {
  244. NSNumber *value = nil;
  245. NSError *error = nil;
  246. if ([URL getResourceValue:&value forKey:NSURLFileSizeKey error:&error]) {
  247. if (error) {
  248. FPRLogNotice(kFPRNetworkTraceFileError, @"Unable to determine the size of file.");
  249. } else {
  250. dispatch_sync(self.syncQueue, ^{
  251. self.responseSize = value.unsignedIntegerValue;
  252. });
  253. }
  254. }
  255. }
  256. - (NSTimeInterval)timeIntervalBetweenCheckpointState:(FPRNetworkTraceCheckpointState)startState
  257. andState:(FPRNetworkTraceCheckpointState)endState {
  258. __block NSNumber *startStateTime;
  259. __block NSNumber *endStateTime;
  260. dispatch_sync(self.syncQueue, ^{
  261. startStateTime = [_states objectForKey:[@(startState) stringValue]];
  262. endStateTime = [_states objectForKey:[@(endState) stringValue]];
  263. });
  264. // Fail fast. If any of the times do not exist, return 0.
  265. if (startStateTime == nil || endStateTime == nil) {
  266. return 0;
  267. }
  268. NSTimeInterval timeDiff = (endStateTime.doubleValue - startStateTime.doubleValue);
  269. return timeDiff;
  270. }
  271. /** Trims and validates the URL string of a given NSURLRequest.
  272. *
  273. * @param URLRequest The NSURLRequest containing the URL string to trim.
  274. * @return The trimmed string.
  275. */
  276. + (NSString *)stringByTrimmingURLString:(NSURLRequest *)URLRequest {
  277. NSURLComponents *components = [NSURLComponents componentsWithURL:URLRequest.URL
  278. resolvingAgainstBaseURL:NO];
  279. components.query = nil;
  280. components.fragment = nil;
  281. components.user = nil;
  282. components.password = nil;
  283. NSURL *trimmedURL = [components URL];
  284. NSString *truncatedURLString = FPRTruncatedURLString(trimmedURL.absoluteString);
  285. NSURL *truncatedURL = [NSURL URLWithString:truncatedURLString];
  286. if (!truncatedURL || truncatedURL.host == nil) {
  287. return nil;
  288. }
  289. return truncatedURLString;
  290. }
  291. /** Validates the trace object by checking that it's http or https, and not a denied URL.
  292. *
  293. * @param trimmedURLString A trimmed URL string from the URLRequest.
  294. * @param URLRequest The NSURLRequest that this trace will operate on.
  295. * @return YES if the trace object is valid, NO otherwise.
  296. */
  297. + (BOOL)isCompleteAndValidTrimmedURLString:(NSString *)trimmedURLString
  298. URLRequest:(NSURLRequest *)URLRequest {
  299. if (![[FPRURLFilter sharedInstance] shouldInstrumentURL:trimmedURLString]) {
  300. return NO;
  301. }
  302. // Check the URL begins with http or https.
  303. NSURLComponents *components = [NSURLComponents componentsWithURL:URLRequest.URL
  304. resolvingAgainstBaseURL:NO];
  305. NSString *scheme = components.scheme;
  306. if (!scheme || !([scheme caseInsensitiveCompare:@"HTTP"] == NSOrderedSame ||
  307. [scheme caseInsensitiveCompare:@"HTTPS"] == NSOrderedSame)) {
  308. FPRLogError(kFPRNetworkTraceInvalidInputs, @"Invalid URL - %@, returning nil.", URLRequest.URL);
  309. return NO;
  310. }
  311. return YES;
  312. }
  313. #pragma mark - Custom attributes related methods
  314. - (NSDictionary<NSString *, NSString *> *)attributes {
  315. return [self.customAttributes copy];
  316. }
  317. - (void)setValue:(NSString *)value forAttribute:(nonnull NSString *)attribute {
  318. BOOL canAddAttribute = YES;
  319. if (self.traceCompleted) {
  320. FPRLogError(kFPRTraceAlreadyStopped,
  321. @"Failed to set attribute %@ because network request %@ has already stopped.",
  322. attribute, self.URLRequest.URL);
  323. canAddAttribute = NO;
  324. }
  325. NSString *validatedName = FPRReservableAttributeName(attribute);
  326. NSString *validatedValue = FPRValidatedAttributeValue(value);
  327. if (validatedName == nil) {
  328. FPRLogError(kFPRAttributeNoName,
  329. @"Failed to initialize because of a nil or zero length attribute name.");
  330. canAddAttribute = NO;
  331. }
  332. if (validatedValue == nil) {
  333. FPRLogError(kFPRAttributeNoValue,
  334. @"Failed to initialize because of a nil or zero length attribute value.");
  335. canAddAttribute = NO;
  336. }
  337. if (self.customAttributes.allKeys.count >= kFPRMaxGlobalCustomAttributesCount) {
  338. FPRLogError(kFPRMaxAttributesReached,
  339. @"Only %d attributes allowed. Already reached maximum attribute count.",
  340. kFPRMaxGlobalCustomAttributesCount);
  341. canAddAttribute = NO;
  342. }
  343. if (canAddAttribute) {
  344. // Ensure concurrency during update of attributes.
  345. dispatch_sync(self.syncQueue, ^{
  346. self.customAttributes[validatedName] = validatedValue;
  347. FPRLogDebug(kFPRClientMetricLogged, @"Setting attribute %@ to %@ on network request %@",
  348. validatedName, validatedValue, self.URLRequest.URL);
  349. });
  350. }
  351. }
  352. - (NSString *)valueForAttribute:(NSString *)attribute {
  353. // TODO(b/175053654): Should this be happening on the serial queue for thread safety?
  354. return self.customAttributes[attribute];
  355. }
  356. - (void)removeAttribute:(NSString *)attribute {
  357. if (self.traceCompleted) {
  358. FPRLogError(kFPRTraceAlreadyStopped,
  359. @"Failed to remove attribute %@ because network request %@ has already stopped.",
  360. attribute, self.URLRequest.URL);
  361. return;
  362. }
  363. [self.customAttributes removeObjectForKey:attribute];
  364. }
  365. #pragma mark - Class methods related to object association.
  366. + (void)addNetworkTrace:(FPRNetworkTrace *)networkTrace toObject:(id)object {
  367. if (object != nil && networkTrace != nil) {
  368. [FPRObjectSwizzler
  369. setAssociatedObject:object
  370. key:(__bridge const void *_Nonnull)kFPRNetworkTracePropertyName
  371. value:networkTrace
  372. association:GUL_ASSOCIATION_RETAIN_NONATOMIC];
  373. }
  374. }
  375. + (FPRNetworkTrace *)networkTraceFromObject:(id)object {
  376. FPRNetworkTrace *networkTrace = nil;
  377. if (object != nil) {
  378. id traceObject = [FPRObjectSwizzler
  379. getAssociatedObject:object
  380. key:(__bridge const void *_Nonnull)kFPRNetworkTracePropertyName];
  381. if ([traceObject isKindOfClass:[FPRNetworkTrace class]]) {
  382. networkTrace = (FPRNetworkTrace *)traceObject;
  383. }
  384. }
  385. return networkTrace;
  386. }
  387. + (void)removeNetworkTraceFromObject:(id)object {
  388. if (object != nil) {
  389. [FPRObjectSwizzler
  390. setAssociatedObject:object
  391. key:(__bridge const void *_Nonnull)kFPRNetworkTracePropertyName
  392. value:nil
  393. association:GUL_ASSOCIATION_RETAIN_NONATOMIC];
  394. }
  395. }
  396. - (BOOL)isValid {
  397. return _hasValidResponseCode;
  398. }
  399. @end