Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): Breadcrumbs added on forked context are now captured #4124

Merged
merged 34 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
494a619
Adds breadcrumb origin in RNSentryBreadcrumb dictionary parsing
antonis Sep 27, 2024
cc0b364
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Oct 8, 2024
a636be5
Use 8.38.0-beta.1 Cocoa SDK that has the new origin field
antonis Oct 8, 2024
522897a
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Oct 9, 2024
197f863
Adds changelog
antonis Oct 9, 2024
9bee5c9
Fixes sentry-java breaking changes
antonis Oct 9, 2024
6268a43
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Oct 10, 2024
6095218
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Oct 11, 2024
0e43c5d
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Oct 15, 2024
8832cf9
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Oct 15, 2024
7a108ee
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Oct 16, 2024
aff18bf
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Oct 23, 2024
611cd97
Adds origin native tests
antonis Oct 23, 2024
37553f2
Adds Capture exception with breadcrumb in the sample
antonis Oct 23, 2024
24a527b
Set react native as event origin
antonis Oct 28, 2024
fabf052
Filter out events with react-native origin from the native layer
antonis Oct 28, 2024
d0b1633
Merge event breadcrumbs with native context
antonis Oct 28, 2024
5d2711c
Lint: removes empty line
antonis Oct 28, 2024
fb0057d
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Oct 31, 2024
78c24f0
Use predicate to filter breadcrumbs
antonis Oct 31, 2024
6fcd93d
Respect max breadcrumbs limit
antonis Oct 31, 2024
80add4f
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Nov 1, 2024
44e02ec
Updates changelog
antonis Nov 1, 2024
a2d29de
Update test names
antonis Nov 1, 2024
52c9e54
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Nov 6, 2024
81a11c3
Fixes lint issue
antonis Nov 6, 2024
f828fc7
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Nov 6, 2024
67bd716
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Nov 7, 2024
c4246d7
Keep the last maxBreadcrumbs (default 100) when merging native and js…
antonis Nov 7, 2024
17e2201
Use client from function parameter
antonis Nov 11, 2024
fef2173
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Nov 11, 2024
76285fa
Refactor and test RNSentryModuleImpl.fetchNativeDeviceContexts (#4253)
antonis Nov 11, 2024
6ea1fe1
Merge branch 'main' into antonis/add-breadcrumb-origin
antonis Nov 18, 2024
af1ab5a
Move changelog to unreleased section
antonis Nov 18, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

### Fixes

- Prevents exception capture context from being overwritten by native scope sync ([#4124](https://github.com/getsentry/sentry-react-native/pull/4124))
antonis marked this conversation as resolved.
Show resolved Hide resolved
- Skips ignoring require cycle logs for RN 0.70 or newer ([#4214](https://github.com/getsentry/sentry-react-native/pull/4214))
- Enhanced accuracy of time-to-display spans. ([#4189](https://github.com/getsentry/sentry-react-native/pull/4189))

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.sentry.rnsentryandroidtester

import com.facebook.react.bridge.JavaOnlyMap
import io.sentry.SentryLevel
import io.sentry.react.RNSentryBreadcrumb
import junit.framework.TestCase.assertEquals
import org.junit.Test
Expand All @@ -10,6 +11,38 @@ import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class RNSentryBreadcrumbTest {

@Test
fun generatesSentryBreadcrumbFromMap() {
val testData = JavaOnlyMap.of(
"test", "data",
)
val map = JavaOnlyMap.of(
"level", "error",
"category", "testCategory",
"origin", "testOrigin",
"type", "testType",
"message", "testMessage",
"data", testData,
)
val actual = RNSentryBreadcrumb.fromMap(map)
assertEquals(SentryLevel.ERROR, actual.level)
assertEquals("testCategory", actual.category)
assertEquals("testOrigin", actual.origin)
assertEquals("testType", actual.type)
assertEquals("testMessage", actual.message)
assertEquals(testData.toHashMap(), actual.data)
}

@Test
fun reactNativeForMissingOrigin() {
val map = JavaOnlyMap.of(
"message", "testMessage",
)
val actual = RNSentryBreadcrumb.fromMap(map)
assertEquals("testMessage", actual.message)
assertEquals("react-native", actual.origin)
}

@Test
fun nullForMissingCategory() {
val map = JavaOnlyMap.of()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
33AFDFED2B8D14B300AAB120 /* RNSentryFramesTrackerListenerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 33AFDFEC2B8D14B300AAB120 /* RNSentryFramesTrackerListenerTests.m */; };
33AFDFF12B8D15E500AAB120 /* RNSentryDependencyContainerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 33AFDFF02B8D15E500AAB120 /* RNSentryDependencyContainerTests.m */; };
33F58AD02977037D008F60EA /* RNSentryTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 33F58ACF2977037D008F60EA /* RNSentryTests.mm */; };
AEFB00422CC90C4B00EC8A9A /* RNSentryBreadcrumbTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3360843C2C340C76008CC412 /* RNSentryBreadcrumbTests.swift */; };
B5859A50A3E865EF5E61465A /* libPods-RNSentryCocoaTesterTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 650CB718ACFBD05609BF2126 /* libPods-RNSentryCocoaTesterTests.a */; };
/* End PBXBuildFile section */

Expand Down Expand Up @@ -212,6 +213,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
AEFB00422CC90C4B00EC8A9A /* RNSentryBreadcrumbTests.swift in Sources */,
33AFDFF12B8D15E500AAB120 /* RNSentryDependencyContainerTests.m in Sources */,
336084392C32E382008CC412 /* RNSentryReplayBreadcrumbConverterTests.swift in Sources */,
33F58AD02977037D008F60EA /* RNSentryTests.mm in Sources */,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import XCTest
import Sentry

class RNSentryBreadcrumbTests: XCTestCase {
final class RNSentryBreadcrumbTests: XCTestCase {

func testGeneratesSentryBreadcrumbFromNSDictionary() {
let actualCrumb = RNSentryBreadcrumb.from([
"level": "error",
"category": "testCategory",
"origin": "testOrigin",
"type": "testType",
"message": "testMessage",
"data": [
Expand All @@ -16,11 +17,29 @@ class RNSentryBreadcrumbTests: XCTestCase {

XCTAssertEqual(actualCrumb!.level, SentryLevel.error)
XCTAssertEqual(actualCrumb!.category, "testCategory")
XCTAssertEqual(actualCrumb!.origin, "testOrigin")
XCTAssertEqual(actualCrumb!.type, "testType")
XCTAssertEqual(actualCrumb!.message, "testMessage")
XCTAssertEqual((actualCrumb!.data)!["test"] as! String, "data")
}

func testUsesReactNativeAsDefaultOrigin() {
let actualCrumb = RNSentryBreadcrumb.from([
"message": "testMessage"
])

XCTAssertEqual(actualCrumb!.origin, "react-native")
}

func testKeepsOriginIfSet() {
let actualCrumb = RNSentryBreadcrumb.from([
"message": "testMessage",
"origin": "someOrigin"
])

XCTAssertEqual(actualCrumb!.origin, "someOrigin")
}

func testUsesInfoAsDefaultSentryLevel() {
let actualCrumb = RNSentryBreadcrumb.from([
"message": "testMessage"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ public static Breadcrumb fromMap(ReadableMap from) {
breadcrumb.setCategory(from.getString("category"));
}

if (from.hasKey("origin")) {
breadcrumb.setOrigin(from.getString("origin"));
} else {
breadcrumb.setOrigin("react-native");
}

if (from.hasKey("level")) {
switch (from.getString("level")) {
case "fatal":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import io.sentry.Breadcrumb;
import io.sentry.HubAdapter;
import io.sentry.ILogger;
import io.sentry.IScope;
Expand Down Expand Up @@ -76,6 +77,7 @@
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
Expand Down Expand Up @@ -905,6 +907,17 @@ public void fetchNativeDeviceContexts(Promise promise) {
}

final @Nullable IScope currentScope = InternalSentrySdk.getCurrentScope();
if (currentScope != null) {
// Remove react-native breadcrumbs
Iterator<Breadcrumb> breadcrumbsIterator = currentScope.getBreadcrumbs().iterator();
while (breadcrumbsIterator.hasNext()) {
Breadcrumb breadcrumb = breadcrumbsIterator.next();
if ("react-native".equals(breadcrumb.getOrigin())) {
breadcrumbsIterator.remove();
}
}
}
krystofwoldrich marked this conversation as resolved.
Show resolved Hide resolved

final @NotNull Map<String, Object> serialized =
InternalSentrySdk.serializeScope(context, (SentryAndroidOptions) options, currentScope);
final @Nullable Object deviceContext = RNSentryMapConverter.convertToWritable(serialized);
Expand Down
10 changes: 10 additions & 0 deletions packages/core/ios/RNSentry.mm
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,16 @@ - (NSDictionary *)fetchNativeStackFramesBy:(NSArray<NSNumber *> *)instructionsAd

[serializedScope setValue:contexts forKey:@"contexts"];
[serializedScope removeObjectForKey:@"context"];

// Remove react-native breadcrumbs
NSPredicate *removeRNBreadcrumbsPredicate =
[NSPredicate predicateWithBlock:^BOOL(NSDictionary *breadcrumb, NSDictionary *bindings) {
return ![breadcrumb[@"origin"] isEqualToString:@"react-native"];
}];
NSArray *breadcrumbs = [[serializedScope[@"breadcrumbs"] mutableCopy]
filteredArrayUsingPredicate:removeRNBreadcrumbsPredicate];
[serializedScope setValue:breadcrumbs forKey:@"breadcrumbs"];

resolve(serializedScope);
}

Expand Down
6 changes: 6 additions & 0 deletions packages/core/ios/RNSentryBreadcrumb.m
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ + (SentryBreadcrumb *)from:(NSDictionary *)dict

[crumb setLevel:sentryLevel];
[crumb setCategory:dict[@"category"]];
id origin = dict[@"origin"];
if (origin != nil) {
[crumb setOrigin:origin];
} else {
[crumb setOrigin:@"react-native"];
}
[crumb setType:dict[@"type"]];
[crumb setMessage:dict[@"message"]];
[crumb setData:dict[@"data"]];
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/js/integrations/devicecontext.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint-disable complexity */
import { getClient } from '@sentry/core';
import type { Event, Integration } from '@sentry/types';
import { logger, severityLevelFromString } from '@sentry/utils';
import { AppState } from 'react-native';
Expand Down Expand Up @@ -83,7 +84,8 @@ async function processEvent(event: Event): Promise<Event> {
? native['breadcrumbs'].map(breadcrumbFromObject)
: undefined;
if (nativeBreadcrumbs) {
event.breadcrumbs = nativeBreadcrumbs;
const maxBreadcrumbs = getClient()?.getOptions().maxBreadcrumbs ?? 100; // Default is 100.
antonis marked this conversation as resolved.
Show resolved Hide resolved
event.breadcrumbs = nativeBreadcrumbs.concat(event.breadcrumbs || []).slice(0, maxBreadcrumbs);
krystofwoldrich marked this conversation as resolved.
Show resolved Hide resolved
}

return event;
Expand Down
58 changes: 54 additions & 4 deletions packages/core/test/integrations/devicecontext.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getClient } from '@sentry/core';
import type { Client, Event, EventHint, SeverityLevel } from '@sentry/types';

import { deviceContextIntegration } from '../../src/js/integrations/devicecontext';
Expand All @@ -12,6 +13,13 @@ jest.mock('react-native', () => ({
NativeModules: {},
Platform: {},
}));
jest.mock('@sentry/core', () => ({
getClient: jest.fn().mockReturnValue({
getOptions: jest.fn().mockReturnValue({
maxBreadcrumbs: 100, // Default value
}),
}),
}));

describe('Device Context Integration', () => {
it('add native user', async () => {
Expand Down Expand Up @@ -158,13 +166,55 @@ describe('Device Context Integration', () => {
).expectEvent.toStrictEqualMockEvent();
});

it('use only native breadcrumbs', async () => {
it('merge native and event breadcrumbs', async () => {
const { processedEvent } = await processEventWith({
nativeContexts: { breadcrumbs: [{ message: 'native-breadcrumb-1' }, { message: 'native-breadcrumb-2' }] },
mockEvent: { breadcrumbs: [{ message: 'event-breadcrumb-1' }, { message: 'event-breadcrumb-2' }] },
});
expect(processedEvent).toStrictEqual({
breadcrumbs: [
{ message: 'native-breadcrumb-1' },
{ message: 'native-breadcrumb-2' },
{ message: 'event-breadcrumb-1' },
{ message: 'event-breadcrumb-2' },
],
});
});

it('use only native breadcrumb if the maxBreadcrumbs limit does not leave space for event breadcrumbs', async () => {
getClient().getOptions().maxBreadcrumbs = 1;
const { processedEvent } = await processEventWith({
nativeContexts: { breadcrumbs: [{ message: 'native-breadcrumb' }] },
mockEvent: { breadcrumbs: [{ message: 'event-breadcrumb' }] },
});
expect(processedEvent).toStrictEqual({
breadcrumbs: [{ message: 'native-breadcrumb' }],
});
});

it('use native breadcrumbs and pick only the event breadcrumbs that fit the maxBreadcrumbs limit', async () => {
getClient().getOptions().maxBreadcrumbs = 3;
const { processedEvent } = await processEventWith({
nativeContexts: { breadcrumbs: [{ message: 'native-breadcrumb-1' }, { message: 'native-breadcrumb-2' }] },
mockEvent: { breadcrumbs: [{ message: 'event-breadcrumb-1' }, { message: 'event-breadcrumb-2' }] },
});
expect(processedEvent).toStrictEqual({
breadcrumbs: [
{ message: 'native-breadcrumb-1' },
{ message: 'native-breadcrumb-2' },
{ message: 'event-breadcrumb-1' },
],
});
});

it('do not use any breadcrumbs if the maxBreadcrumbs limit is set to zero', async () => {
getClient().getOptions().maxBreadcrumbs = 0;
const { processedEvent } = await processEventWith({
nativeContexts: { breadcrumbs: [{ message: 'duplicate-breadcrumb' }, { message: 'native-breadcrumb' }] },
mockEvent: { breadcrumbs: [{ message: 'duplicate-breadcrumb' }, { message: 'event-breadcrumb' }] },
nativeContexts: { breadcrumbs: [{ message: 'native-breadcrumb' }] },
mockEvent: { breadcrumbs: [{ message: 'event-breadcrumb' }] },
});
expect(processedEvent).toStrictEqual({
breadcrumbs: [{ message: 'duplicate-breadcrumb' }, { message: 'native-breadcrumb' }],
breadcrumbs: [],
});
});

Expand Down
7 changes: 7 additions & 0 deletions samples/react-native/src/Screens/ErrorsScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,13 @@ const ErrorsScreen = (_props: Props) => {
Sentry.captureException(error);
}}
/>
<Button
title="Capture exception with breadcrumb"
onPress={() => {
Sentry.captureException(new Error('Captured exception with breadcrumb'),
context => context.addBreadcrumb({ message: 'error with breadcrumb' }));
krystofwoldrich marked this conversation as resolved.
Show resolved Hide resolved
}}
/>
<Button
title="Uncaught Thrown Error"
onPress={() => {
Expand Down
Loading