Skip to content

feat(browser): Add detail to measure spans and add regression tests #16557

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
Show file tree
Hide file tree
Changes from 3 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,16 @@
import * as Sentry from '@sentry/browser';

// Create a simple measure with detail before SDK init
performance.measure('test-measure', {
duration: 100,
detail: { foo: 'bar' },
});

window.Sentry = Sentry;
window._testBaseTimestamp = performance.timeOrigin / 1000;

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,24 @@
import { expect } from '@playwright/test';
import type { Event } from '@sentry/core';
import { sentryTest } from '../../../../utils/fixtures';
import { getFirstSentryEnvelopeRequest, shouldSkipTracingTest } from '../../../../utils/helpers';

sentryTest('should capture measure detail as span attributes', async ({ getLocalTestUrl, page }) => {
if (shouldSkipTracingTest()) {
sentryTest.skip();
}

const url = await getLocalTestUrl({ testDir: __dirname });
const eventData = await getFirstSentryEnvelopeRequest<Event>(page, url);

const measureSpan = eventData.spans?.find(({ op }) => op === 'measure');
expect(measureSpan).toBeDefined();
expect(measureSpan?.description).toBe('test-measure');

// Verify detail was captured
expect(measureSpan?.data).toMatchObject({
'sentry.browser.measure.detail.foo': 'bar',
'sentry.op': 'measure',
'sentry.origin': 'auto.resource.browser.metrics',
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import * as Sentry from '@sentry/browser';

// Create measures BEFORE SDK initializes

// Create a measure with detail
const measure = performance.measure('firefox-test-measure', {
duration: 100,
detail: { test: 'initial-value' },
});

// Simulate Firefox's permission denial by overriding the detail getter
// This mimics the actual Firefox behavior where accessing detail throws
Object.defineProperty(measure, 'detail', {
get() {
throw new DOMException('Permission denied to access object', 'SecurityError');
},
configurable: false,
enumerable: true,
});

// Also create a normal measure to ensure SDK still works
performance.measure('normal-measure', {
duration: 50,
detail: 'this-should-work',
});

window.Sentry = Sentry;

Sentry.init({
debug: true,
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,44 @@
import { expect } from '@playwright/test';
import type { Event } from '@sentry/core';
import { sentryTest } from '../../../../utils/fixtures';
import { getFirstSentryEnvelopeRequest, shouldSkipTracingTest } from '../../../../utils/helpers';

// This is a regression test for https://github.com/getsentry/sentry-javascript/issues/16347

sentryTest(
'should handle permission denial gracefully and still create measure spans',
async ({ getLocalTestUrl, page }) => {
if (shouldSkipTracingTest()) {
sentryTest.skip();
}

const url = await getLocalTestUrl({ testDir: __dirname });
const eventData = await getFirstSentryEnvelopeRequest<Event>(page, url);

// Find all measure spans
const measureSpans = eventData.spans?.filter(({ op }) => op === 'measure');
expect(measureSpans?.length).toBe(2); // Both measures should create spans

// Test 1: Verify the restricted-test-measure span exists but has no detail
const restrictedMeasure = measureSpans?.find(span => span.description === 'restricted-test-measure');
expect(restrictedMeasure).toBeDefined();
expect(restrictedMeasure?.data).toMatchObject({
'sentry.op': 'measure',
'sentry.origin': 'auto.resource.browser.metrics',
});

// Verify no detail attributes were added due to the permission error
const restrictedDataKeys = Object.keys(restrictedMeasure?.data || {});
const restrictedDetailKeys = restrictedDataKeys.filter(key => key.includes('detail'));
expect(restrictedDetailKeys).toHaveLength(0);

// Test 2: Verify the normal measure still captures detail correctly
const normalMeasure = measureSpans?.find(span => span.description === 'normal-measure');
expect(normalMeasure).toBeDefined();
expect(normalMeasure?.data).toMatchObject({
'sentry.browser.measure.detail': 'this-should-work',
'sentry.op': 'measure',
'sentry.origin': 'auto.resource.browser.metrics',
});
},
);
43 changes: 42 additions & 1 deletion 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 @@ -483,6 +484,46 @@ export function _addMeasureSpans(
attributes['sentry.browser.measure_start_time'] = measureStartTimestamp;
}

// Safely access and process detail property
// Cast to PerformanceMeasure to access detail property
const performanceMeasure = entry as PerformanceMeasure;
if (performanceMeasure.detail !== undefined) {
try {
// Accessing detail might throw in some browsers (e.g., Firefox) due to security restrictions
const detail = performanceMeasure.detail;

// Process detail based on its type
if (detail && typeof detail === 'object') {
// Handle object details
for (const [key, value] of Object.entries(detail)) {
if (value && isPrimitive(value)) {
attributes[`sentry.browser.measure.detail.${key}`] = value as SpanAttributeValue;
} else if (value !== undefined) {
try {
// This is user defined so we can't guarantee it's serializable
attributes[`sentry.browser.measure.detail.${key}`] = JSON.stringify(value);
} catch {
// Skip values that can't be stringified
}
}
}
} else if (isPrimitive(detail)) {
// Handle primitive details
attributes['sentry.browser.measure.detail'] = detail as SpanAttributeValue;
} else if (detail !== null) {
// Handle non-primitive, non-object details
try {
attributes['sentry.browser.measure.detail'] = JSON.stringify(detail);
} catch {
// Skip if stringification fails
}
}
} catch {
// Silently ignore any errors when accessing detail
// This handles the Firefox "Permission denied to access object" error
}
}

// 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
Loading