Skip to content
Open
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
1 change: 1 addition & 0 deletions packages/core/src/tracing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export { SPAN_STATUS_ERROR, SPAN_STATUS_OK, SPAN_STATUS_UNSET } from './spanstat
export {
startSpan,
startInactiveSpan,
_INTERNAL_startInactiveSpan,
startSpanManual,
continueTrace,
withActiveSpan,
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/tracing/sentrySpan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ export class SentrySpan implements Span {
* @hidden
* @internal
*/
public recordException(_exception: unknown, _time?: number | undefined): void {
public recordException(_exception: unknown, _time?: SpanTimeInput | undefined): void {
// noop
}

Expand Down
14 changes: 14 additions & 0 deletions packages/core/src/tracing/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,20 @@ export function startInactiveSpan(options: StartSpanOptions): Span {
return acs.startInactiveSpan(options);
}

return _startInactiveSpanImpl(options);
}

/**
* Internal version of startInactiveSpan that bypasses the ACS check.
* Used by SentryTracerProvider to create spans without triggering recursion
* through ACS overrides.
* @hidden
*/
export function _INTERNAL_startInactiveSpan(options: StartSpanOptions): Span {
return _startInactiveSpanImpl(options);
}

function _startInactiveSpanImpl(options: StartSpanOptions): Span {
const spanArguments = parseSentrySpanArguments(options);
const { forceTransaction, parentSpan: customParentSpan } = options;

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/types/span.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,5 +319,5 @@ export interface Span {
/**
* NOT USED IN SENTRY, only added for compliance with OTEL Span interface
*/
recordException(exception: unknown, time?: number): void;
recordException(exception: unknown, time?: SpanTimeInput): void;
}
30 changes: 30 additions & 0 deletions packages/opentelemetry/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,36 @@ function setupSentry() {
A full setup example can be found in
[node-experimental](https://github.com/getsentry/sentry-javascript/blob/develop/packages/node-experimental).

## Experimental Sentry Tracer Provider

`SentryTracerProvider` is an experimental minimal OpenTelemetry tracer provider which creates native Sentry spans directly.
It is useful when code uses the global OpenTelemetry API and you do not need the full OpenTelemetry SDK span processor
and exporter pipeline.

```js
import { trace } from '@opentelemetry/api';
import { SentryTracerProvider } from '@sentry/opentelemetry';

trace.setGlobalTracerProvider(new SentryTracerProvider());

const span = trace.getTracer('example').startSpan('work');
span.end();
```

In `@sentry/node`, this provider can be enabled with the experimental option:

```js
Sentry.init({
dsn: 'xxx',
_experiments: {
useSentryTraceProvider: true,
},
});
```

When this provider is enabled, additional OpenTelemetry span processors are ignored because Sentry spans are created
directly. OpenTelemetry logs and metrics are not handled by this provider.

## Links

- [Official SDK Docs](https://docs.sentry.io/quickstart/)
114 changes: 114 additions & 0 deletions packages/opentelemetry/src/applyOtelSpanData.ts
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' });
}
Comment thread
cursor[bot] marked this conversation as resolved.
}
Comment thread
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;
}
}
5 changes: 2 additions & 3 deletions packages/opentelemetry/src/custom/client.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import type { Tracer } from '@opentelemetry/api';
import { trace } from '@opentelemetry/api';
import type { BasicTracerProvider } from '@opentelemetry/sdk-trace-base';
import type { Client } from '@sentry/core';
import { SDK_VERSION } from '@sentry/core';
import type { OpenTelemetryClient as OpenTelemetryClientInterface } from '../types';
import type { OpenTelemetryClient as OpenTelemetryClientInterface, OpenTelemetryTraceProvider } from '../types';

// Typescript complains if we do not use `...args: any[]` for the mixin, with:
// A mixin class must have a constructor with a single rest parameter of type 'any[]'.ts(2545)
Expand All @@ -23,7 +22,7 @@ export function wrapClientClass<
>(ClientClass: ClassConstructor): WrappedClassConstructor {
// @ts-expect-error We just assume that this is non-abstract, if you pass in an abstract class this would make it non-abstract
class OpenTelemetryClient extends ClientClass implements OpenTelemetryClientInterface {
public traceProvider: BasicTracerProvider | undefined;
public traceProvider: OpenTelemetryTraceProvider | undefined;
private _tracer: Tracer | undefined;

public constructor(...args: any[]) {
Expand Down
5 changes: 4 additions & 1 deletion packages/opentelemetry/src/exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,11 @@ export { wrapContextManagerClass } from './contextManager';
export { SentryPropagator, shouldPropagateTraceForUrl } from './propagator';
export { SentrySpanProcessor } from './spanProcessor';
export { SentrySampler, wrapSamplingDecision } from './sampler';
export { applyOtelSpanData } from './applyOtelSpanData';
export { SentryTracerProvider } from './tracerProvider';
export type { OpenTelemetryTraceProvider } from './types';

export { openTelemetrySetupCheck } from './utils/setupCheck';
export { openTelemetrySetupCheck, setIsSetup } from './utils/setupCheck';

export { getSentryResource } from './resource';

Expand Down
150 changes: 150 additions & 0 deletions packages/opentelemetry/src/tracer.ts
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;
Comment thread
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>;
});
Comment thread
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;
}
}
Loading
Loading