Skip to content

Commit

Permalink
feat(tracing): Expose new browserTracingIntegration (#10351)
Browse files Browse the repository at this point in the history
Extracted this out of
#10327.

This PR:

* Introduces a new `browserTracingIntegration()`
* Does NOT deprecate BrowserTracing yet, as custom implementations in
Angular, Next, Sveltekit have not been migrated over yet, which would be
weird. We can deprecate it once we moved these over.
* Makes sure that custom implementations in Next & Sveltekit are "fixed"
automatically
* Uses a slim fork for the CDN bundles, to avoid shipping multiple
implementations in there.
* This means that in the CDN bundles, you can already use the new
syntax, but you cannot pass a custom routing instrumentation anymore,
and you also don't have the utility functions for it yet. I think this
is the best tradeoff for now, and it's probably not a super common case
to have custom routing instrumentation when using the Loader/CDN bundles
(and if you do, you have to stick to `new BrowserTracing()` until v8).

I copied the browser integration tests we have, which all pass!
  • Loading branch information
mydea committed Jan 26, 2024
1 parent 2879478 commit adccbe6
Show file tree
Hide file tree
Showing 81 changed files with 2,008 additions and 139 deletions.
7 changes: 7 additions & 0 deletions .size-limit.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ module.exports = [
gzip: true,
limit: '35 KB',
},
{
name: '@sentry/browser (incl. browserTracingIntegration) - Webpack (gzipped)',
path: 'packages/browser/build/npm/esm/index.js',
import: '{ init, browserTracingIntegration }',
gzip: true,
limit: '35 KB',
},
{
name: '@sentry/browser (incl. Feedback) - Webpack (gzipped)',
path: 'packages/browser/build/npm/esm/index.js',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;

// Replay should not actually work, but still not error out
window.Replay = new Sentry.replayIntegration({
flushMinDelay: 200,
flushMaxDelay: 200,
minReplayDuration: 0,
});

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
sampleRate: 1,
replaysSessionSampleRate: 1.0,
replaysOnErrorSampleRate: 0.0,
integrations: [window.Replay],
});

// Ensure none of these break
window.Replay.start();
window.Replay.stop();
window.Replay.flush();
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<button onclick="console.log('Test log')">Click me</button>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { expect } from '@playwright/test';

import { sentryTest } from '../../../utils/fixtures';

