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(perf): Cancel spans in background doesn't crash in environments without AppState #3727

Merged
merged 1 commit into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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 @@ -9,6 +9,7 @@
### Fixes

- Do not enable NativeFramesTracking when native is not available ([#3705](https://github.com/getsentry/sentry-react-native/pull/3705))
- Cancel spans in background doesn't crash in environments without AppState ([#3727](https://github.com/getsentry/sentry-react-native/pull/3727))

### Dependencies

Expand Down
34 changes: 22 additions & 12 deletions src/js/tracing/transaction.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type BeforeFinishCallback, type IdleTransaction } from '@sentry/core';
import { logger } from '@sentry/utils';
import type { AppStateStatus } from 'react-native';
import type { AppStateStatus, NativeEventSubscription } from 'react-native';
import { AppState } from 'react-native';

/**
Expand All @@ -22,15 +22,25 @@ export const onlySampleIfChildSpans: BeforeFinishCallback = (transaction: IdleTr
* Hooks on AppState change to cancel the transaction if the app goes background.
*/
export const cancelInBackground = (transaction: IdleTransaction): void => {
const subscription = AppState.addEventListener('change', (newState: AppStateStatus) => {
if (newState === 'background') {
logger.debug(`Setting ${transaction.op} transaction to cancelled because the app is in the background.`);
transaction.setStatus('cancelled');
transaction.finish();
}
});
transaction.registerBeforeFinishCallback(() => {
logger.debug(`Removing AppState listener for ${transaction.op} transaction.`);
subscription.remove();
});
if (!AppState || !AppState.isAvailable) {
logger.warn('AppState is not available, spans will not be canceled in background.');
return;
}

// RN Web can return undefined, https://github.com/necolas/react-native-web/blob/8cf720f0e57c74a254bfa7bed0313e33a4b29c11/packages/react-native-web/src/exports/AppState/index.js#L55
const subscription: NativeEventSubscription | undefined = AppState.addEventListener(
'change',
(newState: AppStateStatus) => {
if (newState === 'background') {
logger.debug(`Setting ${transaction.op} transaction to cancelled because the app is in the background.`);
transaction.setStatus('cancelled');
transaction.finish();
}
},
);
subscription &&
transaction.registerBeforeFinishCallback(() => {
logger.debug(`Removing AppState listener for ${transaction.op} transaction.`);
subscription && subscription.remove && subscription.remove();
});
};
27 changes: 27 additions & 0 deletions test/tracing/reactnativetracing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,13 @@ describe('ReactNativeTracing', () => {
beforeEach(() => {
jest.useFakeTimers();
NATIVE.enableNative = true;
mockedAppState.isAvailable = true;
mockedAppState.addEventListener = (_, listener) => {
mockedAppState.listener = listener;
return {
remove: mockedAppState.removeSubscription,
};
};
});

afterEach(() => {
Expand Down Expand Up @@ -357,6 +364,26 @@ describe('ReactNativeTracing', () => {
expect(mockedAppState.removeSubscription).toBeCalledTimes(1);
});

it('Does not crash when AppState is not available', async () => {
mockedAppState.isAvailable = false;
mockedAppState.addEventListener = (() => {
return undefined;
}) as unknown as (typeof mockedAppState)['addEventListener']; // RN Web can return undefined
const integration = new ReactNativeTracing();

mockAppStartResponse({ cold: false });

const mockHub = getMockHub();
integration.setupOnce(addGlobalEventProcessor, () => mockHub);

await jest.advanceTimersByTimeAsync(500);
const transaction = mockHub.getScope()?.getTransaction();

jest.runAllTimers();

expect(transaction?.endTimestamp).toBeDefined();
});

it('Does not add app start measurement if more than 60s', async () => {
const integration = new ReactNativeTracing();

Expand Down
Loading