Skip to content
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
1 change: 1 addition & 0 deletions packages/browser-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export { elementTimingIntegration, startTrackingElementTiming } from './performa

export { interactionsIntegration } from './performance/interactions';
export { longTasksIntegration } from './performance/longTasks';
export { resourcesIntegration } from './performance/resources';

export { isBotUserAgent } from './isBotUserAgent';

Expand Down
107 changes: 71 additions & 36 deletions packages/browser-utils/src/performance/entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ interface NavigatorDeviceMemory {
const MAX_INT_AS_BYTES = 2147483647;

let _performanceCursor: number = 0;
let _resourceCursor: number = 0;

/**
* Start tracking long tasks.
Expand Down Expand Up @@ -211,33 +212,91 @@ export function startTrackingLongAnimationFrames(): void {

interface AddPerformanceEntriesOptions {
/**
* Resource spans with `op`s matching strings in the array will not be emitted.
*
* Default: []
* Whether span streaming is enabled.
*/
ignoreResourceSpans: Array<'resource.script' | 'resource.css' | 'resource.img' | 'resource.other' | string>;
spanStreamingEnabled?: boolean;
}

interface AddResourceSpansOptions extends AddPerformanceEntriesOptions {
/**
* Whether span streaming is enabled.
* Resource spans with `op`s matching strings in the array will not be emitted.
*
* Default: []
*/
spanStreamingEnabled?: boolean;
ignoreResourceSpans?: Array<'resource.script' | 'resource.css' | 'resource.img' | 'resource.other' | string>;
}

