Skip to content

feat(tracing): Add interaction transaction as an experiment #6210

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 5 commits into from
Dec 7, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
@@ -0,0 +1,12 @@
(() => {
const startTime = Date.now();

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

while (getElasped() < 105) {
//
}
})();
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import * as Sentry from '@sentry/browser';
import { Integrations } from '@sentry/tracing';

window.Sentry = Sentry;

Sentry.init({
dsn: 'https://[email protected]/1337',
integrations: [
new Integrations.BrowserTracing({
idleTimeout: 1000,
_experiments: {
interactionSampleRate: 1.0,
},
}),
],
tracesSampleRate: 1,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div>Rendered Before Long Task</div>
<script src="https://example.com/path/to/script.js"></script>
<button data-test-id="interaction-button">Click Me</button>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { expect, Route } from '@playwright/test';
import { Event } from '@sentry/types';

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

sentryTest('should capture interaction transaction.', async ({ browserName, getLocalTestPath, page }) => {
if (browserName !== 'chromium') {
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 getFirstSentryEnvelopeRequest<Event>(page, url);

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

const envelopes = await getMultipleSentryEnvelopeRequests<Event>(page, 2);
const eventData = envelopes[1];

expect(eventData).toEqual(
expect.objectContaining({
contexts: expect.objectContaining({
trace: expect.objectContaining({
op: 'ui.action.click',
}),
}),
platform: 'javascript',
spans: [],
tags: {},
type: 'transaction',
}),
);
});
75 changes: 71 additions & 4 deletions packages/tracing/src/browser/browsertracing.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
/* eslint-disable max-lines */
import { Hub } from '@sentry/core';
import { EventProcessor, Integration, Transaction, TransactionContext } from '@sentry/types';
import { EventProcessor, Integration, Transaction, TransactionContext, TransactionSource } from '@sentry/types';
import { baggageHeaderToDynamicSamplingContext, getDomElement, logger } from '@sentry/utils';

import { startIdleTransaction } from '../hubextensions';
import { DEFAULT_FINAL_TIMEOUT, DEFAULT_HEARTBEAT_INTERVAL, DEFAULT_IDLE_TIMEOUT } from '../idletransaction';
import {
DEFAULT_FINAL_TIMEOUT,
DEFAULT_HEARTBEAT_INTERVAL,
DEFAULT_IDLE_TIMEOUT,
IdleTransaction,
} from '../idletransaction';
import { extractTraceparentData } from '../utils';
import { registerBackgroundTabDetection } from './backgroundtab';
import { addPerformanceEntries, startTrackingLongTasks, startTrackingWebVitals } from './metrics';
Expand Down Expand Up @@ -87,7 +92,7 @@ export interface BrowserTracingOptions extends RequestInstrumentationOptions {
*
* Default: undefined
*/
_experiments?: Partial<{ enableLongTask: boolean }>;
_experiments?: Partial<{ enableLongTask: boolean; enableInteractions: boolean }>;

/**
* beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction
Expand Down Expand Up @@ -120,7 +125,7 @@ const DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {
routingInstrumentation: instrumentRoutingWithDefaults,
startTransactionOnLocationChange: true,
startTransactionOnPageLoad: true,
_experiments: { enableLongTask: true },
_experiments: { enableLongTask: true, enableInteractions: false },
...defaultRequestInstrumentationOptions,
};

Expand All @@ -147,6 +152,9 @@ export class BrowserTracing implements Integration {

private _getCurrentHub?: () => Hub;

private _latestRouteName?: string;
private _latestRouteSource?: TransactionSource;

public constructor(_options?: Partial<BrowserTracingOptions>) {
this.options = {
...DEFAULT_BROWSER_TRACING_OPTIONS,
Expand Down Expand Up @@ -185,6 +193,7 @@ export class BrowserTracing implements Integration {
traceXHR,
tracePropagationTargets,
shouldCreateSpanForRequest,
_experiments,
} = this.options;

instrumentRouting(
Expand All @@ -197,6 +206,10 @@ export class BrowserTracing implements Integration {
registerBackgroundTabDetection();
}

if (_experiments?.enableInteractions) {
this._registerInteractionListener();
}

instrumentOutgoingRequests({
traceFetch,
traceXHR,
Expand Down Expand Up @@ -248,6 +261,9 @@ export class BrowserTracing implements Integration {
? { ...finalContext.metadata, source: 'custom' }
: finalContext.metadata;

this._latestRouteName = finalContext.name;
this._latestRouteSource = finalContext.metadata?.source;

if (finalContext.sampled === false) {
__DEBUG_BUILD__ &&
logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);
Expand All @@ -273,6 +289,57 @@ export class BrowserTracing implements Integration {

return idleTransaction as Transaction;
}

/** Start listener for interaction transactions */
private _registerInteractionListener(): void {
let inflightInteractionTransaction: IdleTransaction | undefined;
const registerInteractionTransaction = (): void => {
const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;

const op = 'ui.action.click';
if (inflightInteractionTransaction) {
inflightInteractionTransaction.finish();
inflightInteractionTransaction = undefined;
}

if (!this._getCurrentHub) {
__DEBUG_BUILD__ && logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);
return undefined;
}

if (!this._latestRouteName) {
__DEBUG_BUILD__ &&
logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);
return undefined;
}

const hub = this._getCurrentHub();
const { location } = WINDOW;

const context: TransactionContext = {
name: this._latestRouteName,
op,
trimEnd: true,
metadata: {
source: this._latestRouteSource ?? 'url',
},
};

inflightInteractionTransaction = startIdleTransaction(
hub,
context,
idleTimeout,
finalTimeout,
true,
{ location }, // for use in the tracesSampler
heartbeatInterval,
);
};

['click'].forEach(type => {
addEventListener(type, registerInteractionTransaction, { once: false, capture: true });
});
}
}

/** Returns the value of a meta tag */
Expand Down