Skip to content

Commit 1608c4c

Browse files
committed
ref: Use getTraceData instead
1 parent 5201fc8 commit 1608c4c

File tree

11 files changed

+400
-390
lines changed

11 files changed

+400
-390
lines changed

packages/browser/src/tracing/request.ts

+7-9
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@ import {
99
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
1010
SentryNonRecordingSpan,
1111
getActiveSpan,
12-
getClient,
13-
getSentryHeaders,
12+
getTraceData,
1413
hasTracingEnabled,
1514
instrumentFetchRequest,
1615
setHttpStatus,
@@ -396,12 +395,9 @@ export function xhrCallback(
396395
xhr.__sentry_xhr_span_id__ = span.spanContext().spanId;
397396
spans[xhr.__sentry_xhr_span_id__] = span;
398397

399-
const client = getClient();
400-
401-
if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url) && client) {
398+
if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url)) {
402399
addTracingHeadersToXhrRequest(
403400
xhr,
404-
client,
405401
// If performance is disabled (TWP) or there's no active root span (pageload/navigation/interaction),
406402
// we do not want to use the span as base for the trace headers,
407403
// which means that the headers will be generated from the scope and the sampling decision is deferred
@@ -412,10 +408,12 @@ export function xhrCallback(
412408
return span;
413409
}
414410

415-
function addTracingHeadersToXhrRequest(xhr: SentryWrappedXMLHttpRequest, client: Client, span?: Span): void {
416-
const { sentryTrace, baggage } = getSentryHeaders({ span, client });
411+
function addTracingHeadersToXhrRequest(xhr: SentryWrappedXMLHttpRequest, span?: Span): void {
412+
const { 'sentry-trace': sentryTrace, baggage } = getTraceData({ span });
417413

418-
setHeaderOnXhr(xhr, sentryTrace, baggage);
414+
if (sentryTrace) {
415+
setHeaderOnXhr(xhr, sentryTrace, baggage);
416+
}
419417
}
420418

421419
function setHeaderOnXhr(

packages/core/src/fetch.ts

+24-16
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import type { Client, HandlerDataFetch, Scope, Span, SpanOrigin } from '@sentry/types';
22
import { BAGGAGE_HEADER_NAME, SENTRY_BAGGAGE_KEY_PREFIX, isInstanceOf, parseUrl } from '@sentry/utils';
3-
import { getClient, getCurrentScope } from './currentScopes';
43
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from './semanticAttributes';
5-
import { SPAN_STATUS_ERROR, getSentryHeaders, setHttpStatus, startInactiveSpan } from './tracing';
4+
import { SPAN_STATUS_ERROR, setHttpStatus, startInactiveSpan } from './tracing';
65
import { SentryNonRecordingSpan } from './tracing/sentryNonRecordingSpan';
76
import { hasTracingEnabled } from './utils/hasTracingEnabled';
87
import { getActiveSpan } from './utils/spanUtils';
8+
import { getTraceData } from './utils/traceData';
99

1010
type PolymorphicRequestHeaders =
1111
| Record<string, string | undefined>
@@ -50,9 +50,6 @@ export function instrumentFetchRequest(
5050
return undefined;
5151
}
5252

53-
const scope = getCurrentScope();
54-
const client = getClient();
55-
5653
const { method, url } = handlerData.fetchData;
5754

5855
const fullUrl = getFullURL(url);
@@ -79,7 +76,7 @@ export function instrumentFetchRequest(
7976
handlerData.fetchData.__span = span.spanContext().spanId;
8077
spans[span.spanContext().spanId] = span;
8178

82-
if (shouldAttachHeaders(handlerData.fetchData.url) && client) {
79+
if (shouldAttachHeaders(handlerData.fetchData.url)) {
8380
const request: string | Request = handlerData.args[0];
8481

8582
// In case the user hasn't set the second argument of a fetch call we default it to `{}`.
@@ -88,10 +85,10 @@ export function instrumentFetchRequest(
8885
// eslint-disable-next-line @typescript-eslint/no-explicit-any
8986
const options: { [key: string]: any } = handlerData.args[1];
9087

91-
options.headers = addTracingHeadersToFetchRequest(
88+
options.headers = _addTracingHeadersToFetchRequest(
9289
request,
93-
client,
94-
scope,
90+
undefined,
91+
undefined,
9592
options,
9693
// If performance is disabled (TWP) or there's no active root span (pageload/navigation/interaction),
9794
// we do not want to use the span as base for the trace headers,
@@ -104,12 +101,19 @@ export function instrumentFetchRequest(
104101
}
105102

106103
/**
107-
* Adds sentry-trace and baggage headers to the various forms of fetch headers
104+
* Adds sentry-trace and baggage headers to the various forms of fetch headers.
105+
*
106+
* @deprecated This function will not be exported anymore in v9.
107+
*/
108+
export const addTracingHeadersToFetchRequest = _addTracingHeadersToFetchRequest;
109+
110+
/**
111+
* Adds sentry-trace and baggage headers to the various forms of fetch headers.
108112
*/
109-
export function addTracingHeadersToFetchRequest(
113+
function _addTracingHeadersToFetchRequest(
110114
request: string | unknown, // unknown is actually type Request but we can't export DOM types from this package,
111-
client: Client,
112-
scope: Scope,
115+
_client: Client | undefined,
116+
_scope: Scope | undefined,
113117
fetchOptionsObj: {
114118
headers?:
115119
| {
@@ -119,18 +123,22 @@ export function addTracingHeadersToFetchRequest(
119123
},
120124
span?: Span,
121125
): PolymorphicRequestHeaders | undefined {
122-
const { sentryTrace, baggage } = getSentryHeaders({ span, client, scope });
126+
const traceHeaders = getTraceData({ span });
127+
const sentryTrace = traceHeaders['sentry-trace'];
128+
const baggage = traceHeaders.baggage;
123129

124130
const headers =
125131
fetchOptionsObj.headers ||
126132
(typeof Request !== 'undefined' && isInstanceOf(request, Request) ? (request as Request).headers : undefined);
127133

128134
if (!headers) {
129-
return { 'sentry-trace': sentryTrace, baggage };
135+
return { ...traceHeaders };
130136
} else if (typeof Headers !== 'undefined' && isInstanceOf(headers, Headers)) {
131137
const newHeaders = new Headers(headers as Headers);
132138

133-
newHeaders.set('sentry-trace', sentryTrace);
139+
if (sentryTrace) {
140+
newHeaders.set('sentry-trace', sentryTrace);
141+
}
134142

135143
if (baggage) {
136144
const prevBaggageHeader = newHeaders.get(BAGGAGE_HEADER_NAME);

packages/core/src/index.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,11 @@ export type { MetricData } from '@sentry/types';
110110
export { metricsDefault } from './metrics/exports-default';
111111
export { BrowserMetricsAggregator } from './metrics/browser-aggregator';
112112
export { getMetricSummaryJsonForSpan } from './metrics/metric-summary';
113-
export { addTracingHeadersToFetchRequest, instrumentFetchRequest } from './fetch';
113+
export {
114+
// eslint-disable-next-line deprecation/deprecation
115+
addTracingHeadersToFetchRequest,
116+
instrumentFetchRequest,
117+
} from './fetch';
114118
export { trpcMiddleware } from './trpc';
115119
export { captureFeedback } from './feedback';
116120

packages/core/src/tracing/index.ts

-1
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,3 @@ export {
2828
export { setMeasurement, timedEventsToMeasurements } from './measurement';
2929
export { sampleSpan } from './sampling';
3030
export { logSpanEnd, logSpanStart } from './logSpans';
31-
export { getSentryHeaders } from './sentryHeaders';

packages/core/src/tracing/sentryHeaders.ts

-35
This file was deleted.

packages/core/src/utils/traceData.ts

+29-9
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,20 @@
1-
import type { SerializedTraceData } from '@sentry/types';
2-
import { TRACEPARENT_REGEXP, logger } from '@sentry/utils';
1+
import type { SerializedTraceData, Span } from '@sentry/types';
2+
import {
3+
TRACEPARENT_REGEXP,
4+
dynamicSamplingContextToSentryBaggageHeader,
5+
generateSentryTraceHeader,
6+
logger,
7+
} from '@sentry/utils';
38
import { getAsyncContextStrategy } from '../asyncContext';
49
import { getMainCarrier } from '../carrier';
5-
import { getClient } from '../currentScopes';
10+
import { getClient, getCurrentScope } from '../currentScopes';
611
import { isEnabled } from '../exports';
7-
import { getSentryHeaders } from '../tracing';
8-
import { getActiveSpan } from './spanUtils';
12+
import type { Scope } from '../scope';
13+
import {
14+
getDynamicSamplingContextFromScope,
15+
getDynamicSamplingContextFromSpan,
16+
} from '../tracing/dynamicSamplingContext';
17+
import { getActiveSpan, spanToTraceHeader } from './spanUtils';
918

1019
/**
1120
* Extracts trace propagation data from the current span or from the client's scope (via transaction or propagation
@@ -18,7 +27,7 @@ import { getActiveSpan } from './spanUtils';
1827
* @returns an object with the tracing data values. The object keys are the name of the tracing key to be used as header
1928
* or meta tag name.
2029
*/
21-
export function getTraceData(): SerializedTraceData {
30+
export function getTraceData(options: { span?: Span } = {}): SerializedTraceData {
2231
const client = getClient();
2332
if (!isEnabled() || !client) {
2433
return {};
@@ -27,11 +36,14 @@ export function getTraceData(): SerializedTraceData {
2736
const carrier = getMainCarrier();
2837
const acs = getAsyncContextStrategy(carrier);
2938
if (acs.getTraceData) {
30-
return acs.getTraceData();
39+
return acs.getTraceData(options);
3140
}
3241

33-
const span = getActiveSpan();
34-
const { sentryTrace, baggage } = getSentryHeaders({ span, client });
42+
const scope = getCurrentScope();
43+
const span = options.span || getActiveSpan();
44+
const sentryTrace = span ? spanToTraceHeader(span) : scopeToTraceHeader(scope);
45+
const dsc = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope);
46+
const baggage = dynamicSamplingContextToSentryBaggageHeader(dsc);
3547

3648
const isValidSentryTraceHeader = TRACEPARENT_REGEXP.test(sentryTrace);
3749
if (!isValidSentryTraceHeader) {
@@ -71,3 +83,11 @@ export function isValidBaggageString(baggage?: string): boolean {
7183
);
7284
return baggageRegex.test(baggage);
7385
}
86+
87+
/**
88+
* Get a sentry-trace header value for the given scope.
89+
*/
90+
function scopeToTraceHeader(scope: Scope): string {
91+
const { traceId, sampled, spanId } = scope.getPropagationContext();
92+
return generateSentryTraceHeader(traceId, spanId, sampled);
93+
}

0 commit comments

Comments
 (0)