/** Add performance related spans to a transaction */
export function addPerformanceEntries(span: Span, options: AddPerformanceEntriesOptions): void {
const performance = getBrowserPerformanceAPI();
if (!performance?.getEntries) {
// Gatekeeper if performance API not available
const { spanStreamingEnabled } = options;

const cursor = forEachPerformanceEntry(span, _performanceCursor, (entry, startTimestamp, duration) => {
switch (entry.entryType) {
case 'navigation': {
_addNavigationSpans(span, entry as PerformanceNavigationTiming, spanStreamingEnabled);
break;
}
case 'paint': {
_addPaintSpan(span, entry, startTimestamp, duration);
break;
}
// Ignore other entry types.
}
});

if (cursor === undefined) {
return;
}

_performanceCursor = cursor;

_trackNavigator(span, spanStreamingEnabled);
}

/**
* Add `resource.*` spans to a pageload or navigation span.
*/
export function addResourceSpans(span: Span, options: AddResourceSpansOptions): void {
const { spanStreamingEnabled, ignoreResourceSpans } = options;

const cursor = forEachPerformanceEntry(span, _resourceCursor, (entry, startTimestamp, duration) => {
if (entry.entryType === 'resource') {
_addResourceSpans(
span,
entry as PerformanceResourceTiming,
entry.name,
startTimestamp,
duration,
ignoreResourceSpans,
spanStreamingEnabled,
);
}
});

if (cursor !== undefined) {
_resourceCursor = cursor;
}
}

/**
* Calls `callback` for each performance entry recorded since `cursor` that belongs to `span`, and returns
* the new cursor, or `undefined` when the performance API is not available.
*/
function forEachPerformanceEntry(
span: Span,
cursor: number,
callback: (entry: PerformanceEntry, startTimestamp: number, duration: number) => void,
): number | undefined {
const performance = getBrowserPerformanceAPI();
if (!performance?.getEntries) {
return undefined;
}

const performanceEntries = performance.getEntries();

const { attributes, start_timestamp: transactionStartTime } = spanToJSON(span);

performanceEntries.slice(_performanceCursor).forEach(entry => {
performanceEntries.slice(cursor).forEach(entry => {
const startTimestamp = _INTERNAL_performanceTimeToSeconds(entry.startTime);
if (!startTimestamp) {
return;
Expand All @@ -254,34 +313,10 @@ export function addPerformanceEntries(span: Span, options: AddPerformanceEntries
return;
}

switch (entry.entryType) {
case 'navigation': {
_addNavigationSpans(span, entry as PerformanceNavigationTiming, spanStreamingEnabled);
break;
}
case 'paint': {
_addPaintSpan(span, entry, startTimestamp, duration);
break;
}
case 'resource': {
_addResourceSpans(
span,
entry as PerformanceResourceTiming,
entry.name,
startTimestamp,
duration,
ignoreResourceSpans,
spanStreamingEnabled,
);
break;
}
// Ignore other entry types.
}
callback(entry, startTimestamp, duration);
});

_performanceCursor = Math.max(performanceEntries.length - 1, 0);

_trackNavigator(span, spanStreamingEnabled);
return Math.max(performanceEntries.length - 1, 0);
}

/**
Expand Down
48 changes: 48 additions & 0 deletions packages/browser-utils/src/performance/resources.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import type { IntegrationFn } from '@sentry/core';
import { defineIntegration, hasSpanStreamingEnabled, spanToJSON } from '@sentry/core';
import { SENTRY_OP } from '@sentry/conventions/attributes';
import { NAVIGATION, PAGELOAD } from '@sentry/conventions/op';
import { isBotUserAgent } from '../isBotUserAgent';
import { addResourceSpans } from './entries';

interface ResourcesOptions {
/**
* Resource spans with `op`s matching strings in the array will not be emitted.
*
* Default: []
*/
ignoreResourceSpans?: Array<'resource.script' | 'resource.css' | 'resource.img' | 'resource.other' | string>;
}

const INTEGRATION_NAME = 'Resources';

const _resourcesIntegration = ((options: ResourcesOptions = {}) => {
return {
name: INTEGRATION_NAME,
setup(client) {
if (isBotUserAgent()) {
return;
}

client.on('beforeIdleSpanEnd', span => {
// Interaction idle spans also end through this hook. We match the route span by op, since
// `browserTracingIntegration` may already have cleared its active idle span at this point.
const op = spanToJSON(span).attributes?.[SENTRY_OP];
if (op !== PAGELOAD && op !== NAVIGATION) {
return;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}

addResourceSpans(span, {
ignoreResourceSpans: options.ignoreResourceSpans,
spanStreamingEnabled: hasSpanStreamingEnabled(client),
});
});
},
};
}) satisfies IntegrationFn;

/**
* Adds `resource.*` spans for the scripts, stylesheets, images and other resources loaded during a
* pageload or navigation.
*/
export const resourcesIntegration = defineIntegration(_resourcesIntegration);
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Span } from '@sentry/core';
import * as SentryCore from '@sentry/core';
import { getClient, getMainCarrier, SentrySpan, setCurrentClient, spanToJSON } from '@sentry/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { addPerformanceEntries } from '../../src/performance/entries';
import { addResourceSpans } from '../../src/performance/entries';
import { WINDOW } from '../../src/types';
import { getDefaultClientOptions, TestClient } from '../utils/TestClient';

Expand All @@ -23,7 +23,7 @@ const sleepDurationMs = 3_600_000;
// The `performance.now()` time from which the corrected time origin applies.
const correctionFromMs = 10_000;

describe('addPerformanceEntries', () => {
describe('addResourceSpans', () => {
beforeEach(() => {
getMainCarrier().__SENTRY__ = undefined;
const client = new TestClient(getDefaultClientOptions({ tracesSampleRate: 1 }));
Expand Down Expand Up @@ -67,7 +67,7 @@ describe('addPerformanceEntries', () => {
const endedSpans: Span[] = [];
getClient()?.on('spanEnd', endedSpan => void endedSpans.push(endedSpan));

addPerformanceEntries(span, { ignoreResourceSpans: [] });
addResourceSpans(span, { ignoreResourceSpans: [] });

expect(endedSpans.map(spanToJSON)).toEqual([
expect.objectContaining({
Expand Down
66 changes: 66 additions & 0 deletions packages/browser-utils/test/performance/resources.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { SENTRY_OP } from '@sentry/conventions/attributes';
import { NAVIGATION, PAGELOAD, UI_ACTION_CLICK } from '@sentry/conventions/op';
import type { Span } from '@sentry/core';
import { getMainCarrier, SentrySpan, setCurrentClient, spanToJSON } from '@sentry/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { resourcesIntegration } from '../../src/performance/resources';
import { WINDOW } from '../../src/types';
import { getDefaultClientOptions, TestClient } from '../utils/TestClient';

describe('resourcesIntegration', () => {
let client: TestClient;
let endedSpans: Span[];

beforeEach(() => {
getMainCarrier().__SENTRY__ = undefined;
client = new TestClient(getDefaultClientOptions({ tracesSampleRate: 1, integrations: [resourcesIntegration()] }));
setCurrentClient(client);
client.init();

endedSpans = [];
client.on('spanEnd', span => void endedSpans.push(span));

vi.stubGlobal('addEventListener', vi.fn());
vi.stubGlobal('location', { origin: 'https://example.com' });
vi.spyOn(WINDOW.performance, 'getEntries').mockReturnValue([
{
entryType: 'resource',
name: 'https://example.com/app.js',
initiatorType: 'script',
startTime: 100,
duration: 50,
responseEnd: 150,
toJSON: () => ({}),
} as PerformanceResourceTiming,
]);
});

afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});

it.each([
['adds resource spans to pageload spans', PAGELOAD, 1],
['adds resource spans to navigation spans', NAVIGATION, 1],
['skips interaction idle spans', UI_ACTION_CLICK, 0],
])('%s', (_name, op, count) => {
const span = new SentrySpan({ op, name: '/', sampled: true, startTimestamp: 1 });

client.emit('beforeIdleSpanEnd', span);

expect(
endedSpans.map(s => spanToJSON(s).attributes?.[SENTRY_OP]).filter(o => o === 'resource.script'),
).toHaveLength(count);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Test uses hard-coded span op

Low Severity

The new resourcesIntegration tests compare span ops to the literal 'resource.script'. @sentry/conventions/op already exports RESOURCE_SCRIPT, and test assertions on span ops are required to use those constants rather than string literals.

Fix in Cursor Fix in Web

Triggered by project rule: PR Review Guidelines for Cursor Bot

Reviewed by Cursor Bugbot for commit 3d3643d. Configure here.

});

it('does not add resource spans for bot user agents', () => {
vi.spyOn(WINDOW.navigator, 'userAgent', 'get').mockReturnValue('Mozilla/5.0 (compatible; Googlebot/2.1)');
const botClient = new TestClient(getDefaultClientOptions({ tracesSampleRate: 1 }));
resourcesIntegration().setup?.(botClient);

botClient.emit('beforeIdleSpanEnd', new SentrySpan({ op: PAGELOAD, name: '/', sampled: true, startTimestamp: 1 }));

expect(endedSpans).toHaveLength(0);
});
});
1 change: 1 addition & 0 deletions packages/browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export type { CachedRouteProvider, RouteProvider } from '@sentry/browser-utils';
export { interactionsIntegration } from './integrations/interactions';
export { linkedTracesIntegration } from './integrations/linkedTraces';
export { longTasksIntegration } from './integrations/longTasks';
export { resourcesIntegration } from './integrations/resources';
export { fetchTracingIntegration } from './integrations/fetchTracing';
export { xhrTracingIntegration } from './integrations/xhrTracing';

Expand Down
1 change: 1 addition & 0 deletions packages/browser/src/integrations/resources.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { resourcesIntegration } from '@sentry/browser-utils';
12 changes: 6 additions & 6 deletions packages/browser/src/tracing/browserTracingIntegration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import { _INTERNAL_ensureBrowserSpanStreaming, startIdleSpan, startInactiveSpan
import {
addHistoryInstrumentationHandler,
longTasksIntegration,
resourcesIntegration,
addPerformanceEntries,
getLocationHref,
isBotUserAgent,
Expand Down Expand Up @@ -292,6 +293,7 @@ export type BrowserTracingCoreOptions = Omit<
| 'enableElementTiming'
| 'enableLongTask'
| 'enableLongAnimationFrame'
| 'ignoreResourceSpans'
| 'traceFetch'
| 'traceXHR'
| 'shouldCreateSpanForRequest'
Expand All @@ -308,7 +310,6 @@ const DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingCoreOptions = {
instrumentBfcacheRestore: true,
instrumentPageLoad: true,
markBackgroundSpan: true,
ignoreResourceSpans: [],
detectRedirects: true,
enableReportPageLoaded: false,
};
Expand Down Expand Up @@ -352,6 +353,7 @@ export const browserTracingIntegration = ((options: Partial<BrowserTracingOption
webVitals,
enableLongTask,
enableLongAnimationFrame,
ignoreResourceSpans,
traceFetch,
traceXHR,
shouldCreateSpanForRequest,
Expand Down Expand Up @@ -380,6 +382,8 @@ export const browserTracingIntegration = ((options: Partial<BrowserTracingOption
client.addIntegration(longTasksIntegration({ enableLongTask, enableLongAnimationFrame }));
}

client.addIntegration(resourcesIntegration({ ignoreResourceSpans }));

const requestOptions = { shouldCreateSpanForRequest, enableHTTPTimings, onRequestSpanStart, onRequestSpanEnd };

if (traceFetch) {
Expand Down Expand Up @@ -422,7 +426,6 @@ function _browserTracingIntegration(
finalTimeout,
childSpanTimeout,
markBackgroundSpan,
ignoreResourceSpans,
instrumentPageLoad,
instrumentNavigation,
instrumentBfcacheRestore,
Expand Down Expand Up @@ -549,10 +552,7 @@ function _browserTracingIntegration(
return;
}

addPerformanceEntries(span, {
ignoreResourceSpans,
spanStreamingEnabled: hasSpanStreamingEnabled(client),
});
addPerformanceEntries(span, { spanStreamingEnabled: hasSpanStreamingEnabled(client) });
setActiveIdleSpan(client, undefined);

// A trace should stay consistent over the entire timespan of one route - even after the pageload/navigation ended.
Expand Down
13 changes: 13 additions & 0 deletions packages/browser/test/tracing/browserTracingIntegration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,19 @@ describe('browserTracingIntegration', () => {
expect(!!client.getIntegrationByName('LongTasks')).toBe(registered);
});

it('registers resourcesIntegration', () => {
const client = new BrowserClient(
getDefaultBrowserClientOptions({
tracesSampleRate: 1,
integrations: [browserTracingIntegration()],
}),
);
setCurrentClient(client);
client.init();

expect(client.getIntegrationByName('Resources')).toBeDefined();
});

it.each([
['registers fetchTracingIntegration by default', {}, true],
['does not register fetchTracingIntegration when traceFetch is off', { traceFetch: false }, false],
Expand Down
Loading