Skip to content

Commit

Permalink
rework: export getTraceData from core
Browse files Browse the repository at this point in the history
  • Loading branch information
Lms24 committed Aug 2, 2024
1 parent 63283d0 commit 63926bf
Show file tree
Hide file tree
Showing 14 changed files with 53 additions and 52 deletions.
2 changes: 1 addition & 1 deletion packages/astro/src/index.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export {
getSentryRelease,
getSpanDescendants,
getSpanStatusFromHttpCode,
getTracingMetaTagValues,
getTraceData,
graphqlIntegration,
hapiIntegration,
httpIntegration,
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import type { Client, Scope, Span, SpanAttributes } from '@sentry/types';
import { addNonEnumerableProperty, objectify, stripUrlQueryAndFragment } from '@sentry/utils';
import type { APIContext, MiddlewareResponseHandler } from 'astro';

import { getTracingMetaTagValues } from '@sentry/node';
import { getTraceData } from '@sentry/node';

type MiddlewareOptions = {
/**
Expand Down Expand Up @@ -189,7 +189,7 @@ function addMetaTagToHead(htmlChunk: string, scope: Scope, client: Client, span?
if (typeof htmlChunk !== 'string') {
return htmlChunk;
}
const { 'sentry-trace': sentryTrace, baggage } = getTracingMetaTagValues(span, scope, client);
const { 'sentry-trace': sentryTrace, baggage } = getTraceData(span, scope, client);

const sentryTraceMeta = `<meta name="sentry-trace" content="${sentryTrace}"/>`;
const baggageMeta = baggage && `<meta name="baggage" content="${baggage}"/>`;
Expand Down
4 changes: 4 additions & 0 deletions packages/astro/test/server/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ describe('sentryMiddleware', () => {
});
vi.spyOn(SentryNode, 'getActiveSpan').mockImplementation(getSpanMock);
vi.spyOn(SentryNode, 'getClient').mockImplementation(() => ({}) as Client);
vi.spyOn(SentryNode, 'getTraceData').mockImplementation(() => ({
'sentry-trace': '123',
baggage: 'abc',
}));
vi.spyOn(SentryCore, 'getDynamicSamplingContextFromSpan').mockImplementation(() => ({
transaction: 'test',
}));
Expand Down
2 changes: 1 addition & 1 deletion packages/aws-serverless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export {
getCurrentScope,
getGlobalScope,
getIsolationScope,
getTracingMetaTagValues,
getTraceData,
setCurrentClient,
Scope,
SDK_VERSION,
Expand Down
2 changes: 1 addition & 1 deletion packages/bun/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export {
getCurrentScope,
getGlobalScope,
getIsolationScope,
getTracingMetaTagValues,
getTraceData,
setCurrentClient,
Scope,
SDK_VERSION,
Expand Down
1 change: 1 addition & 0 deletions packages/cloudflare/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export {
setMeasurement,
getActiveSpan,
getRootSpan,
getTraceData,
startSpan,
startInactiveSpan,
startSpanManual,
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export {
} from './utils/spanUtils';
export { parseSampleRate } from './utils/parseSampleRate';
export { applySdkMetadata } from './utils/sdkMetadata';
export { getTraceData } from './utils/traceData';
export { DEFAULT_ENVIRONMENT } from './constants';
export { addBreadcrumb } from './breadcrumbs';
export { functionToStringIntegration } from './integrations/functiontostring';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,63 +1,56 @@
import {
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
getRootSpan,
spanToTraceHeader,
} from '@sentry/core';
import type { Client, Scope, Span } from '@sentry/types';
import {
TRACEPARENT_REGEXP,
dynamicSamplingContextToSentryBaggageHeader,
generateSentryTraceHeader,
logger,
} from '@sentry/utils';
import { getClient, getCurrentScope } from '../currentScopes';
import { getDynamicSamplingContextFromClient, getDynamicSamplingContextFromSpan } from '../tracing';
import { getActiveSpan, getRootSpan, spanToTraceHeader } from './spanUtils';

/**
* Extracts trace propagation data from the current span or from the client's scope (via transaction or propagation
* context) and serializes it to meta tag content values.
*
* Use this function to obtain data for the tracing meta tags you can inject when rendering an HTML response to
* continue the server-initiated trace on the client.
* context) and serializes it to `sentry-trace` and `baggage` values to strings. These values can be used to propagate
* a trace via our tracing Http headers or Html `<meta>` tags.
*
* Example usage:
* This function also applies some validation to the generated sentry-trace and baggage values to ensure that
* only valid strings are returned.
*
* ```js
* // render meta tags as html
* const tagValues = getTracingMetaTagValues(span, scope, client);
* return `
* <meta name="sentry-trace" content="${tagValues['sentry-trace']}"/>
* ${tagValues.baggage ? `<meta name="baggage" content="${tagValues.baggage}"/>` : ''}`
* ```
* @param span a span to take the trace data from. By default, the currently active span is used.
* @param scope the scope to take trace data from By default, the active current scope is used.
* @param client the SDK's client to take trace data from. By default, the current client is used.
*
* @param span the currently active span
* @param client the SDK's client
*
* @returns an object with the values of the tracing meta tags. The object keys are the name of the meta tag,
* the respective value is the content.
* @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 getTracingMetaTagValues(
span: Span | undefined,
scope: Scope,
client: Client | undefined,
export function getTraceData(
span?: Span | undefined,
scope?: Scope,
client?: Client,
): { 'sentry-trace': string; baggage?: string } {
const { dsc, sampled, traceId } = scope.getPropagationContext();
const rootSpan = span && getRootSpan(span);
const clientToUse = client || getClient();
const scopeToUser = scope || getCurrentScope();
const spanToUse = span || getActiveSpan();

const { dsc, sampled, traceId } = scopeToUser.getPropagationContext();
const rootSpan = spanToUse && getRootSpan(spanToUse);

const sentryTrace = span ? spanToTraceHeader(span) : generateSentryTraceHeader(traceId, undefined, sampled);
const sentryTrace = spanToUse ? spanToTraceHeader(spanToUse) : generateSentryTraceHeader(traceId, undefined, sampled);

const dynamicSamplingContext = rootSpan
? getDynamicSamplingContextFromSpan(rootSpan)
: dsc
? dsc
: client
? getDynamicSamplingContextFromClient(traceId, client)
: clientToUse
? getDynamicSamplingContextFromClient(traceId, clientToUse)
: undefined;

const baggage = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);

const isValidSentryTraceHeader = TRACEPARENT_REGEXP.test(sentryTrace);
if (!isValidSentryTraceHeader) {
logger.warn('Invalid sentry-trace data. Returning empty "sentry-trace" meta tag');
logger.warn('Invalid sentry-trace data. Returning empty "sentry-trace" value');
}

const validBaggage = isValidBaggageString(baggage);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as SentryCore from '@sentry/core';
import { SentrySpan } from '@sentry/core';
import { SentrySpan, getTraceData } from '../../../src/';
import * as SentryCoreTracing from '../../../src/tracing';

import { getTracingMetaTagValues, isValidBaggageString } from '../../src/utils/meta';
import { isValidBaggageString } from '../../../src/utils/traceData';

const TRACE_FLAG_SAMPLED = 1;

Expand All @@ -19,14 +19,14 @@ const mockedScope = {
}),
} as any;

describe('getTracingMetaTagValues', () => {
describe('getTraceData', () => {
it('returns the tracing meta tags from the span, if it is provided', () => {
{
jest.spyOn(SentryCore, 'getDynamicSamplingContextFromSpan').mockReturnValueOnce({
jest.spyOn(SentryCoreTracing, 'getDynamicSamplingContextFromSpan').mockReturnValueOnce({
environment: 'production',
});

const tags = getTracingMetaTagValues(mockedSpan, mockedScope, mockedClient);
const tags = getTraceData(mockedSpan, mockedScope, mockedClient);

expect(tags).toEqual({
'sentry-trace': '12345678901234567890123456789012-1234567890123456-1',
Expand All @@ -36,7 +36,7 @@ describe('getTracingMetaTagValues', () => {
});

it('returns propagationContext DSC data if no span is available', () => {
const tags = getTracingMetaTagValues(
const tags = getTraceData(
undefined,
{
getPropagationContext: () => ({
Expand All @@ -60,12 +60,12 @@ describe('getTracingMetaTagValues', () => {
});

it('returns only the `sentry-trace` tag if no DSC is available', () => {
jest.spyOn(SentryCore, 'getDynamicSamplingContextFromClient').mockReturnValueOnce({
jest.spyOn(SentryCoreTracing, 'getDynamicSamplingContextFromClient').mockReturnValueOnce({
trace_id: '',
public_key: undefined,
});

const tags = getTracingMetaTagValues(
const tags = getTraceData(
// @ts-expect-error - we don't need to provide all the properties
{
isRecording: () => true,
Expand All @@ -87,12 +87,12 @@ describe('getTracingMetaTagValues', () => {
});

it('returns only the `sentry-trace` tag if no DSC is available without a client', () => {
jest.spyOn(SentryCore, 'getDynamicSamplingContextFromClient').mockReturnValueOnce({
jest.spyOn(SentryCoreTracing, 'getDynamicSamplingContextFromClient').mockReturnValueOnce({
trace_id: '',
public_key: undefined,
});

const tags = getTracingMetaTagValues(
const tags = getTraceData(
// @ts-expect-error - we don't need to provide all the properties
{
isRecording: () => true,
Expand Down
1 change: 1 addition & 0 deletions packages/deno/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export {
setMeasurement,
getActiveSpan,
getRootSpan,
getTraceData,
startSpan,
startInactiveSpan,
startSpanManual,
Expand Down
2 changes: 1 addition & 1 deletion packages/google-cloud-serverless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export {
getCurrentScope,
getGlobalScope,
getIsolationScope,
getTracingMetaTagValues,
getTraceData,
setCurrentClient,
Scope,
SDK_VERSION,
Expand Down
2 changes: 1 addition & 1 deletion packages/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ export { initOpenTelemetry, preloadOpenTelemetry } from './sdk/initOtel';
export { getAutoPerformanceIntegrations } from './integrations/tracing';
export { getSentryRelease, defaultStackParser } from './sdk/api';
export { createGetModuleFromFilename } from './utils/module';
export { getTracingMetaTagValues } from './utils/meta';
export { makeNodeTransport } from './transports';
export { NodeClient } from './sdk/client';
export { cron } from './cron';
Expand Down Expand Up @@ -96,6 +95,7 @@ export {
getCurrentHub,
getCurrentScope,
getIsolationScope,
getTraceData,
withScope,
withIsolationScope,
captureException,
Expand Down
2 changes: 1 addition & 1 deletion packages/sveltekit/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export {
getSentryRelease,
getSpanDescendants,
getSpanStatusFromHttpCode,
getTracingMetaTagValues,
getTraceData,
graphqlIntegration,
hapiIntegration,
httpIntegration,
Expand Down
1 change: 1 addition & 0 deletions packages/vercel-edge/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export {
setMeasurement,
getActiveSpan,
getRootSpan,
getTraceData,
startSpan,
startInactiveSpan,
startSpanManual,
Expand Down

0 comments on commit 63926bf

Please sign in to comment.