FPRNetworkTrace.m 16 KB

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