Skip to content

Commit

Permalink
fix(node): UnifygetDynamicSamplingContextFromSpan (#12522)
Browse files Browse the repository at this point in the history
We used to have a different implementation, that worked slightly
different.

This had two problems:

1. We did not look up the root span in the OTEL implementation, but
relied on already passing in the root span (in core, we convert it to
root span)
2. We did not use frozen DSC properly

Now, the core implementation just works for both OTEL and core spans.

While at this, it also aligns the behavior of looking at the `source` of
a span for DSC. Now, only if the source is `url` we'll _not_ set the
transaction on the DSC - previously, if no source was set at all, we'd
also skip this. But conceptually "no source" is similar to "custom",
which we _do_ allow, so now this is a bit simpler.

Fixes #12508
  • Loading branch information
mydea authored Jun 19, 2024
1 parent 2fbd7cc commit 9724ec1
Show file tree
Hide file tree
Showing 13 changed files with 95 additions and 99 deletions.
4 changes: 2 additions & 2 deletions packages/core/src/baseclient.ts
Original file line number Diff line number Diff 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 Down Expand 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 number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Client, DynamicSamplingContext, Span } from '@sentry/types';
import {
addNonEnumerableProperty,
baggageHeaderToDynamicSamplingContext,
dropUndefinedKeys,
dynamicSamplingContextToSentryBaggageHeader,
} from '@sentry/utils';
Expand Down Expand 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 number Diff line number Diff 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 Down Expand 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 number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
startSession,
} from '@sentry/core';
import {
enhanceDscWithOpenTelemetryRootSpanName,
openTelemetrySetupCheck,
setOpenTelemetryContextAsyncContextStrategy,
setupEventContextTrace,
Expand Down Expand 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 number Diff line number Diff 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 number Diff line number Diff 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 number Diff line number Diff 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 number Diff line number Diff 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 Down Expand 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 number Diff line number Diff 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 number Diff line number Diff 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 number Diff line number Diff 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 Down Expand 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 number Diff line number Diff 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 Down Expand 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

0 comments on commit 9724ec1

Please sign in to comment.