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
4 changes: 2 additions & 2 deletions packages/core/src/baseclient.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -414,7 +414,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;

/** @inheritdoc */
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/** @inheritdoc */
public on(
Expand DownExpand Up@@ -499,7 +499,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;

/** @inheritdoc */
public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
public emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/** @inheritdoc */
public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;
Expand Down
24 changes: 18 additions & 6 deletions packages/core/src/tracing/dynamicSamplingContext.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, DynamicSamplingContext, Span } from '@sentry/types';
import {
addNonEnumerableProperty,
baggageHeaderToDynamicSamplingContext,
dropUndefinedKeys,
dynamicSamplingContextToSentryBaggageHeader,
} from '@sentry/utils';
Expand DownExpand Up@@ -66,15 +67,25 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client);

const rootSpan = getRootSpan(span);
if (!rootSpan) {
return dsc;
}

// For core implementation, we freeze the DSC onto the span as a non-enumerable property
const frozenDsc = (rootSpan as SpanWithMaybeDsc)[FROZEN_DSC_FIELD];
if (frozenDsc) {
return frozenDsc;
}

// For OpenTelemetry, we freeze the DSC on the trace state
const traceState = rootSpan.spanContext().traceState;
const traceStateDsc = traceState && traceState.get('sentry.dsc');

// If the span has a DSC, we want it to take precedence
const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);

if (dscOnTraceState) {
return dscOnTraceState;
}

// Else, we generate it from the span
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
Expand All@@ -87,13 +98,14 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

