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

feat(browser): Extract and send frontend component name when available #9855

Closed
wants to merge 14 commits into from
Closed
Show file tree
Hide file tree
Changes from 12 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
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@
<body>
<button id="button1" type="button">Button 1</button>
<button id="button2" type="button">Button 2</button>
<button id="annotated-button" type="button" data-sentry-component="AnnotatedButton">Button 3</button>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,39 @@ sentryTest('captures Breadcrumb for clicks & debounces them for a second', async
},
]);
});

sentryTest(
'uses the annotated component name in the breadcrumb messages and adds it to the data object',
async ({ getLocalTestUrl, page }) => {
const url = await getLocalTestUrl({ testDir: __dirname });

await page.route('**/foo', route => {
return route.fulfill({
status: 200,
body: JSON.stringify({
userNames: ['John', 'Jane'],
}),
headers: {
'Content-Type': 'application/json',
},
});
});

const promise = getFirstSentryEnvelopeRequest<Event>(page);

await page.goto(url);
await page.click('#annotated-button');
await page.evaluate('Sentry.captureException("test exception")');

const eventData = await promise;

expect(eventData.breadcrumbs).toEqual([
{
timestamp: expect.any(Number),
category: 'ui.click',
message: 'body > AnnotatedButton',
data: { componentName: 'AnnotatedButton' },
},
]);
},
);
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@
<body>
<input id="input1" type="text" />
<input id="input2" type="text" />
<input id="annotated-input" data-sentry-component="AnnotatedInput" type="text" />
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,48 @@ sentryTest('captures Breadcrumb for events on inputs & debounced them', async ({
},
]);
});

sentryTest(
'includes the annotated component name within the breadcrumb message and data',
async ({ getLocalTestUrl, page }) => {
const url = await getLocalTestUrl({ testDir: __dirname });

await page.route('**/foo', route => {
return route.fulfill({
status: 200,
body: JSON.stringify({
userNames: ['John', 'Jane'],
}),
headers: {
'Content-Type': 'application/json',
},
});
});

const promise = getFirstSentryEnvelopeRequest<Event>(page);

await page.goto(url);

await page.click('#annotated-input');
await page.type('#annotated-input', 'John', { delay: 1 });

await page.evaluate('Sentry.captureException("test exception")');
const eventData = await promise;
expect(eventData.exception?.values).toHaveLength(1);

expect(eventData.breadcrumbs).toEqual([
{
timestamp: expect.any(Number),
category: 'ui.click',
message: 'body > AnnotatedInput',
data: { componentName: 'AnnotatedInput' },
},
{
timestamp: expect.any(Number),
category: 'ui.input',
message: 'body > AnnotatedInput',
data: { componentName: 'AnnotatedInput' },
},
]);
},
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;
window.Replay = new Sentry.Replay({
flushMinDelay: 200,
flushMaxDelay: 200,
minReplayDuration: 0,
});

Sentry.init({
dsn: 'https://[email protected]/1337',
sampleRate: 0,
replaysSessionSampleRate: 1.0,
replaysOnErrorSampleRate: 0.0,

integrations: [window.Replay],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<button data-sentry-component="MyCoolButton" id="button">😎</button>
<input data-sentry-component="MyCoolInput" id="input" />
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { expect } from '@playwright/test';

import { sentryTest } from '../../../utils/fixtures';
import { getCustomRecordingEvents, shouldSkipReplayTest, waitForReplayRequest } from '../../../utils/replayHelpers';

sentryTest('captures component name attribute when available', async ({ forceFlushReplay, getLocalTestPath, page }) => {
if (shouldSkipReplayTest()) {
sentryTest.skip();
}

const reqPromise0 = waitForReplayRequest(page, 0);

await page.route('https://dsn.ingest.sentry.io/**/*', route => {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ id: 'test-id' }),
});
});

const url = await getLocalTestPath({ testDir: __dirname });

await page.goto(url);
await reqPromise0;
await forceFlushReplay();

const reqPromise1 = waitForReplayRequest(page, (event, res) => {
return getCustomRecordingEvents(res).breadcrumbs.some(breadcrumb => breadcrumb.category === 'ui.click');
});
const reqPromise2 = waitForReplayRequest(page, (event, res) => {
return getCustomRecordingEvents(res).breadcrumbs.some(breadcrumb => breadcrumb.category === 'ui.input');
});

await page.locator('#button').click();

await page.locator('#input').focus();
await page.keyboard.press('Control+A');
await page.keyboard.type('Hello', { delay: 10 });

await forceFlushReplay();
const { breadcrumbs } = getCustomRecordingEvents(await reqPromise1);
const { breadcrumbs: breadcrumbs2 } = getCustomRecordingEvents(await reqPromise2);

// Combine the two together
breadcrumbs2.forEach(breadcrumb => {
if (!breadcrumbs.some(b => b.category === breadcrumb.category && b.timestamp === breadcrumb.timestamp)) {
breadcrumbs.push(breadcrumb);
}
});

expect(breadcrumbs).toEqual([
{
timestamp: expect.any(Number),
type: 'default',
category: 'ui.click',
message: 'body > MyCoolButton',
data: {
nodeId: expect.any(Number),
node: {
attributes: { id: 'button', 'data-sentry-component': 'MyCoolButton' },
id: expect.any(Number),
tagName: 'button',
textContent: '**',
},
},
},
{
timestamp: expect.any(Number),
type: 'default',
category: 'ui.input',
message: 'body > MyCoolInput',
data: {
nodeId: expect.any(Number),
node: {
attributes: { id: 'input', 'data-sentry-component': 'MyCoolInput' },
id: expect.any(Number),
tagName: 'input',
textContent: '',
},
},
},
]);
});
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ const delay = e => {
};

