diff --git a/CHANGELOG.md b/CHANGELOG.md index 48e7d8c449..917ec2ce33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,20 @@ ## Unreleased +### Features + +- Attach a flame graph of the sampled JS stacks to JS hang events on iOS with the experimental `attachJsHangFlamegraph` option ([#7042](https://github.com/getsentry/sentry-react-native/pull/7042)) + - The flame graph shows where the JS thread spent its time during the hang. It requires `enableJsHangTracking` and Hermes. + - The frames in the flame graph are not yet symbolicated with source maps. + + ```js + Sentry.init({ + dsn: '__DSN__', + enableJsHangTracking: true, + attachJsHangFlamegraph: true, + }); + ``` + ### Fixes - Start the native Android SDK when `sentry-android-replay` is excluded and a replay sample rate is set ([#7035](https://github.com/getsentry/sentry-react-native/pull/7035)) diff --git a/packages/core/RNSentryCocoaTester/RNSentryCocoaTester.xcodeproj/project.pbxproj b/packages/core/RNSentryCocoaTester/RNSentryCocoaTester.xcodeproj/project.pbxproj index f18ca43a40..7562cde630 100644 --- a/packages/core/RNSentryCocoaTester/RNSentryCocoaTester.xcodeproj/project.pbxproj +++ b/packages/core/RNSentryCocoaTester/RNSentryCocoaTester.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 03B26FDC6BB58ACBB2529D8E /* RNSentryJSHangTrackerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 0ABE44D72B4F98081D9C182F /* RNSentryJSHangTrackerTests.m */; }; 00C7702ED388EA0682DBCC48 /* RNSentryStartInvalidOptionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26C9B2501FF3EBD8B91BA6C1 /* RNSentryStartInvalidOptionsTests.swift */; }; 2639D71D3BD04F17B0BAC987 /* RNSentryTurboModulePerfControllerTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = E795057A6D534A80A9D06356 /* RNSentryTurboModulePerfControllerTests.mm */; }; 332D33472CDBDBB600547D76 /* RNSentryReplayOptionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 332D33462CDBDBB600547D76 /* RNSentryReplayOptionsTests.swift */; }; @@ -33,6 +34,7 @@ /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 0ABE44D72B4F98081D9C182F /* RNSentryJSHangTrackerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = RNSentryJSHangTrackerTests.m; sourceTree = ""; }; 1482D5685A340AB93348A43D /* Pods-RNSentryCocoaTesterTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RNSentryCocoaTesterTests.release.xcconfig"; path = "Target Support Files/Pods-RNSentryCocoaTesterTests/Pods-RNSentryCocoaTesterTests.release.xcconfig"; sourceTree = ""; }; 26C9B2501FF3EBD8B91BA6C1 /* RNSentryStartInvalidOptionsTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = RNSentryStartInvalidOptionsTests.swift; sourceTree = ""; }; 330F308D2C0F385A002A0D4E /* RNSentryBreadcrumb.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RNSentryBreadcrumb.h; path = ../ios/RNSentryBreadcrumb.h; sourceTree = ""; }; @@ -67,6 +69,8 @@ 33DEDFEF2D9185E3006066E4 /* RNSentryTimeToDisplayTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RNSentryTimeToDisplayTests.swift; sourceTree = ""; }; 33F58ACE2977037D008F60EB /* RNSentryScreenshotSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RNSentryScreenshotSourceTests.swift; sourceTree = ""; }; 33F58ACF2977037D008F60EA /* RNSentryTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNSentryTests.m; sourceTree = ""; }; + 6C460E16960E3309F7396CCF /* RNSentryJSHangTracker.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RNSentryJSHangTracker.h; path = ../ios/RNSentryJSHangTracker.h; sourceTree = SOURCE_ROOT; }; + CCD339BBC5ECC684CED30588 /* RNSentryJSHangTracker+Test.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "RNSentryJSHangTracker+Test.h"; sourceTree = ""; }; 3E3742693F7643C2ADE1BDF2 /* RNSentryUriValidationTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = RNSentryUriValidationTests.m; sourceTree = ""; }; 650CB718ACFBD05609BF2126 /* libPods-RNSentryCocoaTesterTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-RNSentryCocoaTesterTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 864F5BFD9CFDA4502ADAE72E /* RNSentrySDKStartInvalidOptionsTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = RNSentrySDKStartInvalidOptionsTests.swift; sourceTree = ""; }; @@ -134,6 +138,8 @@ 3339C4802D6625570088EB3A /* RNSentryUserTests.m */, 3339C4822D6625570088EB3A /* RNSentryReplayControlTests.m */, 3E3742693F7643C2ADE1BDF2 /* RNSentryUriValidationTests.m */, + CCD339BBC5ECC684CED30588 /* RNSentryJSHangTracker+Test.h */, + 0ABE44D72B4F98081D9C182F /* RNSentryJSHangTrackerTests.m */, E795057A6D534A80A9D06356 /* RNSentryTurboModulePerfControllerTests.mm */, 33AFDFEC2B8D14B300AAB120 /* RNSentryFramesTrackerListenerTests.m */, 33AFDFF02B8D15E500AAB120 /* RNSentryDependencyContainerTests.m */, @@ -176,6 +182,7 @@ 3360843A2C32E3A8008CC412 /* RNSentryReplayBreadcrumbConverter.h */, 330F308D2C0F385A002A0D4E /* RNSentryBreadcrumb.h */, 33958C672BFCEF5A00AD1FB6 /* RNSentryOnDrawReporter.h */, + 6C460E16960E3309F7396CCF /* RNSentryJSHangTracker.h */, FADF868E2EBD053E00D6652D /* SentrySDKWrapper.h */, 33AFE0132B8F31AF00AAB120 /* RNSentryDependencyContainer.h */, 338739072A7D7D2800950DDD /* RNSentryReplay.h */, @@ -320,6 +327,7 @@ 3339C4812D6625570088EB3A /* RNSentryUserTests.m in Sources */, 3339C4832D6625570088EB3A /* RNSentryReplayControlTests.m in Sources */, B4DEB41739F14AA38202D4D4 /* RNSentryUriValidationTests.m in Sources */, + 03B26FDC6BB58ACBB2529D8E /* RNSentryJSHangTrackerTests.m in Sources */, 2639D71D3BD04F17B0BAC987 /* RNSentryTurboModulePerfControllerTests.mm in Sources */, 33DEDFF02D9185EB006066E4 /* RNSentryTimeToDisplayTests.swift in Sources */, 3380C6C42CE25ECA0018B9B6 /* RNSentryReplayPostInitTests.swift in Sources */, diff --git a/packages/core/RNSentryCocoaTester/RNSentryCocoaTesterTests/RNSentryJSHangTracker+Test.h b/packages/core/RNSentryCocoaTester/RNSentryCocoaTesterTests/RNSentryJSHangTracker+Test.h new file mode 100644 index 0000000000..6f342b960d --- /dev/null +++ b/packages/core/RNSentryCocoaTester/RNSentryCocoaTesterTests/RNSentryJSHangTracker+Test.h @@ -0,0 +1,18 @@ +#import "RNSentryJSHangTracker.h" +#import + +@class SentryFrame; + +NS_ASSUME_NONNULL_BEGIN + +@interface RNSentryJSHangTracker (Testing) + ++ (nullable NSData *)flamegraphFromHermesTrace:(NSData *)trace + newestFirst:(BOOL)newestFirst + bundleDebugId:(nullable NSString *)bundleDebugId; + ++ (nullable SentryFrame *)frameFromHermesFrame:(NSDictionary *)hermesFrame; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/core/RNSentryCocoaTester/RNSentryCocoaTesterTests/RNSentryJSHangTrackerTests.m b/packages/core/RNSentryCocoaTester/RNSentryCocoaTesterTests/RNSentryJSHangTrackerTests.m new file mode 100644 index 0000000000..241f800ebe --- /dev/null +++ b/packages/core/RNSentryCocoaTester/RNSentryCocoaTesterTests/RNSentryJSHangTrackerTests.m @@ -0,0 +1,350 @@ +#import "RNSentryJSHangTracker+Test.h" +#import +@import Sentry; + +static NSDictionary * +jsFrame(NSString *name, NSNumber *_Nullable parent) +{ + NSMutableDictionary *frame = [@ { + @"name" : name, + @"category" : @"JavaScript", + @"line" : @"10", + @"column" : @"20", + } mutableCopy]; + frame[@"parent"] = parent; + return frame; +} + +static NSDictionary * +sample(NSString *ts, NSString *tid, NSNumber *sf) +{ + return @{ + @"cpu" : @"-1", + @"name" : @"", + @"ts" : ts, + @"pid" : @1, + @"tid" : tid, + @"weight" : @"1", + @"sf" : sf, + }; +} + +static NSData * +hermesTrace(NSDictionary *stackFrames, NSArray *samples) +{ + return [NSJSONSerialization dataWithJSONObject:@{ + @"traceEvents" : @[], + @"stackFrames" : stackFrames, + @"samples" : samples, + } + options:0 + error:nil]; +} + +// [root] -> main -> (a -> native, b) +static NSDictionary * +branchingStackFrames(void) +{ + return @{ + @"1" : @ { @"name" : @"[root]", @"category" : @"root" }, + @"2" : jsFrame(@"main(app:///main.jsbundle:1:1)", @1), + @"3" : jsFrame(@"a(app:///main.jsbundle:2:1)", @2), + @"4" : jsFrame(@"b(app:///main.jsbundle:3:1)", @2), + @"5" : @ { @"name" : @"nativeCall", @"category" : @"Native", @"parent" : @3 }, + }; +} + +@interface RNSentryJSHangTrackerTests : XCTestCase +@end + +@implementation RNSentryJSHangTrackerTests + +- (NSDictionary *)flamegraphFromTrace:(NSData *)trace + newestFirst:(BOOL)newestFirst + bundleDebugId:(nullable NSString *)bundleDebugId +{ + NSData *data = [RNSentryJSHangTracker flamegraphFromHermesTrace:trace + newestFirst:newestFirst + bundleDebugId:bundleDebugId]; + XCTAssertNotNil(data); + if (data == nil) { + return @{ }; + } + NSDictionary *flamegraph = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + [self assertValidFlamegraph:flamegraph]; + return flamegraph; +} + +- (void)assertValidFlamegraph:(NSDictionary *)flamegraph +{ + XCTAssertEqualObjects(flamegraph[@"version"], @"1"); + XCTAssertEqualObjects(flamegraph[@"platform"], @"javascript"); + NSArray *frames = flamegraph[@"frames"]; + NSArray *nodes = flamegraph[@"nodes"]; + NSArray *trees = flamegraph[@"trees"]; + XCTAssertGreaterThan(frames.count, 0); + XCTAssertGreaterThan(nodes.count, 0); + XCTAssertGreaterThan(trees.count, 0); + + for (NSDictionary *frame in frames) { + XCTAssertTrue([frame[@"filename"] length] > 0 || [frame[@"function"] length] > 0); + } + for (NSDictionary *node in nodes) { + NSInteger frameId = [node[@"frame_id"] integerValue]; + XCTAssertTrue(frameId >= 0 && frameId < (NSInteger)frames.count); + NSInteger sampleCount = [node[@"sample_count"] integerValue]; + XCTAssertGreaterThan(sampleCount, 0); + NSInteger childrenCount = 0; + for (NSNumber *child in node[@"children"]) { + XCTAssertTrue(child.integerValue >= 0 && child.integerValue < (NSInteger)nodes.count); + if (child.integerValue >= 0 && child.integerValue < (NSInteger)nodes.count) { + childrenCount += [nodes[child.integerValue][@"sample_count"] integerValue]; + } + } + XCTAssertLessThanOrEqual(childrenCount, sampleCount); + } + for (NSDictionary *tree in trees) { + NSArray *roots = tree[@"roots"]; + XCTAssertGreaterThan(roots.count, 0); + for (NSNumber *root in roots) { + XCTAssertTrue(root.integerValue >= 0 && root.integerValue < (NSInteger)nodes.count); + } + } +} + +- (NSString *)functionOfNode:(NSNumber *)nodeIndex inFlamegraph:(NSDictionary *)flamegraph +{ + NSDictionary *node = flamegraph[@"nodes"][nodeIndex.unsignedIntegerValue]; + return flamegraph[@"frames"] [[node[@"frame_id"] unsignedIntegerValue]][@"function"]; +} + +- (void)testFlamegraphHasInclusiveCountsFromCallerToCallee +{ + NSData *trace = hermesTrace(branchingStackFrames(), @[ + sample(@"1000", @"7", @3), sample(@"2000", @"7", @3), sample(@"3000", @"7", @4), + sample(@"4000", @"7", @2) + ]); + + NSDictionary *flamegraph = [self flamegraphFromTrace:trace newestFirst:NO bundleDebugId:nil]; + + NSArray *nodes = flamegraph[@"nodes"]; + NSArray *roots = flamegraph[@"trees"][0][@"roots"]; + XCTAssertEqual(roots.count, 1); + NSDictionary *main = nodes[roots[0].unsignedIntegerValue]; + XCTAssertEqualObjects([self functionOfNode:roots[0] inFlamegraph:flamegraph], @"main"); + XCTAssertEqualObjects(main[@"sample_count"], @4); + + NSArray *children = main[@"children"]; + XCTAssertEqual(children.count, 2); + XCTAssertEqualObjects([self functionOfNode:children[0] inFlamegraph:flamegraph], @"a"); + XCTAssertEqualObjects(nodes[children[0].unsignedIntegerValue][@"sample_count"], @2); + XCTAssertEqualObjects([self functionOfNode:children[1] inFlamegraph:flamegraph], @"b"); + XCTAssertEqualObjects(nodes[children[1].unsignedIntegerValue][@"sample_count"], @1); + XCTAssertEqual(nodes.count, 3); +} + +- (void)testFlamegraphFiltersOutNativeAndRootFrames +{ + NSData *trace = hermesTrace(branchingStackFrames(), @[ sample(@"1000", @"7", @5) ]); + + NSDictionary *flamegraph = [self flamegraphFromTrace:trace newestFirst:NO bundleDebugId:nil]; + + NSArray *functions = [flamegraph[@"frames"] valueForKey:@"function"]; + XCTAssertEqualObjects(functions, (@[ @"main", @"a" ])); + XCTAssertEqual([flamegraph[@"nodes"] count], 2); +} + +- (void)testFlamegraphSkipsSamplesWithoutJsFrames +{ + NSData *trace = hermesTrace(branchingStackFrames(), + @[ sample(@"1000", @"7", @1), sample(@"2000", @"7", @4), sample(@"3000", @"7", @1) ]); + + NSDictionary *flamegraph = [self flamegraphFromTrace:trace newestFirst:NO bundleDebugId:nil]; + + NSArray *roots = flamegraph[@"trees"][0][@"roots"]; + XCTAssertEqualObjects(flamegraph[@"nodes"][roots[0].unsignedIntegerValue][@"sample_count"], @1); +} + +- (void)testFlamegraphIsNilWithoutJsSamples +{ + NSDictionary *stackFrames = @{ + @"1" : @ { @"name" : @"[root]", @"category" : @"root" }, + @"2" : @ { @"name" : @"nativeCall", @"category" : @"Native", @"parent" : @1 }, + }; + NSData *trace + = hermesTrace(stackFrames, @[ sample(@"1000", @"7", @1), sample(@"2000", @"7", @2) ]); + + XCTAssertNil([RNSentryJSHangTracker flamegraphFromHermesTrace:trace + newestFirst:NO + bundleDebugId:nil]); + XCTAssertNil([RNSentryJSHangTracker flamegraphFromHermesTrace:hermesTrace(stackFrames, @[]) + newestFirst:YES + bundleDebugId:nil]); +} + +- (void)testFlamegraphIsNilForInvalidTrace +{ + NSData *trace = [@"not json" dataUsingEncoding:NSUTF8StringEncoding]; + XCTAssertNil([RNSentryJSHangTracker flamegraphFromHermesTrace:trace + newestFirst:NO + bundleDebugId:nil]); + + NSData *wrongTypes = [NSJSONSerialization dataWithJSONObject:@{ @"samples" : @"x" } + options:0 + error:nil]; + XCTAssertNil([RNSentryJSHangTracker flamegraphFromHermesTrace:wrongTypes + newestFirst:NO + bundleDebugId:nil]); +} + +- (void)testFlamegraphIsNilWhenLargerThan10MiB +{ + NSString *longName = [@"" stringByPaddingToLength:6000 withString:@"f" startingAtIndex:0]; + NSData * (^traceWithLongFrames)(NSInteger) = ^(NSInteger count) { + NSMutableDictionary *stackFrames = [@{ @"1" : jsFrame(@"main", nil) } mutableCopy]; + NSMutableArray *samples = [NSMutableArray array]; + for (NSInteger i = 2; i < count + 2; i++) { + NSString *frameId = [@(i) stringValue]; + stackFrames[frameId] = jsFrame([longName stringByAppendingString:frameId], @1); + [samples addObject:sample(frameId, @"7", @(i))]; + } + return hermesTrace(stackFrames, samples); + }; + + XCTAssertNotNil([RNSentryJSHangTracker flamegraphFromHermesTrace:traceWithLongFrames(1000) + newestFirst:NO + bundleDebugId:nil]); + XCTAssertNil([RNSentryJSHangTracker flamegraphFromHermesTrace:traceWithLongFrames(2000) + newestFirst:NO + bundleDebugId:nil]); +} + +- (void)testFlamegraphFromProfileKeepsOnlyTheLastWindow +{ + NSData *trace = hermesTrace(branchingStackFrames(), @[ + sample(@"1000000", @"7", @3), sample(@"1199999", @"7", @3), sample(@"1200000", @"7", @4), + sample(@"1500000", @"7", @4) + ]); + + NSDictionary *profileGraph = [self flamegraphFromTrace:trace newestFirst:YES bundleDebugId:nil]; + NSDictionary *fullGraph = [self flamegraphFromTrace:trace newestFirst:NO bundleDebugId:nil]; + + NSArray *profileFunctions = [profileGraph[@"frames"] valueForKey:@"function"]; + XCTAssertEqualObjects(profileFunctions, (@[ @"main", @"b" ])); + NSNumber *profileRoot = profileGraph[@"trees"][0][@"roots"][0]; + XCTAssertEqualObjects( + profileGraph[@"nodes"][profileRoot.unsignedIntegerValue][@"sample_count"], @2); + + NSNumber *fullRoot = fullGraph[@"trees"][0][@"roots"][0]; + XCTAssertEqualObjects(fullGraph[@"nodes"][fullRoot.unsignedIntegerValue][@"sample_count"], @4); +} + +- (void)testFlamegraphAttributesTheThreadOfTheEventStack +{ + NSData *trace = hermesTrace(branchingStackFrames(), @[ + sample(@"1000", @"1", @1), sample(@"2000", @"1", @3), sample(@"3000", @"2", @4), + sample(@"4000", @"2", @1) + ]); + + NSArray *oldestFirstTrees = [self flamegraphFromTrace:trace + newestFirst:NO + bundleDebugId:nil][@"trees"]; + NSArray *newestFirstTrees = [self flamegraphFromTrace:trace + newestFirst:YES + bundleDebugId:nil][@"trees"]; + + XCTAssertEqual(oldestFirstTrees.count, 2); + XCTAssertEqualObjects(oldestFirstTrees[0][@"thread_id"], @"1"); + XCTAssertEqualObjects(oldestFirstTrees[0][@"thread_attributed"], @YES); + XCTAssertEqualObjects(oldestFirstTrees[1][@"thread_id"], @"2"); + XCTAssertNil(oldestFirstTrees[1][@"thread_attributed"]); + + XCTAssertEqual(newestFirstTrees.count, 2); + XCTAssertNil(newestFirstTrees[0][@"thread_attributed"]); + XCTAssertEqualObjects(newestFirstTrees[1][@"thread_id"], @"2"); + XCTAssertEqualObjects(newestFirstTrees[1][@"thread_attributed"], @YES); +} + +- (void)testFlamegraphHasDebugMetaWhenBundleDebugIdIsSet +{ + NSData *trace = hermesTrace(branchingStackFrames(), @[ sample(@"1000", @"7", @3) ]); + + NSDictionary *withDebugId = [self flamegraphFromTrace:trace + newestFirst:NO + bundleDebugId:@"debug-id"]; + NSDictionary *withoutDebugId = [self flamegraphFromTrace:trace + newestFirst:NO + bundleDebugId:nil]; + + XCTAssertEqualObjects(withDebugId[@"debug_meta"], (@{ + @"images" : @[ @{ + @"type" : @"sourcemap", + @"debug_id" : @"debug-id", + @"code_file" : @"app:///main.jsbundle", + } ] + })); + XCTAssertNil(withoutDebugId[@"debug_meta"]); +} + +- (void)testFlamegraphFramesMatchEventStackFrames +{ + NSDictionary *bytecode = @{ + @"name" : @"bytecodeFn(app:///main.jsbundle)", + @"category" : @"JavaScript", + @"funcVirtAddr" : @"100", + @"offset" : @"5", + }; + NSDictionary *anonymous = @{ + @"name" : @"(app:///main.jsbundle:1:1)", + @"category" : @"JavaScript", + @"line" : @"10", + @"column" : @"20", + @"parent" : @1, + }; + NSDictionary *stackFrames = @{ @"1" : bytecode, @"2" : anonymous }; + NSData *trace = hermesTrace(stackFrames, @[ sample(@"1000", @"7", @2) ]); + + NSArray *frames = [self flamegraphFromTrace:trace + newestFirst:NO + bundleDebugId:nil][@"frames"]; + + XCTAssertEqualObjects(frames[0], (@{ + @"function" : @"bytecodeFn", + @"filename" : @"app:///main.jsbundle", + @"abs_path" : @"app:///main.jsbundle", + @"lineno" : @1, + @"colno" : @106, + @"platform" : @"javascript", + })); + XCTAssertEqualObjects(frames[1], (@{ + @"filename" : @"app:///main.jsbundle", + @"abs_path" : @"app:///main.jsbundle", + @"lineno" : @10, + @"colno" : @20, + @"platform" : @"javascript", + })); + + NSArray *hermesFrames = @[ bytecode, anonymous ]; + for (NSUInteger i = 0; i < hermesFrames.count; i++) { + SentryFrame *eventFrame = [RNSentryJSHangTracker frameFromHermesFrame:hermesFrames[i]]; + XCTAssertEqualObjects(frames[i][@"function"], eventFrame.function); + XCTAssertEqualObjects(frames[i][@"filename"], eventFrame.fileName); + XCTAssertEqualObjects(frames[i][@"lineno"], eventFrame.lineNumber); + XCTAssertEqualObjects(frames[i][@"colno"], eventFrame.columnNumber); + XCTAssertEqualObjects(frames[i][@"platform"], eventFrame.platform); + } +} + +- (void)testFlamegraphReusesFramesAcrossThreads +{ + NSData *trace = hermesTrace(branchingStackFrames(), + @[ sample(@"1000", @"1", @3), sample(@"2000", @"2", @3), sample(@"3000", @"1", @3) ]); + + NSDictionary *flamegraph = [self flamegraphFromTrace:trace newestFirst:NO bundleDebugId:nil]; + + XCTAssertEqual([flamegraph[@"frames"] count], 2); + XCTAssertEqual([flamegraph[@"nodes"] count], 4); + XCTAssertEqual([flamegraph[@"trees"] count], 2); +} + +@end diff --git a/packages/core/android/src/main/java/io/sentry/react/RNSentryModuleImpl.java b/packages/core/android/src/main/java/io/sentry/react/RNSentryModuleImpl.java index 3c0beea631..105de62705 100644 --- a/packages/core/android/src/main/java/io/sentry/react/RNSentryModuleImpl.java +++ b/packages/core/android/src/main/java/io/sentry/react/RNSentryModuleImpl.java @@ -353,6 +353,10 @@ public void stopJsHangTracking() { // No-op: JS hang tracking is iOS-only } + public void setAttachJsHangFlamegraph(boolean enabled) { + // No-op: JS hang tracking is iOS-only + } + public void fetchModules(Promise promise) { final AssetManager assets = this.getReactApplicationContext().getResources().getAssets(); try (InputStream stream = new BufferedInputStream(assets.open(modulesPath))) { diff --git a/packages/core/android/src/newarch/java/io/sentry/react/RNSentryModule.java b/packages/core/android/src/newarch/java/io/sentry/react/RNSentryModule.java index e9d3874bd9..5456a946a6 100644 --- a/packages/core/android/src/newarch/java/io/sentry/react/RNSentryModule.java +++ b/packages/core/android/src/newarch/java/io/sentry/react/RNSentryModule.java @@ -320,6 +320,11 @@ public void stopJsHangTracking() { this.impl.stopJsHangTracking(); } + @Override + public void setAttachJsHangFlamegraph(boolean enabled) { + this.impl.setAttachJsHangFlamegraph(enabled); + } + @Override public void invalidate() { this.impl.invalidate(); diff --git a/packages/core/android/src/oldarch/java/io/sentry/react/RNSentryModule.java b/packages/core/android/src/oldarch/java/io/sentry/react/RNSentryModule.java index 6c87070c4f..a2b75c80b3 100644 --- a/packages/core/android/src/oldarch/java/io/sentry/react/RNSentryModule.java +++ b/packages/core/android/src/oldarch/java/io/sentry/react/RNSentryModule.java @@ -320,6 +320,11 @@ public void stopJsHangTracking() { this.impl.stopJsHangTracking(); } + @ReactMethod + public void setAttachJsHangFlamegraph(boolean enabled) { + this.impl.setAttachJsHangFlamegraph(enabled); + } + @Override public void invalidate() { this.impl.invalidate(); diff --git a/packages/core/etc/sentry-react-native.api.md b/packages/core/etc/sentry-react-native.api.md index 9e90bdfe9f..1b8be7558a 100644 --- a/packages/core/etc/sentry-react-native.api.md +++ b/packages/core/etc/sentry-react-native.api.md @@ -156,6 +156,7 @@ export interface BaseReactNativeOptions { anrProfilingSampleRate?: number; appHangTimeoutInterval?: number; attachAllThreads?: boolean; + attachJsHangFlamegraph?: boolean; attachScreenshot?: boolean; attachThreads?: boolean; attachViewHierarchy?: boolean; diff --git a/packages/core/ios/RNSentry.mm b/packages/core/ios/RNSentry.mm index 55a906648a..8158be1053 100644 --- a/packages/core/ios/RNSentry.mm +++ b/packages/core/ios/RNSentry.mm @@ -901,6 +901,11 @@ - (RNSentryJSThreadScheduler)jsThreadScheduler RCT_EXPORT_METHOD(stopJsHangTracking) { [[RNSentryJSHangTracker sharedInstance] stop]; } +RCT_EXPORT_METHOD(setAttachJsHangFlamegraph : (BOOL)enabled) +{ + [RNSentryJSHangTracker sharedInstance].attachFlamegraph = enabled; +} + - (void)invalidate { [[RNSentryJSHangTracker sharedInstance] stop]; diff --git a/packages/core/ios/RNSentryJSHangTracker.h b/packages/core/ios/RNSentryJSHangTracker.h index c389e36861..fac60c933a 100644 --- a/packages/core/ios/RNSentryJSHangTracker.h +++ b/packages/core/ios/RNSentryJSHangTracker.h @@ -17,6 +17,9 @@ typedef BOOL (^RNSentryJSThreadScheduler)(dispatch_block_t block); + (instancetype)sharedInstance; +/// Attaches a flame graph of the sampled JS stacks to each JS hang event. +@property (atomic) BOOL attachFlamegraph; + /// Starts tracking, or restarts it with the new values when it already runs. - (void)startWithTimeoutIntervalMs:(uint64_t)timeoutIntervalMs bundleDebugId:(nullable NSString *)bundleDebugId diff --git a/packages/core/ios/RNSentryJSHangTracker.mm b/packages/core/ios/RNSentryJSHangTracker.mm index bb4be8089d..57f37b31ca 100644 --- a/packages/core/ios/RNSentryJSHangTracker.mm +++ b/packages/core/ios/RNSentryJSHangTracker.mm @@ -15,6 +15,7 @@ static const int64_t kPollIntervalNs = 100 * NSEC_PER_MSEC; static const std::chrono::milliseconds kStackSampleWindow(300); static NSString *const kBundleFileName = @"app:///main.jsbundle"; +static const NSUInteger kMaxFlamegraphBytes = 10 * 1024 * 1024; namespace { struct PingState { @@ -197,6 +198,7 @@ - (void)reportHangWithTimeoutIntervalMs:(uint64_t)timeoutIntervalMs NSData *traceData = trace ? [NSData dataWithBytes:trace->json.data() length:trace->json.size()] : nil; BOOL newestFirst = trace && trace->fromProfile; + BOOL attachFlamegraph = self.attachFlamegraph; // `stop` waits for this thread, so only the sample runs here. The capture also waits for the // main thread to take the screenshot. @@ -205,10 +207,24 @@ - (void)reportHangWithTimeoutIntervalMs:(uint64_t)timeoutIntervalMs NSArray *frames = traceData != nil ? [RNSentryJSHangTracker framesFromHermesTrace:traceData newestFirst:newestFirst] : @[]; - [SentrySDKWrapper - captureEvent:[RNSentryJSHangTracker eventWithTimeoutIntervalMs:timeoutIntervalMs - frames:frames - bundleDebugId:bundleDebugId]]; + SentryEvent *event = [RNSentryJSHangTracker eventWithTimeoutIntervalMs:timeoutIntervalMs + frames:frames + bundleDebugId:bundleDebugId]; + NSData *flamegraph = attachFlamegraph && traceData != nil + ? [RNSentryJSHangTracker flamegraphFromHermesTrace:traceData + newestFirst:newestFirst + bundleDebugId:bundleDebugId] + : nil; + if (flamegraph != nil) { + SentryAttachment *attachment = + [[SentryAttachment alloc] initWithData:flamegraph + filename:@"flamegraph.json" + contentType:@"application/json" + attachmentType:kSentryAttachmentTypeFlamegraph]; + [SentrySDKWrapper captureEvent:event attachment:attachment]; + } else { + [SentrySDKWrapper captureEvent:event]; + } } @catch (NSException *exception) { NSLog(@"[Sentry] Failed to report JS thread hang: %@", exception.reason); } @@ -240,26 +256,175 @@ - (void)reportHangWithTimeoutIntervalMs:(uint64_t)timeoutIntervalMs } } ++ (nullable NSData *)flamegraphFromHermesTrace:(NSData *)trace + newestFirst:(BOOL)newestFirst + bundleDebugId:(nullable NSString *)bundleDebugId +{ + @try { + NSDictionary *profile = [NSJSONSerialization JSONObjectWithData:trace options:0 error:nil]; + NSDictionary *stackFrames = profile[@"stackFrames"]; + NSArray *samples = profile[@"samples"]; + + NSString *attributedThreadId = nil; + NSEnumerator *ordered + = newestFirst ? samples.reverseObjectEnumerator : samples.objectEnumerator; + for (NSDictionary *sample in ordered) { + if ([self jsFrameIdsFromFrameId:sample[@"sf"] stackFrames:stackFrames].count > 0) { + attributedThreadId = [sample[@"tid"] description] ?: @""; + break; + } + } + + double newestTs = [samples.lastObject[@"ts"] doubleValue]; + double windowUs + = std::chrono::duration_cast(kStackSampleWindow).count(); + + NSMutableArray *frames = [NSMutableArray array]; + NSMutableDictionary *frameIndexes = + [NSMutableDictionary dictionary]; + NSMutableArray *nodes = [NSMutableArray array]; + NSMutableArray *> *nodeIndexesByFrame = + [NSMutableArray array]; + NSMutableArray *trees = [NSMutableArray array]; + NSMutableDictionary *treesByThread = + [NSMutableDictionary dictionary]; + NSMutableDictionary *> + *rootIndexesByThread = [NSMutableDictionary dictionary]; + + for (NSDictionary *sample in samples) { + if (newestFirst && newestTs - [sample[@"ts"] doubleValue] > windowUs) { + continue; + } + NSArray *frameIds = [self jsFrameIdsFromFrameId:sample[@"sf"] + stackFrames:stackFrames]; + if (frameIds.count == 0) { + continue; + } + + id tid = sample[@"tid"]; + NSString *threadId = [tid description] ?: @""; + NSMutableDictionary *tree = treesByThread[threadId]; + if (tree == nil) { + tree = [NSMutableDictionary dictionaryWithObject:[NSMutableArray array] + forKey:@"roots"]; + if (tid != nil) { + tree[@"thread_id"] = threadId; + } + if ([threadId isEqualToString:attributedThreadId]) { + tree[@"thread_attributed"] = @YES; + } + [trees addObject:tree]; + treesByThread[threadId] = tree; + rootIndexesByThread[threadId] = [NSMutableDictionary dictionary]; + } + + NSMutableArray *siblings = tree[@"roots"]; + NSMutableDictionary *siblingIndexesByFrame + = rootIndexesByThread[threadId]; + for (NSString *frameId in frameIds) { + NSNumber *frameIndex = frameIndexes[frameId]; + if (frameIndex == nil) { + frameIndex = @(frames.count); + [frames addObject:[self profileFrameFromHermesFrame:stackFrames[frameId]]]; + frameIndexes[frameId] = frameIndex; + } + + NSNumber *nodeIndex = siblingIndexesByFrame[frameIndex]; + if (nodeIndex == nil) { + nodeIndex = @(nodes.count); + [nodes addObject:[@{ + @"frame_id" : frameIndex, + @"sample_count" : @0, + @"children" : [NSMutableArray array], + } mutableCopy]]; + [nodeIndexesByFrame addObject:[NSMutableDictionary dictionary]]; + [siblings addObject:nodeIndex]; + siblingIndexesByFrame[frameIndex] = nodeIndex; + } + + NSMutableDictionary *node = nodes[nodeIndex.unsignedIntegerValue]; + node[@"sample_count"] = @([node[@"sample_count"] unsignedIntegerValue] + 1); + siblings = node[@"children"]; + siblingIndexesByFrame = nodeIndexesByFrame[nodeIndex.unsignedIntegerValue]; + } + } + + if (nodes.count == 0) { + return nil; + } + + NSMutableDictionary *flamegraph = [@{ + @"version" : @"1", + @"platform" : @"javascript", + @"frames" : frames, + @"nodes" : nodes, + @"trees" : trees, + } mutableCopy]; + if (bundleDebugId != nil) { + flamegraph[@"debug_meta"] = @{ + @"images" : @[ @{ + @"type" : @"sourcemap", + @"debug_id" : bundleDebugId, + @"code_file" : kBundleFileName, + } ] + }; + } + + NSData *data = [NSJSONSerialization dataWithJSONObject:flamegraph options:0 error:nil]; + return data.length <= kMaxFlamegraphBytes ? data : nil; + } @catch (NSException *exception) { + return nil; + } +} + + (NSArray *)framesFromFrameId:(nullable id)frameId stackFrames:(NSDictionary *)stackFrames { - // Hermes links each frame to its caller, so the walk goes from the top frame to the root. NSMutableArray *frames = [NSMutableArray array]; + for (NSString *jsFrameId in [self jsFrameIdsFromFrameId:frameId stackFrames:stackFrames]) { + [frames addObject:[self frameFromHermesFrame:stackFrames[jsFrameId]]]; + } + return frames; +} + +/// Returns the ids of the JS frames in the stack, from the caller to the callee. ++ (NSArray *)jsFrameIdsFromFrameId:(nullable id)frameId + stackFrames:(NSDictionary *)stackFrames +{ + // Hermes links each frame to its caller, so the walk goes from the top frame to the root. + NSMutableArray *frameIds = [NSMutableArray array]; for (NSUInteger depth = 0; frameId != nil && depth < stackFrames.count; depth++) { - NSDictionary *hermesFrame = stackFrames[[frameId description]]; + NSString *key = [frameId description]; + NSDictionary *hermesFrame = stackFrames[key]; if (hermesFrame == nil) { break; } - SentryFrame *frame = [self frameFromHermesFrame:hermesFrame]; - if (frame != nil) { - [frames insertObject:frame atIndex:0]; + if ([self profileFrameFromHermesFrame:hermesFrame] != nil) { + [frameIds insertObject:key atIndex:0]; } frameId = hermesFrame[@"parent"]; } - return frames; + return frameIds; } + (nullable SentryFrame *)frameFromHermesFrame:(NSDictionary *)hermesFrame +{ + NSDictionary *profileFrame = [self profileFrameFromHermesFrame:hermesFrame]; + if (profileFrame == nil) { + return nil; + } + + SentryFrame *frame = [[SentryFrame alloc] init]; + frame.platform = profileFrame[@"platform"]; + frame.fileName = profileFrame[@"filename"]; + frame.function = profileFrame[@"function"]; + frame.lineNumber = profileFrame[@"lineno"]; + frame.columnNumber = profileFrame[@"colno"]; + return frame; +} + +/// Maps a Hermes frame to a profile frame, which the event stack and the flame graph share. ++ (nullable NSDictionary *)profileFrameFromHermesFrame:(NSDictionary *)hermesFrame { NSString *name = hermesFrame[@"name"]; if (![hermesFrame[@"category"] isEqual:@"JavaScript"] || name == nil || @@ -267,25 +432,32 @@ + (nullable SentryFrame *)frameFromHermesFrame:(NSDictionary *)hermesFrame return nil; } - SentryFrame *frame = [[SentryFrame alloc] init]; - frame.platform = @"javascript"; - frame.fileName = kBundleFileName; + NSMutableDictionary *frame = [NSMutableDictionary dictionary]; + frame[@"platform"] = @"javascript"; + frame[@"filename"] = kBundleFileName; + frame[@"abs_path"] = kBundleFileName; NSRange paren = [name rangeOfString:@"("]; NSString *function = paren.location == NSNotFound ? name : [name substringToIndex:paren.location]; - frame.function = function.length > 0 ? function : nil; + if (function.length > 0) { + frame[@"function"] = function; + } id funcVirtAddr = hermesFrame[@"funcVirtAddr"]; id offset = hermesFrame[@"offset"]; if (funcVirtAddr != nil && offset != nil) { // Hermes bytecode has one line, and its column is 0-based while Sentry's is 1-based. - frame.lineNumber = @1; - frame.columnNumber = @([funcVirtAddr longLongValue] + [offset longLongValue] + 1); + frame[@"lineno"] = @1; + frame[@"colno"] = @([funcVirtAddr longLongValue] + [offset longLongValue] + 1); } else { id line = hermesFrame[@"line"]; id column = hermesFrame[@"column"]; - frame.lineNumber = line != nil ? @([line longLongValue]) : nil; - frame.columnNumber = column != nil ? @([column longLongValue]) : nil; + if (line != nil) { + frame[@"lineno"] = @([line longLongValue]); + } + if (column != nil) { + frame[@"colno"] = @([column longLongValue]); + } } return frame; } diff --git a/packages/core/ios/SentrySDKWrapper.h b/packages/core/ios/SentrySDKWrapper.h index 248f358918..d74a8ac154 100644 --- a/packages/core/ios/SentrySDKWrapper.h +++ b/packages/core/ios/SentrySDKWrapper.h @@ -1,5 +1,6 @@ #import +@class SentryAttachment; @class SentryEvent; @class SentryScope; @@ -9,6 +10,8 @@ + (void)captureEvent:(SentryEvent *)event; ++ (void)captureEvent:(SentryEvent *)event attachment:(SentryAttachment *)attachment; + + (void)crash; + (void)close; diff --git a/packages/core/ios/SentrySDKWrapper.m b/packages/core/ios/SentrySDKWrapper.m index 9095f4bb8c..16197cd4b8 100644 --- a/packages/core/ios/SentrySDKWrapper.m +++ b/packages/core/ios/SentrySDKWrapper.m @@ -10,6 +10,12 @@ + (void)captureEvent:(SentryEvent *)event [SentrySDK captureEvent:event]; } ++ (void)captureEvent:(SentryEvent *)event attachment:(SentryAttachment *)attachment +{ + [SentrySDK captureEvent:event + withScopeBlock:^(SentryScope *scope) { [scope addAttachment:attachment]; }]; +} + + (void)crash { [SentrySDK crash]; diff --git a/packages/core/src/js/NativeRNSentry.ts b/packages/core/src/js/NativeRNSentry.ts index 7710b3432f..a125b0d54d 100644 --- a/packages/core/src/js/NativeRNSentry.ts +++ b/packages/core/src/js/NativeRNSentry.ts @@ -77,6 +77,7 @@ export interface Spec extends TurboModule { resumeAppHangTracking(): void; startJsHangTracking(timeoutIntervalMs: number, bundleDebugId: string | null): void; stopJsHangTracking(): void; + setAttachJsHangFlamegraph(enabled: boolean): void; } export type NativeStackFrame = { diff --git a/packages/core/src/js/integrations/default.ts b/packages/core/src/js/integrations/default.ts index 91f9033743..6dc0081603 100644 --- a/packages/core/src/js/integrations/default.ts +++ b/packages/core/src/js/integrations/default.ts @@ -120,7 +120,12 @@ export function getDefaultIntegrations(options: ReactNativeClientOptions): Integ integrations.push(uiProfilingIntegration()); } if (options.enableJsHangTracking) { - integrations.push(jsHangTrackingIntegration({ timeoutIntervalSeconds: options.jsHangTimeoutInterval })); + integrations.push( + jsHangTrackingIntegration({ + timeoutIntervalSeconds: options.jsHangTimeoutInterval, + attachFlamegraph: options.attachJsHangFlamegraph, + }), + ); } } diff --git a/packages/core/src/js/integrations/jsHangTracking.ts b/packages/core/src/js/integrations/jsHangTracking.ts index 4bb038fbe7..e30b762045 100644 --- a/packages/core/src/js/integrations/jsHangTracking.ts +++ b/packages/core/src/js/integrations/jsHangTracking.ts @@ -20,8 +20,10 @@ const MIN_TIMEOUT_INTERVAL_SECONDS = 0.25; */ export const jsHangTrackingIntegration = ({ timeoutIntervalSeconds = DEFAULT_TIMEOUT_INTERVAL_SECONDS, + attachFlamegraph = false, }: { timeoutIntervalSeconds?: number; + attachFlamegraph?: boolean; } = {}): Integration => { let timeoutIntervalMs = DEFAULT_TIMEOUT_INTERVAL_SECONDS * 1000; if (!Number.isFinite(timeoutIntervalSeconds)) { @@ -49,6 +51,7 @@ export const jsHangTrackingIntegration = ({ debug.log(`[${INTEGRATION_NAME}] Not tracking JS hangs in development builds.`); return; } + NATIVE.setAttachJsHangFlamegraph(attachFlamegraph); NATIVE.startJsHangTracking(timeoutIntervalMs, getDebugMetadata()[0]?.debug_id ?? null); }); client.on('close', () => { diff --git a/packages/core/src/js/options.ts b/packages/core/src/js/options.ts index a956a3bfd5..d3d78d00f7 100644 --- a/packages/core/src/js/options.ts +++ b/packages/core/src/js/options.ts @@ -243,6 +243,21 @@ export interface BaseReactNativeOptions { */ jsHangTimeoutInterval?: number; + /** + * When enabled, the SDK attaches a flame graph of the sampled JavaScript stacks to the events + * of `enableJsHangTracking`. The flame graph shows where the JavaScript thread spent its time + * during the hang. It requires `enableJsHangTracking` and Hermes. + * + * The frames in the flame graph are not yet symbolicated with source maps. + * + * iOS only + * + * @default false + * @experimental + * @platform ios + */ + attachJsHangFlamegraph?: boolean; + /** * When enabled, the SDK uses sentry-native's heartbeat-based app-hang detection * to track when the application stops responding for a specific amount of time diff --git a/packages/core/src/js/wrapper.ts b/packages/core/src/js/wrapper.ts index 778fa003d4..f514886ce9 100644 --- a/packages/core/src/js/wrapper.ts +++ b/packages/core/src/js/wrapper.ts @@ -108,6 +108,7 @@ interface SentryNativeWrapper { resumeAppHangTracking(): void; startJsHangTracking(timeoutIntervalMs: number, bundleDebugId: string | null): void; stopJsHangTracking(): void; + setAttachJsHangFlamegraph(enabled: boolean): void; addBreadcrumb(breadcrumb: Breadcrumb): void; // oxlint-disable-next-line typescript-eslint(no-explicit-any) @@ -352,6 +353,7 @@ export const NATIVE: SentryNativeWrapper = { androidProfilingOptions, enableJsHangTracking, jsHangTimeoutInterval, + attachJsHangFlamegraph, ...remainingOptions } = options; /* oxlint-enable typescript-eslint(no-unused-vars) */ @@ -807,6 +809,22 @@ export const NATIVE: SentryNativeWrapper = { } }, + setAttachJsHangFlamegraph(enabled: boolean): void { + if ( + !this.enableNative || + !this._isModuleLoaded(RNSentry) || + typeof RNSentry.setAttachJsHangFlamegraph !== 'function' + ) { + return; + } + + try { + RNSentry.setAttachJsHangFlamegraph(enabled); + } catch (error) { + debug.error('[NATIVE] Set Attach JS Hang Flamegraph Failed', error); + } + }, + isNativeAvailable(): boolean { if (!RNSentry) { RNSentry = getRNSentryModule(); diff --git a/packages/core/test/integrations/defaultJsHangTracking.test.ts b/packages/core/test/integrations/defaultJsHangTracking.test.ts index d7eb45c134..3f65bd7fac 100644 --- a/packages/core/test/integrations/defaultJsHangTracking.test.ts +++ b/packages/core/test/integrations/defaultJsHangTracking.test.ts @@ -1,6 +1,12 @@ import type { ReactNativeClientOptions } from '../../src/js/options'; import { getDefaultIntegrations } from '../../src/js/integrations/default'; +import { jsHangTrackingIntegration } from '../../src/js/integrations/jsHangTracking'; + +jest.mock('../../src/js/integrations/jsHangTracking', () => { + const actual = jest.requireActual('../../src/js/integrations/jsHangTracking'); + return { jsHangTrackingIntegration: jest.fn(actual.jsHangTrackingIntegration) }; +}); const getIntegrationNames = (overrides: Partial): string[] => getDefaultIntegrations({ @@ -14,6 +20,12 @@ describe('getDefaultIntegrations - JS hang tracking integration', () => { expect(getIntegrationNames({ enableJsHangTracking: true })).toContain('JsHangTracking'); }); + it('passes the JS hang options to the integration', () => { + getIntegrationNames({ enableJsHangTracking: true, jsHangTimeoutInterval: 3, attachJsHangFlamegraph: true }); + + expect(jsHangTrackingIntegration).toHaveBeenCalledWith({ timeoutIntervalSeconds: 3, attachFlamegraph: true }); + }); + it('does not add the integration by default', () => { expect(getIntegrationNames({})).not.toContain('JsHangTracking'); }); diff --git a/packages/core/test/integrations/jsHangTracking.test.ts b/packages/core/test/integrations/jsHangTracking.test.ts index 41f80da186..1c5650b817 100644 --- a/packages/core/test/integrations/jsHangTracking.test.ts +++ b/packages/core/test/integrations/jsHangTracking.test.ts @@ -50,6 +50,7 @@ describe('jsHangTrackingIntegration', () => { client.emit('afterInit'); expect(NATIVE.startJsHangTracking).not.toHaveBeenCalled(); + expect(NATIVE.setAttachJsHangFlamegraph).not.toHaveBeenCalled(); }); it('does not start native tracking before the native SDK is initialized', () => { @@ -67,6 +68,27 @@ describe('jsHangTrackingIntegration', () => { expect(NATIVE.startJsHangTracking).toHaveBeenCalledWith(2000, DEBUG_IMAGE.debug_id); }); + it('does not attach a flame graph by default', () => { + const client = initClient(); + + // @ts-expect-error Only available on ReactNativeClient + client.emit('afterInit'); + + expect(NATIVE.setAttachJsHangFlamegraph).toHaveBeenCalledWith(false); + }); + + it('enables the flame graph attachment before it starts native tracking', () => { + const client = initClient(jsHangTrackingIntegration({ attachFlamegraph: true })); + + // @ts-expect-error Only available on ReactNativeClient + client.emit('afterInit'); + + expect(NATIVE.setAttachJsHangFlamegraph).toHaveBeenCalledWith(true); + const setterOrder = (NATIVE.setAttachJsHangFlamegraph as jest.Mock).mock.invocationCallOrder[0]; + const startOrder = (NATIVE.startJsHangTracking as jest.Mock).mock.invocationCallOrder[0]; + expect(setterOrder).toBeLessThan(startOrder); + }); + it('converts the timeout interval from seconds to milliseconds', () => { const client = initClient(jsHangTrackingIntegration({ timeoutIntervalSeconds: 0.5 })); @@ -120,5 +142,6 @@ describe('jsHangTrackingIntegration', () => { client.emit('afterInit'); expect(NATIVE.startJsHangTracking).not.toHaveBeenCalled(); + expect(NATIVE.setAttachJsHangFlamegraph).not.toHaveBeenCalled(); }); }); diff --git a/packages/core/test/mockWrapper.ts b/packages/core/test/mockWrapper.ts index dabc4555f9..b7e7b754c4 100644 --- a/packages/core/test/mockWrapper.ts +++ b/packages/core/test/mockWrapper.ts @@ -41,6 +41,7 @@ const NATIVE: MockInterface = { resumeAppHangTracking: jest.fn(), startJsHangTracking: jest.fn(), stopJsHangTracking: jest.fn(), + setAttachJsHangFlamegraph: jest.fn(), addBreadcrumb: jest.fn(), setContext: jest.fn(), diff --git a/packages/core/test/wrapper.test.ts b/packages/core/test/wrapper.test.ts index 24a0b60edf..ac7c5fd1ff 100644 --- a/packages/core/test/wrapper.test.ts +++ b/packages/core/test/wrapper.test.ts @@ -65,6 +65,7 @@ jest.mock('react-native', () => { resumeAppHangTracking: jest.fn(), startJsHangTracking: jest.fn(), stopJsHangTracking: jest.fn(), + setAttachJsHangFlamegraph: jest.fn(), startReplay: jest.fn(() => Promise.resolve()), startReplayBuffering: jest.fn(() => Promise.resolve()), stopReplay: jest.fn(() => Promise.resolve()), @@ -358,6 +359,7 @@ describe('Tests Native Wrapper', () => { autoInitializeNativeSdk: true, enableJsHangTracking: true, jsHangTimeoutInterval: 3, + attachJsHangFlamegraph: true, devServerUrl: undefined, defaultSidecarUrl: undefined, mobileReplayOptions: undefined, @@ -367,6 +369,7 @@ describe('Tests Native Wrapper', () => { const initParameter = RNSentry.initNativeSdk.mock.calls[0][0]; expect(initParameter).not.toHaveProperty('enableJsHangTracking'); expect(initParameter).not.toHaveProperty('jsHangTimeoutInterval'); + expect(initParameter).not.toHaveProperty('attachJsHangFlamegraph'); }); test('filter beforeBreadcrumb when initializing Native SDK', async () => { @@ -1684,29 +1687,52 @@ describe('Tests Native Wrapper', () => { expect(RNSentry.stopJsHangTracking).toHaveBeenCalled(); }); + test('setAttachJsHangFlamegraph passes the value to native', async () => { + await initNative(true); + + NATIVE.setAttachJsHangFlamegraph(true); + + expect(RNSentry.setAttachJsHangFlamegraph).toHaveBeenCalledWith(true); + }); + + test('setAttachJsHangFlamegraph does not throw when native throws', async () => { + await initNative(true); + (RNSentry.setAttachJsHangFlamegraph as jest.Mock).mockImplementationOnce(() => { + throw new Error('native error'); + }); + + expect(() => NATIVE.setAttachJsHangFlamegraph(true)).not.toThrow(); + }); + test('does not call native when enableNative is false', async () => { await initNative(false); NATIVE.startJsHangTracking(2000, null); NATIVE.stopJsHangTracking(); + NATIVE.setAttachJsHangFlamegraph(true); expect(RNSentry.startJsHangTracking).not.toHaveBeenCalled(); expect(RNSentry.stopJsHangTracking).not.toHaveBeenCalled(); + expect(RNSentry.setAttachJsHangFlamegraph).not.toHaveBeenCalled(); }); test('does not throw when an older native binary does not have the methods', async () => { await initNative(true); - const { startJsHangTracking, stopJsHangTracking } = RNSentry; + const { startJsHangTracking, stopJsHangTracking, setAttachJsHangFlamegraph } = RNSentry; // @ts-expect-error simulates an older native binary RNSentry.startJsHangTracking = undefined; // @ts-expect-error simulates an older native binary RNSentry.stopJsHangTracking = undefined; + // @ts-expect-error simulates an older native binary + RNSentry.setAttachJsHangFlamegraph = undefined; expect(() => NATIVE.startJsHangTracking(2000, null)).not.toThrow(); expect(() => NATIVE.stopJsHangTracking()).not.toThrow(); + expect(() => NATIVE.setAttachJsHangFlamegraph(true)).not.toThrow(); RNSentry.startJsHangTracking = startJsHangTracking; RNSentry.stopJsHangTracking = stopJsHangTracking; + RNSentry.setAttachJsHangFlamegraph = setAttachJsHangFlamegraph; }); }); diff --git a/samples/react-native/src/App.tsx b/samples/react-native/src/App.tsx index bdea5d6481..7475901636 100644 --- a/samples/react-native/src/App.tsx +++ b/samples/react-native/src/App.tsx @@ -81,6 +81,7 @@ Sentry.init({ enableUnhandledCPPExceptionsV2: true, }, enableJsHangTracking: true, + attachJsHangFlamegraph: true, logsOrigin: 'all', enableLogs: true, beforeSendLog: log => {