Skip to content

feat(redux): Add 'attachReduxState' option #8953

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

Merged
merged 8 commits into from
Sep 11, 2023
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
26 changes: 25 additions & 1 deletion packages/react/src/redux.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { configureScope, getCurrentHub } from '@sentry/browser';
import { addGlobalEventProcessor, configureScope, getCurrentHub } from '@sentry/browser';
import type { Scope } from '@sentry/types';
import { addNonEnumerableProperty } from '@sentry/utils';

Expand Down Expand Up @@ -49,6 +49,12 @@ type StoreEnhancerStoreCreator<Ext = Record<string, unknown>, StateExt = never>
) => Store<ExtendState<S, StateExt>, A, StateExt, Ext> & Ext;

export interface SentryEnhancerOptions<S = any> {
/**
* Redux state in attachments or not.
* @default true
*/
attachReduxState?: boolean;

/**
* Transforms the state before attaching it to an event.
* Use this to remove any private data before sending it to Sentry.
Expand All @@ -71,6 +77,7 @@ const ACTION_BREADCRUMB_CATEGORY = 'redux.action';
const ACTION_BREADCRUMB_TYPE = 'info';

const defaultOptions: SentryEnhancerOptions = {
attachReduxState: true,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure we can default this to be true because attachments have their own quota. Thoughts @HazAT?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm I think it's fine - Redux while popular is not in every React app - and this feature is very helpful.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright let's :shipit: after we get some tests in @malay44!

actionTransformer: action => action,
stateTransformer: state => state || null,
};
Expand All @@ -89,6 +96,23 @@ function createReduxEnhancer(enhancerOptions?: Partial<SentryEnhancerOptions>):

return (next: StoreEnhancerStoreCreator): StoreEnhancerStoreCreator =>
<S = any, A extends Action = AnyAction>(reducer: Reducer<S, A>, initialState?: PreloadedState<S>) => {
options.attachReduxState &&
addGlobalEventProcessor((event, hint) => {
try {
// @ts-expect-error try catch to reduce bundle size
if (event.type === undefined && event.contexts.state.state.type === 'redux') {
hint.attachments = [
...(hint.attachments || []),
// @ts-expect-error try catch to reduce bundle size
{ filename: 'redux_state.json', data: JSON.stringify(event.contexts.state.state.value) },
];
}
} catch (_) {
// empty
}
return event;
});

const sentryReducer: Reducer<S, A> = (state, action): S => {
const newState = reducer(state, action);

Expand Down
170 changes: 170 additions & 0 deletions packages/react/test/redux.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,15 @@ jest.mock('@sentry/browser', () => ({
addBreadcrumb: mockAddBreadcrumb,
setContext: mockSetContext,
}),
addGlobalEventProcessor: jest.fn(),
}));

const mockAddGlobalEventProcessor = Sentry.addGlobalEventProcessor as jest.Mock;

afterEach(() => {
mockAddBreadcrumb.mockReset();
mockSetContext.mockReset();
mockAddGlobalEventProcessor.mockReset();
});

describe('createReduxEnhancer', () => {
Expand Down Expand Up @@ -243,4 +247,170 @@ describe('createReduxEnhancer', () => {
value: 'latest',
});
});

describe('Redux State Attachments', () => {
it('attaches Redux state to Sentry scope', () => {
const enhancer = createReduxEnhancer();

const initialState = {
value: 'initial',
};

Redux.createStore((state = initialState) => state, enhancer);

expect(mockAddGlobalEventProcessor).toHaveBeenCalledTimes(1);

const callbackFunction = mockAddGlobalEventProcessor.mock.calls[0][0];

const mockEvent = {
contexts: {
state: {
state: {
type: 'redux',
value: 'UPDATED_VALUE',
},
},
},
};

const mockHint = {
attachments: [],
};

const result = callbackFunction(mockEvent, mockHint);

expect(result).toEqual({
...mockEvent,
contexts: {
state: {
state: {
type: 'redux',
value: 'UPDATED_VALUE',
},
},
},
});

expect(mockHint.attachments).toHaveLength(1);
expect(mockHint.attachments[0]).toEqual({
filename: 'redux_state.json',
data: JSON.stringify('UPDATED_VALUE'),
});
});

it('does not attach when attachReduxState is false', () => {
const enhancer = createReduxEnhancer({ attachReduxState: false });

const initialState = {
value: 'initial',
};

Redux.createStore((state = initialState) => state, enhancer);

expect(mockAddGlobalEventProcessor).toHaveBeenCalledTimes(0);
});

it('does not attach when state.type is not redux', () => {
const enhancer = createReduxEnhancer();

const initialState = {
value: 'initial',
};

Redux.createStore((state = initialState) => state, enhancer);

expect(mockAddGlobalEventProcessor).toHaveBeenCalledTimes(1);

const callbackFunction = mockAddGlobalEventProcessor.mock.calls[0][0];

const mockEvent = {
contexts: {
state: {
state: {
type: 'not_redux',
value: 'UPDATED_VALUE',
},
},
},
};

const mockHint = {
attachments: [],
};

const result = callbackFunction(mockEvent, mockHint);

expect(result).toEqual(mockEvent);

expect(mockHint.attachments).toHaveLength(0);
});

it('does not attach when state is undefined', () => {
const enhancer = createReduxEnhancer();

const initialState = {
value: 'initial',
};

Redux.createStore((state = initialState) => state, enhancer);

expect(mockAddGlobalEventProcessor).toHaveBeenCalledTimes(1);

const callbackFunction = mockAddGlobalEventProcessor.mock.calls[0][0];

const mockEvent = {
contexts: {
state: {
state: undefined,
},
},
};

const mockHint = {
attachments: [],
};

const result = callbackFunction(mockEvent, mockHint);

expect(result).toEqual(mockEvent);

expect(mockHint.attachments).toHaveLength(0);
});

it('does not attach when event type is not undefined', () => {
const enhancer = createReduxEnhancer();

const initialState = {
value: 'initial',
};

Redux.createStore((state = initialState) => state, enhancer);

expect(mockAddGlobalEventProcessor).toHaveBeenCalledTimes(1);

const callbackFunction = mockAddGlobalEventProcessor.mock.calls[0][0];

const mockEvent = {
type: 'not_redux',
contexts: {
state: {
state: {
type: 'redux',
value: 'UPDATED_VALUE',
},
},
},
};

const mockHint = {
attachments: [],
};

const result = callbackFunction(mockEvent, mockHint);

expect(result).toEqual(mockEvent);

expect(mockHint.attachments).toHaveLength(0);
});
});
});
8 changes: 8 additions & 0 deletions packages/types/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ export interface Contexts extends Record<string, Context | undefined> {
response?: ResponseContext;
trace?: TraceContext;
cloud_resource?: CloudResourceContext;
state?: StateContext;
}

export interface StateContext extends Record<string, unknown> {
state: {
type: string;
value: Record<string, unknown>;
};
}

export interface AppContext extends Record<string, unknown> {
Expand Down