document.querySelector('[data-test-id=interaction-button]').addEventListener('click', delay);
document.querySelector('[data-test-id=annotated-button]').addEventListener('click', delay);
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<body>
<div>Rendered Before Long Task</div>
<button data-test-id="interaction-button">Click Me</button>
<button data-test-id="annotated-button" data-sentry-component="AnnotatedButton">Click Me</button>
<script src="https://example.com/path/to/script.js"></script>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,35 @@ sentryTest(
}
},
);

sentryTest(
'should use the component name for a clicked element when it is available',
async ({ browserName, getLocalTestPath, page }) => {
const supportedBrowsers = ['chromium', 'firefox'];

if (shouldSkipTracingTest() || !supportedBrowsers.includes(browserName)) {
sentryTest.skip();
}

await page.route('**/path/to/script.js', (route: Route) =>
route.fulfill({ path: `${__dirname}/assets/script.js` }),
);

const url = await getLocalTestPath({ testDir: __dirname });

await page.goto(url);
await getFirstSentryEnvelopeRequest<Event>(page);

await page.locator('[data-test-id=annotated-button]').click();

const envelopes = await getMultipleSentryEnvelopeRequests<TransactionJSON>(page, 1);
expect(envelopes).toHaveLength(1);
const eventData = envelopes[0];

expect(eventData.spans).toHaveLength(1);

const interactionSpan = eventData.spans![0];
expect(interactionSpan.op).toBe('ui.interaction.click');
expect(interactionSpan.description).toBe('body > AnnotatedButton');
},
);
31 changes: 20 additions & 11 deletions packages/browser/src/integrations/breadcrumbs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
Integration,
} from '@sentry/types';
import type {
Breadcrumb,
FetchBreadcrumbData,
FetchBreadcrumbHint,
XhrBreadcrumbData,
Expand All @@ -22,6 +23,7 @@ import {
addFetchInstrumentationHandler,
addHistoryInstrumentationHandler,
addXhrInstrumentationHandler,
getComponentName,
getEventDescription,
htmlTreeAsString,
logger,
Expand Down Expand Up @@ -143,6 +145,7 @@ function addSentryBreadcrumb(event: SentryEvent): void {
function _domBreadcrumb(dom: BreadcrumbsOptions['dom']): (handlerData: HandlerDataDom) => void {
function _innerDomBreadcrumb(handlerData: HandlerDataDom): void {
let target;
let componentName;
let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;

let maxStringLength =
Expand All @@ -165,25 +168,31 @@ function _domBreadcrumb(dom: BreadcrumbsOptions['dom']): (handlerData: HandlerDa
target = _isEvent(event)
? htmlTreeAsString(event.target, { keyAttrs, maxStringLength })
: htmlTreeAsString(event, { keyAttrs, maxStringLength });

componentName = _isEvent(event) ? getComponentName(event.target) : getComponentName(event);
} catch (e) {
target = '<unknown>';
componentName = null;
Copy link
Contributor

Choose a reason for hiding this comment

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

This line is unnecessary

}

if (target.length === 0) {
return;
}

getCurrentHub().addBreadcrumb(
{
category: `ui.${handlerData.name}`,
message: target,
},
{
event: handlerData.event,
name: handlerData.name,
global: handlerData.global,
},
);
const breadcrumb: Breadcrumb = {
category: `ui.${handlerData.name}`,
message: target,
};

if (componentName) {
breadcrumb.data = { componentName };
}

getCurrentHub().addBreadcrumb(breadcrumb, {
event: handlerData.event,
name: handlerData.name,
global: handlerData.global,
});
}

return _innerDomBreadcrumb;
Expand Down
5 changes: 5 additions & 0 deletions packages/react/src/profiler.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ class Profiler extends React.Component<ProfilerProps> {
description: `<${name}>`,
op: REACT_MOUNT_OP,
origin: 'auto.ui.react.profiler',
data: { 'ui.component_name': name },
});
}
}
Expand All @@ -87,6 +88,7 @@ class Profiler extends React.Component<ProfilerProps> {
this._updateSpan = this._mountSpan.startChild({
data: {
changedProps,
'ui.component_name': this.props.name,
},
description: `<${this.props.name}>`,
op: REACT_UPDATE_OP,
Expand Down Expand Up @@ -120,6 +122,7 @@ class Profiler extends React.Component<ProfilerProps> {
op: REACT_RENDER_OP,
origin: 'auto.ui.react.profiler',
startTimestamp: this._mountSpan.endTimestamp,
data: { 'ui.component_name': name },
});
}
}
Expand Down Expand Up @@ -184,6 +187,7 @@ function useProfiler(
description: `<${name}>`,
op: REACT_MOUNT_OP,
origin: 'auto.ui.react.profiler',
data: { 'ui.component_name': name },
});
}

Expand All @@ -203,6 +207,7 @@ function useProfiler(
op: REACT_RENDER_OP,
origin: 'auto.ui.react.profiler',
startTimestamp: mountSpan.endTimestamp,
data: { 'ui.component_name': name },
});
}
};
Expand Down
Loading