-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(opentelemetry): Add SentryTracerProvider #21666
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
Open
andreiborza
wants to merge
1
commit into
develop
Choose a base branch
from
ab/sentry-trace-provider-otel
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| import { SpanKind } from '@opentelemetry/api'; | ||
| import { HTTP_RESPONSE_STATUS_CODE, HTTP_STATUS_CODE } from '@sentry/conventions/attributes'; | ||
| import { | ||
| addNonEnumerableProperty, | ||
| SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, | ||
| SEMANTIC_ATTRIBUTE_SENTRY_OP, | ||
| SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, | ||
| spanShouldInferOtelSource, | ||
| spanToJSON, | ||
| SPAN_STATUS_ERROR, | ||
| SPAN_STATUS_OK, | ||
| } from '@sentry/core'; | ||
| import type { Span, SpanAttributes } from '@sentry/core'; | ||
| import { inferStatusFromAttributes, isStatusErrorMessageValid } from './utils/mapStatus'; | ||
| import { inferSpanData } from './utils/parseSpanDescription'; | ||
|
|
||
| type SentrySpanWithOtelKind = Span & { kind?: SpanKind }; | ||
|
|
||
| /** | ||
| * Backfill a native Sentry span with the data the OpenTelemetry SDK pipeline would otherwise derive | ||
| * from OTel semantic attributes: `sentry.op`, `sentry.source`, the span name, `otel.kind`, and status. | ||
| * | ||
| * On the OTel SDK provider this happens in the `SentrySpanProcessor`/`SentrySpanExporter` while | ||
| * converting `ReadableSpan`s to Sentry payloads (via `parseSpanDescription` + `mapStatus`). | ||
| * `SentryTracerProvider` creates native Sentry spans directly and never goes through that pipeline, | ||
| * so the same inference has to run here instead — once at span start, and again at span end | ||
| * (`finalizeStatus`, once attributes like `http.route` and the status code are available). | ||
| */ | ||
| export function applyOtelSpanData(span: Span, options: { finalizeStatus?: boolean } = {}): void { | ||
| const spanJSON = spanToJSON(span); | ||
| const attributes = spanJSON.data; | ||
| const kind = (span as SentrySpanWithOtelKind).kind ?? SpanKind.INTERNAL; | ||
| const mayInferSource = spanShouldInferOtelSource(span); | ||
| const hasCustomSpanName = attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME] !== undefined; | ||
| const attributesForInference = | ||
| mayInferSource && !hasCustomSpanName && attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === 'custom' | ||
| ? { ...attributes, [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: undefined } | ||
| : attributes; | ||
| const inferred = inferSpanData(spanJSON.description || '<unknown>', attributesForInference, kind); | ||
|
|
||
| if (kind !== SpanKind.INTERNAL && attributes['otel.kind'] === undefined) { | ||
| span.setAttribute('otel.kind', SpanKind[kind]); | ||
| } | ||
|
|
||
| if (inferred.op && attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] === undefined) { | ||
| span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, inferred.op); | ||
| } | ||
|
|
||
| // Don't apply 'url' source at creation time — only at span end (finalizeStatus). | ||
| // At creation, http.route may not be set yet, so inference falls back to 'url'. | ||
| // Keeping the default 'custom' source from _startRootSpan allows | ||
| // enhanceDscWithOpenTelemetryRootSpanName to include the transaction name in | ||
| // the DSC. At span end, http.route is typically available and inference returns | ||
| // 'route' instead. If it's still 'url', it's applied then. | ||
| const shouldApplyInferredSource = | ||
| inferred.source !== undefined && | ||
| inferred.source !== 'custom' && | ||
| (options.finalizeStatus || inferred.source !== 'url') && | ||
| (spanJSON.parent_span_id === undefined || kind === SpanKind.SERVER); | ||
|
|
||
| if ( | ||
| shouldApplyInferredSource && | ||
| (attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === undefined || (mayInferSource && !hasCustomSpanName)) | ||
| ) { | ||
| span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, inferred.source); | ||
| } | ||
|
|
||
| if (inferred.data) { | ||
| Object.entries(inferred.data).forEach(([key, value]) => { | ||
| if (value !== undefined && attributes[key] === undefined) { | ||
| span.setAttribute(key, value); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| if (options.finalizeStatus) { | ||
| applyOtelCompatibilityAttributes(span, attributes); | ||
| applyOtelSpanStatus(span, attributes, spanJSON.status); | ||
| } | ||
|
|
||
| if ( | ||
| inferred.description !== spanJSON.description && | ||
| (attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] !== 'custom' || (mayInferSource && !hasCustomSpanName)) | ||
| ) { | ||
| addNonEnumerableProperty(span as Span & { _name?: string }, '_name', inferred.description); | ||
| } | ||
| } | ||
|
|
||
| /** Stash the OTel span kind on a Sentry span so {@link applyOtelSpanData} can read it. */ | ||
| export function applyOtelSpanKind(span: Span, kind: SpanKind | undefined): void { | ||
| addNonEnumerableProperty(span as SentrySpanWithOtelKind, 'kind', kind ?? SpanKind.INTERNAL); | ||
| } | ||
|
|
||
| function applyOtelSpanStatus(span: Span, attributes: SpanAttributes, status: string | undefined): void { | ||
| if (status === undefined) { | ||
| span.setStatus(inferStatusFromAttributes(attributes) || { code: SPAN_STATUS_OK }); | ||
| return; | ||
| } | ||
|
|
||
| if (status !== 'ok' && !isStatusErrorMessageValid(status)) { | ||
| span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); | ||
| } | ||
| } | ||
|
sentry[bot] marked this conversation as resolved.
|
||
|
|
||
| function applyOtelCompatibilityAttributes(span: Span, attributes: SpanAttributes): void { | ||
| // `http.status_code` is the deprecated legacy attribute, read for backward compatibility. | ||
| // eslint-disable-next-line typescript/no-deprecated | ||
| const legacyHttpStatusCode = attributes[HTTP_STATUS_CODE]; | ||
|
|
||
| if (attributes[HTTP_RESPONSE_STATUS_CODE] === undefined && legacyHttpStatusCode !== undefined) { | ||
| span.setAttribute(HTTP_RESPONSE_STATUS_CODE, legacyHttpStatusCode); | ||
| attributes[HTTP_RESPONSE_STATUS_CODE] = legacyHttpStatusCode; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| import type { Context, Span as OpenTelemetrySpan, SpanOptions, Tracer } from '@opentelemetry/api'; | ||
| import { context, trace } from '@opentelemetry/api'; | ||
| import { isTracingSuppressed } from '@opentelemetry/core'; | ||
| import { | ||
| _INTERNAL_safeMathRandom, | ||
| _INTERNAL_setSpanForScope, | ||
| _INTERNAL_startInactiveSpan, | ||
| addChildSpanToSpan, | ||
| getCapturedScopesOnSpan, | ||
| getCurrentScope, | ||
| getDynamicSamplingContextFromSpan, | ||
| getIsolationScope, | ||
| markSpanForOtelSourceInference, | ||
| SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, | ||
| SentryNonRecordingSpan, | ||
| setCapturedScopesOnSpan, | ||
| startNewTrace, | ||
| withScope, | ||
| } from '@sentry/core'; | ||
| import type { Span, SpanAttributes, SpanLink } from '@sentry/core'; | ||
| import { applyOtelSpanData, applyOtelSpanKind } from './applyOtelSpanData'; | ||
| import { SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY } from './constants'; | ||
| import { getSamplingDecision } from './utils/getSamplingDecision'; | ||
|
|
||
| export class SentryTracer implements Tracer { | ||
| /** @inheritdoc */ | ||
| public startSpan(name: string, options: SpanOptions = {}, ctx?: Context): OpenTelemetrySpan { | ||
| const parentContext = ctx || context.active(); | ||
| const parentSpan = options.root ? undefined : trace.getSpan(parentContext); | ||
|
|
||
| if (isTracingSuppressed(parentContext)) { | ||
| return this._createNonRecordingSpan(parentSpan); | ||
| } | ||
|
|
||
| const span = this._startSentrySpan(name, options, parentSpan, ctx !== undefined); | ||
|
|
||
| applyOtelSpanKind(span, options.kind); | ||
| if (options.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === undefined) { | ||
| markSpanForOtelSourceInference(span); | ||
| } | ||
| applyOtelSpanData(span); | ||
| return span as OpenTelemetrySpan; | ||
|
andreiborza marked this conversation as resolved.
|
||
| } | ||
|
|
||
| /** @inheritdoc */ | ||
| public startActiveSpan<F extends (span: OpenTelemetrySpan) => unknown>(name: string, fn: F): ReturnType<F>; | ||
| public startActiveSpan<F extends (span: OpenTelemetrySpan) => unknown>( | ||
| name: string, | ||
| options: SpanOptions, | ||
| fn: F, | ||
| ): ReturnType<F>; | ||
| public startActiveSpan<F extends (span: OpenTelemetrySpan) => unknown>( | ||
| name: string, | ||
| options: SpanOptions, | ||
| ctx: Context, | ||
| fn: F, | ||
| ): ReturnType<F>; | ||
| public startActiveSpan<F extends (span: OpenTelemetrySpan) => unknown>( | ||
| name: string, | ||
| optionsOrFn: SpanOptions | F, | ||
| contextOrFn?: Context | F, | ||
| fn?: F, | ||
| ): ReturnType<F> { | ||
| const options = typeof optionsOrFn === 'function' ? {} : optionsOrFn; | ||
| const ctx = typeof contextOrFn === 'function' || contextOrFn === undefined ? context.active() : contextOrFn; | ||
| const callback = ( | ||
| typeof optionsOrFn === 'function' ? optionsOrFn : typeof contextOrFn === 'function' ? contextOrFn : fn | ||
| ) as F; | ||
|
|
||
| const span = this.startSpan(name, options, ctx); | ||
| let ctxWithSpan = trace.setSpan(ctx, span); | ||
|
|
||
| const capturedIsolationScope = getCapturedScopesOnSpan(span as unknown as Span).isolationScope; | ||
| if (capturedIsolationScope) { | ||
| ctxWithSpan = ctxWithSpan.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, capturedIsolationScope); | ||
| } | ||
|
|
||
| return context.with(ctxWithSpan, () => { | ||
| _INTERNAL_setSpanForScope(getCurrentScope(), span as unknown as Span); | ||
| return callback(span) as ReturnType<F>; | ||
| }); | ||
|
andreiborza marked this conversation as resolved.
|
||
| } | ||
|
|
||
| private _startSentrySpan( | ||
| name: string, | ||
| options: SpanOptions, | ||
| parentSpan: OpenTelemetrySpan | undefined, | ||
| hasExplicitContext: boolean, | ||
| ): Span { | ||
| const sentryOptions = { | ||
| name, | ||
| attributes: options.attributes as SpanAttributes | undefined, | ||
| links: options.links as SpanLink[] | undefined, | ||
| startTime: options.startTime, | ||
| }; | ||
|
|
||
| if (options.root) { | ||
| return startNewTrace(() => _INTERNAL_startInactiveSpan({ ...sentryOptions, parentSpan: null })); | ||
| } | ||
|
|
||
| if (parentSpan?.spanContext().isRemote) { | ||
| return this._startRootSpanWithRemoteParent(sentryOptions, parentSpan); | ||
| } | ||
|
|
||
| if (parentSpan) { | ||
| return _INTERNAL_startInactiveSpan({ ...sentryOptions, parentSpan: parentSpan as unknown as Span }); | ||
| } | ||
|
|
||
| return _INTERNAL_startInactiveSpan({ | ||
| ...sentryOptions, | ||
| parentSpan: hasExplicitContext ? null : undefined, | ||
| }); | ||
| } | ||
|
|
||
| private _startRootSpanWithRemoteParent( | ||
| options: Parameters<typeof _INTERNAL_startInactiveSpan>[0], | ||
| parentSpan: OpenTelemetrySpan, | ||
| ): Span { | ||
| const { spanId, traceId } = parentSpan.spanContext(); | ||
| const dsc = getDynamicSamplingContextFromSpan(parentSpan as unknown as Span); | ||
| const sampleRand = typeof dsc.sample_rand === 'string' ? Number(dsc.sample_rand) : undefined; | ||
|
|
||
| return withScope(scope => { | ||
| scope.setPropagationContext({ | ||
| traceId, | ||
| parentSpanId: spanId, | ||
| sampled: getSamplingDecision(parentSpan.spanContext()), | ||
| dsc, | ||
| sampleRand: | ||
| typeof sampleRand === 'number' && !Number.isNaN(sampleRand) ? sampleRand : _INTERNAL_safeMathRandom(), | ||
| }); | ||
| _INTERNAL_setSpanForScope(scope, undefined); | ||
|
|
||
| return _INTERNAL_startInactiveSpan({ ...options, parentSpan: null }); | ||
| }); | ||
| } | ||
|
|
||
| private _createNonRecordingSpan(parentSpan: OpenTelemetrySpan | undefined): OpenTelemetrySpan { | ||
| const span = new SentryNonRecordingSpan({ traceId: parentSpan?.spanContext().traceId }); | ||
| // Link to the parent (like core's `createChildOrRootSpan`) so `getRootSpan` and DSC | ||
| // resolution reach the parent. Non-recording spans no longer carry a `parentSpanId`. | ||
| if (parentSpan) { | ||
| addChildSpanToSpan(parentSpan as unknown as Span, span); | ||
| } | ||
| // Capture the scopes (mirroring `createChildOrRootSpan`) so `startActiveSpan` can | ||
| // fork the isolation scope onto the OTel context for work inside a suppressed span. | ||
| setCapturedScopesOnSpan(span, getCurrentScope(), getIsolationScope()); | ||
| return span as OpenTelemetrySpan; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.