sentryTest(
'exports a shim replayIntegration integration for non-replay bundles',
async ({ getLocalTestPath, page, forceFlushReplay }) => {
const bundle = process.env.PW_BUNDLE;

if (!bundle || !bundle.startsWith('bundle_') || bundle.includes('replay')) {
sentryTest.skip();
}

const consoleMessages: string[] = [];
page.on('console', msg => consoleMessages.push(msg.text()));

let requestCount = 0;
await page.route('https://dsn.ingest.sentry.io/**/*', route => {
requestCount++;
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 forceFlushReplay();

expect(requestCount).toBe(0);
expect(consoleMessages).toEqual(['You are using new Replay() even though this bundle does not include replay.']);
},
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
integrations: [Sentry.browserTracingIntegration({ idleTimeout: 9000 })],
tracesSampleRate: 1,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
document.getElementById('go-background').addEventListener('click', () => {
Object.defineProperty(document, 'hidden', { value: true, writable: true });
const ev = document.createEvent('Event');
ev.initEvent('visibilitychange');
document.dispatchEvent(ev);
});

document.getElementById('start-transaction').addEventListener('click', () => {
window.transaction = Sentry.startTransaction({ name: 'test-transaction' });
Sentry.getCurrentHub().configureScope(scope => scope.setSpan(window.transaction));
});
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 id="start-transaction">Start Transaction</button>
<button id="go-background">New Tab</button>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import type { JSHandle } from '@playwright/test';
import { expect } from '@playwright/test';
import type { Event } from '@sentry/types';

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

async function getPropertyValue(handle: JSHandle, prop: string) {
return (await handle.getProperty(prop))?.jsonValue();
}

sentryTest('should finish a custom transaction when the page goes background', async ({ getLocalTestPath, page }) => {
if (shouldSkipTracingTest()) {
sentryTest.skip();
}

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

const pageloadTransaction = await getFirstSentryEnvelopeRequest<Event>(page, url);
expect(pageloadTransaction).toBeDefined();

await page.locator('#start-transaction').click();
const transactionHandle = await page.evaluateHandle('window.transaction');

const id_before = await getPropertyValue(transactionHandle, 'span_id');
const name_before = await getPropertyValue(transactionHandle, 'name');
const status_before = await getPropertyValue(transactionHandle, 'status');
const tags_before = await getPropertyValue(transactionHandle, 'tags');

expect(name_before).toBe('test-transaction');
expect(status_before).toBeUndefined();
expect(tags_before).toStrictEqual({});

await page.locator('#go-background').click();

const id_after = await getPropertyValue(transactionHandle, 'span_id');
const name_after = await getPropertyValue(transactionHandle, 'name');
const status_after = await getPropertyValue(transactionHandle, 'status');
const tags_after = await getPropertyValue(transactionHandle, 'tags');

expect(id_before).toBe(id_after);
expect(name_after).toBe(name_before);
expect(status_after).toBe('cancelled');
expect(tags_after).toStrictEqual({ visibilitychange: 'document.hidden' });
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
document.getElementById('go-background').addEventListener('click', () => {
setTimeout(() => {
Object.defineProperty(document, 'hidden', { value: true, writable: true });
const ev = document.createEvent('Event');
ev.initEvent('visibilitychange');
document.dispatchEvent(ev);
}, 250);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<button id="go-background">New Tab</button>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { expect } from '@playwright/test';
import type { Event } from '@sentry/types';

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

sentryTest('should finish pageload transaction when the page goes background', async ({ getLocalTestPath, page }) => {
if (shouldSkipTracingTest()) {
sentryTest.skip();
}
const url = await getLocalTestPath({ testDir: __dirname });

await page.goto(url);
await page.locator('#go-background').click();

const pageloadTransaction = await getFirstSentryEnvelopeRequest<Event>(page);

expect(pageloadTransaction.contexts?.trace?.op).toBe('pageload');
expect(pageloadTransaction.contexts?.trace?.status).toBe('cancelled');
expect(pageloadTransaction.contexts?.trace?.tags).toMatchObject({
visibilitychange: 'document.hidden',
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
integrations: [
Sentry.browserTracingIntegration({
idleTimeout: 1000,
_experiments: {
enableHTTPTimings: true,
},
}),
],
tracesSampleRate: 1,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
fetch('http://example.com/0').then(fetch('http://example.com/1').then(fetch('http://example.com/2')));
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { expect } from '@playwright/test';
import type { SerializedEvent } from '@sentry/types';

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

sentryTest('should create fetch spans with http timing @firefox', async ({ browserName, getLocalTestPath, page }) => {
const supportedBrowsers = ['chromium', 'firefox'];

if (shouldSkipTracingTest() || !supportedBrowsers.includes(browserName)) {
sentryTest.skip();
}
await page.route('http://example.com/*', async route => {
const request = route.request();
const postData = await request.postDataJSON();

await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(Object.assign({ id: 1 }, postData)),
});
});

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

const envelopes = await getMultipleSentryEnvelopeRequests<SerializedEvent>(page, 2, { url, timeout: 10000 });
const tracingEvent = envelopes[envelopes.length - 1]; // last envelope contains tracing data on all browsers

// eslint-disable-next-line deprecation/deprecation
const requestSpans = tracingEvent.spans?.filter(({ op }) => op === 'http.client');

expect(requestSpans).toHaveLength(3);

await page.pause();
requestSpans?.forEach((span, index) =>
expect(span).toMatchObject({
description: `GET http://example.com/${index}`,
parent_span_id: tracingEvent.contexts?.trace?.span_id,
span_id: expect.any(String),
start_timestamp: expect.any(Number),
timestamp: expect.any(Number),
trace_id: tracingEvent.contexts?.trace?.trace_id,
data: expect.objectContaining({
'http.request.redirect_start': expect.any(Number),
'http.request.fetch_start': expect.any(Number),
'http.request.domain_lookup_start': expect.any(Number),
'http.request.domain_lookup_end': expect.any(Number),
'http.request.connect_start': expect.any(Number),
'http.request.secure_connection_start': expect.any(Number),
'http.request.connection_end': expect.any(Number),
'http.request.request_start': expect.any(Number),
'http.request.response_start': expect.any(Number),
'http.request.response_end': expect.any(Number),
'network.protocol.version': expect.any(String),
}),
}),
);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;

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

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

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

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);
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
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,
_experiments: {
enableInteractions: true,
},
}),
],
tracesSampleRate: 1,
});
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="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>

0 comments on commit adccbe6

Please sign in to comment.