Skip to content

feat(browser): Track measure detail as span attributes #16240

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
May 15, 2025
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'),
gzip: true,
limit: '70.1 KB',
limit: '71 KB',
modifyWebpackConfig: function (config) {
const webpack = require('webpack');

Expand Down Expand Up @@ -206,7 +206,7 @@ module.exports = [
import: createImport('init'),
ignore: ['next/router', 'next/constants'],
gzip: true,
limit: '42 KB',
limit: '42.5 KB',
},
// SvelteKit SDK (ESM)
{
Expand Down
35 changes: 32 additions & 3 deletions packages/browser-utils/src/metrics/browserMetrics.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
/* eslint-disable max-lines */
import type { Measurements, Span, SpanAttributes, StartSpanOptions } from '@sentry/core';
import type { Measurements, Span, SpanAttributes, SpanAttributeValue, StartSpanOptions } from '@sentry/core';
import {
browserPerformanceTimeOrigin,
getActiveSpan,
getComponentName,
htmlTreeAsString,
isPrimitive,
parseUrl,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
setMeasurement,
Expand Down Expand Up @@ -339,7 +340,7 @@ export function addPerformanceEntries(span: Span, options: AddPerformanceEntries
case 'mark':
case 'paint':
case 'measure': {
_addMeasureSpans(span, entry, startTime, duration, timeOrigin);
_addMeasureSpans(span, entry as PerformanceMeasure, startTime, duration, timeOrigin);

// capture web vitals
const firstHidden = getVisibilityWatcher();
Expand Down Expand Up @@ -421,7 +422,7 @@ export function addPerformanceEntries(span: Span, options: AddPerformanceEntries
*/
export function _addMeasureSpans(
span: Span,
entry: PerformanceEntry,
entry: PerformanceMeasure,
startTime: number,
duration: number,
timeOrigin: number,
Expand Down Expand Up @@ -450,6 +451,34 @@ export function _addMeasureSpans(
attributes['sentry.browser.measure_start_time'] = measureStartTimestamp;
}

// https://developer.mozilla.org/en-US/docs/Web/API/Performance/measure#detail
if (entry.detail) {
// Handle detail as an object
if (typeof entry.detail === 'object') {
Copy link

Choose a reason for hiding this comment

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

I would also ask to support arrays of primitives, here and as object props 🙏

Listing some things in spans is very useful, and SpanAttributeValue supports this.

Copy link
Member Author

Choose a reason for hiding this comment

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

We'll still handle this via serializing to JSON, so you'll get this in the UI. I'd rather not pay the bundle size cost of the extra array processing logic.

for (const [key, value] of Object.entries(entry.detail)) {
if (value && isPrimitive(value)) {
attributes[`sentry.browser.measure.detail.${key}`] = value as SpanAttributeValue;
} else {
try {
// This is user defined so we can't guarantee it's serializable
Copy link
Member

Choose a reason for hiding this comment

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

l: Can we instead just wrap the whole block inside of if (entry.detail) in a try-catch, maybe slightly less redundant?

Copy link
Member Author

Choose a reason for hiding this comment

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

If we wrap everything in try catch it means we stop iterating through Object.entries(entry.detail), which means some valid attributes might not get serialized properly.

attributes[`sentry.browser.measure.detail.${key}`] = JSON.stringify(value);
} catch {
// skip
}
}
}
} else if (isPrimitive(entry.detail)) {
attributes['sentry.browser.measure.detail'] = entry.detail as SpanAttributeValue;
} else {
// This is user defined so we can't guarantee it's serializable
try {
attributes['sentry.browser.measure.detail'] = JSON.stringify(entry.detail);
} catch {
// skip
}
}
}

// Measurements from third parties can be off, which would create invalid spans, dropping transactions in the process.
if (measureStartTimestamp <= measureEndTimestamp) {
startAndEndSpan(span, measureStartTimestamp, measureEndTimestamp, {
Expand Down
166 changes: 163 additions & 3 deletions packages/browser-utils/test/browser/browserMetrics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ describe('_addMeasureSpans', () => {
name: 'measure-1',
duration: 10,
startTime: 12,
} as PerformanceEntry;
detail: null,
} as PerformanceMeasure;

const timeOrigin = 100;
const startTime = 23;
Expand Down Expand Up @@ -106,7 +107,8 @@ describe('_addMeasureSpans', () => {
name: 'measure-1',
duration: 10,
startTime: 12,
} as PerformanceEntry;
detail: null,
} as PerformanceMeasure;

const timeOrigin = 100;
const startTime = 23;
Expand All @@ -116,6 +118,165 @@ describe('_addMeasureSpans', () => {

expect(spans).toHaveLength(0);
});

it('adds measure spans with primitive detail', () => {
const spans: Span[] = [];

getClient()?.on('spanEnd', span => {
spans.push(span);
});

const entry = {
entryType: 'measure',
name: 'measure-1',
duration: 10,
startTime: 12,
detail: 'test-detail',
} as PerformanceMeasure;

const timeOrigin = 100;
const startTime = 23;
const duration = 356;

_addMeasureSpans(span, entry, startTime, duration, timeOrigin);

expect(spans).toHaveLength(1);
expect(spanToJSON(spans[0]!)).toEqual(
expect.objectContaining({
description: 'measure-1',
start_timestamp: timeOrigin + startTime,
timestamp: timeOrigin + startTime + duration,
op: 'measure',
origin: 'auto.resource.browser.metrics',
data: {
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'measure',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.resource.browser.metrics',
'sentry.browser.measure.detail': 'test-detail',
},
}),
);
});

it('adds measure spans with object detail', () => {
const spans: Span[] = [];

getClient()?.on('spanEnd', span => {
spans.push(span);
});

const detail = {
component: 'Button',
action: 'click',
metadata: { id: 123 },
};

const entry = {
entryType: 'measure',
name: 'measure-1',
duration: 10,
startTime: 12,
detail,
} as PerformanceMeasure;

const timeOrigin = 100;
const startTime = 23;
const duration = 356;

_addMeasureSpans(span, entry, startTime, duration, timeOrigin);

expect(spans).toHaveLength(1);
expect(spanToJSON(spans[0]!)).toEqual(
expect.objectContaining({
description: 'measure-1',
start_timestamp: timeOrigin + startTime,
timestamp: timeOrigin + startTime + duration,
op: 'measure',
origin: 'auto.resource.browser.metrics',
data: {
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'measure',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.resource.browser.metrics',
'sentry.browser.measure.detail.component': 'Button',
'sentry.browser.measure.detail.action': 'click',
'sentry.browser.measure.detail.metadata': JSON.stringify({ id: 123 }),
},
}),
);
});

it('handles non-primitive detail values by stringifying them', () => {
const spans: Span[] = [];

getClient()?.on('spanEnd', span => {
spans.push(span);
});

const detail = {
component: 'Button',
action: 'click',
metadata: { id: 123 },
callback: () => {},
};

const entry = {
entryType: 'measure',
name: 'measure-1',
duration: 10,
startTime: 12,
detail,
} as PerformanceMeasure;

const timeOrigin = 100;
const startTime = 23;
const duration = 356;

_addMeasureSpans(span, entry, startTime, duration, timeOrigin);

expect(spans).toHaveLength(1);
const spanData = spanToJSON(spans[0]!).data;
expect(spanData['sentry.browser.measure.detail.component']).toBe('Button');
expect(spanData['sentry.browser.measure.detail.action']).toBe('click');
expect(spanData['sentry.browser.measure.detail.metadata']).toBe(JSON.stringify({ id: 123 }));
expect(spanData['sentry.browser.measure.detail.callback']).toBe(JSON.stringify(detail.callback));
});

it('handles errors in object detail value stringification', () => {
const spans: Span[] = [];

getClient()?.on('spanEnd', span => {
spans.push(span);
});

const circular: any = {};
circular.self = circular;

const detail = {
component: 'Button',
action: 'click',
circular,
};

const entry = {
entryType: 'measure',
name: 'measure-1',
duration: 10,
startTime: 12,
detail,
} as PerformanceMeasure;

const timeOrigin = 100;
const startTime = 23;
const duration = 356;

// Should not throw
_addMeasureSpans(span, entry, startTime, duration, timeOrigin);

expect(spans).toHaveLength(1);
const spanData = spanToJSON(spans[0]!).data;
expect(spanData['sentry.browser.measure.detail.component']).toBe('Button');
expect(spanData['sentry.browser.measure.detail.action']).toBe('click');
// The circular reference should be skipped
expect(spanData['sentry.browser.measure.detail.circular']).toBeUndefined();
});
});

describe('_addResourceSpans', () => {
Expand Down Expand Up @@ -464,7 +625,6 @@ describe('_addNavigationSpans', () => {
transferSize: 14726,
encodedBodySize: 14426,
decodedBodySize: 67232,
responseStatus: 200,
serverTiming: [],
unloadEventStart: 0,
unloadEventEnd: 0,
Expand Down
Loading