Skip to content

feat(browser): Add INP support for v8 #11650

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 13 commits into from
Apr 22, 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
4 changes: 2 additions & 2 deletions .size-limit.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ module.exports = [
path: 'packages/browser/build/npm/esm/index.js',
import: createImport('init', 'browserTracingIntegration', 'replayIntegration', 'feedbackIntegration'),
gzip: true,
limit: '86 KB',
limit: '87 KB',
},
{
name: '@sentry/browser (incl. Feedback)',
Expand Down Expand Up @@ -165,7 +165,7 @@ module.exports = [
path: createCDNPath('bundle.tracing.replay.feedback.min.js'),
gzip: false,
brotli: false,
limit: '261 KB',
limit: '264 KB',
},
// Next.js SDK (ESM)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const delay = e => {
const blockUI = e => {
const startTime = Date.now();

function getElasped() {
Expand All @@ -13,6 +13,6 @@ const delay = e => {
e.target.classList.add('clicked');
};

document.querySelector('[data-test-id=interaction-button]').addEventListener('click', delay);
document.querySelector('[data-test-id=annotated-button]').addEventListener('click', delay);
document.querySelector('[data-test-id=styled-button]').addEventListener('click', delay);
document.querySelector('[data-test-id=interaction-button]').addEventListener('click', blockUI);
document.querySelector('[data-test-id=annotated-button]').addEventListener('click', blockUI);
document.querySelector('[data-test-id=styled-button]').addEventListener('click', blockUI);
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,5 @@
<button data-test-id="interaction-button">Click Me</button>
<button data-test-id="annotated-button" data-sentry-component="AnnotatedButton" data-sentry-element="StyledButton">Click Me</button>
<button data-test-id="styled-button" data-sentry-element="StyledButton">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
@@ -1,6 +1,5 @@
import type { Route } from '@playwright/test';
import { expect } from '@playwright/test';
import type { Contexts, Event, SpanJSON } from '@sentry/types';
import type { Event as SentryEvent } from '@sentry/types';

import { sentryTest } from '../../../../utils/fixtures';
import {
Expand All @@ -9,33 +8,24 @@ import {
shouldSkipTracingTest,
} from '../../../../utils/helpers';

type TransactionJSON = SpanJSON & {
spans: SpanJSON[];
contexts: Contexts;
platform: string;
type: string;
};

const wait = (time: number) => new Promise(res => setTimeout(res, time));

sentryTest('should capture interaction transaction. @firefox', 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 getFirstSentryEnvelopeRequest<SentryEvent>(page);

const envelopesPromise = getMultipleSentryEnvelopeRequests<SentryEvent>(page, 1);

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

const envelopes = await getMultipleSentryEnvelopeRequests<TransactionJSON>(page, 1);
const envelopes = await envelopesPromise;

expect(envelopes).toHaveLength(1);

const eventData = envelopes[0];
Expand Down Expand Up @@ -64,18 +54,15 @@ sentryTest(
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 getFirstSentryEnvelopeRequest<SentryEvent>(page);

for (let i = 0; i < 4; i++) {
await wait(100);
const envelopePromise = getMultipleSentryEnvelopeRequests<SentryEvent>(page, 1);
await page.waitForTimeout(1000);
await page.locator('[data-test-id=interaction-button]').click();
const envelope = await getMultipleSentryEnvelopeRequests<Event>(page, 1);
const envelope = await envelopePromise;
expect(envelope[0].spans).toHaveLength(1);
}
},
Expand All @@ -90,18 +77,16 @@ sentryTest(
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 getFirstSentryEnvelopeRequest<SentryEvent>(page);

const envelopePromise = getMultipleSentryEnvelopeRequests<SentryEvent>(page, 1);

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

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

Expand All @@ -122,21 +107,19 @@ sentryTest(
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 getFirstSentryEnvelopeRequest<SentryEvent>(page);

const envelopesPromise = getMultipleSentryEnvelopeRequests<SentryEvent>(page, 1);

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

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

const eventData = envelopes[0];
expect(eventData.spans).toHaveLength(1);

const interactionSpan = eventData.spans![0];
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
integrations: [
Sentry.browserTracingIntegration({
idleTimeout: 1000,
enableLongTask: false,
enableInp: true,
}),
],
tracesSampleRate: 1,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const blockUI = (delay = 70) => e => {
const startTime = Date.now();

function getElasped() {
const time = Date.now();
return time - startTime;
}

while (getElasped() < delay) {
//
}

e.target.classList.add('clicked');
};

document.querySelector('[data-test-id=not-so-slow-button]').addEventListener('click', blockUI(300));
document.querySelector('[data-test-id=slow-button]').addEventListener('click', blockUI(450));
document.querySelector('[data-test-id=normal-button]').addEventListener('click', blockUI());
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div>Rendered Before Long Task</div>
<button data-test-id="slow-button" data-sentry-element="SlowButton">Slow</button>
<button data-test-id="not-so-slow-button" data-sentry-element="NotSoSlowButton">Not so slow</button>
<button data-test-id="normal-button" data-sentry-element="NormalButton">Click Me</button>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { expect } from '@playwright/test';
import type { Event as SentryEvent, SpanJSON } from '@sentry/types';

import { sentryTest } from '../../../../utils/fixtures';
import {
getFirstSentryEnvelopeRequest,
getMultipleSentryEnvelopeRequests,
shouldSkipTracingTest,
} from '../../../../utils/helpers';

sentryTest('should capture an INP click event span.', async ({ browserName, getLocalTestPath, page }) => {
const supportedBrowsers = ['chromium'];

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

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 getFirstSentryEnvelopeRequest<SentryEvent>(page); // wait for page load

const spanEnvelopesPromise = getMultipleSentryEnvelopeRequests<SpanJSON>(page, 1, {
envelopeType: 'span',
});

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

await page.waitForTimeout(500);

// Page hide to trigger INP
await page.evaluate(() => {
window.dispatchEvent(new Event('pagehide'));
});

// Get the INP span envelope
const spanEnvelopes = await spanEnvelopesPromise;

expect(spanEnvelopes).toHaveLength(1);
expect(spanEnvelopes[0].op).toBe('ui.interaction.click');
expect(spanEnvelopes[0].description).toBe('body > NormalButton');
expect(spanEnvelopes[0].exclusive_time).toBeGreaterThan(0);
expect(spanEnvelopes[0].measurements?.inp.value).toBeGreaterThan(0);
expect(spanEnvelopes[0].measurements?.inp.unit).toBe('millisecond');
});

sentryTest(
'should choose the slowest interaction click event when INP is triggered.',
async ({ browserName, getLocalTestPath, page }) => {
const supportedBrowsers = ['chromium'];

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

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 getFirstSentryEnvelopeRequest<SentryEvent>(page);

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

await page.waitForTimeout(500);

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

await page.waitForTimeout(500);

const spanEnvelopesPromise = getMultipleSentryEnvelopeRequests<SpanJSON>(page, 1, {
envelopeType: 'span',
});

// Page hide to trigger INP
await page.evaluate(() => {
window.dispatchEvent(new Event('pagehide'));
});

// Get the INP span envelope
const spanEnvelopes = await spanEnvelopesPromise;

expect(spanEnvelopes).toHaveLength(1);
expect(spanEnvelopes[0].op).toBe('ui.interaction.click');
expect(spanEnvelopes[0].description).toBe('body > SlowButton');
expect(spanEnvelopes[0].exclusive_time).toBeGreaterThan(400);
expect(spanEnvelopes[0].measurements?.inp.value).toBeGreaterThan(400);
expect(spanEnvelopes[0].measurements?.inp.unit).toBe('millisecond');
},
);
1 change: 1 addition & 0 deletions packages/browser-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export {
startTrackingInteractions,
startTrackingLongTasks,
startTrackingWebVitals,
startTrackingINP,
} from './metrics/browserMetrics';

export { addClickKeypressInstrumentationHandler } from './instrument/dom';
Expand Down
19 changes: 4 additions & 15 deletions packages/browser-utils/src/metrics/browserMetrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
addTtfbInstrumentationHandler,
} from './instrument';
import { WINDOW } from './types';
import { isMeasurementValue, startAndEndSpan } from './utils';
import { getBrowserPerformanceAPI, isMeasurementValue, msToSec, startAndEndSpan } from './utils';
import { getNavigationEntry } from './web-vitals/lib/getNavigationEntry';
import { getVisibilityWatcher } from './web-vitals/lib/getVisibilityWatcher';

Expand Down Expand Up @@ -58,19 +58,6 @@ interface NavigatorDeviceMemory {

const MAX_INT_AS_BYTES = 2147483647;

/**
* Converts from milliseconds to seconds
* @param time time in ms
*/
function msToSec(time: number): number {
return time / 1000;
}

function getBrowserPerformanceAPI(): Performance | undefined {
// @ts-expect-error we want to make sure all of these are available, even if TS is sure they are
return WINDOW && WINDOW.addEventListener && WINDOW.performance;
}

let _performanceCursor: number = 0;

let _measurements: Measurements = {};
Expand Down Expand Up @@ -170,6 +157,8 @@ export function startTrackingInteractions(): void {
});
}

export { startTrackingINP } from './inp';

/** Starts tracking the Cumulative Layout Shift on the current page. */
function _trackCLS(): () => void {
return addClsInstrumentationHandler(({ metric }) => {
Expand Down Expand Up @@ -226,7 +215,7 @@ function _trackTtfb(): () => void {
});
}

/** Add performance related spans to a span */
/** Add performance related spans to a transaction */
export function addPerformanceEntries(span: Span): void {
const performance = getBrowserPerformanceAPI();
if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {
Expand Down
Loading