FPRNetworkTrace.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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 <GoogleUtilities/GULObjectSwizzler.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. _responseCode = responseCode;
  200. if (responseCode != 0) {
  201. _hasValidResponseCode = YES;
  202. }
  203. }
  204. #pragma mark - FPRNetworkResponseHandler methods
  205. - (void)didCompleteRequestWithResponse:(NSURLResponse *)response error:(NSError *)error {
  206. if (!self.traceCompleted && self.traceStarted) {
  207. // Extract needed fields for the trace object.
  208. if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
  209. NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
  210. self.responseCode = (int32_t)HTTPResponse.statusCode;
  211. }
  212. self.responseError = error;
  213. self.responseContentType = response.MIMEType;
  214. [self checkpointState:FPRNetworkTraceCheckpointStateResponseCompleted];
  215. // Send the network trace for logging.
  216. [[FPRSessionManager sharedInstance] collectAllGaugesOnce];
  217. [[FPRClient sharedInstance] logNetworkTrace:self];
  218. self.traceCompleted = YES;
  219. }
  220. FPRSessionManager *sessionManager = [FPRSessionManager sharedInstance];
  221. [sessionManager.sessionNotificationCenter removeObserver:self
  222. name:kFPRSessionIdUpdatedNotification
  223. object:sessionManager];
  224. }
  225. - (void)didUploadFileWithURL:(NSURL *)URL {
  226. NSNumber *value = nil;
  227. NSError *error = nil;
  228. if ([URL getResourceValue:&value forKey:NSURLFileSizeKey error:&error]) {
  229. if (error) {
  230. FPRLogNotice(kFPRNetworkTraceFileError, @"Unable to determine the size of file.");
  231. } else {
  232. self.requestSize = value.unsignedIntegerValue;
  233. }
  234. }
  235. }
  236. - (void)didReceiveData:(NSData *)data {
  237. self.responseSize = data.length;
  238. }
  239. - (void)didReceiveFileURL:(NSURL *)URL {
  240. NSNumber *value = nil;
  241. NSError *error = nil;
  242. if ([URL getResourceValue:&value forKey:NSURLFileSizeKey error:&error]) {
  243. if (error) {
  244. FPRLogNotice(kFPRNetworkTraceFileError, @"Unable to determine the size of file.");
  245. } else {
  246. self.responseSize = value.unsignedIntegerValue;
  247. }
  248. }
  249. }
  250. - (NSTimeInterval)timeIntervalBetweenCheckpointState:(FPRNetworkTraceCheckpointState)startState
  251. andState:(FPRNetworkTraceCheckpointState)endState {
  252. __block NSNumber *startStateTime;
  253. __block NSNumber *endStateTime;
  254. dispatch_sync(self.syncQueue, ^{
  255. startStateTime = [_states objectForKey:[@(startState) stringValue]];
  256. endStateTime = [_states objectForKey:[@(endState) stringValue]];
  257. });
  258. // Fail fast. If any of the times do not exist, return 0.
  259. if (startStateTime == nil || endStateTime == nil) {
  260. return 0;
  261. }
  262. NSTimeInterval timeDiff = (endStateTime.doubleValue - startStateTime.doubleValue);
  263. return timeDiff;
  264. }
  265. /** Trims and validates the URL string of a given NSURLRequest.
  266. *
  267. * @param URLRequest The NSURLRequest containing the URL string to trim.
  268. * @return The trimmed string.
  269. */
  270. + (NSString *)stringByTrimmingURLString:(NSURLRequest *)URLRequest {
  271. NSURLComponents *components = [NSURLComponents componentsWithURL:URLRequest.URL
  272. resolvingAgainstBaseURL:NO];
  273. components.query = nil;
  274. components.fragment = nil;
  275. components.user = nil;
  276. components.password = nil;
  277. NSURL *trimmedURL = [components URL];
  278. NSString *truncatedURLString = FPRTruncatedURLString(trimmedURL.absoluteString);
  279. NSURL *truncatedURL = [NSURL URLWithString:truncatedURLString];
  280. if (!truncatedURL || truncatedURL.host == nil) {
  281. return nil;
  282. }
  283. return truncatedURLString;
  284. }
  285. /** Validates the trace object by checking that it's http or https, and not a denied URL.
  286. *
  287. * @param trimmedURLString A trimmed URL string from the URLRequest.
  288. * @param URLRequest The NSURLRequest that this trace will operate on.
  289. * @return YES if the trace object is valid, NO otherwise.
  290. */
  291. + (BOOL)isCompleteAndValidTrimmedURLString:(NSString *)trimmedURLString
  292. URLRequest:(NSURLRequest *)URLRequest {
  293. if (![[FPRURLFilter sharedInstance] shouldInstrumentURL:trimmedURLString]) {
  294. return NO;
  295. }
  296. // Check the URL begins with http or https.
  297. NSURLComponents *components = [NSURLComponents componentsWithURL:URLRequest.URL
  298. resolvingAgainstBaseURL:NO];
  299. NSString *scheme = components.scheme;
  300. if (!scheme || !([scheme caseInsensitiveCompare:@"HTTP"] == NSOrderedSame ||
  301. [scheme caseInsensitiveCompare:@"HTTPS"] == NSOrderedSame)) {
  302. FPRLogError(kFPRNetworkTraceInvalidInputs, @"Invalid URL - %@, returning nil.", URLRequest.URL);
  303. return NO;
  304. }
  305. return YES;
  306. }
  307. #pragma mark - Custom attributes related methods
  308. - (NSDictionary<NSString *, NSString *> *)attributes {
  309. return [self.customAttributes copy];
  310. }
  311. - (void)setValue:(NSString *)value forAttribute:(nonnull NSString *)attribute {
  312. BOOL canAddAttribute = YES;
  313. if (self.traceCompleted) {
  314. FPRLogError(kFPRTraceAlreadyStopped,
  315. @"Failed to set attribute %@ because network request %@ has already stopped.",
  316. attribute, self.URLRequest.URL);
  317. canAddAttribute = NO;
  318. }
  319. NSString *validatedName = FPRReservableAttributeName(attribute);
  320. NSString *validatedValue = FPRValidatedAttributeValue(value);
  321. if (validatedName == nil) {
  322. FPRLogError(kFPRAttributeNoName,
  323. @"Failed to initialize because of a nil or zero length attribute name.");
  324. canAddAttribute = NO;
  325. }
  326. if (validatedValue == nil) {
  327. FPRLogError(kFPRAttributeNoValue,
  328. @"Failed to initialize because of a nil or zero length attribute value.");
  329. canAddAttribute = NO;
  330. }
  331. if (self.customAttributes.allKeys.count >= kFPRMaxGlobalCustomAttributesCount) {
  332. FPRLogError(kFPRMaxAttributesReached,
  333. @"Only %d attributes allowed. Already reached maximum attribute count.",
  334. kFPRMaxGlobalCustomAttributesCount);
  335. canAddAttribute = NO;
  336. }
  337. if (canAddAttribute) {
  338. // Ensure concurrency during update of attributes.
  339. dispatch_sync(self.syncQueue, ^{
  340. self.customAttributes[validatedName] = validatedValue;
  341. FPRLogDebug(kFPRClientMetricLogged, @"Setting attribute %@ to %@ on network request %@",
  342. validatedName, validatedValue, self.URLRequest.URL);
  343. });
  344. }
  345. }
  346. - (NSString *)valueForAttribute:(NSString *)attribute {
  347. // TODO(b/175053654): Should this be happening on the serial queue for thread safety?
  348. return self.customAttributes[attribute];
  349. }
  350. - (void)removeAttribute:(NSString *)attribute {
  351. if (self.traceCompleted) {
  352. FPRLogError(kFPRTraceAlreadyStopped,
  353. @"Failed to remove attribute %@ because network request %@ has already stopped.",
  354. attribute, self.URLRequest.URL);
  355. return;
  356. }
  357. [self.customAttributes removeObjectForKey:attribute];
  358. }
  359. #pragma mark - Class methods related to object association.
  360. + (void)addNetworkTrace:(FPRNetworkTrace *)networkTrace toObject:(id)object {
  361. if (object != nil && networkTrace != nil) {
  362. [GULObjectSwizzler setAssociatedObject:object
  363. key:kFPRNetworkTracePropertyName
  364. value:networkTrace
  365. association:GUL_ASSOCIATION_RETAIN_NONATOMIC];
  366. }
  367. }
  368. + (FPRNetworkTrace *)networkTraceFromObject:(id)object {
  369. FPRNetworkTrace *networkTrace = nil;
  370. if (object != nil) {
  371. id traceObject = [GULObjectSwizzler getAssociatedObject:object
  372. key:kFPRNetworkTracePropertyName];
  373. if ([traceObject isKindOfClass:[FPRNetworkTrace class]]) {
  374. networkTrace = (FPRNetworkTrace *)traceObject;
  375. }
  376. }
  377. return networkTrace;
  378. }
  379. + (void)removeNetworkTraceFromObject:(id)object {
  380. if (object != nil) {
  381. [GULObjectSwizzler setAssociatedObject:object
  382. key:kFPRNetworkTracePropertyName
  383. value:nil
  384. association:GUL_ASSOCIATION_RETAIN_NONATOMIC];
  385. }
  386. }
  387. - (BOOL)isValid {
  388. return _hasValidResponseCode;
  389. }
  390. @end