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/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export {
export type { CachedRouteProvider, RouteProvider } from '@sentry/browser-utils';
export { interactionsIntegration } from './integrations/interactions';
export { longTasksIntegration } from './integrations/longTasks';
export { xhrTracingIntegration } from './integrations/xhrTracing';

export type { RequestInstrumentationOptions } from './tracing/request';
export {
Expand Down
35 changes: 35 additions & 0 deletions packages/browser/src/integrations/xhrTracing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { isBotUserAgent } from '@sentry/browser-utils';
import type { IntegrationFn } from '@sentry/core';
import { defineIntegration } from '@sentry/core';
import type { RequestInstrumentationOptions } from '../tracing/request';
import { instrumentXhrRequests } from '../tracing/request';

const INTEGRATION_NAME = 'XhrTracing';

type XhrTracingOptions = Partial<
Pick<
RequestInstrumentationOptions,
'shouldCreateSpanForRequest' | 'enableHTTPTimings' | 'onRequestSpanStart' | 'onRequestSpanEnd'
>
>;

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

instrumentXhrRequests(client, {
...options,
tracePropagationTargets: client.getOptions().tracePropagationTargets,
});
},
};
}) satisfies IntegrationFn;

/**
* Creates spans for outgoing XHR requests and attaches trace propagation headers to them.
*/
export const xhrTracingIntegration = defineIntegration(_xhrTracingIntegration);
36 changes: 24 additions & 12 deletions packages/browser/src/tracing/browserTracingIntegration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ import type { WebVitalsOptions } from '../integrations/webVitals';
import { webVitalsIntegration } from '../integrations/webVitals';
import { registerBackgroundTabDetection } from './backgroundtab';
import { linkTraces } from './linkedTraces';
import { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';
import { xhrTracingIntegration } from '../integrations/xhrTracing';
import { defaultRequestInstrumentationOptions, instrumentFetchRequests } from './request';
import {
SENTRY_SEGMENT_NAME_SOURCE,
SENTRY_OP,
Expand Down Expand Up @@ -286,7 +287,7 @@ export interface BrowserTracingOptions {
*/
export type BrowserTracingCoreOptions = Omit<
BrowserTracingOptions,
'enableInp' | 'webVitals' | 'enableElementTiming' | 'enableLongTask' | 'enableLongAnimationFrame'
'enableInp' | 'webVitals' | 'enableElementTiming' | 'enableLongTask' | 'enableLongAnimationFrame' | 'traceXHR'
>;

const DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingCoreOptions = {
Expand All @@ -312,6 +313,7 @@ const DEFAULT_FORWARDED_OPTIONS = {
enableInp: true,
enableLongTask: true,
enableLongAnimationFrame: true,
traceXHR: true,
} satisfies Partial<BrowserTracingOptions>;

/**
Expand Down Expand Up @@ -339,6 +341,11 @@ export const browserTracingIntegration = ((options: Partial<BrowserTracingOption
webVitals,
enableLongTask,
enableLongAnimationFrame,
traceXHR,
shouldCreateSpanForRequest,
enableHTTPTimings,
onRequestSpanStart,
onRequestSpanEnd,
} = { ...DEFAULT_FORWARDED_OPTIONS, ...options };

return _browserTracingIntegration(options, client => {
Expand All @@ -358,6 +365,12 @@ export const browserTracingIntegration = ((options: Partial<BrowserTracingOption
if (enableLongTask || enableLongAnimationFrame) {
client.addIntegration(longTasksIntegration({ enableLongTask, enableLongAnimationFrame }));
}

if (traceXHR) {
client.addIntegration(
xhrTracingIntegration({ shouldCreateSpanForRequest, enableHTTPTimings, onRequestSpanStart, onRequestSpanEnd }),
);
}
});
}) satisfies IntegrationFn;

Expand Down Expand Up @@ -388,7 +401,6 @@ function _browserTracingIntegration(
childSpanTimeout,
markBackgroundSpan,
traceFetch,
traceXHR,
shouldCreateSpanForRequest,
enableHTTPTimings,
ignoreResourceSpans,
Expand Down Expand Up @@ -777,15 +789,15 @@ function _browserTracingIntegration(
registerBackgroundTabDetection();
}

instrumentOutgoingRequests(client, {
traceFetch,
traceXHR,
tracePropagationTargets: client.getOptions().tracePropagationTargets,
shouldCreateSpanForRequest,
enableHTTPTimings,
onRequestSpanStart,
onRequestSpanEnd,
});
if (traceFetch) {
instrumentFetchRequests(client, {
tracePropagationTargets: client.getOptions().tracePropagationTargets,
shouldCreateSpanForRequest,
enableHTTPTimings,
onRequestSpanStart,
onRequestSpanEnd,
});
}
},
} satisfies Integration;
}
Expand Down
148 changes: 87 additions & 61 deletions packages/browser/src/tracing/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,81 +127,107 @@ export const defaultRequestInstrumentationOptions: RequestInstrumentationOptions

/** Registers span creators for xhr and fetch requests */
export function instrumentOutgoingRequests(client: Client, _options?: Partial<RequestInstrumentationOptions>): void {
const {
traceFetch,
traceXHR,
shouldCreateSpanForRequest,
enableHTTPTimings,
tracePropagationTargets,
onRequestSpanStart,
onRequestSpanEnd,
} = {
const options = {
...defaultRequestInstrumentationOptions,
..._options,
};

const shouldCreateSpan =
typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_: string) => true;

const shouldAttachHeadersWithTargets = (url: string): boolean => shouldAttachHeaders(url, tracePropagationTargets);
if (options.traceFetch) {
instrumentFetchRequests(client, options);
}

const spans: Record<string, Span> = {};
if (options.traceXHR) {
instrumentXhrRequests(client, options);
}
}

const propagateTraceparent = (client as BrowserClient).getOptions().propagateTraceparent;
/**
* Registers the span creator for fetch requests.
*/
export function instrumentFetchRequests(client: Client, options: Partial<RequestInstrumentationOptions>): void {
const { enableHTTPTimings = true, onRequestSpanStart, onRequestSpanEnd } = options;
const { shouldCreateSpan, shouldAttachHeadersWithTargets, spans, propagateTraceparent } = getRequestSpanContext(
client,
options,
);

addFetchInstrumentationHandler(handlerData => {
const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans, {
propagateTraceparent,
onRequestSpanEnd,
// The generic fetch instrumentation has no page origin to resolve relative URLs against.
urlBase: WINDOW.location?.href,
});

if (traceFetch) {
addFetchInstrumentationHandler(handlerData => {
const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans, {
propagateTraceparent,
onRequestSpanEnd,
// The generic fetch instrumentation has no page origin to resolve relative URLs against.
urlBase: WINDOW.location?.href,
// We cannot use `window.location` in the generic fetch instrumentation,
// but we need it for reliable `server.address` attribute.
// so we extend this in here
if (createdSpan) {
const fullUrl = getFullURL(handlerData.fetchData.url);
// `parseUrl` returns the raw authority — userinfo credentials must never reach an attribute.
const host = fullUrl ? parseUrl(fullUrl).host?.replace(/^.*@/, '') : undefined;
const sanitizedFullUrl = fullUrl ? stripDataUrlContent(fullUrl) : undefined;
createdSpan.setAttributes({
[URL_FULL]: filterCollectedUrl(sanitizedFullUrl),
[SERVER_ADDRESS]: host,
});

// We cannot use `window.location` in the generic fetch instrumentation,
// but we need it for reliable `server.address` attribute.
// so we extend this in here
if (createdSpan) {
const fullUrl = getFullURL(handlerData.fetchData.url);
// `parseUrl` returns the raw authority — userinfo credentials must never reach an attribute.
const host = fullUrl ? parseUrl(fullUrl).host?.replace(/^.*@/, '') : undefined;
const sanitizedFullUrl = fullUrl ? stripDataUrlContent(fullUrl) : undefined;
createdSpan.setAttributes({
[URL_FULL]: filterCollectedUrl(sanitizedFullUrl),
[SERVER_ADDRESS]: host,
});

if (enableHTTPTimings) {
addHTTPTimings(createdSpan, client);
}

onRequestSpanStart?.(createdSpan, { headers: handlerData.headers });
if (enableHTTPTimings) {
addHTTPTimings(createdSpan, client);
}
});
}

if (traceXHR) {
addXhrInstrumentationHandler(handlerData => {
const createdSpan = xhrCallback(
handlerData,
shouldCreateSpan,
shouldAttachHeadersWithTargets,
spans,
propagateTraceparent,
onRequestSpanEnd,
);
onRequestSpanStart?.(createdSpan, { headers: handlerData.headers });
}
});
}

if (createdSpan) {
if (enableHTTPTimings) {
addHTTPTimings(createdSpan, client);
}
/**
* Registers the span creator for XHR requests.
*/
export function instrumentXhrRequests(client: Client, options: Partial<RequestInstrumentationOptions>): void {
const { enableHTTPTimings = true, onRequestSpanStart, onRequestSpanEnd } = options;
const { shouldCreateSpan, shouldAttachHeadersWithTargets, spans, propagateTraceparent } = getRequestSpanContext(
client,
options,
);

addXhrInstrumentationHandler(handlerData => {
const createdSpan = xhrCallback(
handlerData,
shouldCreateSpan,
shouldAttachHeadersWithTargets,
spans,
propagateTraceparent,
onRequestSpanEnd,
);

onRequestSpanStart?.(createdSpan, {
headers: createHeadersSafely(handlerData.xhr.__sentry_xhr_v3__?.request_headers),
});
if (createdSpan) {
if (enableHTTPTimings) {
addHTTPTimings(createdSpan, client);
}
});
}

onRequestSpanStart?.(createdSpan, {
headers: createHeadersSafely(handlerData.xhr.__sentry_xhr_v3__?.request_headers),
});
}
});
}

function getRequestSpanContext(
client: Client,
{ shouldCreateSpanForRequest, tracePropagationTargets }: Partial<RequestInstrumentationOptions>,
): {
shouldCreateSpan: (url: string) => boolean;
shouldAttachHeadersWithTargets: (url: string) => boolean;
spans: Record<string, Span>;
propagateTraceparent: boolean | undefined;
} {
return {
shouldCreateSpan: typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : () => true,
shouldAttachHeadersWithTargets: url => shouldAttachHeaders(url, tracePropagationTargets),
spans: {},
propagateTraceparent: (client as BrowserClient).getOptions().propagateTraceparent,
};
}

/**
Expand Down
31 changes: 31 additions & 0 deletions packages/browser/test/integrations/xhrTracing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* @vitest-environment jsdom
*/

import { afterEach, describe, expect, it, vi } from 'vitest';
import { BrowserClient } from '../../src/client';
import { xhrTracingIntegration } from '../../src/integrations/xhrTracing';
import * as requestModule from '../../src/tracing/request';
import { getDefaultBrowserClientOptions } from '../helper/browser-client-options';

describe('xhrTracingIntegration', () => {
afterEach(() => {
vi.restoreAllMocks();
});

it.each([
[
'instruments XHR requests for normal user agents',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/120.0.0.0',
1,
],
['does not instrument XHR requests for bot user agents', 'Mozilla/5.0 (compatible; Googlebot/2.1)', 0],
])('%s', (_name, userAgent, calls) => {
const instrumentSpy = vi.spyOn(requestModule, 'instrumentXhrRequests').mockImplementation(() => {});
vi.spyOn(window.navigator, 'userAgent', 'get').mockReturnValue(userAgent);

xhrTracingIntegration().setup?.(new BrowserClient(getDefaultBrowserClientOptions()));

expect(instrumentSpy).toHaveBeenCalledTimes(calls);
});
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Missing integration test coverage

Low Severity

This feat PR only adds unit tests that mock instrumentXhrRequests and check registration by name. There is no integration or E2E test for the documented browserTracingCoreIntegration() plus xhrTracingIntegration() setup. Flagged because the testing conventions require at least one integration or E2E test on feat PRs.

Additional Locations (1)
Fix in Cursor Fix in Web

Triggered by project rule: PR Review Guidelines for Cursor Bot

Reviewed by Cursor Bugbot for commit 9c59c53. Configure here.

17 changes: 17 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,23 @@ describe('browserTracingIntegration', () => {
expect(!!client.getIntegrationByName('LongTasks')).toBe(registered);
});

it.each([
['registers xhrTracingIntegration by default', {}, true],
['does not register xhrTracingIntegration when traceXHR is off', { traceXHR: false }, false],
['does not register xhrTracingIntegration when traceXHR is explicitly undefined', { traceXHR: undefined }, false],
])('%s', (_name, options, registered) => {
const client = new BrowserClient(
getDefaultBrowserClientOptions({
tracesSampleRate: 1,
integrations: [browserTracingIntegration(options)],
}),
);
setCurrentClient(client);
client.init();

expect(!!client.getIntegrationByName('XhrTracing')).toBe(registered);
});
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

it('keeps the webVitalsIntegration the user supplies', () => {
const userWebVitals = webVitalsModule.webVitalsIntegration({ softNavigations: false });

Expand Down
Loading