Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ref(tracing): Extract propagation context from meta tags #8430

Merged
merged 2 commits into from
Jun 30, 2023
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
52 changes: 32 additions & 20 deletions packages/tracing-internal/src/browser/browsertracing.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
/* eslint-disable max-lines */
import type { Hub, IdleTransaction } from '@sentry/core';
import {
addTracingExtensions,
extractTraceparentData,
getActiveTransaction,
startIdleTransaction,
TRACING_DEFAULTS,
} from '@sentry/core';
import { addTracingExtensions, getActiveTransaction, startIdleTransaction, TRACING_DEFAULTS } from '@sentry/core';
import type { EventProcessor, Integration, Transaction, TransactionContext, TransactionSource } from '@sentry/types';
import { baggageHeaderToDynamicSamplingContext, getDomElement, logger } from '@sentry/utils';
import { getDomElement, logger, tracingContextFromHeaders } from '@sentry/utils';

import { registerBackgroundTabDetection } from './backgroundtab';
import {
Expand Down Expand Up @@ -297,24 +291,25 @@ export class BrowserTracing implements Integration {
return undefined;
}

const hub = this._getCurrentHub();

const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;

const isPageloadTransaction = context.op === 'pageload';

const sentryTraceMetaTagValue = isPageloadTransaction ? getMetaContent('sentry-trace') : null;
const baggageMetaTagValue = isPageloadTransaction ? getMetaContent('baggage') : null;

const traceParentData = sentryTraceMetaTagValue ? extractTraceparentData(sentryTraceMetaTagValue) : undefined;
const dynamicSamplingContext = baggageMetaTagValue
? baggageHeaderToDynamicSamplingContext(baggageMetaTagValue)
: undefined;
const sentryTrace = isPageloadTransaction ? getMetaContent('sentry-trace') : '';
const baggage = isPageloadTransaction ? getMetaContent('baggage') : '';
const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders(
sentryTrace,
baggage,
);

const expandedContext: TransactionContext = {
...context,
...traceParentData,
...traceparentData,
metadata: {
...context.metadata,
dynamicSamplingContext: traceParentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,
dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,
},
trimEnd: true,
};
Expand All @@ -341,7 +336,6 @@ export class BrowserTracing implements Integration {

__DEBUG_BUILD__ && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);

const hub = this._getCurrentHub();
const { location } = WINDOW;

const idleTransaction = startIdleTransaction(
Expand All @@ -353,6 +347,24 @@ export class BrowserTracing implements Integration {
{ location }, // for use in the tracesSampler
heartbeatInterval,
);

const scope = hub.getScope();

// If it's a pageload and there is a meta tag set
// use the traceparentData as the propagation context
if (isPageloadTransaction && traceparentData) {
scope.setPropagationContext(propagationContext);
} else {
// Navigation transactions should set a new propagation context based on the
// created idle transaction.
scope.setPropagationContext({
traceId: idleTransaction.traceId,
spanId: idleTransaction.spanId,
parentSpanId: idleTransaction.parentSpanId,
sampled: !!idleTransaction.sampled,
});
}

idleTransaction.registerBeforeFinishCallback(transaction => {
this._collectWebVitals();
addPerformanceEntries(transaction);
Expand Down Expand Up @@ -424,11 +436,11 @@ export class BrowserTracing implements Integration {
}

/** Returns the value of a meta tag */
export function getMetaContent(metaName: string): string | null {
export function getMetaContent(metaName: string): string | undefined {
// Can't specify generic to `getDomElement` because tracing can be used
// in a variety of environments, have to disable `no-unsafe-member-access`
// as a result.
const metaTag = getDomElement(`meta[name=${metaName}]`);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return metaTag ? metaTag.getAttribute('content') : null;
return metaTag ? metaTag.getAttribute('content') : undefined;
}
4 changes: 2 additions & 2 deletions packages/tracing-internal/src/browser/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ export function shouldAttachHeaders(url: string, tracePropagationTargets: (strin
*
* @returns Span if a span was created, otherwise void.
*/
function fetchCallback(
export function fetchCallback(
Copy link
Member

Choose a reason for hiding this comment

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

l: why is this change necessary?

Copy link
Member Author

Choose a reason for hiding this comment

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

It was because this was actually being imported by tests:

import { fetchCallback, instrumentOutgoingRequests, shouldAttachHeaders, xhrCallback } from '../../src/browser/request';

handlerData: FetchData,
shouldCreateSpan: (url: string) => boolean,
shouldAttachHeaders: (url: string) => boolean,
Expand Down Expand Up @@ -364,7 +364,7 @@ export function addTracingHeadersToFetchRequest(
*
* @returns Span if a span was created, otherwise void.
*/
function xhrCallback(
export function xhrCallback(
Copy link
Member

Choose a reason for hiding this comment

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

l: same question here

handlerData: XHRData,
shouldCreateSpan: (url: string) => boolean,
shouldAttachHeaders: (url: string) => boolean,
Expand Down
12 changes: 6 additions & 6 deletions packages/tracing-internal/test/browser/browsertracing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@ describe('BrowserTracing', () => {
const browserTracing = createBrowserTracing();

expect(browserTracing.options).toEqual({
_experiments: {},
enableLongTask: true,
...TRACING_DEFAULTS,
markBackgroundTransactions: true,
Expand All @@ -113,16 +112,16 @@ describe('BrowserTracing', () => {
});

expect(browserTracing.options).toEqual({
_experiments: {
enableLongTask: false,
},
enableLongTask: false,
...TRACING_DEFAULTS,
markBackgroundTransactions: true,
routingInstrumentation: instrumentRoutingWithDefaults,
startTransactionOnLocationChange: true,
startTransactionOnPageLoad: true,
...defaultRequestInstrumentationOptions,
_experiments: {
enableLongTask: false,
},
});
});

Expand All @@ -132,7 +131,6 @@ describe('BrowserTracing', () => {
});

expect(browserTracing.options).toEqual({
_experiments: {},
enableLongTask: false,
...TRACING_DEFAULTS,
markBackgroundTransactions: true,
Expand Down Expand Up @@ -248,6 +246,7 @@ describe('BrowserTracing', () => {
traceFetch: true,
traceXHR: true,
tracePropagationTargets: ['something'],
_experiments: {},
});
});

Expand All @@ -261,6 +260,7 @@ describe('BrowserTracing', () => {
});

expect(instrumentOutgoingRequestsMock).toHaveBeenCalledWith({
_experiments: {},
traceFetch: true,
traceXHR: true,
tracePropagationTargets: ['something-else'],
Expand Down Expand Up @@ -546,7 +546,7 @@ describe('BrowserTracing', () => {
document.head.innerHTML = '<meta name="cat-cafe">';

const metaTagValue = getMetaContent('dogpark');
expect(metaTagValue).toBe(null);
expect(metaTagValue).toBe(undefined);
});

it('can pick the correct tag out of multiple options', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ describe('_addMeasureSpans', () => {
name: 'measure-1',
duration: 10,
startTime: 12,
detail: undefined,
};

const timeOrigin = 100;
Expand Down
1 change: 1 addition & 0 deletions packages/tracing-internal/test/browser/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ describe('callbacks', () => {
expect(finishedSpan.data).toEqual({
'http.response_content_length': 123,
'http.method': 'GET',
'http.response.status_code': 404,
type: 'fetch',
url: 'http://dogs.are.great/',
});
Expand Down
1 change: 1 addition & 0 deletions packages/tracing-internal/test/browser/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ describe('instrumentRoutingWithDefaults', () => {
name: 'blank',
op: 'pageload',
metadata: { source: 'url' },
startTimestamp: expect.any(Number),
});
});

Expand Down