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(webvitals): Adds INP instrumentation to browserTracingIntegration #10629

Closed
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
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export {
export { applyScopeDataToEvent, mergeScopeData } from './utils/applyScopeDataToEvent';
export { prepareEvent } from './utils/prepareEvent';
export { createCheckInEnvelope } from './checkin';
export { createSpanEnvelope } from './span';
export { hasTracingEnabled } from './utils/hasTracingEnabled';
export { isSentryRequestUrl } from './utils/isSentryRequestUrl';
export { handleCallbackErrors } from './utils/handleCallbackErrors';
Expand Down
22 changes: 22 additions & 0 deletions packages/core/src/span.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { SpanEnvelope, SpanItem } from '@sentry/types';
import type { Span } from '@sentry/types/build/types/span';
import { createEnvelope } from '@sentry/utils';

/**
* Create envelope from Span item.
*/
export function createSpanEnvelope(span: Span): SpanEnvelope {
const headers: SpanEnvelope[0] = {
sent_at: new Date().toISOString(),
};

const item = createSpanItem(span);
return createEnvelope<SpanEnvelope>(headers, [item]);
}

function createSpanItem(span: Span): SpanItem {
const spanHeaders: SpanItem[0] = {
type: 'span',
};
return [spanHeaders, span];
}
52 changes: 52 additions & 0 deletions packages/tracing-internal/src/browser/browserTracingIntegration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,18 @@ import {

import { DEBUG_BUILD } from '../common/debug-build';
import { registerBackgroundTabDetection } from './backgroundtab';
import { addPerformanceInstrumentationHandler } from './instrument';
import {
addPerformanceEntries,
startTrackingINP,
startTrackingInteractions,
startTrackingLongTasks,
startTrackingWebVitals,
} from './metrics';
import type { RequestInstrumentationOptions } from './request';
import { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';
import { WINDOW } from './types';
import type { InteractionRouteNameMapping } from './web-vitals/types';

export const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';

Expand Down Expand Up @@ -126,6 +129,7 @@ export interface BrowserTracingOptions extends RequestInstrumentationOptions {
*/
_experiments: Partial<{
enableInteractions: boolean;
enableInp: boolean;
}>;

/**
Expand Down Expand Up @@ -180,6 +184,12 @@ export const browserTracingIntegration = ((_options: Partial<BrowserTracingOptio

const _collectWebVitals = startTrackingWebVitals();

/** Stores a mapping of interactionIds from PerformanceEventTimings to the origin interaction path */
const interactionIdtoRouteNameMapping: InteractionRouteNameMapping = {};
if (options._experiments.enableInp) {
startTrackingINP(interactionIdtoRouteNameMapping);
}

if (options.enableLongTask) {
startTrackingLongTasks();
}
Expand Down Expand Up @@ -383,6 +393,10 @@ export const browserTracingIntegration = ((_options: Partial<BrowserTracingOptio
registerInteractionListener(options, latestRouteName, latestRouteSource);
}

if (_experiments.enableInp) {
registerInpInteractionListener(interactionIdtoRouteNameMapping);
}

instrumentOutgoingRequests({
traceFetch,
traceXHR,
Expand Down Expand Up @@ -491,6 +505,44 @@ function registerInteractionListener(
});
}

function isPerformanceEventTiming(entry: PerformanceEntry): entry is PerformanceEventTiming {
return 'duration' in entry;
}

const MAX_INTERACTIONS = 10;

/** Creates a listener on interaction entries, and maps interactionIds to the origin path of the interaction */
function registerInpInteractionListener(interactionIdtoRouteNameMapping: InteractionRouteNameMapping): void {
addPerformanceInstrumentationHandler('event', ({ entries }) => {
for (const entry of entries) {
if (isPerformanceEventTiming(entry)) {
const duration = entry.duration;
const keys = Object.keys(interactionIdtoRouteNameMapping);
const minInteractionId =
keys.length > 0
? keys.reduce((a, b) => {
return interactionIdtoRouteNameMapping[a].duration < interactionIdtoRouteNameMapping[b].duration
? a
: b;
})
: undefined;
if (minInteractionId === undefined || duration > interactionIdtoRouteNameMapping[minInteractionId].duration) {
const interactionId = entry.interactionId;
const route = entry.target?.baseURI;
const path = route ? new URL(route).pathname : undefined;
if (interactionId && path) {
if (minInteractionId && Object.keys(interactionIdtoRouteNameMapping).length >= MAX_INTERACTIONS) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete interactionIdtoRouteNameMapping[minInteractionId];
}
interactionIdtoRouteNameMapping[interactionId] = { routeName: path, duration };
}
}
}
}
});
}

function getSource(context: TransactionContext): TransactionSource | undefined {
const sourceFromAttributes = context.attributes && context.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
// eslint-disable-next-line deprecation/deprecation
Expand Down
25 changes: 23 additions & 2 deletions packages/tracing-internal/src/browser/instrument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import { getFunctionName, logger } from '@sentry/utils';
import { DEBUG_BUILD } from '../common/debug-build';
import { onCLS } from './web-vitals/getCLS';
import { onFID } from './web-vitals/getFID';
import { onINP } from './web-vitals/getINP';
import { onLCP } from './web-vitals/getLCP';
import { observe } from './web-vitals/lib/observe';

type InstrumentHandlerTypePerformanceObserver = 'longtask' | 'event' | 'navigation' | 'paint' | 'resource';

type InstrumentHandlerTypeMetric = 'cls' | 'lcp' | 'fid';
type InstrumentHandlerTypeMetric = 'cls' | 'lcp' | 'fid' | 'inp';

// We provide this here manually instead of relying on a global, as this is not available in non-browser environements
// And we do not want to expose such types
Expand Down Expand Up @@ -86,6 +87,7 @@ const instrumented: { [key in InstrumentHandlerType]?: boolean } = {};
let _previousCls: Metric | undefined;
let _previousFid: Metric | undefined;
let _previousLcp: Metric | undefined;
let _previousInp: Metric | undefined;

/**
* Add a callback that will be triggered when a CLS metric is available.
Expand Down Expand Up @@ -123,9 +125,19 @@ export function addFidInstrumentationHandler(callback: (data: { metric: Metric }
return addMetricObserver('fid', callback, instrumentFid, _previousFid);
}

/**
* Add a callback that will be triggered when a INP metric is available.
* Returns a cleanup callback which can be called to remove the instrumentation handler.
*/
export function addInpInstrumentationHandler(
callback: (data: { metric: Omit<Metric, 'entries'> & { entries: PerformanceEventTiming[] } }) => void,
): CleanupHandlerCallback {
return addMetricObserver('inp', callback, instrumentInp, _previousInp);
}

export function addPerformanceInstrumentationHandler(
type: 'event',
callback: (data: { entries: (PerformanceEntry & { target?: unknown | null })[] }) => void,
callback: (data: { entries: ((PerformanceEntry & { target?: unknown | null }) | PerformanceEventTiming)[] }) => void,
): CleanupHandlerCallback;
export function addPerformanceInstrumentationHandler(
type: InstrumentHandlerTypePerformanceObserver,
Expand Down Expand Up @@ -199,6 +211,15 @@ function instrumentLcp(): StopListening {
});
}

function instrumentInp(): void {
return onINP(metric => {
triggerHandlers('inp', {
metric,
});
_previousInp = metric;
});
}

function addMetricObserver(
type: InstrumentHandlerTypeMetric,
callback: InstrumentHandlerCallback,
Expand Down
64 changes: 62 additions & 2 deletions packages/tracing-internal/src/browser/metrics/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable max-lines */
import type { IdleTransaction, Transaction } from '@sentry/core';
import { getActiveTransaction, setMeasurement } from '@sentry/core';
import { Span, getActiveTransaction, getClient, setMeasurement } from '@sentry/core';
import type { Measurements, SpanContext } from '@sentry/types';
import { browserPerformanceTimeOrigin, getComponentName, htmlTreeAsString, logger, parseUrl } from '@sentry/utils';

Expand All @@ -9,14 +9,21 @@ import { DEBUG_BUILD } from '../../common/debug-build';
import {
addClsInstrumentationHandler,
addFidInstrumentationHandler,
addInpInstrumentationHandler,
addLcpInstrumentationHandler,
addPerformanceInstrumentationHandler,
} from '../instrument';
import { WINDOW } from '../types';
import { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher';
import type { NavigatorDeviceMemory, NavigatorNetworkInformation } from '../web-vitals/types';
import type {
InteractionRouteNameMapping,
NavigatorDeviceMemory,
NavigatorNetworkInformation,
} from '../web-vitals/types';
import { _startChild, isMeasurementValue } from './utils';

import { createSpanEnvelope } from '@sentry/core';

const MAX_INT_AS_BYTES = 2147483647;

/**
Expand Down Expand Up @@ -127,6 +134,22 @@ export function startTrackingInteractions(): void {
});
}

/**
* Start tracking INP webvital events.
*/
export function startTrackingINP(interactionIdtoRouteNameMapping: InteractionRouteNameMapping): () => void {
const performance = getBrowserPerformanceAPI();
if (performance && browserPerformanceTimeOrigin) {
const inpCallback = _trackINP(interactionIdtoRouteNameMapping);

return (): void => {
inpCallback();
};
}

return () => undefined;
}

/** Starts tracking the Cumulative Layout Shift on the current page. */
function _trackCLS(): () => void {
return addClsInstrumentationHandler(({ metric }) => {
Expand Down Expand Up @@ -171,6 +194,43 @@ function _trackFID(): () => void {
});
}

/** Starts tracking the Interaction to Next Paint on the current page. */
function _trackINP(interactionIdtoRouteNameMapping: InteractionRouteNameMapping): () => void {
return addInpInstrumentationHandler(({ metric }) => {
const entry = metric.entries.find(e => e.name === 'click');
const client = getClient();
if (!entry || !client) {
return;
}
const { release, environment } = client.getOptions();
/** Build the INP span, create an envelope from the span, and then send the envelope */
const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);
const duration = msToSec(metric.value);
const routeName =
entry.interactionId !== undefined ? interactionIdtoRouteNameMapping[entry.interactionId].routeName : undefined;
const span = new Span({
startTimestamp: startTime,
endTimestamp: startTime + duration,
op: 'ui.interaction.click',
name: routeName,
attributes: {
measurements: {
inp: { value: metric.value, unit: 'millisecond' },
},
release,
environment,
},
});
const envelope = span ? createSpanEnvelope(span) : undefined;
const transport = client && client.getTransport();
if (transport && envelope) {
transport.send(envelope).then(null, reason => {
DEBUG_BUILD && logger.error('Error while sending interaction:', reason);
});
}
});
}

/** Add performance related spans to a transaction */
export function addPerformanceEntries(transaction: Transaction): void {
const performance = getBrowserPerformanceAPI();
Expand Down
2 changes: 2 additions & 0 deletions packages/tracing-internal/src/browser/web-vitals/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,5 @@ declare global {
element?: Element;
}
}

export type InteractionRouteNameMapping = { [key: string]: { routeName: string; duration: number } };
4 changes: 3 additions & 1 deletion packages/types/src/datacategory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,6 @@ export type DataCategory =
// Feedback type event (v2)
| 'feedback'
// Unknown data category
| 'unknown';
| 'unknown'
// Span
| 'span';
11 changes: 9 additions & 2 deletions packages/types/src/envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { Profile } from './profiling';
import type { ReplayEvent, ReplayRecordingData } from './replay';
import type { SdkInfo } from './sdkinfo';
import type { SerializedSession, Session, SessionAggregates } from './session';
import type { Span } from './span';
import type { Transaction } from './transaction';
import type { UserFeedback } from './user';

Expand Down Expand Up @@ -41,7 +42,8 @@ export type EnvelopeItemType =
| 'replay_event'
| 'replay_recording'
| 'check_in'
| 'statsd';
| 'statsd'
| 'span';

export type BaseEnvelopeHeaders = {
[key: string]: unknown;
Expand Down Expand Up @@ -82,6 +84,7 @@ type ReplayRecordingItemHeaders = { type: 'replay_recording'; length: number };
type CheckInItemHeaders = { type: 'check_in' };
type StatsdItemHeaders = { type: 'statsd'; length: number };
type ProfileItemHeaders = { type: 'profile' };
type SpanItemHeaders = { type: 'span' };

// TODO (v8): Replace `Event` with `SerializedEvent`
export type EventItem = BaseEnvelopeItem<EventItemHeaders, Event>;
Expand All @@ -98,13 +101,15 @@ type ReplayRecordingItem = BaseEnvelopeItem<ReplayRecordingItemHeaders, ReplayRe
export type StatsdItem = BaseEnvelopeItem<StatsdItemHeaders, string>;
export type FeedbackItem = BaseEnvelopeItem<FeedbackItemHeaders, FeedbackEvent>;
export type ProfileItem = BaseEnvelopeItem<ProfileItemHeaders, Profile>;
export type SpanItem = BaseEnvelopeItem<SpanItemHeaders, Span>;

export type EventEnvelopeHeaders = { event_id: string; sent_at: string; trace?: DynamicSamplingContext };
type SessionEnvelopeHeaders = { sent_at: string };
type CheckInEnvelopeHeaders = { trace?: DynamicSamplingContext };
type ClientReportEnvelopeHeaders = BaseEnvelopeHeaders;
type ReplayEnvelopeHeaders = BaseEnvelopeHeaders;
type StatsdEnvelopeHeaders = BaseEnvelopeHeaders;
type SpanEnvelopeHeaders = BaseEnvelopeHeaders;

export type EventEnvelope = BaseEnvelope<
EventEnvelopeHeaders,
Expand All @@ -115,12 +120,14 @@ export type ClientReportEnvelope = BaseEnvelope<ClientReportEnvelopeHeaders, Cli
export type ReplayEnvelope = [ReplayEnvelopeHeaders, [ReplayEventItem, ReplayRecordingItem]];
export type CheckInEnvelope = BaseEnvelope<CheckInEnvelopeHeaders, CheckInItem>;
export type StatsdEnvelope = BaseEnvelope<StatsdEnvelopeHeaders, StatsdItem>;
export type SpanEnvelope = BaseEnvelope<SpanEnvelopeHeaders, SpanItem>;

export type Envelope =
| EventEnvelope
| SessionEnvelope
| ClientReportEnvelope
| ReplayEnvelope
| CheckInEnvelope
| StatsdEnvelope;
| StatsdEnvelope
| SpanEnvelope;
export type EnvelopeItem = Envelope[1][number];
2 changes: 2 additions & 0 deletions packages/types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ export type {
StatsdItem,
StatsdEnvelope,
ProfileItem,
SpanEnvelope,
SpanItem,
} from './envelope';
export type { ExtendedError } from './error';
export type { Event, EventHint, EventType, ErrorEvent, TransactionEvent, SerializedEvent } from './event';
Expand Down
4 changes: 3 additions & 1 deletion packages/types/src/span.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { TraceContext } from './context';
import type { Instrumenter } from './instrumenter';
import type { Measurements } from './measurement';
import type { Primitive } from './misc';
import type { HrTime } from './opentelemetry';
import type { Transaction } from './transaction';
Expand All @@ -21,7 +22,8 @@ export type SpanAttributeValue =
| boolean
| Array<null | undefined | string>
| Array<null | undefined | number>
| Array<null | undefined | boolean>;
| Array<null | undefined | boolean>
| Measurements;

export type SpanAttributes = Partial<{
'sentry.origin': string;
Expand Down
1 change: 1 addition & 0 deletions packages/utils/src/envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ const ITEM_TYPE_TO_DATA_CATEGORY_MAP: Record<EnvelopeItemType, DataCategory> = {
replay_recording: 'replay',
check_in: 'monitor',
feedback: 'feedback',
span: 'span',
// TODO: This is a temporary workaround until we have a proper data category for metrics
statsd: 'unknown',
};
Expand Down
Loading