Skip to content

feat(core): Allow to pass scope & client to getTraceData #16633

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 18, 2025
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
7 changes: 4 additions & 3 deletions packages/core/src/utils/traceData.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getAsyncContextStrategy } from '../asyncContext';
import { getMainCarrier } from '../carrier';
import type { Client } from '../client';
import { getClient, getCurrentScope } from '../currentScopes';
import { isEnabled } from '../exports';
import type { Scope } from '../scope';
Expand All @@ -22,8 +23,8 @@ import { getActiveSpan, spanToTraceHeader } from './spanUtils';
* @returns an object with the tracing data values. The object keys are the name of the tracing key to be used as header
* or meta tag name.
*/
export function getTraceData(options: { span?: Span } = {}): SerializedTraceData {
const client = getClient();
export function getTraceData(options: { span?: Span; scope?: Scope; client?: Client } = {}): SerializedTraceData {
const client = options.client || getClient();
if (!isEnabled() || !client) {
return {};
}
Expand All @@ -34,7 +35,7 @@ export function getTraceData(options: { span?: Span } = {}): SerializedTraceData
return acs.getTraceData(options);
}

const scope = getCurrentScope();
const scope = options.scope || getCurrentScope();
const span = options.span || getActiveSpan();
const sentryTrace = span ? spanToTraceHeader(span) : scopeToTraceHeader(scope);
const dsc = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope);
Expand Down
30 changes: 30 additions & 0 deletions packages/core/test/lib/utils/traceData.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
getIsolationScope,
getMainCarrier,
getTraceData,
Scope,
SentrySpan,
setAsyncContextStrategy,
setCurrentClient,
Expand Down Expand Up @@ -158,6 +159,35 @@ describe('getTraceData', () => {
});
});

it('allows to pass a scope & client directly', () => {
// this default client & scope should not be used!
setupClient();
getCurrentScope().setPropagationContext({
traceId: '12345678901234567890123456789099',
sampleRand: 0.44,
});

const options = getDefaultTestClientOptions({
dsn: 'https://567@sentry.io/42',
tracesSampleRate: 1,
});
const customClient = new TestClient(options);

const scope = new Scope();
scope.setPropagationContext({
traceId: '12345678901234567890123456789012',
sampleRand: 0.42,
});
scope.setClient(customClient);

const traceData = getTraceData({ client: customClient, scope });

expect(traceData['sentry-trace']).toMatch(/^12345678901234567890123456789012-[a-f0-9]{16}$/);
expect(traceData.baggage).toEqual(
'sentry-environment=production,sentry-public_key=567,sentry-trace_id=12345678901234567890123456789012',
);
});

