FPRNetworkTrace.m 16 KB

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