Skip to content

Commit daf2edf

Browse files
authored
feat(core): Add server.address to browser http.client spans (#11634)
Closes #11632
1 parent 2c840c3 commit daf2edf

File tree

13 files changed

+278
-20
lines changed

13 files changed

+278
-20
lines changed

.size-limit.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ module.exports = [
208208
'tls',
209209
],
210210
gzip: true,
211-
limit: '150 KB',
211+
limit: '160 KB',
212212
},
213213
];
214214

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
@@ -36,6 +36,13 @@ sentryTest('should create spans for fetch requests', async ({ getLocalTestPath,
3636
start_timestamp: expect.any(Number),
3737
timestamp: expect.any(Number),
3838
trace_id: tracingEvent.contexts?.trace?.trace_id,
39+
data: {
40+
'http.method': 'GET',
41+
'http.url': `http://example.com/${index}`,
42+
url: `http://example.com/${index}`,
43+
'server.address': 'example.com',
44+
type: 'fetch',
45+
},
3946
}),
4047
);
4148
});
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
@@ -24,6 +24,13 @@ sentryTest('should create spans for XHR requests', async ({ getLocalTestPath, pa
2424
start_timestamp: expect.any(Number),
2525
timestamp: expect.any(Number),
2626
trace_id: eventData.contexts?.trace?.trace_id,
27+
data: {
28+
'http.method': 'GET',
29+
'http.url': `http://example.com/${index}`,
30+
url: `http://example.com/${index}`,
31+
'server.address': 'example.com',
32+
type: 'xhr',
33+
},
2734
}),
2835
);
2936
});

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

+2
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ test('Should trace outgoing fetch requests inside middleware and create breadcru
7676
'http.response.status_code': 200,
7777
type: 'fetch',
7878
url: 'http://localhost:3030/',
79+
'http.url': 'http://localhost:3030/',
80+
'server.address': 'localhost:3030',
7981
'sentry.op': 'http.client',
8082
'sentry.origin': 'auto.http.wintercg_fetch',
8183
},

packages/browser/src/tracing/request.ts

+31-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
addXhrInstrumentationHandler,
55
} from '@sentry-internal/browser-utils';
66
import {
7+
SEMANTIC_ATTRIBUTE_SENTRY_OP,
78
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
89
SentryNonRecordingSpan,
910
getActiveSpan,
@@ -26,6 +27,7 @@ import {
2627
browserPerformanceTimeOrigin,
2728
dynamicSamplingContextToSentryBaggageHeader,
2829
generateSentryTraceHeader,
30+
parseUrl,
2931
stringMatchesSomePattern,
3032
} from '@sentry/utils';
3133
import { WINDOW } from '../helpers';
@@ -115,6 +117,18 @@ export function instrumentOutgoingRequests(_options?: Partial<RequestInstrumenta
115117
if (traceFetch) {
116118
addFetchInstrumentationHandler(handlerData => {
117119
const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);
120+
// We cannot use `window.location` in the generic fetch instrumentation,
121+
// but we need it for reliable `server.address` attribute.
122+
// so we extend this in here
123+
if (createdSpan) {
124+
const fullUrl = getFullURL(handlerData.fetchData.url);
125+
const host = fullUrl ? parseUrl(fullUrl).host : undefined;
126+
createdSpan.setAttributes({
127+
'http.url': fullUrl,
128+
'server.address': host,
129+
});
130+
}
131+
118132
if (enableHTTPTimings && createdSpan) {
119133
addHTTPTimings(createdSpan);
120134
}
@@ -310,17 +324,22 @@ export function xhrCallback(
310324

311325
const hasParent = !!getActiveSpan();
312326

327+
const fullUrl = getFullURL(sentryXhrData.url);
328+
const host = fullUrl ? parseUrl(fullUrl).host : undefined;
329+
313330
const span =
314331
shouldCreateSpanResult && hasParent
315332
? startInactiveSpan({
316333
name: `${sentryXhrData.method} ${sentryXhrData.url}`,
317334
attributes: {
318335
type: 'xhr',
319336
'http.method': sentryXhrData.method,
337+
'http.url': fullUrl,
320338
url: sentryXhrData.url,
339+
'server.address': host,
321340
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser',
341+
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.client',
322342
},
323-
op: 'http.client',
324343
})
325344
: new SentryNonRecordingSpan();
326345

@@ -381,3 +400,14 @@ function setHeaderOnXhr(
381400
// Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
382401
}
383402
}
403+
404+
function getFullURL(url: string): string | undefined {
405+
try {
406+
// By adding a base URL to new URL(), this will also work for relative urls
407+
// If `url` is a full URL, the base URL is ignored anyhow
408+
const parsed = new URL(url, WINDOW.location.origin);
409+
return parsed.href;
410+
} catch {
411+
return undefined;
412+
}
413+
}

0 commit comments

Comments
 (0)