it('returns propagationContext DSC data if no span is available', () => {
setupClient();

Expand Down
12 changes: 8 additions & 4 deletions packages/opentelemetry/src/propagator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Baggage, Context, Span, SpanContext, TextMapGetter, TextMapSetter
import { context, INVALID_TRACEID, propagation, trace, TraceFlags } from '@opentelemetry/api';
import { isTracingSuppressed, W3CBaggagePropagator } from '@opentelemetry/core';
import { ATTR_URL_FULL, SEMATTRS_HTTP_URL } from '@opentelemetry/semantic-conventions';
import type { continueTrace, DynamicSamplingContext, Options } from '@sentry/core';
import type { Client, continueTrace, DynamicSamplingContext, Options, Scope } from '@sentry/core';
import {
generateSentryTraceHeader,
getClient,
Expand Down Expand Up @@ -152,8 +152,12 @@ export function shouldPropagateTraceForUrl(

/**
* Get propagation injection data for the given context.
* The additional options can be passed to override the scope and client that is otherwise derived from the context.
*/
export function getInjectionData(context: Context): {
export function getInjectionData(
context: Context,
options: { scope?: Scope; client?: Client } = {},
): {
dynamicSamplingContext: Partial<DynamicSamplingContext> | undefined;
traceId: string | undefined;
spanId: string | undefined;
Expand Down Expand Up @@ -190,8 +194,8 @@ export function getInjectionData(context: Context): {

// Else we try to use the propagation context from the scope
// The only scenario where this should happen is when we neither have a span, nor an incoming trace
const scope = getScopesFromContext(context)?.scope || getCurrentScope();
const client = getClient();
const scope = options.scope || getScopesFromContext(context)?.scope || getCurrentScope();
const client = options.client || getClient();

const propagationContext = scope.getPropagationContext();
const dynamicSamplingContext = client ? getDynamicSamplingContextFromScope(client, scope) : undefined;
Expand Down
12 changes: 8 additions & 4 deletions packages/opentelemetry/src/utils/getTraceData.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as api from '@opentelemetry/api';
import type { SerializedTraceData, Span } from '@sentry/core';
import type { Client, Scope, SerializedTraceData, Span } from '@sentry/core';
import {
dynamicSamplingContextToSentryBaggageHeader,
generateSentryTraceHeader,
Expand All @@ -12,16 +12,20 @@ import { getContextFromScope } from './contextData';
* Otel-specific implementation of `getTraceData`.
* @see `@sentry/core` version of `getTraceData` for more information
*/
export function getTraceData({ span }: { span?: Span } = {}): SerializedTraceData {
let ctx = api.context.active();
export function getTraceData({
span,
scope,
client,
}: { span?: Span; scope?: Scope; client?: Client } = {}): SerializedTraceData {
let ctx = (scope && getContextFromScope(scope)) ?? api.context.active();

if (span) {
const { scope } = getCapturedScopesOnSpan(span);
// fall back to current context if for whatever reason we can't find the one of the span
ctx = (scope && getContextFromScope(scope)) || api.trace.setSpan(api.context.active(), span);
}

const { traceId, spanId, sampled, dynamicSamplingContext } = getInjectionData(ctx);
const { traceId, spanId, sampled, dynamicSamplingContext } = getInjectionData(ctx, { scope, client });

return {
'sentry-trace': generateSentryTraceHeader(traceId, spanId, sampled),
Expand Down
29 changes: 28 additions & 1 deletion packages/opentelemetry/test/utils/getTraceData.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { context, trace } from '@opentelemetry/api';
import { getCurrentScope, setAsyncContextStrategy } from '@sentry/core';
import { getCurrentScope, Scope, setAsyncContextStrategy } from '@sentry/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTraceData } from '../../src/utils/getTraceData';
import { makeTraceState } from '../../src/utils/makeTraceState';
import { cleanupOtel, mockSdkInit } from '../helpers/mockSdkInit';
import { getDefaultTestClientOptions, TestClient } from '../helpers/TestClient';

describe('getTraceData', () => {
beforeEach(() => {
Expand Down Expand Up @@ -52,6 +53,32 @@ describe('getTraceData', () => {
});
});

it('allows to pass a scope & client directly', () => {
getCurrentScope().setPropagationContext({
traceId: '12345678901234567890123456789099',
sampleRand: 0.44,
});

const customClient = new TestClient(
getDefaultTestClientOptions({ tracesSampleRate: 1, dsn: 'https://123@sentry.io/42' }),
);

// note: Right now, this only works properly if the scope is linked to a context
const scope = new Scope();
scope.setPropagationContext({
traceId: '12345678901234567890123456789012',
sampleRand: 0.42,
});
scope.setClient(customClient);

const traceData = getTraceData({ client: customClient, scope });

expect(traceData['sentry-trace']).toMatch(/^12345678901234567890123456789012-[a-f0-9]{16}$/);
expect(traceData.baggage).toEqual(
'sentry-environment=production,sentry-public_key=123,sentry-trace_id=12345678901234567890123456789012',
);
});

it('returns propagationContext DSC data if no span is available', () => {
getCurrentScope().setPropagationContext({
traceId: '12345678901234567890123456789012',
Expand Down
Loading