Skip to content

Commit 670d5e9

Browse files
mydeaAbhiPrasad
authored andcommitted
feat(core): Add server.address to browser http.client spans (#11634)
Closes #11632
1 parent 705f919 commit 670d5e9

File tree

13 files changed

+301
-4
lines changed

13 files changed

+301
-4
lines changed

.size-limit.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,6 @@ module.exports = [
170170
path: 'packages/feedback/build/npm/esm/index.js',
171171
import: '{ Feedback }',
172172
gzip: true,
173-
limit: '25 KB',
173+
limit: '160 KB',
174174
},
175175
];
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import * as Sentry from '@sentry/browser';
2+
3+
window.Sentry = Sentry;
4+
5+
Sentry.init({
6+
dsn: 'https://public@dsn.ingest.sentry.io/1337',
7+
integrations: [Sentry.browserTracingIntegration()],
8+
tracesSampleRate: 1,
9+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
fetch('/test-req/0').then(
2+
fetch('/test-req/1', { headers: { 'X-Test-Header': 'existing-header' } }).then(fetch('/test-req/2')),
3+
);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import { expect } from '@playwright/test';
2+
3+
import { TEST_HOST, sentryTest } from '../../../../utils/fixtures';
4+
import {
5+
envelopeRequestParser,
6+
shouldSkipTracingTest,
7+
waitForTransactionRequestOnUrl,
8+
} from '../../../../utils/helpers';
9+
10+
sentryTest('should create spans for fetch requests', async ({ getLocalTestUrl, page }) => {
11+
if (shouldSkipTracingTest()) {
12+
sentryTest.skip();
13+
}
14+
15+
const url = await getLocalTestUrl({ testDir: __dirname });
16+
const req = await waitForTransactionRequestOnUrl(page, url);
17+
const tracingEvent = envelopeRequestParser(req);
18+
19+
const requestSpans = tracingEvent.spans?.filter(({ op }) => op === 'http.client');
20+
21+
expect(requestSpans).toHaveLength(3);
22+
23+
requestSpans?.forEach((span, index) =>
24+
expect(span).toMatchObject({
25+
description: `GET /test-req/${index}`,
26+
parent_span_id: tracingEvent.contexts?.trace?.span_id,
27+
span_id: expect.any(String),
28+
start_timestamp: expect.any(Number),
29+
timestamp: expect.any(Number),
30+
trace_id: tracingEvent.contexts?.trace?.trace_id,
31+
data: {
32+
'http.method': 'GET',
33+
'http.url': `${TEST_HOST}/test-req/${index}`,
34+
url: `/test-req/${index}`,
35+
'server.address': 'sentry-test.io',
36+
type: 'fetch',
37+
},
38+
}),
39+
);
40+
});
41+
42+
sentryTest('should attach `sentry-trace` header to fetch requests', async ({ getLocalTestUrl, page }) => {
43+
if (shouldSkipTracingTest()) {
44+
sentryTest.skip();
45+
}
46+
47+
const url = await getLocalTestUrl({ testDir: __dirname });
48+
49+
const requests = (
50+
await Promise.all([
51+
page.goto(url),
52+
Promise.all([0, 1, 2].map(idx => page.waitForRequest(`${TEST_HOST}/test-req/${idx}`))),
53+
])
54+
)[1];
55+
56+
expect(requests).toHaveLength(3);
57+
58+
const request1 = requests[0];
59+
const requestHeaders1 = request1.headers();
60+
expect(requestHeaders1).toMatchObject({
61+
'sentry-trace': expect.stringMatching(/^([a-f0-9]{32})-([a-f0-9]{16})-1$/),
62+
baggage: expect.any(String),
63+
});
64+
65+
const request2 = requests[1];
66+
const requestHeaders2 = request2.headers();
67+
expect(requestHeaders2).toMatchObject({
68+
'sentry-trace': expect.stringMatching(/^([a-f0-9]{32})-([a-f0-9]{16})-1$/),
69+
baggage: expect.any(String),
70+
'x-test-header': 'existing-header',
71+
});
72+
73+
const request3 = requests[2];
74+
const requestHeaders3 = request3.headers();
75+
expect(requestHeaders3).toMatchObject({
76+
'sentry-trace': expect.stringMatching(/^([a-f0-9]{32})-([a-f0-9]{16})-1$/),
77+
baggage: expect.any(String),
78+
});
79+
});

dev-packages/browser-integration-tests/suites/tracing/request/fetch/test.ts

+7
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,13 @@ sentryTest('should create spans for multiple fetch requests', async ({ getLocalT
3737
start_timestamp: expect.any(Number),
3838
timestamp: expect.any(Number),
3939
trace_id: tracingEvent.contexts?.trace?.trace_id,
40+
data: {
41+
'http.method': 'GET',
42+
'http.url': `http://example.com/${index}`,
43+
url: `http://example.com/${index}`,
44+
'server.address': 'example.com',
45+
type: 'fetch',
46+
},
4047
}),
4148
);
4249
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import * as Sentry from '@sentry/browser';
2+
3+
window.Sentry = Sentry;
4+
5+
Sentry.init({
6+
dsn: 'https://public@dsn.ingest.sentry.io/1337',
7+
integrations: [Sentry.browserTracingIntegration()],
8+
tracesSampleRate: 1,
9+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const xhr_1 = new XMLHttpRequest();
2+
xhr_1.open('GET', '/test-req/0');
3+
xhr_1.send();
4+
5+
const xhr_2 = new XMLHttpRequest();
6+
xhr_2.open('GET', '/test-req/1');
7+
xhr_2.setRequestHeader('X-Test-Header', 'existing-header');
8+
xhr_2.send();
9+
10+
const xhr_3 = new XMLHttpRequest();
11+
xhr_3.open('GET', '/test-req/2');
12+
xhr_3.send();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import { expect } from '@playwright/test';
2+
3+
import { TEST_HOST, sentryTest } from '../../../../utils/fixtures';
4+
import {
5+
envelopeRequestParser,
6+
shouldSkipTracingTest,
7+
waitForTransactionRequestOnUrl,
8+
} from '../../../../utils/helpers';
9+
10+
sentryTest('should create spans for xhr requests', async ({ getLocalTestUrl, page }) => {
11+
if (shouldSkipTracingTest()) {
12+
sentryTest.skip();
13+
}
14+
15+
const url = await getLocalTestUrl({ testDir: __dirname });
16+
const req = await waitForTransactionRequestOnUrl(page, url);
17+
const tracingEvent = envelopeRequestParser(req);
18+
19+
const requestSpans = tracingEvent.spans?.filter(({ op }) => op === 'http.client');
20+
21+
expect(requestSpans).toHaveLength(3);
22+
23+
requestSpans?.forEach((span, index) =>
24+
expect(span).toMatchObject({
25+
description: `GET /test-req/${index}`,
26+
parent_span_id: tracingEvent.contexts?.trace?.span_id,
27+
span_id: expect.any(String),
28+
start_timestamp: expect.any(Number),
29+
timestamp: expect.any(Number),
30+
trace_id: tracingEvent.contexts?.trace?.trace_id,
31+
data: {
32+
'http.method': 'GET',
33+
'http.url': `${TEST_HOST}/test-req/${index}`,
34+
url: `/test-req/${index}`,
35+
'server.address': 'sentry-test.io',
36+
type: 'xhr',
37+
},
38+
}),
39+
);
40+
});
41+
42+
sentryTest('should attach `sentry-trace` header to xhr requests', async ({ getLocalTestUrl, page }) => {
43+
if (shouldSkipTracingTest()) {
44+
sentryTest.skip();
45+
}
46+
47+
const url = await getLocalTestUrl({ testDir: __dirname });
48+
49+
const requests = (
50+
await Promise.all([
51+
page.goto(url),
52+
Promise.all([0, 1, 2].map(idx => page.waitForRequest(`${TEST_HOST}/test-req/${idx}`))),
53+
])
54+
)[1];
55+
56+
expect(requests).toHaveLength(3);
57+
58+
const request1 = requests[0];
59+
const requestHeaders1 = request1.headers();
60+
expect(requestHeaders1).toMatchObject({
61+
'sentry-trace': expect.stringMatching(/^([a-f0-9]{32})-([a-f0-9]{16})-1$/),
62+
baggage: expect.any(String),
63+
});
64+
65+
const request2 = requests[1];
66+
const requestHeaders2 = request2.headers();
67+
expect(requestHeaders2).toMatchObject({
68+
'sentry-trace': expect.stringMatching(/^([a-f0-9]{32})-([a-f0-9]{16})-1$/),
69+
baggage: expect.any(String),
70+
'x-test-header': 'existing-header',
71+
});
72+
73+
const request3 = requests[2];
74+
const requestHeaders3 = request3.headers();
75+
expect(requestHeaders3).toMatchObject({
76+
'sentry-trace': expect.stringMatching(/^([a-f0-9]{32})-([a-f0-9]{16})-1$/),
77+
baggage: expect.any(String),
78+
});
79+
});

dev-packages/browser-integration-tests/suites/tracing/request/xhr/test.ts

+7
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,13 @@ sentryTest('should create spans for multiple XHR requests', async ({ getLocalTes
2525
start_timestamp: expect.any(Number),
2626
timestamp: expect.any(Number),
2727
trace_id: eventData.contexts?.trace?.trace_id,
28+
data: {
29+
'http.method': 'GET',
30+
'http.url': `http://example.com/${index}`,
31+
url: `http://example.com/${index}`,
32+
'server.address': 'example.com',
33+
type: 'xhr',
34+
},
2835
}),
2936
);
3037
});

dev-packages/e2e-tests/test-applications/nextjs-app-dir/tests/middleware.test.ts

+2
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ test('Should trace outgoing fetch requests inside middleware and create breadcru
6868
'http.response.status_code': 200,
6969
type: 'fetch',
7070
url: 'http://localhost:3030/',
71+
'http.url': 'http://localhost:3030/',
72+
'server.address': 'localhost:3030',
7173
'sentry.op': 'http.client',
7274
'sentry.origin': 'auto.http.wintercg_fetch',
7375
},

packages/nextjs/test/integration/test/client/tracingFetch.test.ts

+2
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ test('should correctly instrument `fetch` for performance tracing', async ({ pag
3333
data: {
3434
'http.method': 'GET',
3535
url: 'http://example.com',
36+
'http.url': 'http://example.com/',
37+
'server.address': 'example.com',
3638
type: 'fetch',
3739
'http.response_content_length': expect.any(Number),
3840
'http.response.status_code': 200,

packages/tracing-internal/src/browser/request.ts

+30
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/* eslint-disable max-lines */
22
import {
3+
SEMANTIC_ATTRIBUTE_SENTRY_OP,
34
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
45
getClient,
56
getCurrentScope,
@@ -21,6 +22,7 @@ import {
2122
browserPerformanceTimeOrigin,
2223
dynamicSamplingContextToSentryBaggageHeader,
2324
generateSentryTraceHeader,
25+
parseUrl,
2426
stringMatchesSomePattern,
2527
} from '@sentry/utils';
2628

@@ -119,6 +121,18 @@ export function instrumentOutgoingRequests(_options?: Partial<RequestInstrumenta
119121
if (traceFetch) {
120122
addFetchInstrumentationHandler(handlerData => {
121123
const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);
124+
// We cannot use `window.location` in the generic fetch instrumentation,
125+
// but we need it for reliable `server.address` attribute.
126+
// so we extend this in here
127+
if (createdSpan) {
128+
const fullUrl = getFullURL(handlerData.fetchData.url);
129+
const host = fullUrl ? parseUrl(fullUrl).host : undefined;
130+
createdSpan.setAttributes({
131+
'http.url': fullUrl,
132+
'server.address': host,
133+
});
134+
}
135+
122136
if (enableHTTPTimings && createdSpan) {
123137
addHTTPTimings(createdSpan);
124138
}
@@ -279,14 +293,19 @@ export function xhrCallback(
279293
const scope = getCurrentScope();
280294
const isolationScope = getIsolationScope();
281295

296+
const fullUrl = getFullURL(sentryXhrData.url);
297+
const host = fullUrl ? parseUrl(fullUrl).host : undefined;
298+
282299
const span = shouldCreateSpanResult
283300
? startInactiveSpan({
284301
name: `${sentryXhrData.method} ${sentryXhrData.url}`,
285302
onlyIfParent: true,
286303
attributes: {
287304
type: 'xhr',
288305
'http.method': sentryXhrData.method,
306+
'http.url': fullUrl,
289307
url: sentryXhrData.url,
308+
'server.address': host,
290309
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser',
291310
},
292311
op: 'http.client',
@@ -338,3 +357,14 @@ function setHeaderOnXhr(
338357
// Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
339358
}
340359
}
360+
361+
function getFullURL(url: string): string | undefined {
362+
try {
363+
// By adding a base URL to new URL(), this will also work for relative urls
364+
// If `url` is a full URL, the base URL is ignored anyhow
365+
const parsed = new URL(url, WINDOW.location.origin);
366+
return parsed.href;
367+
} catch {
368+
return undefined;
369+
}
370+
}

0 commit comments

Comments
 (0)