// after JSON conversion, txn.name becomes jsonSpan.description
if (source && source !== 'url') {
dsc.transaction = jsonSpan.description;
const name = jsonSpan.description;
if (source !== 'url' && name) {
dsc.transaction = name;
}

dsc.sampled = String(spanIsSampled(rootSpan));

client.emit('createDsc', dsc);
client.emit('createDsc', dsc, rootSpan);

return dsc;
}
Expand Down
23 changes: 22 additions & 1 deletion packages/core/test/lib/tracing/dynamicSamplingContext.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import type { TransactionSource } from '@sentry/types';
import type { Span, SpanContextData, TransactionSource } from '@sentry/types';
import {
SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
Expand DownExpand Up@@ -33,6 +33,27 @@ describe('getDynamicSamplingContextFromSpan', () => {
expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv' });
});

test('uses frozen DSC from traceState', () => {
const rootSpan = {
spanContext() {
return {
traceId: '1234',
spanId: '12345',
traceFlags: 0,
traceState: {
get() {
return 'sentry-environment=myEnv2';
},
} as unknown as SpanContextData['traceState'],
};
},
} as Span;

const dynamicSamplingContext = getDynamicSamplingContextFromSpan(rootSpan);

expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv2' });
});

test('returns a new DSC, if no DSC was provided during rootSpan creation (via attributes)', () => {
const rootSpan = startInactiveSpan({ name: 'tx' });

Expand Down
2 changes: 2 additions & 0 deletions packages/node/src/sdk/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
startSession,
} from '@sentry/core';
import {
enhanceDscWithOpenTelemetryRootSpanName,
openTelemetrySetupCheck,
setOpenTelemetryContextAsyncContextStrategy,
setupEventContextTrace,
Expand DownExpand Up@@ -175,6 +176,7 @@ function _init(
validateOpenTelemetrySetup();
}

enhanceDscWithOpenTelemetryRootSpanName(client);
setupEventContextTrace(client);
}

Expand Down
5 changes: 4 additions & 1 deletion packages/opentelemetry/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,10 +16,13 @@ export {
spanHasStatus,
} from './utils/spanTypes';

export { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
// Re-export this for backwards compatibility (this used to be a different implementation)
export { getDynamicSamplingContextFromSpan } from '@sentry/core';

export { isSentryRequestSpan } from './utils/isSentryRequest';

export { enhanceDscWithOpenTelemetryRootSpanName } from './utils/enhanceDscWithOpenTelemetryRootSpanName';

export { getActiveSpan } from './utils/getActiveSpan';
export { startSpan, startSpanManual, startInactiveSpan, withActiveSpan, continueTrace } from './trace';

Expand Down
9 changes: 7 additions & 2 deletions packages/opentelemetry/src/propagator.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,13 @@ import type { continueTrace } from '@sentry/core';
import { hasTracingEnabled } from '@sentry/core';
import { getRootSpan } from '@sentry/core';
import { spanToJSON } from '@sentry/core';
import { getClient, getCurrentScope, getDynamicSamplingContextFromClient, getIsolationScope } from '@sentry/core';
import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getIsolationScope,
} from '@sentry/core';
import type { DynamicSamplingContext, Options, PropagationContext } from '@sentry/types';
import {
LRUMap,
Expand All@@ -32,7 +38,6 @@ import {
} from './constants';
import { DEBUG_BUILD } from './debug-build';
import { getScopesFromContext, setScopesOnContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';
import { setIsSetup } from './utils/setupCheck';

Expand Down
4 changes: 1 addition & 3 deletions packages/opentelemetry/src/setupEventContextTrace.ts
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
import { getDynamicSamplingContextFromSpan, getRootSpan } from '@sentry/core';
import type { Client } from '@sentry/types';
import { dropUndefinedKeys } from '@sentry/utils';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';

import { getRootSpan } from '@sentry/core';
import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { getActiveSpan } from './utils/getActiveSpan';
import { spanHasParentId } from './utils/spanTypes';
Expand Down
4 changes: 2 additions & 2 deletions packages/opentelemetry/src/spanExporter.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@ import { SEMATTRS_HTTP_STATUS_CODE } from '@opentelemetry/semantic-conventions';
import {
captureEvent,
getCapturedScopesOnSpan,
getDynamicSamplingContextFromSpan,
getMetricSummaryJsonForSpan,
timedEventsToMeasurements,
} from '@sentry/core';
Expand All@@ -22,7 +23,6 @@ import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { DEBUG_BUILD } from './debug-build';
import { SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE } from './semanticAttributes';
import { convertOtelTimeToSeconds } from './utils/convertOtelTimeToSeconds';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getRequestSpanData } from './utils/getRequestSpanData';
import type { SpanNode } from './utils/groupSpansWithParents';
import { getLocalParentId } from './utils/groupSpansWithParents';
Expand DownExpand Up@@ -242,7 +242,7 @@ function createTransactionForOtelSpan(span: ReadableSpan): TransactionEvent {
capturedSpanScope: capturedSpanScopes.scope,
capturedSpanIsolationScope: capturedSpanScopes.isolationScope,
sampleRate,
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span as unknown as Span),
}),
},
...(source && {
Expand Down
2 changes: 1 addition & 1 deletion packages/opentelemetry/src/trace.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@ import {
continueTrace as baseContinueTrace,
getClient,
getCurrentScope,
getDynamicSamplingContextFromSpan,
getRootSpan,
handleCallbackErrors,
spanToJSON,
Expand All@@ -16,7 +17,6 @@ import { continueTraceAsRemoteSpan, makeTraceState } from './propagator';

import type { OpenTelemetryClient, OpenTelemetrySpanContext } from './types';
import { getContextFromScope, getScopesFromContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';

/**
Expand Down
65 changes: 0 additions & 65 deletions packages/opentelemetry/src/utils/dynamicSamplingContext.ts

This file was deleted.

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, spanToJSON } from '@sentry/core';
import type { Client } from '@sentry/types';
import { parseSpanDescription } from './parseSpanDescription';
import { spanHasName } from './spanTypes';

/**
* Setup a DSC handler on the passed client,
* ensuring that the transaction name is inferred from the span correctly.
*/
export function enhanceDscWithOpenTelemetryRootSpanName(client: Client): void {
client.on('createDsc', (dsc, rootSpan) => {
// We want to overwrite the transaction on the DSC that is created by default in core
// The reason for this is that we want to infer the span name, not use the initial one
// Otherwise, we'll get names like "GET" instead of e.g. "GET /foo"
// `parseSpanDescription` takes the attributes of the span into account for the name
// This mutates the passed-in DSC
if (rootSpan) {
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: undefined };
if (source !== 'url' && description) {
dsc.transaction = description;
}
}
});
}
20 changes: 6 additions & 14 deletions packages/opentelemetry/test/trace.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getRootSpan,
spanIsSampled,
spanToJSON,
Expand All@@ -24,7 +25,6 @@ import { makeTraceState } from '../src/propagator';
import { SEMATTRS_HTTP_METHOD } from '@opentelemetry/semantic-conventions';
import { continueTrace, startInactiveSpan, startSpan, startSpanManual } from '../src/trace';
import type { AbstractSpan } from '../src/types';
import { getDynamicSamplingContextFromSpan } from '../src/utils/dynamicSamplingContext';
import { getActiveSpan } from '../src/utils/getActiveSpan';
import { getSamplingDecision } from '../src/utils/getSamplingDecision';
import { getSpanKind } from '../src/utils/getSpanKind';
Expand DownExpand Up@@ -983,24 +983,16 @@ describe('trace', () => {
withScope(scope => {
const propagationContext = scope.getPropagationContext();

const ctx = trace.setSpanContext(ROOT_CONTEXT, {
traceId: '12312012123120121231201212312012',
spanId: '1121201211212012',
isRemote: false,
traceFlags: TraceFlags.SAMPLED,
traceState: undefined,
});

context.with(ctx, () => {
startSpan({ name: 'parent span' }, parentSpan => {
const span = startInactiveSpan({ name: 'test span' });

expect(span).toBeDefined();
expect(spanToJSON(span).trace_id).toEqual('12312012123120121231201212312012');
expect(spanToJSON(span).parent_span_id).toEqual('1121201211212012');
expect(spanToJSON(span).trace_id).toEqual(parentSpan.spanContext().traceId);
expect(spanToJSON(span).parent_span_id).toEqual(parentSpan.spanContext().spanId);
expect(getDynamicSamplingContextFromSpan(span)).toEqual({
...getDynamicSamplingContextFromClient(propagationContext.traceId, getClient()!),
trace_id: '12312012123120121231201212312012',
transaction: 'test span',
trace_id: parentSpan.spanContext().traceId,
transaction: 'parent span',
sampled: 'true',
sample_rate: '1',
});
Expand Down
4 changes: 2 additions & 2 deletions packages/types/src/client.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -244,7 +244,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Register a callback when a DSC (Dynamic Sampling Context) is created.
*/
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/**
* Register a callback when a Feedback event has been prepared.
Expand DownExpand Up@@ -338,7 +338,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Fire a hook for when a DSC (Dynamic Sampling Context) is created. Expects the DSC as second argument.
*/
emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/**
* Fire a hook event for after preparing a feedback event. Events to be given
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all \u003cpre\u003e\u003ccode\u003e blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks"); } } catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); } })(); (function(){ try { var __m = "github.com"; var __re = new RegExp('^' + "github\\.com" + '
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
4 changes: 2 additions & 2 deletions packages/core/src/baseclient.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -414,7 +414,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;

/** @inheritdoc */
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/** @inheritdoc */
public on(
Expand DownExpand Up@@ -499,7 +499,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;

/** @inheritdoc */
public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
public emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/** @inheritdoc */
public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;
Expand Down
24 changes: 18 additions & 6 deletions packages/core/src/tracing/dynamicSamplingContext.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, DynamicSamplingContext, Span } from '@sentry/types';
import {
addNonEnumerableProperty,
baggageHeaderToDynamicSamplingContext,
dropUndefinedKeys,
dynamicSamplingContextToSentryBaggageHeader,
} from '@sentry/utils';
Expand DownExpand Up@@ -66,15 +67,25 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client);

const rootSpan = getRootSpan(span);
if (!rootSpan) {
return dsc;
}

// For core implementation, we freeze the DSC onto the span as a non-enumerable property
const frozenDsc = (rootSpan as SpanWithMaybeDsc)[FROZEN_DSC_FIELD];
if (frozenDsc) {
return frozenDsc;
}

// For OpenTelemetry, we freeze the DSC on the trace state
const traceState = rootSpan.spanContext().traceState;
const traceStateDsc = traceState && traceState.get('sentry.dsc');

// If the span has a DSC, we want it to take precedence
const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);

if (dscOnTraceState) {
return dscOnTraceState;
}

// Else, we generate it from the span
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
Expand All@@ -87,13 +98,14 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

// after JSON conversion, txn.name becomes jsonSpan.description
if (source && source !== 'url') {
dsc.transaction = jsonSpan.description;
const name = jsonSpan.description;
if (source !== 'url' && name) {
dsc.transaction = name;
}

dsc.sampled = String(spanIsSampled(rootSpan));

client.emit('createDsc', dsc);
client.emit('createDsc', dsc, rootSpan);

return dsc;
}
Expand Down
23 changes: 22 additions & 1 deletion packages/core/test/lib/tracing/dynamicSamplingContext.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import type { TransactionSource } from '@sentry/types';
import type { Span, SpanContextData, TransactionSource } from '@sentry/types';
import {
SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
Expand DownExpand Up@@ -33,6 +33,27 @@ describe('getDynamicSamplingContextFromSpan', () => {
expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv' });
});

test('uses frozen DSC from traceState', () => {
const rootSpan = {
spanContext() {
return {
traceId: '1234',
spanId: '12345',
traceFlags: 0,
traceState: {
get() {
return 'sentry-environment=myEnv2';
},
} as unknown as SpanContextData['traceState'],
};
},
} as Span;

const dynamicSamplingContext = getDynamicSamplingContextFromSpan(rootSpan);

expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv2' });
});

test('returns a new DSC, if no DSC was provided during rootSpan creation (via attributes)', () => {
const rootSpan = startInactiveSpan({ name: 'tx' });

Expand Down
2 changes: 2 additions & 0 deletions packages/node/src/sdk/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
startSession,
} from '@sentry/core';
import {
enhanceDscWithOpenTelemetryRootSpanName,
openTelemetrySetupCheck,
setOpenTelemetryContextAsyncContextStrategy,
setupEventContextTrace,
Expand DownExpand Up@@ -175,6 +176,7 @@ function _init(
validateOpenTelemetrySetup();
}

enhanceDscWithOpenTelemetryRootSpanName(client);
setupEventContextTrace(client);
}

Expand Down
5 changes: 4 additions & 1 deletion packages/opentelemetry/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,10 +16,13 @@ export {
spanHasStatus,
} from './utils/spanTypes';

export { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
// Re-export this for backwards compatibility (this used to be a different implementation)
export { getDynamicSamplingContextFromSpan } from '@sentry/core';

export { isSentryRequestSpan } from './utils/isSentryRequest';

export { enhanceDscWithOpenTelemetryRootSpanName } from './utils/enhanceDscWithOpenTelemetryRootSpanName';

export { getActiveSpan } from './utils/getActiveSpan';
export { startSpan, startSpanManual, startInactiveSpan, withActiveSpan, continueTrace } from './trace';

Expand Down
9 changes: 7 additions & 2 deletions packages/opentelemetry/src/propagator.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,13 @@ import type { continueTrace } from '@sentry/core';
import { hasTracingEnabled } from '@sentry/core';
import { getRootSpan } from '@sentry/core';
import { spanToJSON } from '@sentry/core';
import { getClient, getCurrentScope, getDynamicSamplingContextFromClient, getIsolationScope } from '@sentry/core';
import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getIsolationScope,
} from '@sentry/core';
import type { DynamicSamplingContext, Options, PropagationContext } from '@sentry/types';
import {
LRUMap,
Expand All@@ -32,7 +38,6 @@ import {
} from './constants';
import { DEBUG_BUILD } from './debug-build';
import { getScopesFromContext, setScopesOnContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';
import { setIsSetup } from './utils/setupCheck';

Expand Down
4 changes: 1 addition & 3 deletions packages/opentelemetry/src/setupEventContextTrace.ts
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
import { getDynamicSamplingContextFromSpan, getRootSpan } from '@sentry/core';
import type { Client } from '@sentry/types';
import { dropUndefinedKeys } from '@sentry/utils';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';

import { getRootSpan } from '@sentry/core';
import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { getActiveSpan } from './utils/getActiveSpan';
import { spanHasParentId } from './utils/spanTypes';
Expand Down
4 changes: 2 additions & 2 deletions packages/opentelemetry/src/spanExporter.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@ import { SEMATTRS_HTTP_STATUS_CODE } from '@opentelemetry/semantic-conventions';
import {
captureEvent,
getCapturedScopesOnSpan,
getDynamicSamplingContextFromSpan,
getMetricSummaryJsonForSpan,
timedEventsToMeasurements,
} from '@sentry/core';
Expand All@@ -22,7 +23,6 @@ import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { DEBUG_BUILD } from './debug-build';
import { SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE } from './semanticAttributes';
import { convertOtelTimeToSeconds } from './utils/convertOtelTimeToSeconds';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getRequestSpanData } from './utils/getRequestSpanData';
import type { SpanNode } from './utils/groupSpansWithParents';
import { getLocalParentId } from './utils/groupSpansWithParents';
Expand DownExpand Up@@ -242,7 +242,7 @@ function createTransactionForOtelSpan(span: ReadableSpan): TransactionEvent {
capturedSpanScope: capturedSpanScopes.scope,
capturedSpanIsolationScope: capturedSpanScopes.isolationScope,
sampleRate,
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span as unknown as Span),
}),
},
...(source && {
Expand Down
2 changes: 1 addition & 1 deletion packages/opentelemetry/src/trace.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@ import {
continueTrace as baseContinueTrace,
getClient,
getCurrentScope,
getDynamicSamplingContextFromSpan,
getRootSpan,
handleCallbackErrors,
spanToJSON,
Expand All@@ -16,7 +17,6 @@ import { continueTraceAsRemoteSpan, makeTraceState } from './propagator';

import type { OpenTelemetryClient, OpenTelemetrySpanContext } from './types';
import { getContextFromScope, getScopesFromContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';

/**
Expand Down
65 changes: 0 additions & 65 deletions packages/opentelemetry/src/utils/dynamicSamplingContext.ts

This file was deleted.

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, spanToJSON } from '@sentry/core';
import type { Client } from '@sentry/types';
import { parseSpanDescription } from './parseSpanDescription';
import { spanHasName } from './spanTypes';

/**
* Setup a DSC handler on the passed client,
* ensuring that the transaction name is inferred from the span correctly.
*/
export function enhanceDscWithOpenTelemetryRootSpanName(client: Client): void {
client.on('createDsc', (dsc, rootSpan) => {
// We want to overwrite the transaction on the DSC that is created by default in core
// The reason for this is that we want to infer the span name, not use the initial one
// Otherwise, we'll get names like "GET" instead of e.g. "GET /foo"
// `parseSpanDescription` takes the attributes of the span into account for the name
// This mutates the passed-in DSC
if (rootSpan) {
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: undefined };
if (source !== 'url' && description) {
dsc.transaction = description;
}
}
});
}
20 changes: 6 additions & 14 deletions packages/opentelemetry/test/trace.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getRootSpan,
spanIsSampled,
spanToJSON,
Expand All@@ -24,7 +25,6 @@ import { makeTraceState } from '../src/propagator';
import { SEMATTRS_HTTP_METHOD } from '@opentelemetry/semantic-conventions';
import { continueTrace, startInactiveSpan, startSpan, startSpanManual } from '../src/trace';
import type { AbstractSpan } from '../src/types';
import { getDynamicSamplingContextFromSpan } from '../src/utils/dynamicSamplingContext';
import { getActiveSpan } from '../src/utils/getActiveSpan';
import { getSamplingDecision } from '../src/utils/getSamplingDecision';
import { getSpanKind } from '../src/utils/getSpanKind';
Expand DownExpand Up@@ -983,24 +983,16 @@ describe('trace', () => {
withScope(scope => {
const propagationContext = scope.getPropagationContext();

const ctx = trace.setSpanContext(ROOT_CONTEXT, {
traceId: '12312012123120121231201212312012',
spanId: '1121201211212012',
isRemote: false,
traceFlags: TraceFlags.SAMPLED,
traceState: undefined,
});

context.with(ctx, () => {
startSpan({ name: 'parent span' }, parentSpan => {
const span = startInactiveSpan({ name: 'test span' });

expect(span).toBeDefined();
expect(spanToJSON(span).trace_id).toEqual('12312012123120121231201212312012');
expect(spanToJSON(span).parent_span_id).toEqual('1121201211212012');
expect(spanToJSON(span).trace_id).toEqual(parentSpan.spanContext().traceId);
expect(spanToJSON(span).parent_span_id).toEqual(parentSpan.spanContext().spanId);
expect(getDynamicSamplingContextFromSpan(span)).toEqual({
...getDynamicSamplingContextFromClient(propagationContext.traceId, getClient()!),
trace_id: '12312012123120121231201212312012',
transaction: 'test span',
trace_id: parentSpan.spanContext().traceId,
transaction: 'parent span',
sampled: 'true',
sample_rate: '1',
});
Expand Down
4 changes: 2 additions & 2 deletions packages/types/src/client.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -244,7 +244,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Register a callback when a DSC (Dynamic Sampling Context) is created.
*/
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/**
* Register a callback when a Feedback event has been prepared.
Expand DownExpand Up@@ -338,7 +338,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Fire a hook for when a DSC (Dynamic Sampling Context) is created. Expects the DSC as second argument.
*/
emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/**
* Fire a hook event for after preparing a feedback event. Events to be given
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
4 changes: 2 additions & 2 deletions packages/core/src/baseclient.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -414,7 +414,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;

/** @inheritdoc */
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/** @inheritdoc */
public on(
Expand DownExpand Up@@ -499,7 +499,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;

/** @inheritdoc */
public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
public emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/** @inheritdoc */
public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;
Expand Down
24 changes: 18 additions & 6 deletions packages/core/src/tracing/dynamicSamplingContext.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, DynamicSamplingContext, Span } from '@sentry/types';
import {
addNonEnumerableProperty,
baggageHeaderToDynamicSamplingContext,
dropUndefinedKeys,
dynamicSamplingContextToSentryBaggageHeader,
} from '@sentry/utils';
Expand DownExpand Up@@ -66,15 +67,25 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client);

const rootSpan = getRootSpan(span);
if (!rootSpan) {
return dsc;
}

// For core implementation, we freeze the DSC onto the span as a non-enumerable property
const frozenDsc = (rootSpan as SpanWithMaybeDsc)[FROZEN_DSC_FIELD];
if (frozenDsc) {
return frozenDsc;
}

// For OpenTelemetry, we freeze the DSC on the trace state
const traceState = rootSpan.spanContext().traceState;
const traceStateDsc = traceState && traceState.get('sentry.dsc');

// If the span has a DSC, we want it to take precedence
const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);

if (dscOnTraceState) {
return dscOnTraceState;
}

// Else, we generate it from the span
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
Expand All@@ -87,13 +98,14 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

// after JSON conversion, txn.name becomes jsonSpan.description
if (source && source !== 'url') {
dsc.transaction = jsonSpan.description;
const name = jsonSpan.description;
if (source !== 'url' && name) {
dsc.transaction = name;
}

dsc.sampled = String(spanIsSampled(rootSpan));

client.emit('createDsc', dsc);
client.emit('createDsc', dsc, rootSpan);

return dsc;
}
Expand Down
23 changes: 22 additions & 1 deletion packages/core/test/lib/tracing/dynamicSamplingContext.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import type { TransactionSource } from '@sentry/types';
import type { Span, SpanContextData, TransactionSource } from '@sentry/types';
import {
SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
Expand DownExpand Up@@ -33,6 +33,27 @@ describe('getDynamicSamplingContextFromSpan', () => {
expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv' });
});

test('uses frozen DSC from traceState', () => {
const rootSpan = {
spanContext() {
return {
traceId: '1234',
spanId: '12345',
traceFlags: 0,
traceState: {
get() {
return 'sentry-environment=myEnv2';
},
} as unknown as SpanContextData['traceState'],
};
},
} as Span;

const dynamicSamplingContext = getDynamicSamplingContextFromSpan(rootSpan);

expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv2' });
});

test('returns a new DSC, if no DSC was provided during rootSpan creation (via attributes)', () => {
const rootSpan = startInactiveSpan({ name: 'tx' });

Expand Down
2 changes: 2 additions & 0 deletions packages/node/src/sdk/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
startSession,
} from '@sentry/core';
import {
enhanceDscWithOpenTelemetryRootSpanName,
openTelemetrySetupCheck,
setOpenTelemetryContextAsyncContextStrategy,
setupEventContextTrace,
Expand DownExpand Up@@ -175,6 +176,7 @@ function _init(
validateOpenTelemetrySetup();
}

enhanceDscWithOpenTelemetryRootSpanName(client);
setupEventContextTrace(client);
}

Expand Down
5 changes: 4 additions & 1 deletion packages/opentelemetry/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,10 +16,13 @@ export {
spanHasStatus,
} from './utils/spanTypes';

export { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
// Re-export this for backwards compatibility (this used to be a different implementation)
export { getDynamicSamplingContextFromSpan } from '@sentry/core';

export { isSentryRequestSpan } from './utils/isSentryRequest';

export { enhanceDscWithOpenTelemetryRootSpanName } from './utils/enhanceDscWithOpenTelemetryRootSpanName';

export { getActiveSpan } from './utils/getActiveSpan';
export { startSpan, startSpanManual, startInactiveSpan, withActiveSpan, continueTrace } from './trace';

Expand Down
9 changes: 7 additions & 2 deletions packages/opentelemetry/src/propagator.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,13 @@ import type { continueTrace } from '@sentry/core';
import { hasTracingEnabled } from '@sentry/core';
import { getRootSpan } from '@sentry/core';
import { spanToJSON } from '@sentry/core';
import { getClient, getCurrentScope, getDynamicSamplingContextFromClient, getIsolationScope } from '@sentry/core';
import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getIsolationScope,
} from '@sentry/core';
import type { DynamicSamplingContext, Options, PropagationContext } from '@sentry/types';
import {
LRUMap,
Expand All@@ -32,7 +38,6 @@ import {
} from './constants';
import { DEBUG_BUILD } from './debug-build';
import { getScopesFromContext, setScopesOnContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';
import { setIsSetup } from './utils/setupCheck';

Expand Down
4 changes: 1 addition & 3 deletions packages/opentelemetry/src/setupEventContextTrace.ts
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
import { getDynamicSamplingContextFromSpan, getRootSpan } from '@sentry/core';
import type { Client } from '@sentry/types';
import { dropUndefinedKeys } from '@sentry/utils';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';

import { getRootSpan } from '@sentry/core';
import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { getActiveSpan } from './utils/getActiveSpan';
import { spanHasParentId } from './utils/spanTypes';
Expand Down
4 changes: 2 additions & 2 deletions packages/opentelemetry/src/spanExporter.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@ import { SEMATTRS_HTTP_STATUS_CODE } from '@opentelemetry/semantic-conventions';
import {
captureEvent,
getCapturedScopesOnSpan,
getDynamicSamplingContextFromSpan,
getMetricSummaryJsonForSpan,
timedEventsToMeasurements,
} from '@sentry/core';
Expand All@@ -22,7 +23,6 @@ import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { DEBUG_BUILD } from './debug-build';
import { SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE } from './semanticAttributes';
import { convertOtelTimeToSeconds } from './utils/convertOtelTimeToSeconds';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getRequestSpanData } from './utils/getRequestSpanData';
import type { SpanNode } from './utils/groupSpansWithParents';
import { getLocalParentId } from './utils/groupSpansWithParents';
Expand DownExpand Up@@ -242,7 +242,7 @@ function createTransactionForOtelSpan(span: ReadableSpan): TransactionEvent {
capturedSpanScope: capturedSpanScopes.scope,
capturedSpanIsolationScope: capturedSpanScopes.isolationScope,
sampleRate,
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span as unknown as Span),
}),
},
...(source && {
Expand Down
2 changes: 1 addition & 1 deletion packages/opentelemetry/src/trace.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@ import {
continueTrace as baseContinueTrace,
getClient,
getCurrentScope,
getDynamicSamplingContextFromSpan,
getRootSpan,
handleCallbackErrors,
spanToJSON,
Expand All@@ -16,7 +17,6 @@ import { continueTraceAsRemoteSpan, makeTraceState } from './propagator';

import type { OpenTelemetryClient, OpenTelemetrySpanContext } from './types';
import { getContextFromScope, getScopesFromContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';

/**
Expand Down
65 changes: 0 additions & 65 deletions packages/opentelemetry/src/utils/dynamicSamplingContext.ts

This file was deleted.

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, spanToJSON } from '@sentry/core';
import type { Client } from '@sentry/types';
import { parseSpanDescription } from './parseSpanDescription';
import { spanHasName } from './spanTypes';

/**
* Setup a DSC handler on the passed client,
* ensuring that the transaction name is inferred from the span correctly.
*/
export function enhanceDscWithOpenTelemetryRootSpanName(client: Client): void {
client.on('createDsc', (dsc, rootSpan) => {
// We want to overwrite the transaction on the DSC that is created by default in core
// The reason for this is that we want to infer the span name, not use the initial one
// Otherwise, we'll get names like "GET" instead of e.g. "GET /foo"
// `parseSpanDescription` takes the attributes of the span into account for the name
// This mutates the passed-in DSC
if (rootSpan) {
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: undefined };
if (source !== 'url' && description) {
dsc.transaction = description;
}
}
});
}
20 changes: 6 additions & 14 deletions packages/opentelemetry/test/trace.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getRootSpan,
spanIsSampled,
spanToJSON,
Expand All@@ -24,7 +25,6 @@ import { makeTraceState } from '../src/propagator';
import { SEMATTRS_HTTP_METHOD } from '@opentelemetry/semantic-conventions';
import { continueTrace, startInactiveSpan, startSpan, startSpanManual } from '../src/trace';
import type { AbstractSpan } from '../src/types';
import { getDynamicSamplingContextFromSpan } from '../src/utils/dynamicSamplingContext';
import { getActiveSpan } from '../src/utils/getActiveSpan';
import { getSamplingDecision } from '../src/utils/getSamplingDecision';
import { getSpanKind } from '../src/utils/getSpanKind';
Expand DownExpand Up@@ -983,24 +983,16 @@ describe('trace', () => {
withScope(scope => {
const propagationContext = scope.getPropagationContext();

const ctx = trace.setSpanContext(ROOT_CONTEXT, {
traceId: '12312012123120121231201212312012',
spanId: '1121201211212012',
isRemote: false,
traceFlags: TraceFlags.SAMPLED,
traceState: undefined,
});

context.with(ctx, () => {
startSpan({ name: 'parent span' }, parentSpan => {
const span = startInactiveSpan({ name: 'test span' });

expect(span).toBeDefined();
expect(spanToJSON(span).trace_id).toEqual('12312012123120121231201212312012');
expect(spanToJSON(span).parent_span_id).toEqual('1121201211212012');
expect(spanToJSON(span).trace_id).toEqual(parentSpan.spanContext().traceId);
expect(spanToJSON(span).parent_span_id).toEqual(parentSpan.spanContext().spanId);
expect(getDynamicSamplingContextFromSpan(span)).toEqual({
...getDynamicSamplingContextFromClient(propagationContext.traceId, getClient()!),
trace_id: '12312012123120121231201212312012',
transaction: 'test span',
trace_id: parentSpan.spanContext().traceId,
transaction: 'parent span',
sampled: 'true',
sample_rate: '1',
});
Expand Down
4 changes: 2 additions & 2 deletions packages/types/src/client.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -244,7 +244,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Register a callback when a DSC (Dynamic Sampling Context) is created.
*/
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/**
* Register a callback when a Feedback event has been prepared.
Expand DownExpand Up@@ -338,7 +338,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Fire a hook for when a DSC (Dynamic Sampling Context) is created. Expects the DSC as second argument.
*/
emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/**
* Fire a hook event for after preparing a feedback event. Events to be given
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length \u003e 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
4 changes: 2 additions & 2 deletions packages/core/src/baseclient.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -414,7 +414,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;

/** @inheritdoc */
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/** @inheritdoc */
public on(
Expand DownExpand Up@@ -499,7 +499,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;

/** @inheritdoc */
public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
public emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/** @inheritdoc */
public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;
Expand Down
24 changes: 18 additions & 6 deletions packages/core/src/tracing/dynamicSamplingContext.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, DynamicSamplingContext, Span } from '@sentry/types';
import {
addNonEnumerableProperty,
baggageHeaderToDynamicSamplingContext,
dropUndefinedKeys,
dynamicSamplingContextToSentryBaggageHeader,
} from '@sentry/utils';
Expand DownExpand Up@@ -66,15 +67,25 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client);

const rootSpan = getRootSpan(span);
if (!rootSpan) {
return dsc;
}

// For core implementation, we freeze the DSC onto the span as a non-enumerable property
const frozenDsc = (rootSpan as SpanWithMaybeDsc)[FROZEN_DSC_FIELD];
if (frozenDsc) {
return frozenDsc;
}

// For OpenTelemetry, we freeze the DSC on the trace state
const traceState = rootSpan.spanContext().traceState;
const traceStateDsc = traceState && traceState.get('sentry.dsc');

// If the span has a DSC, we want it to take precedence
const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);

if (dscOnTraceState) {
return dscOnTraceState;
}

// Else, we generate it from the span
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
Expand All@@ -87,13 +98,14 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

// after JSON conversion, txn.name becomes jsonSpan.description
if (source && source !== 'url') {
dsc.transaction = jsonSpan.description;
const name = jsonSpan.description;
if (source !== 'url' && name) {
dsc.transaction = name;
}

dsc.sampled = String(spanIsSampled(rootSpan));

client.emit('createDsc', dsc);
client.emit('createDsc', dsc, rootSpan);

return dsc;
}
Expand Down
23 changes: 22 additions & 1 deletion packages/core/test/lib/tracing/dynamicSamplingContext.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import type { TransactionSource } from '@sentry/types';
import type { Span, SpanContextData, TransactionSource } from '@sentry/types';
import {
SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
Expand DownExpand Up@@ -33,6 +33,27 @@ describe('getDynamicSamplingContextFromSpan', () => {
expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv' });
});

test('uses frozen DSC from traceState', () => {
const rootSpan = {
spanContext() {
return {
traceId: '1234',
spanId: '12345',
traceFlags: 0,
traceState: {
get() {
return 'sentry-environment=myEnv2';
},
} as unknown as SpanContextData['traceState'],
};
},
} as Span;

const dynamicSamplingContext = getDynamicSamplingContextFromSpan(rootSpan);

expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv2' });
});

test('returns a new DSC, if no DSC was provided during rootSpan creation (via attributes)', () => {
const rootSpan = startInactiveSpan({ name: 'tx' });

Expand Down
2 changes: 2 additions & 0 deletions packages/node/src/sdk/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
startSession,
} from '@sentry/core';
import {
enhanceDscWithOpenTelemetryRootSpanName,
openTelemetrySetupCheck,
setOpenTelemetryContextAsyncContextStrategy,
setupEventContextTrace,
Expand DownExpand Up@@ -175,6 +176,7 @@ function _init(
validateOpenTelemetrySetup();
}

enhanceDscWithOpenTelemetryRootSpanName(client);
setupEventContextTrace(client);
}

Expand Down
5 changes: 4 additions & 1 deletion packages/opentelemetry/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,10 +16,13 @@ export {
spanHasStatus,
} from './utils/spanTypes';

export { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
// Re-export this for backwards compatibility (this used to be a different implementation)
export { getDynamicSamplingContextFromSpan } from '@sentry/core';

export { isSentryRequestSpan } from './utils/isSentryRequest';

export { enhanceDscWithOpenTelemetryRootSpanName } from './utils/enhanceDscWithOpenTelemetryRootSpanName';

export { getActiveSpan } from './utils/getActiveSpan';
export { startSpan, startSpanManual, startInactiveSpan, withActiveSpan, continueTrace } from './trace';

Expand Down
9 changes: 7 additions & 2 deletions packages/opentelemetry/src/propagator.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,13 @@ import type { continueTrace } from '@sentry/core';
import { hasTracingEnabled } from '@sentry/core';
import { getRootSpan } from '@sentry/core';
import { spanToJSON } from '@sentry/core';
import { getClient, getCurrentScope, getDynamicSamplingContextFromClient, getIsolationScope } from '@sentry/core';
import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getIsolationScope,
} from '@sentry/core';
import type { DynamicSamplingContext, Options, PropagationContext } from '@sentry/types';
import {
LRUMap,
Expand All@@ -32,7 +38,6 @@ import {
} from './constants';
import { DEBUG_BUILD } from './debug-build';
import { getScopesFromContext, setScopesOnContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';
import { setIsSetup } from './utils/setupCheck';

Expand Down
4 changes: 1 addition & 3 deletions packages/opentelemetry/src/setupEventContextTrace.ts
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
import { getDynamicSamplingContextFromSpan, getRootSpan } from '@sentry/core';
import type { Client } from '@sentry/types';
import { dropUndefinedKeys } from '@sentry/utils';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';

import { getRootSpan } from '@sentry/core';
import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { getActiveSpan } from './utils/getActiveSpan';
import { spanHasParentId } from './utils/spanTypes';
Expand Down
4 changes: 2 additions & 2 deletions packages/opentelemetry/src/spanExporter.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@ import { SEMATTRS_HTTP_STATUS_CODE } from '@opentelemetry/semantic-conventions';
import {
captureEvent,
getCapturedScopesOnSpan,
getDynamicSamplingContextFromSpan,
getMetricSummaryJsonForSpan,
timedEventsToMeasurements,
} from '@sentry/core';
Expand All@@ -22,7 +23,6 @@ import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { DEBUG_BUILD } from './debug-build';
import { SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE } from './semanticAttributes';
import { convertOtelTimeToSeconds } from './utils/convertOtelTimeToSeconds';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getRequestSpanData } from './utils/getRequestSpanData';
import type { SpanNode } from './utils/groupSpansWithParents';
import { getLocalParentId } from './utils/groupSpansWithParents';
Expand DownExpand Up@@ -242,7 +242,7 @@ function createTransactionForOtelSpan(span: ReadableSpan): TransactionEvent {
capturedSpanScope: capturedSpanScopes.scope,
capturedSpanIsolationScope: capturedSpanScopes.isolationScope,
sampleRate,
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span as unknown as Span),
}),
},
...(source && {
Expand Down
2 changes: 1 addition & 1 deletion packages/opentelemetry/src/trace.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@ import {
continueTrace as baseContinueTrace,
getClient,
getCurrentScope,
getDynamicSamplingContextFromSpan,
getRootSpan,
handleCallbackErrors,
spanToJSON,
Expand All@@ -16,7 +17,6 @@ import { continueTraceAsRemoteSpan, makeTraceState } from './propagator';

import type { OpenTelemetryClient, OpenTelemetrySpanContext } from './types';
import { getContextFromScope, getScopesFromContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';

/**
Expand Down
65 changes: 0 additions & 65 deletions packages/opentelemetry/src/utils/dynamicSamplingContext.ts

This file was deleted.

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, spanToJSON } from '@sentry/core';
import type { Client } from '@sentry/types';
import { parseSpanDescription } from './parseSpanDescription';
import { spanHasName } from './spanTypes';

/**
* Setup a DSC handler on the passed client,
* ensuring that the transaction name is inferred from the span correctly.
*/
export function enhanceDscWithOpenTelemetryRootSpanName(client: Client): void {
client.on('createDsc', (dsc, rootSpan) => {
// We want to overwrite the transaction on the DSC that is created by default in core
// The reason for this is that we want to infer the span name, not use the initial one
// Otherwise, we'll get names like "GET" instead of e.g. "GET /foo"
// `parseSpanDescription` takes the attributes of the span into account for the name
// This mutates the passed-in DSC
if (rootSpan) {
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: undefined };
if (source !== 'url' && description) {
dsc.transaction = description;
}
}
});
}
20 changes: 6 additions & 14 deletions packages/opentelemetry/test/trace.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getRootSpan,
spanIsSampled,
spanToJSON,
Expand All@@ -24,7 +25,6 @@ import { makeTraceState } from '../src/propagator';
import { SEMATTRS_HTTP_METHOD } from '@opentelemetry/semantic-conventions';
import { continueTrace, startInactiveSpan, startSpan, startSpanManual } from '../src/trace';
import type { AbstractSpan } from '../src/types';
import { getDynamicSamplingContextFromSpan } from '../src/utils/dynamicSamplingContext';
import { getActiveSpan } from '../src/utils/getActiveSpan';
import { getSamplingDecision } from '../src/utils/getSamplingDecision';
import { getSpanKind } from '../src/utils/getSpanKind';
Expand DownExpand Up@@ -983,24 +983,16 @@ describe('trace', () => {
withScope(scope => {
const propagationContext = scope.getPropagationContext();

const ctx = trace.setSpanContext(ROOT_CONTEXT, {
traceId: '12312012123120121231201212312012',
spanId: '1121201211212012',
isRemote: false,
traceFlags: TraceFlags.SAMPLED,
traceState: undefined,
});

context.with(ctx, () => {
startSpan({ name: 'parent span' }, parentSpan => {
const span = startInactiveSpan({ name: 'test span' });

expect(span).toBeDefined();
expect(spanToJSON(span).trace_id).toEqual('12312012123120121231201212312012');
expect(spanToJSON(span).parent_span_id).toEqual('1121201211212012');
expect(spanToJSON(span).trace_id).toEqual(parentSpan.spanContext().traceId);
expect(spanToJSON(span).parent_span_id).toEqual(parentSpan.spanContext().spanId);
expect(getDynamicSamplingContextFromSpan(span)).toEqual({
...getDynamicSamplingContextFromClient(propagationContext.traceId, getClient()!),
trace_id: '12312012123120121231201212312012',
transaction: 'test span',
trace_id: parentSpan.spanContext().traceId,
transaction: 'parent span',
sampled: 'true',
sample_rate: '1',
});
Expand Down
4 changes: 2 additions & 2 deletions packages/types/src/client.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -244,7 +244,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Register a callback when a DSC (Dynamic Sampling Context) is created.
*/
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/**
* Register a callback when a Feedback event has been prepared.
Expand DownExpand Up@@ -338,7 +338,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Fire a hook for when a DSC (Dynamic Sampling Context) is created. Expects the DSC as second argument.
*/
emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/**
* Fire a hook event for after preparing a feedback event. Events to be given
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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
4 changes: 2 additions & 2 deletions packages/core/src/baseclient.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -414,7 +414,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;

/** @inheritdoc */
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/** @inheritdoc */
public on(
Expand DownExpand Up@@ -499,7 +499,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;

/** @inheritdoc */
public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
public emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/** @inheritdoc */
public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;
Expand Down
24 changes: 18 additions & 6 deletions packages/core/src/tracing/dynamicSamplingContext.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, DynamicSamplingContext, Span } from '@sentry/types';
import {
addNonEnumerableProperty,
baggageHeaderToDynamicSamplingContext,
dropUndefinedKeys,
dynamicSamplingContextToSentryBaggageHeader,
} from '@sentry/utils';
Expand DownExpand Up@@ -66,15 +67,25 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client);

const rootSpan = getRootSpan(span);
if (!rootSpan) {
return dsc;
}

// For core implementation, we freeze the DSC onto the span as a non-enumerable property
const frozenDsc = (rootSpan as SpanWithMaybeDsc)[FROZEN_DSC_FIELD];
if (frozenDsc) {
return frozenDsc;
}

// For OpenTelemetry, we freeze the DSC on the trace state
const traceState = rootSpan.spanContext().traceState;
const traceStateDsc = traceState && traceState.get('sentry.dsc');

// If the span has a DSC, we want it to take precedence
const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);

if (dscOnTraceState) {
return dscOnTraceState;
}

// Else, we generate it from the span
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
Expand All@@ -87,13 +98,14 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

// after JSON conversion, txn.name becomes jsonSpan.description
if (source && source !== 'url') {
dsc.transaction = jsonSpan.description;
const name = jsonSpan.description;
if (source !== 'url' && name) {
dsc.transaction = name;
}

dsc.sampled = String(spanIsSampled(rootSpan));

client.emit('createDsc', dsc);
client.emit('createDsc', dsc, rootSpan);

return dsc;
}
Expand Down
23 changes: 22 additions & 1 deletion packages/core/test/lib/tracing/dynamicSamplingContext.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import type { TransactionSource } from '@sentry/types';
import type { Span, SpanContextData, TransactionSource } from '@sentry/types';
import {
SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
Expand DownExpand Up@@ -33,6 +33,27 @@ describe('getDynamicSamplingContextFromSpan', () => {
expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv' });
});

test('uses frozen DSC from traceState', () => {
const rootSpan = {
spanContext() {
return {
traceId: '1234',
spanId: '12345',
traceFlags: 0,
traceState: {
get() {
return 'sentry-environment=myEnv2';
},
} as unknown as SpanContextData['traceState'],
};
},
} as Span;

const dynamicSamplingContext = getDynamicSamplingContextFromSpan(rootSpan);

expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv2' });
});

test('returns a new DSC, if no DSC was provided during rootSpan creation (via attributes)', () => {
const rootSpan = startInactiveSpan({ name: 'tx' });

Expand Down
2 changes: 2 additions & 0 deletions packages/node/src/sdk/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
startSession,
} from '@sentry/core';
import {
enhanceDscWithOpenTelemetryRootSpanName,
openTelemetrySetupCheck,
setOpenTelemetryContextAsyncContextStrategy,
setupEventContextTrace,
Expand DownExpand Up@@ -175,6 +176,7 @@ function _init(
validateOpenTelemetrySetup();
}

enhanceDscWithOpenTelemetryRootSpanName(client);
setupEventContextTrace(client);
}

Expand Down
5 changes: 4 additions & 1 deletion packages/opentelemetry/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,10 +16,13 @@ export {
spanHasStatus,
} from './utils/spanTypes';

export { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
// Re-export this for backwards compatibility (this used to be a different implementation)
export { getDynamicSamplingContextFromSpan } from '@sentry/core';

export { isSentryRequestSpan } from './utils/isSentryRequest';

export { enhanceDscWithOpenTelemetryRootSpanName } from './utils/enhanceDscWithOpenTelemetryRootSpanName';

export { getActiveSpan } from './utils/getActiveSpan';
export { startSpan, startSpanManual, startInactiveSpan, withActiveSpan, continueTrace } from './trace';

Expand Down
9 changes: 7 additions & 2 deletions packages/opentelemetry/src/propagator.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,13 @@ import type { continueTrace } from '@sentry/core';
import { hasTracingEnabled } from '@sentry/core';
import { getRootSpan } from '@sentry/core';
import { spanToJSON } from '@sentry/core';
import { getClient, getCurrentScope, getDynamicSamplingContextFromClient, getIsolationScope } from '@sentry/core';
import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getIsolationScope,
} from '@sentry/core';
import type { DynamicSamplingContext, Options, PropagationContext } from '@sentry/types';
import {
LRUMap,
Expand All@@ -32,7 +38,6 @@ import {
} from './constants';
import { DEBUG_BUILD } from './debug-build';
import { getScopesFromContext, setScopesOnContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';
import { setIsSetup } from './utils/setupCheck';

Expand Down
4 changes: 1 addition & 3 deletions packages/opentelemetry/src/setupEventContextTrace.ts
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
import { getDynamicSamplingContextFromSpan, getRootSpan } from '@sentry/core';
import type { Client } from '@sentry/types';
import { dropUndefinedKeys } from '@sentry/utils';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';

import { getRootSpan } from '@sentry/core';
import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { getActiveSpan } from './utils/getActiveSpan';
import { spanHasParentId } from './utils/spanTypes';
Expand Down
4 changes: 2 additions & 2 deletions packages/opentelemetry/src/spanExporter.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@ import { SEMATTRS_HTTP_STATUS_CODE } from '@opentelemetry/semantic-conventions';
import {
captureEvent,
getCapturedScopesOnSpan,
getDynamicSamplingContextFromSpan,
getMetricSummaryJsonForSpan,
timedEventsToMeasurements,
} from '@sentry/core';
Expand All@@ -22,7 +23,6 @@ import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { DEBUG_BUILD } from './debug-build';
import { SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE } from './semanticAttributes';
import { convertOtelTimeToSeconds } from './utils/convertOtelTimeToSeconds';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getRequestSpanData } from './utils/getRequestSpanData';
import type { SpanNode } from './utils/groupSpansWithParents';
import { getLocalParentId } from './utils/groupSpansWithParents';
Expand DownExpand Up@@ -242,7 +242,7 @@ function createTransactionForOtelSpan(span: ReadableSpan): TransactionEvent {
capturedSpanScope: capturedSpanScopes.scope,
capturedSpanIsolationScope: capturedSpanScopes.isolationScope,
sampleRate,
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span as unknown as Span),
}),
},
...(source && {
Expand Down
2 changes: 1 addition & 1 deletion packages/opentelemetry/src/trace.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@ import {
continueTrace as baseContinueTrace,
getClient,
getCurrentScope,
getDynamicSamplingContextFromSpan,
getRootSpan,
handleCallbackErrors,
spanToJSON,
Expand All@@ -16,7 +17,6 @@ import { continueTraceAsRemoteSpan, makeTraceState } from './propagator';

import type { OpenTelemetryClient, OpenTelemetrySpanContext } from './types';
import { getContextFromScope, getScopesFromContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';

/**
Expand Down
65 changes: 0 additions & 65 deletions packages/opentelemetry/src/utils/dynamicSamplingContext.ts

This file was deleted.

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, spanToJSON } from '@sentry/core';
import type { Client } from '@sentry/types';
import { parseSpanDescription } from './parseSpanDescription';
import { spanHasName } from './spanTypes';

/**
* Setup a DSC handler on the passed client,
* ensuring that the transaction name is inferred from the span correctly.
*/
export function enhanceDscWithOpenTelemetryRootSpanName(client: Client): void {
client.on('createDsc', (dsc, rootSpan) => {
// We want to overwrite the transaction on the DSC that is created by default in core
// The reason for this is that we want to infer the span name, not use the initial one
// Otherwise, we'll get names like "GET" instead of e.g. "GET /foo"
// `parseSpanDescription` takes the attributes of the span into account for the name
// This mutates the passed-in DSC
if (rootSpan) {
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: undefined };
if (source !== 'url' && description) {
dsc.transaction = description;
}
}
});
}
20 changes: 6 additions & 14 deletions packages/opentelemetry/test/trace.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getRootSpan,
spanIsSampled,
spanToJSON,
Expand All@@ -24,7 +25,6 @@ import { makeTraceState } from '../src/propagator';
import { SEMATTRS_HTTP_METHOD } from '@opentelemetry/semantic-conventions';
import { continueTrace, startInactiveSpan, startSpan, startSpanManual } from '../src/trace';
import type { AbstractSpan } from '../src/types';
import { getDynamicSamplingContextFromSpan } from '../src/utils/dynamicSamplingContext';
import { getActiveSpan } from '../src/utils/getActiveSpan';
import { getSamplingDecision } from '../src/utils/getSamplingDecision';
import { getSpanKind } from '../src/utils/getSpanKind';
Expand DownExpand Up@@ -983,24 +983,16 @@ describe('trace', () => {
withScope(scope => {
const propagationContext = scope.getPropagationContext();

const ctx = trace.setSpanContext(ROOT_CONTEXT, {
traceId: '12312012123120121231201212312012',
spanId: '1121201211212012',
isRemote: false,
traceFlags: TraceFlags.SAMPLED,
traceState: undefined,
});

context.with(ctx, () => {
startSpan({ name: 'parent span' }, parentSpan => {
const span = startInactiveSpan({ name: 'test span' });

expect(span).toBeDefined();
expect(spanToJSON(span).trace_id).toEqual('12312012123120121231201212312012');
expect(spanToJSON(span).parent_span_id).toEqual('1121201211212012');
expect(spanToJSON(span).trace_id).toEqual(parentSpan.spanContext().traceId);
expect(spanToJSON(span).parent_span_id).toEqual(parentSpan.spanContext().spanId);
expect(getDynamicSamplingContextFromSpan(span)).toEqual({
...getDynamicSamplingContextFromClient(propagationContext.traceId, getClient()!),
trace_id: '12312012123120121231201212312012',
transaction: 'test span',
trace_id: parentSpan.spanContext().traceId,
transaction: 'parent span',
sampled: 'true',
sample_rate: '1',
});
Expand Down
4 changes: 2 additions & 2 deletions packages/types/src/client.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -244,7 +244,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Register a callback when a DSC (Dynamic Sampling Context) is created.
*/
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/**
* Register a callback when a Feedback event has been prepared.
Expand DownExpand Up@@ -338,7 +338,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Fire a hook for when a DSC (Dynamic Sampling Context) is created. Expects the DSC as second argument.
*/
emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/**
* Fire a hook event for after preparing a feedback event. Events to be given
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
4 changes: 2 additions & 2 deletions packages/core/src/baseclient.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -414,7 +414,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;

/** @inheritdoc */
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/** @inheritdoc */
public on(
Expand DownExpand Up@@ -499,7 +499,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;

/** @inheritdoc */
public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
public emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/** @inheritdoc */
public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;
Expand Down
24 changes: 18 additions & 6 deletions packages/core/src/tracing/dynamicSamplingContext.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, DynamicSamplingContext, Span } from '@sentry/types';
import {
addNonEnumerableProperty,
baggageHeaderToDynamicSamplingContext,
dropUndefinedKeys,
dynamicSamplingContextToSentryBaggageHeader,
} from '@sentry/utils';
Expand DownExpand Up@@ -66,15 +67,25 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client);

const rootSpan = getRootSpan(span);
if (!rootSpan) {
return dsc;
}

// For core implementation, we freeze the DSC onto the span as a non-enumerable property
const frozenDsc = (rootSpan as SpanWithMaybeDsc)[FROZEN_DSC_FIELD];
if (frozenDsc) {
return frozenDsc;
}

// For OpenTelemetry, we freeze the DSC on the trace state
const traceState = rootSpan.spanContext().traceState;
const traceStateDsc = traceState && traceState.get('sentry.dsc');

// If the span has a DSC, we want it to take precedence
const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);

if (dscOnTraceState) {
return dscOnTraceState;
}

// Else, we generate it from the span
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
Expand All@@ -87,13 +98,14 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

// after JSON conversion, txn.name becomes jsonSpan.description
if (source && source !== 'url') {
dsc.transaction = jsonSpan.description;
const name = jsonSpan.description;
if (source !== 'url' && name) {
dsc.transaction = name;
}

dsc.sampled = String(spanIsSampled(rootSpan));

client.emit('createDsc', dsc);
client.emit('createDsc', dsc, rootSpan);

return dsc;
}
Expand Down
23 changes: 22 additions & 1 deletion packages/core/test/lib/tracing/dynamicSamplingContext.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import type { TransactionSource } from '@sentry/types';
import type { Span, SpanContextData, TransactionSource } from '@sentry/types';
import {
SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
Expand DownExpand Up@@ -33,6 +33,27 @@ describe('getDynamicSamplingContextFromSpan', () => {
expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv' });
});

test('uses frozen DSC from traceState', () => {
const rootSpan = {
spanContext() {
return {
traceId: '1234',
spanId: '12345',
traceFlags: 0,
traceState: {
get() {
return 'sentry-environment=myEnv2';
},
} as unknown as SpanContextData['traceState'],
};
},
} as Span;

const dynamicSamplingContext = getDynamicSamplingContextFromSpan(rootSpan);

expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv2' });
});

test('returns a new DSC, if no DSC was provided during rootSpan creation (via attributes)', () => {
const rootSpan = startInactiveSpan({ name: 'tx' });

Expand Down
2 changes: 2 additions & 0 deletions packages/node/src/sdk/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
startSession,
} from '@sentry/core';
import {
enhanceDscWithOpenTelemetryRootSpanName,
openTelemetrySetupCheck,
setOpenTelemetryContextAsyncContextStrategy,
setupEventContextTrace,
Expand DownExpand Up@@ -175,6 +176,7 @@ function _init(
validateOpenTelemetrySetup();
}

enhanceDscWithOpenTelemetryRootSpanName(client);
setupEventContextTrace(client);
}

Expand Down
5 changes: 4 additions & 1 deletion packages/opentelemetry/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,10 +16,13 @@ export {
spanHasStatus,
} from './utils/spanTypes';

export { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
// Re-export this for backwards compatibility (this used to be a different implementation)
export { getDynamicSamplingContextFromSpan } from '@sentry/core';

export { isSentryRequestSpan } from './utils/isSentryRequest';

export { enhanceDscWithOpenTelemetryRootSpanName } from './utils/enhanceDscWithOpenTelemetryRootSpanName';

export { getActiveSpan } from './utils/getActiveSpan';
export { startSpan, startSpanManual, startInactiveSpan, withActiveSpan, continueTrace } from './trace';

Expand Down
9 changes: 7 additions & 2 deletions packages/opentelemetry/src/propagator.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,13 @@ import type { continueTrace } from '@sentry/core';
import { hasTracingEnabled } from '@sentry/core';
import { getRootSpan } from '@sentry/core';
import { spanToJSON } from '@sentry/core';
import { getClient, getCurrentScope, getDynamicSamplingContextFromClient, getIsolationScope } from '@sentry/core';
import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getIsolationScope,
} from '@sentry/core';
import type { DynamicSamplingContext, Options, PropagationContext } from '@sentry/types';
import {
LRUMap,
Expand All@@ -32,7 +38,6 @@ import {
} from './constants';
import { DEBUG_BUILD } from './debug-build';
import { getScopesFromContext, setScopesOnContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';
import { setIsSetup } from './utils/setupCheck';

Expand Down
4 changes: 1 addition & 3 deletions packages/opentelemetry/src/setupEventContextTrace.ts
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
import { getDynamicSamplingContextFromSpan, getRootSpan } from '@sentry/core';
import type { Client } from '@sentry/types';
import { dropUndefinedKeys } from '@sentry/utils';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';

import { getRootSpan } from '@sentry/core';
import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { getActiveSpan } from './utils/getActiveSpan';
import { spanHasParentId } from './utils/spanTypes';
Expand Down
4 changes: 2 additions & 2 deletions packages/opentelemetry/src/spanExporter.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@ import { SEMATTRS_HTTP_STATUS_CODE } from '@opentelemetry/semantic-conventions';
import {
captureEvent,
getCapturedScopesOnSpan,
getDynamicSamplingContextFromSpan,
getMetricSummaryJsonForSpan,
timedEventsToMeasurements,
} from '@sentry/core';
Expand All@@ -22,7 +23,6 @@ import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { DEBUG_BUILD } from './debug-build';
import { SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE } from './semanticAttributes';
import { convertOtelTimeToSeconds } from './utils/convertOtelTimeToSeconds';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getRequestSpanData } from './utils/getRequestSpanData';
import type { SpanNode } from './utils/groupSpansWithParents';
import { getLocalParentId } from './utils/groupSpansWithParents';
Expand DownExpand Up@@ -242,7 +242,7 @@ function createTransactionForOtelSpan(span: ReadableSpan): TransactionEvent {
capturedSpanScope: capturedSpanScopes.scope,
capturedSpanIsolationScope: capturedSpanScopes.isolationScope,
sampleRate,
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span as unknown as Span),
}),
},
...(source && {
Expand Down
2 changes: 1 addition & 1 deletion packages/opentelemetry/src/trace.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@ import {
continueTrace as baseContinueTrace,
getClient,
getCurrentScope,
getDynamicSamplingContextFromSpan,
getRootSpan,
handleCallbackErrors,
spanToJSON,
Expand All@@ -16,7 +17,6 @@ import { continueTraceAsRemoteSpan, makeTraceState } from './propagator';

import type { OpenTelemetryClient, OpenTelemetrySpanContext } from './types';
import { getContextFromScope, getScopesFromContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';

/**
Expand Down
65 changes: 0 additions & 65 deletions packages/opentelemetry/src/utils/dynamicSamplingContext.ts

This file was deleted.

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, spanToJSON } from '@sentry/core';
import type { Client } from '@sentry/types';
import { parseSpanDescription } from './parseSpanDescription';
import { spanHasName } from './spanTypes';

/**
* Setup a DSC handler on the passed client,
* ensuring that the transaction name is inferred from the span correctly.
*/
export function enhanceDscWithOpenTelemetryRootSpanName(client: Client): void {
client.on('createDsc', (dsc, rootSpan) => {
// We want to overwrite the transaction on the DSC that is created by default in core
// The reason for this is that we want to infer the span name, not use the initial one
// Otherwise, we'll get names like "GET" instead of e.g. "GET /foo"
// `parseSpanDescription` takes the attributes of the span into account for the name
// This mutates the passed-in DSC
if (rootSpan) {
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: undefined };
if (source !== 'url' && description) {
dsc.transaction = description;
}
}
});
}
20 changes: 6 additions & 14 deletions packages/opentelemetry/test/trace.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getRootSpan,
spanIsSampled,
spanToJSON,
Expand All@@ -24,7 +25,6 @@ import { makeTraceState } from '../src/propagator';
import { SEMATTRS_HTTP_METHOD } from '@opentelemetry/semantic-conventions';
import { continueTrace, startInactiveSpan, startSpan, startSpanManual } from '../src/trace';
import type { AbstractSpan } from '../src/types';
import { getDynamicSamplingContextFromSpan } from '../src/utils/dynamicSamplingContext';
import { getActiveSpan } from '../src/utils/getActiveSpan';
import { getSamplingDecision } from '../src/utils/getSamplingDecision';
import { getSpanKind } from '../src/utils/getSpanKind';
Expand DownExpand Up@@ -983,24 +983,16 @@ describe('trace', () => {
withScope(scope => {
const propagationContext = scope.getPropagationContext();

const ctx = trace.setSpanContext(ROOT_CONTEXT, {
traceId: '12312012123120121231201212312012',
spanId: '1121201211212012',
isRemote: false,
traceFlags: TraceFlags.SAMPLED,
traceState: undefined,
});

context.with(ctx, () => {
startSpan({ name: 'parent span' }, parentSpan => {
const span = startInactiveSpan({ name: 'test span' });

expect(span).toBeDefined();
expect(spanToJSON(span).trace_id).toEqual('12312012123120121231201212312012');
expect(spanToJSON(span).parent_span_id).toEqual('1121201211212012');
expect(spanToJSON(span).trace_id).toEqual(parentSpan.spanContext().traceId);
expect(spanToJSON(span).parent_span_id).toEqual(parentSpan.spanContext().spanId);
expect(getDynamicSamplingContextFromSpan(span)).toEqual({
...getDynamicSamplingContextFromClient(propagationContext.traceId, getClient()!),
trace_id: '12312012123120121231201212312012',
transaction: 'test span',
trace_id: parentSpan.spanContext().traceId,
transaction: 'parent span',
sampled: 'true',
sample_rate: '1',
});
Expand Down
4 changes: 2 additions & 2 deletions packages/types/src/client.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -244,7 +244,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Register a callback when a DSC (Dynamic Sampling Context) is created.
*/
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/**
* Register a callback when a Feedback event has been prepared.
Expand DownExpand Up@@ -338,7 +338,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Fire a hook for when a DSC (Dynamic Sampling Context) is created. Expects the DSC as second argument.
*/
emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/**
* Fire a hook event for after preparing a feedback event. Events to be given
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
4 changes: 2 additions & 2 deletions packages/core/src/baseclient.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -414,7 +414,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;

/** @inheritdoc */
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/** @inheritdoc */
public on(
Expand DownExpand Up@@ -499,7 +499,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;

/** @inheritdoc */
public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
public emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/** @inheritdoc */
public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;
Expand Down
24 changes: 18 additions & 6 deletions packages/core/src/tracing/dynamicSamplingContext.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, DynamicSamplingContext, Span } from '@sentry/types';
import {
addNonEnumerableProperty,
baggageHeaderToDynamicSamplingContext,
dropUndefinedKeys,
dynamicSamplingContextToSentryBaggageHeader,
} from '@sentry/utils';
Expand DownExpand Up@@ -66,15 +67,25 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client);

const rootSpan = getRootSpan(span);
if (!rootSpan) {
return dsc;
}

// For core implementation, we freeze the DSC onto the span as a non-enumerable property
const frozenDsc = (rootSpan as SpanWithMaybeDsc)[FROZEN_DSC_FIELD];
if (frozenDsc) {
return frozenDsc;
}

// For OpenTelemetry, we freeze the DSC on the trace state
const traceState = rootSpan.spanContext().traceState;
const traceStateDsc = traceState && traceState.get('sentry.dsc');

// If the span has a DSC, we want it to take precedence
const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);

if (dscOnTraceState) {
return dscOnTraceState;
}

// Else, we generate it from the span
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
Expand All@@ -87,13 +98,14 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

// after JSON conversion, txn.name becomes jsonSpan.description
if (source && source !== 'url') {
dsc.transaction = jsonSpan.description;
const name = jsonSpan.description;
if (source !== 'url' && name) {
dsc.transaction = name;
}

dsc.sampled = String(spanIsSampled(rootSpan));

client.emit('createDsc', dsc);
client.emit('createDsc', dsc, rootSpan);

return dsc;
}
Expand Down
23 changes: 22 additions & 1 deletion packages/core/test/lib/tracing/dynamicSamplingContext.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import type { TransactionSource } from '@sentry/types';
import type { Span, SpanContextData, TransactionSource } from '@sentry/types';
import {
SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
Expand DownExpand Up@@ -33,6 +33,27 @@ describe('getDynamicSamplingContextFromSpan', () => {
expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv' });
});

test('uses frozen DSC from traceState', () => {
const rootSpan = {
spanContext() {
return {
traceId: '1234',
spanId: '12345',
traceFlags: 0,
traceState: {
get() {
return 'sentry-environment=myEnv2';
},
} as unknown as SpanContextData['traceState'],
};
},
} as Span;

const dynamicSamplingContext = getDynamicSamplingContextFromSpan(rootSpan);

expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv2' });
});

test('returns a new DSC, if no DSC was provided during rootSpan creation (via attributes)', () => {
const rootSpan = startInactiveSpan({ name: 'tx' });

Expand Down
2 changes: 2 additions & 0 deletions packages/node/src/sdk/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
startSession,
} from '@sentry/core';
import {
enhanceDscWithOpenTelemetryRootSpanName,
openTelemetrySetupCheck,
setOpenTelemetryContextAsyncContextStrategy,
setupEventContextTrace,
Expand DownExpand Up@@ -175,6 +176,7 @@ function _init(
validateOpenTelemetrySetup();
}

enhanceDscWithOpenTelemetryRootSpanName(client);
setupEventContextTrace(client);
}

Expand Down
5 changes: 4 additions & 1 deletion packages/opentelemetry/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,10 +16,13 @@ export {
spanHasStatus,
} from './utils/spanTypes';

export { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
// Re-export this for backwards compatibility (this used to be a different implementation)
export { getDynamicSamplingContextFromSpan } from '@sentry/core';

export { isSentryRequestSpan } from './utils/isSentryRequest';

export { enhanceDscWithOpenTelemetryRootSpanName } from './utils/enhanceDscWithOpenTelemetryRootSpanName';

export { getActiveSpan } from './utils/getActiveSpan';
export { startSpan, startSpanManual, startInactiveSpan, withActiveSpan, continueTrace } from './trace';

Expand Down
9 changes: 7 additions & 2 deletions packages/opentelemetry/src/propagator.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,13 @@ import type { continueTrace } from '@sentry/core';
import { hasTracingEnabled } from '@sentry/core';
import { getRootSpan } from '@sentry/core';
import { spanToJSON } from '@sentry/core';
import { getClient, getCurrentScope, getDynamicSamplingContextFromClient, getIsolationScope } from '@sentry/core';
import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getIsolationScope,
} from '@sentry/core';
import type { DynamicSamplingContext, Options, PropagationContext } from '@sentry/types';
import {
LRUMap,
Expand All@@ -32,7 +38,6 @@ import {
} from './constants';
import { DEBUG_BUILD } from './debug-build';
import { getScopesFromContext, setScopesOnContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';
import { setIsSetup } from './utils/setupCheck';

Expand Down
4 changes: 1 addition & 3 deletions packages/opentelemetry/src/setupEventContextTrace.ts
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
import { getDynamicSamplingContextFromSpan, getRootSpan } from '@sentry/core';
import type { Client } from '@sentry/types';
import { dropUndefinedKeys } from '@sentry/utils';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';

import { getRootSpan } from '@sentry/core';
import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { getActiveSpan } from './utils/getActiveSpan';
import { spanHasParentId } from './utils/spanTypes';
Expand Down
4 changes: 2 additions & 2 deletions packages/opentelemetry/src/spanExporter.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@ import { SEMATTRS_HTTP_STATUS_CODE } from '@opentelemetry/semantic-conventions';
import {
captureEvent,
getCapturedScopesOnSpan,
getDynamicSamplingContextFromSpan,
getMetricSummaryJsonForSpan,
timedEventsToMeasurements,
} from '@sentry/core';
Expand All@@ -22,7 +23,6 @@ import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { DEBUG_BUILD } from './debug-build';
import { SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE } from './semanticAttributes';
import { convertOtelTimeToSeconds } from './utils/convertOtelTimeToSeconds';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getRequestSpanData } from './utils/getRequestSpanData';
import type { SpanNode } from './utils/groupSpansWithParents';
import { getLocalParentId } from './utils/groupSpansWithParents';
Expand DownExpand Up@@ -242,7 +242,7 @@ function createTransactionForOtelSpan(span: ReadableSpan): TransactionEvent {
capturedSpanScope: capturedSpanScopes.scope,
capturedSpanIsolationScope: capturedSpanScopes.isolationScope,
sampleRate,
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span as unknown as Span),
}),
},
...(source && {
Expand Down
2 changes: 1 addition & 1 deletion packages/opentelemetry/src/trace.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@ import {
continueTrace as baseContinueTrace,
getClient,
getCurrentScope,
getDynamicSamplingContextFromSpan,
getRootSpan,
handleCallbackErrors,
spanToJSON,
Expand All@@ -16,7 +17,6 @@ import { continueTraceAsRemoteSpan, makeTraceState } from './propagator';

import type { OpenTelemetryClient, OpenTelemetrySpanContext } from './types';
import { getContextFromScope, getScopesFromContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';

/**
Expand Down
65 changes: 0 additions & 65 deletions packages/opentelemetry/src/utils/dynamicSamplingContext.ts

This file was deleted.

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, spanToJSON } from '@sentry/core';
import type { Client } from '@sentry/types';
import { parseSpanDescription } from './parseSpanDescription';
import { spanHasName } from './spanTypes';

/**
* Setup a DSC handler on the passed client,
* ensuring that the transaction name is inferred from the span correctly.
*/
export function enhanceDscWithOpenTelemetryRootSpanName(client: Client): void {
client.on('createDsc', (dsc, rootSpan) => {
// We want to overwrite the transaction on the DSC that is created by default in core
// The reason for this is that we want to infer the span name, not use the initial one
// Otherwise, we'll get names like "GET" instead of e.g. "GET /foo"
// `parseSpanDescription` takes the attributes of the span into account for the name
// This mutates the passed-in DSC
if (rootSpan) {
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: undefined };
if (source !== 'url' && description) {
dsc.transaction = description;
}
}
});
}
20 changes: 6 additions & 14 deletions packages/opentelemetry/test/trace.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getRootSpan,
spanIsSampled,
spanToJSON,
Expand All@@ -24,7 +25,6 @@ import { makeTraceState } from '../src/propagator';
import { SEMATTRS_HTTP_METHOD } from '@opentelemetry/semantic-conventions';
import { continueTrace, startInactiveSpan, startSpan, startSpanManual } from '../src/trace';
import type { AbstractSpan } from '../src/types';
import { getDynamicSamplingContextFromSpan } from '../src/utils/dynamicSamplingContext';
import { getActiveSpan } from '../src/utils/getActiveSpan';
import { getSamplingDecision } from '../src/utils/getSamplingDecision';
import { getSpanKind } from '../src/utils/getSpanKind';
Expand DownExpand Up@@ -983,24 +983,16 @@ describe('trace', () => {
withScope(scope => {
const propagationContext = scope.getPropagationContext();

const ctx = trace.setSpanContext(ROOT_CONTEXT, {
traceId: '12312012123120121231201212312012',
spanId: '1121201211212012',
isRemote: false,
traceFlags: TraceFlags.SAMPLED,
traceState: undefined,
});

context.with(ctx, () => {
startSpan({ name: 'parent span' }, parentSpan => {
const span = startInactiveSpan({ name: 'test span' });

expect(span).toBeDefined();
expect(spanToJSON(span).trace_id).toEqual('12312012123120121231201212312012');
expect(spanToJSON(span).parent_span_id).toEqual('1121201211212012');
expect(spanToJSON(span).trace_id).toEqual(parentSpan.spanContext().traceId);
expect(spanToJSON(span).parent_span_id).toEqual(parentSpan.spanContext().spanId);
expect(getDynamicSamplingContextFromSpan(span)).toEqual({
...getDynamicSamplingContextFromClient(propagationContext.traceId, getClient()!),
trace_id: '12312012123120121231201212312012',
transaction: 'test span',
trace_id: parentSpan.spanContext().traceId,
transaction: 'parent span',
sampled: 'true',
sample_rate: '1',
});
Expand Down
4 changes: 2 additions & 2 deletions packages/types/src/client.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -244,7 +244,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Register a callback when a DSC (Dynamic Sampling Context) is created.
*/
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/**
* Register a callback when a Feedback event has been prepared.
Expand DownExpand Up@@ -338,7 +338,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Fire a hook for when a DSC (Dynamic Sampling Context) is created. Expects the DSC as second argument.
*/
emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/**
* Fire a hook event for after preparing a feedback event. Events to be given
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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
4 changes: 2 additions & 2 deletions packages/core/src/baseclient.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -414,7 +414,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;

/** @inheritdoc */
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/** @inheritdoc */
public on(
Expand DownExpand Up@@ -499,7 +499,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;

/** @inheritdoc */
public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
public emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/** @inheritdoc */
public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean }): void;
Expand Down
24 changes: 18 additions & 6 deletions packages/core/src/tracing/dynamicSamplingContext.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, DynamicSamplingContext, Span } from '@sentry/types';
import {
addNonEnumerableProperty,
baggageHeaderToDynamicSamplingContext,
dropUndefinedKeys,
dynamicSamplingContextToSentryBaggageHeader,
} from '@sentry/utils';
Expand DownExpand Up@@ -66,15 +67,25 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client);

const rootSpan = getRootSpan(span);
if (!rootSpan) {
return dsc;
}

// For core implementation, we freeze the DSC onto the span as a non-enumerable property
const frozenDsc = (rootSpan as SpanWithMaybeDsc)[FROZEN_DSC_FIELD];
if (frozenDsc) {
return frozenDsc;
}

// For OpenTelemetry, we freeze the DSC on the trace state
const traceState = rootSpan.spanContext().traceState;
const traceStateDsc = traceState && traceState.get('sentry.dsc');

// If the span has a DSC, we want it to take precedence
const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);

if (dscOnTraceState) {
return dscOnTraceState;
}

// Else, we generate it from the span
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
Expand All@@ -87,13 +98,14 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

// after JSON conversion, txn.name becomes jsonSpan.description
if (source && source !== 'url') {
dsc.transaction = jsonSpan.description;
const name = jsonSpan.description;
if (source !== 'url' && name) {
dsc.transaction = name;
}

dsc.sampled = String(spanIsSampled(rootSpan));

client.emit('createDsc', dsc);
client.emit('createDsc', dsc, rootSpan);

return dsc;
}
Expand Down
23 changes: 22 additions & 1 deletion packages/core/test/lib/tracing/dynamicSamplingContext.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import type { TransactionSource } from '@sentry/types';
import type { Span, SpanContextData, TransactionSource } from '@sentry/types';
import {
SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
Expand DownExpand Up@@ -33,6 +33,27 @@ describe('getDynamicSamplingContextFromSpan', () => {
expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv' });
});

test('uses frozen DSC from traceState', () => {
const rootSpan = {
spanContext() {
return {
traceId: '1234',
spanId: '12345',
traceFlags: 0,
traceState: {
get() {
return 'sentry-environment=myEnv2';
},
} as unknown as SpanContextData['traceState'],
};
},
} as Span;

const dynamicSamplingContext = getDynamicSamplingContextFromSpan(rootSpan);

expect(dynamicSamplingContext).toStrictEqual({ environment: 'myEnv2' });
});

test('returns a new DSC, if no DSC was provided during rootSpan creation (via attributes)', () => {
const rootSpan = startInactiveSpan({ name: 'tx' });

Expand Down
2 changes: 2 additions & 0 deletions packages/node/src/sdk/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
startSession,
} from '@sentry/core';
import {
enhanceDscWithOpenTelemetryRootSpanName,
openTelemetrySetupCheck,
setOpenTelemetryContextAsyncContextStrategy,
setupEventContextTrace,
Expand DownExpand Up@@ -175,6 +176,7 @@ function _init(
validateOpenTelemetrySetup();
}

enhanceDscWithOpenTelemetryRootSpanName(client);
setupEventContextTrace(client);
}

Expand Down
5 changes: 4 additions & 1 deletion packages/opentelemetry/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,10 +16,13 @@ export {
spanHasStatus,
} from './utils/spanTypes';

export { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
// Re-export this for backwards compatibility (this used to be a different implementation)
export { getDynamicSamplingContextFromSpan } from '@sentry/core';

export { isSentryRequestSpan } from './utils/isSentryRequest';

export { enhanceDscWithOpenTelemetryRootSpanName } from './utils/enhanceDscWithOpenTelemetryRootSpanName';

export { getActiveSpan } from './utils/getActiveSpan';
export { startSpan, startSpanManual, startInactiveSpan, withActiveSpan, continueTrace } from './trace';

Expand Down
9 changes: 7 additions & 2 deletions packages/opentelemetry/src/propagator.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,13 @@ import type { continueTrace } from '@sentry/core';
import { hasTracingEnabled } from '@sentry/core';
import { getRootSpan } from '@sentry/core';
import { spanToJSON } from '@sentry/core';
import { getClient, getCurrentScope, getDynamicSamplingContextFromClient, getIsolationScope } from '@sentry/core';
import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getIsolationScope,
} from '@sentry/core';
import type { DynamicSamplingContext, Options, PropagationContext } from '@sentry/types';
import {
LRUMap,
Expand All@@ -32,7 +38,6 @@ import {
} from './constants';
import { DEBUG_BUILD } from './debug-build';
import { getScopesFromContext, setScopesOnContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';
import { setIsSetup } from './utils/setupCheck';

Expand Down
4 changes: 1 addition & 3 deletions packages/opentelemetry/src/setupEventContextTrace.ts
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
import { getDynamicSamplingContextFromSpan, getRootSpan } from '@sentry/core';
import type { Client } from '@sentry/types';
import { dropUndefinedKeys } from '@sentry/utils';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';

import { getRootSpan } from '@sentry/core';
import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { getActiveSpan } from './utils/getActiveSpan';
import { spanHasParentId } from './utils/spanTypes';
Expand Down
4 changes: 2 additions & 2 deletions packages/opentelemetry/src/spanExporter.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@ import { SEMATTRS_HTTP_STATUS_CODE } from '@opentelemetry/semantic-conventions';
import {
captureEvent,
getCapturedScopesOnSpan,
getDynamicSamplingContextFromSpan,
getMetricSummaryJsonForSpan,
timedEventsToMeasurements,
} from '@sentry/core';
Expand All@@ -22,7 +23,6 @@ import { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';
import { DEBUG_BUILD } from './debug-build';
import { SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE } from './semanticAttributes';
import { convertOtelTimeToSeconds } from './utils/convertOtelTimeToSeconds';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getRequestSpanData } from './utils/getRequestSpanData';
import type { SpanNode } from './utils/groupSpansWithParents';
import { getLocalParentId } from './utils/groupSpansWithParents';
Expand DownExpand Up@@ -242,7 +242,7 @@ function createTransactionForOtelSpan(span: ReadableSpan): TransactionEvent {
capturedSpanScope: capturedSpanScopes.scope,
capturedSpanIsolationScope: capturedSpanScopes.isolationScope,
sampleRate,
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
dynamicSamplingContext: getDynamicSamplingContextFromSpan(span as unknown as Span),
}),
},
...(source && {
Expand Down
2 changes: 1 addition & 1 deletion packages/opentelemetry/src/trace.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@ import {
continueTrace as baseContinueTrace,
getClient,
getCurrentScope,
getDynamicSamplingContextFromSpan,
getRootSpan,
handleCallbackErrors,
spanToJSON,
Expand All@@ -16,7 +17,6 @@ import { continueTraceAsRemoteSpan, makeTraceState } from './propagator';

import type { OpenTelemetryClient, OpenTelemetrySpanContext } from './types';
import { getContextFromScope, getScopesFromContext } from './utils/contextData';
import { getDynamicSamplingContextFromSpan } from './utils/dynamicSamplingContext';
import { getSamplingDecision } from './utils/getSamplingDecision';

/**
Expand Down
65 changes: 0 additions & 65 deletions packages/opentelemetry/src/utils/dynamicSamplingContext.ts

This file was deleted.

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, spanToJSON } from '@sentry/core';
import type { Client } from '@sentry/types';
import { parseSpanDescription } from './parseSpanDescription';
import { spanHasName } from './spanTypes';

/**
* Setup a DSC handler on the passed client,
* ensuring that the transaction name is inferred from the span correctly.
*/
export function enhanceDscWithOpenTelemetryRootSpanName(client: Client): void {
client.on('createDsc', (dsc, rootSpan) => {
// We want to overwrite the transaction on the DSC that is created by default in core
// The reason for this is that we want to infer the span name, not use the initial one
// Otherwise, we'll get names like "GET" instead of e.g. "GET /foo"
// `parseSpanDescription` takes the attributes of the span into account for the name
// This mutates the passed-in DSC
if (rootSpan) {
const jsonSpan = spanToJSON(rootSpan);
const attributes = jsonSpan.data || {};
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];

const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: undefined };
if (source !== 'url' && description) {
dsc.transaction = description;
}
}
});
}
20 changes: 6 additions & 14 deletions packages/opentelemetry/test/trace.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ import {
getClient,
getCurrentScope,
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getRootSpan,
spanIsSampled,
spanToJSON,
Expand All@@ -24,7 +25,6 @@ import { makeTraceState } from '../src/propagator';
import { SEMATTRS_HTTP_METHOD } from '@opentelemetry/semantic-conventions';
import { continueTrace, startInactiveSpan, startSpan, startSpanManual } from '../src/trace';
import type { AbstractSpan } from '../src/types';
import { getDynamicSamplingContextFromSpan } from '../src/utils/dynamicSamplingContext';
import { getActiveSpan } from '../src/utils/getActiveSpan';
import { getSamplingDecision } from '../src/utils/getSamplingDecision';
import { getSpanKind } from '../src/utils/getSpanKind';
Expand DownExpand Up@@ -983,24 +983,16 @@ describe('trace', () => {
withScope(scope => {
const propagationContext = scope.getPropagationContext();

const ctx = trace.setSpanContext(ROOT_CONTEXT, {
traceId: '12312012123120121231201212312012',
spanId: '1121201211212012',
isRemote: false,
traceFlags: TraceFlags.SAMPLED,
traceState: undefined,
});

context.with(ctx, () => {
startSpan({ name: 'parent span' }, parentSpan => {
const span = startInactiveSpan({ name: 'test span' });

expect(span).toBeDefined();
expect(spanToJSON(span).trace_id).toEqual('12312012123120121231201212312012');
expect(spanToJSON(span).parent_span_id).toEqual('1121201211212012');
expect(spanToJSON(span).trace_id).toEqual(parentSpan.spanContext().traceId);
expect(spanToJSON(span).parent_span_id).toEqual(parentSpan.spanContext().spanId);
expect(getDynamicSamplingContextFromSpan(span)).toEqual({
...getDynamicSamplingContextFromClient(propagationContext.traceId, getClient()!),
trace_id: '12312012123120121231201212312012',
transaction: 'test span',
trace_id: parentSpan.spanContext().traceId,
transaction: 'parent span',
sampled: 'true',
sample_rate: '1',
});
Expand Down
4 changes: 2 additions & 2 deletions packages/types/src/client.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -244,7 +244,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Register a callback when a DSC (Dynamic Sampling Context) is created.
*/
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;
on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void): void;

/**
* Register a callback when a Feedback event has been prepared.
Expand DownExpand Up@@ -338,7 +338,7 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/**
* Fire a hook for when a DSC (Dynamic Sampling Context) is created. Expects the DSC as second argument.
*/
emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;
emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;

/**
* Fire a hook event for after preparing a feedback event. Events to be given
Expand Down