diff --git a/dev-packages/e2e-tests/test-applications/node-connect/tests/transactions.test.ts b/dev-packages/e2e-tests/test-applications/node-connect/tests/transactions.test.ts index 9b06ad052f58..f6991ed7a75a 100644 --- a/dev-packages/e2e-tests/test-applications/node-connect/tests/transactions.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-connect/tests/transactions.test.ts @@ -54,41 +54,44 @@ test('Sends an API route transaction', async ({ baseURL }) => { origin: 'auto.http.otel.http', }); + const manualSpanExpectation = { + data: { + 'sentry.origin': 'manual', + }, + description: 'test-span', + parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), + span_id: expect.stringMatching(/[a-f0-9]{16}/), + start_timestamp: expect.any(Number), + status: 'ok', + timestamp: expect.any(Number), + trace_id: expect.stringMatching(/[a-f0-9]{32}/), + origin: 'manual', + }; + + const connectSpanExpectation = { + data: { + 'sentry.origin': 'auto.http.otel.connect', + 'sentry.op': 'request_handler.connect', + 'http.route': '/test-transaction', + 'connect.type': 'request_handler', + 'connect.name': '/test-transaction', + }, + op: 'request_handler.connect', + description: '/test-transaction', + parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), + span_id: expect.stringMatching(/[a-f0-9]{16}/), + start_timestamp: expect.any(Number), + status: 'ok', + timestamp: expect.any(Number), + trace_id: expect.stringMatching(/[a-f0-9]{32}/), + origin: 'auto.http.otel.connect', + }; + expect(transactionEvent).toEqual( expect.objectContaining({ - spans: [ - { - data: { - 'sentry.origin': 'manual', - }, - description: 'test-span', - parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), - span_id: expect.stringMatching(/[a-f0-9]{16}/), - start_timestamp: expect.any(Number), - status: 'ok', - timestamp: expect.any(Number), - trace_id: expect.stringMatching(/[a-f0-9]{32}/), - origin: 'manual', - }, - { - data: { - 'sentry.origin': 'auto.http.otel.connect', - 'sentry.op': 'request_handler.connect', - 'http.route': '/test-transaction', - 'connect.type': 'request_handler', - 'connect.name': '/test-transaction', - }, - op: 'request_handler.connect', - description: '/test-transaction', - parent_span_id: expect.stringMatching(/[a-f0-9]{16}/), - span_id: expect.stringMatching(/[a-f0-9]{16}/), - start_timestamp: expect.any(Number), - status: 'ok', - timestamp: expect.any(Number), - trace_id: expect.stringMatching(/[a-f0-9]{32}/), - origin: 'auto.http.otel.connect', - }, - ], + // The SentryTracerProvider serializes native child spans in start/tree order, so the + // Connect handler span appears before the manual span created inside it. + spans: [connectSpanExpectation, manualSpanExpectation], transaction: 'GET /test-transaction', type: 'transaction', transaction_info: { diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/basic-usage-streamed/test.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/basic-usage-streamed/test.ts index cc52933a1106..7bc6db742834 100644 --- a/dev-packages/node-integration-tests/suites/public-api/startSpan/basic-usage-streamed/test.ts +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/basic-usage-streamed/test.ts @@ -2,6 +2,7 @@ import { SDK_VERSION, SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT, SEMANTIC_ATTRIBUTE_SENTRY_OP, + SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_RELEASE, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SDK_INTEGRATIONS, @@ -63,6 +64,7 @@ test('sends a streamed span envelope with correct spans for a manually started s [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { type: 'string', value: 'test-span' }, [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { type: 'string', value: '1.0.0' }, [SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT]: { type: 'string', value: 'production' }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'manual' }, [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { type: 'string', value: 'custom' }, 'sentry.span.source': { type: 'string', value: 'custom' }, }, @@ -86,6 +88,7 @@ test('sends a streamed span envelope with correct spans for a manually started s [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { type: 'string', value: 'test-span' }, [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { type: 'string', value: '1.0.0' }, [SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT]: { type: 'string', value: 'production' }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'manual' }, [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { type: 'string', value: 'custom' }, 'sentry.span.source': { type: 'string', value: 'custom' }, }, @@ -122,6 +125,7 @@ test('sends a streamed span envelope with correct spans for a manually started s [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { type: 'string', value: 'test-span' }, [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { type: 'string', value: '1.0.0' }, [SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT]: { type: 'string', value: 'production' }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'manual' }, [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { type: 'string', value: 'custom' }, 'sentry.span.source': { type: 'string', value: 'custom' }, }, @@ -148,6 +152,7 @@ test('sends a streamed span envelope with correct spans for a manually started s [SEMANTIC_ATTRIBUTE_SENTRY_SEGMENT_NAME]: { type: 'string', value: 'test-span' }, [SEMANTIC_ATTRIBUTE_SENTRY_RELEASE]: { type: 'string', value: '1.0.0' }, [SEMANTIC_ATTRIBUTE_SENTRY_ENVIRONMENT]: { type: 'string', value: 'production' }, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: { type: 'string', value: 'manual' }, [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { type: 'string', value: 'custom' }, 'sentry.span.source': { type: 'string', value: 'custom' }, 'process.runtime.engine.name': { type: 'string', value: 'v8' }, diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method-streamed/test.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method-streamed/test.ts index f9d15cf60e30..258c37d65b4c 100644 --- a/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method-streamed/test.ts +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method-streamed/test.ts @@ -15,7 +15,9 @@ test('updates the span name when calling `span.updateName` (streamed)', async () name: 'new name', is_segment: true, attributes: { - [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { type: 'string', value: 'url' }, + // `updateName` marks the name as explicitly chosen, so the source becomes `custom`, + // overriding the `url` source set at span start (a stale `url` no longer describes the name). + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: { type: 'string', value: 'custom' }, }, }, ], diff --git a/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method/test.ts b/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method/test.ts index c46efa9a7fc3..74c0f5b8f7ea 100644 --- a/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method/test.ts +++ b/dev-packages/node-integration-tests/suites/public-api/startSpan/updateName-method/test.ts @@ -7,16 +7,18 @@ afterAll(() => { }); test('updates the span name when calling `span.updateName`', async () => { - createRunner(__dirname, 'scenario.ts') + await createRunner(__dirname, 'scenario.ts') .expect({ transaction: { transaction: 'new name', - transaction_info: { source: 'url' }, + // `updateName` marks the name as explicitly chosen, so the source becomes `custom`, + // overriding the `url` source set at span start (a stale `url` no longer describes the name). + transaction_info: { source: 'custom' }, contexts: { trace: { span_id: expect.any(String), trace_id: expect.any(String), - data: { [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url' }, + data: { [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom' }, }, }, }, diff --git a/dev-packages/node-integration-tests/suites/tracing/no-parent-span-client-report/scenario-fetch.mjs b/dev-packages/node-integration-tests/suites/tracing/no-parent-span-client-report/scenario-fetch.mjs new file mode 100644 index 000000000000..a122330366e4 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/no-parent-span-client-report/scenario-fetch.mjs @@ -0,0 +1 @@ +fetch('http://localhost:9999/external').catch(() => {}); diff --git a/dev-packages/node-integration-tests/suites/tracing/no-parent-span-client-report/test.ts b/dev-packages/node-integration-tests/suites/tracing/no-parent-span-client-report/test.ts index 699dec65ddcf..4ad1b3150f2c 100644 --- a/dev-packages/node-integration-tests/suites/tracing/no-parent-span-client-report/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/no-parent-span-client-report/test.ts @@ -7,7 +7,28 @@ describe('no_parent_span client report', () => { }); createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { - test('records no_parent_span outcome for http.client span without a local parent', async () => { + test('records no_parent_span outcome for an outgoing http request without a local parent', async () => { + const runner = createRunner() + .unignore('client_report') + .expect({ + client_report: report => { + expect(report.discarded_events).toEqual([ + { + category: 'span', + quantity: 1, + reason: 'no_parent_span', + }, + ]); + }, + }) + .start(); + + await runner.completed(); + }); + }); + + createEsmAndCjsTests(__dirname, 'scenario-fetch.mjs', 'instrument.mjs', (createRunner, test) => { + test('records no_parent_span outcome for an outgoing fetch request without a local parent', async () => { const runner = createRunner() .unignore('client_report') .expect({ diff --git a/packages/node-core/src/integrations/http/httpServerSpansIntegration.ts b/packages/node-core/src/integrations/http/httpServerSpansIntegration.ts index b20210bb8e54..b99eeb2bf918 100644 --- a/packages/node-core/src/integrations/http/httpServerSpansIntegration.ts +++ b/packages/node-core/src/integrations/http/httpServerSpansIntegration.ts @@ -2,7 +2,7 @@ import { errorMonitor } from 'node:events'; import type { IncomingHttpHeaders } from 'node:http'; import { context, SpanKind, trace } from '@opentelemetry/api'; import type { RPCMetadata } from '@opentelemetry/core'; -import { getRPCMetadata, isTracingSuppressed, RPCType, setRPCMetadata } from '@opentelemetry/core'; +import { isTracingSuppressed, RPCType, setRPCMetadata } from '@opentelemetry/core'; import { HTTP_RESPONSE_STATUS_CODE, HTTP_ROUTE, @@ -196,7 +196,7 @@ const _httpServerSpansIntegration = ((options: HttpServerSpansIntegrationOptions isEnded = true; - const newAttributes = getIncomingRequestAttributesOnResponse(request, response); + const newAttributes = getIncomingRequestAttributesOnResponse(request, response, rpcMetadata); span.setAttributes(newAttributes); span.setStatus(status); span.end(); @@ -225,15 +225,25 @@ const _httpServerSpansIntegration = ((options: HttpServerSpansIntegrationOptions }); }, processEvent(event) { - // Drop transaction if it has a status code that should be ignored if (event.type === 'transaction') { const statusCode = event.contexts?.trace?.data?.['http.response.status_code']; if (typeof statusCode === 'number') { - const shouldDrop = shouldFilterStatusCode(statusCode, ignoreStatusCodes); - if (shouldDrop) { + // Drop transaction if it has a status code that should be ignored + if (shouldFilterStatusCode(statusCode, ignoreStatusCodes)) { DEBUG_BUILD && debug.log('Dropping transaction due to status code', statusCode); return null; } + + // Surface the HTTP status as the top-level `response` context. The OTel SDK span + // exporter already does this on its path; doing it here covers transactions produced + // by the `SentryTracerProvider`, which bypasses that exporter. + event.contexts = { + ...event.contexts, + response: { + ...event.contexts?.response, + status_code: statusCode, + }, + }; } } @@ -368,6 +378,7 @@ function isCompressed(headers: IncomingHttpHeaders): boolean { function getIncomingRequestAttributesOnResponse( request: HttpIncomingMessage, response: HttpServerResponse, + rpcMetadata?: RPCMetadata, ): SpanAttributes { // take socket from the request, // since it may be detached from the response object in keep-alive mode @@ -381,7 +392,6 @@ function getIncomingRequestAttributesOnResponse( 'http.status_text': statusMessage?.toUpperCase(), }; - const rpcMetadata = getRPCMetadata(context.active()); if (socket) { const { localAddress, localPort, remoteAddress, remotePort } = socket; // eslint-disable-next-line typescript/no-deprecated diff --git a/packages/node-core/src/sdk/client.ts b/packages/node-core/src/sdk/client.ts index 80a233aa3954..69bdb226edf9 100644 --- a/packages/node-core/src/sdk/client.ts +++ b/packages/node-core/src/sdk/client.ts @@ -2,7 +2,6 @@ import * as os from 'node:os'; import type { Tracer } from '@opentelemetry/api'; import { trace } from '@opentelemetry/api'; import { registerInstrumentations } from '@opentelemetry/instrumentation'; -import type { BasicTracerProvider } from '@opentelemetry/sdk-trace-base'; import type { DynamicSamplingContext, Scope, ServerRuntimeClientOptions, TraceContext } from '@sentry/core'; import { _INTERNAL_clearAiProviderSkips, @@ -12,7 +11,11 @@ import { SDK_VERSION, ServerRuntimeClient, } from '@sentry/core'; -import { type AsyncLocalStorageLookup, getTraceContextForScope } from '@sentry/opentelemetry'; +import { + type AsyncLocalStorageLookup, + getTraceContextForScope, + type OpenTelemetryTracerProvider, +} from '@sentry/opentelemetry'; import { isMainThread, threadId } from 'worker_threads'; import { DEBUG_BUILD } from '../debug-build'; import type { NodeClientOptions } from '../types'; @@ -21,7 +24,7 @@ const DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS = 60_000; // 60s was chosen arbitr /** A client for using Sentry with Node & OpenTelemetry. */ export class NodeClient extends ServerRuntimeClient { - public traceProvider: BasicTracerProvider | undefined; + public traceProvider: OpenTelemetryTracerProvider | undefined; public asyncLocalStorageLookup: AsyncLocalStorageLookup | undefined; private _tracer: Tracer | undefined; diff --git a/packages/node-core/src/sdk/index.ts b/packages/node-core/src/sdk/index.ts index 31493a273d4a..f7dfc1a34376 100644 --- a/packages/node-core/src/sdk/index.ts +++ b/packages/node-core/src/sdk/index.ts @@ -168,7 +168,9 @@ export function validateOpenTelemetrySetup(): void { const required: ReturnType = ['SentryContextManager', 'SentryPropagator']; - if (hasSpansEnabled()) { + const hasSentryTracerProvider = setup.includes('SentryTracerProvider'); + + if (hasSpansEnabled() && !hasSentryTracerProvider) { required.push('SentrySpanProcessor'); } @@ -180,7 +182,7 @@ export function validateOpenTelemetrySetup(): void { } } - if (!setup.includes('SentrySampler')) { + if (!hasSentryTracerProvider && !setup.includes('SentrySampler')) { debug.warn( 'You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.', ); diff --git a/packages/node-core/src/types.ts b/packages/node-core/src/types.ts index 174eb039a8c7..a83885aa56db 100644 --- a/packages/node-core/src/types.ts +++ b/packages/node-core/src/types.ts @@ -31,6 +31,20 @@ export interface OpenTelemetryServerRuntimeOptions extends ServerRuntimeOptions * Provide an array of additional OpenTelemetry SpanProcessors that should be registered. */ openTelemetrySpanProcessors?: SpanProcessor[]; + + /** + * By default, the SDK uses Sentry's minimal OpenTelemetry tracer provider, which creates native + * Sentry spans directly instead of going through the full OpenTelemetry SDK span pipeline. + * + * Set this to `true` to use the full OpenTelemetry SDK `BasicTracerProvider` instead, e.g. if you + * rely on OpenTelemetry SDK features that the minimal provider does not support. + * + * Note: providing `openTelemetrySpanProcessors` also forces the full OpenTelemetry SDK provider, + * since custom span processors require the SDK span pipeline. + * + * @default false + */ + openTelemetryBasicTracerProvider?: boolean; } /** diff --git a/packages/node-core/test/integrations/httpServerSpansIntegration.test.ts b/packages/node-core/test/integrations/httpServerSpansIntegration.test.ts index 5603310db108..f1b5af564d79 100644 --- a/packages/node-core/test/integrations/httpServerSpansIntegration.test.ts +++ b/packages/node-core/test/integrations/httpServerSpansIntegration.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { isStaticAssetRequest } from '../../src/integrations/http/httpServerSpansIntegration'; +import { + httpServerSpansIntegration, + isStaticAssetRequest, +} from '../../src/integrations/http/httpServerSpansIntegration'; describe('httpIntegration', () => { describe('isStaticAssetRequest', () => { @@ -31,4 +34,50 @@ describe('httpIntegration', () => { expect(isStaticAssetRequest(urlPath)).toBe(expected); }); }); + + describe('processEvent', () => { + function runProcessEvent(event: Record, options = {}): any { + const integration = httpServerSpansIntegration(options); + return (integration as any).processEvent(event, {}, {}); + } + + it('lifts the HTTP response status code into the top-level `response` context', () => { + const event = runProcessEvent( + { type: 'transaction', contexts: { trace: { data: { 'http.response.status_code': 200 } } } }, + { ignoreStatusCodes: [] }, + ); + + expect(event.contexts.response).toEqual({ status_code: 200 }); + }); + + it('preserves existing `response` context fields', () => { + const event = runProcessEvent( + { + type: 'transaction', + contexts: { response: { body_size: 42 }, trace: { data: { 'http.response.status_code': 201 } } }, + }, + { ignoreStatusCodes: [] }, + ); + + expect(event.contexts.response).toEqual({ body_size: 42, status_code: 201 }); + }); + + it('does not add a `response` context when there is no HTTP status code', () => { + const event = runProcessEvent( + { type: 'transaction', contexts: { trace: { data: {} } } }, + { ignoreStatusCodes: [] }, + ); + + expect(event.contexts.response).toBeUndefined(); + }); + + it('drops transactions whose status code is in `ignoreStatusCodes`', () => { + const event = runProcessEvent( + { type: 'transaction', contexts: { trace: { data: { 'http.response.status_code': 404 } } } }, + { ignoreStatusCodes: [404] }, + ); + + expect(event).toBeNull(); + }); + }); }); diff --git a/packages/node/src/integrations/node-fetch/vendored/undici.ts b/packages/node/src/integrations/node-fetch/vendored/undici.ts index 814613921a20..48a514347b44 100644 --- a/packages/node/src/integrations/node-fetch/vendored/undici.ts +++ b/packages/node/src/integrations/node-fetch/vendored/undici.ts @@ -9,6 +9,9 @@ * - Refactored to use Sentry's span APIs instead of OpenTelemetry tracing APIs * - Dropped the OTel metrics (no MeterProvider is wired up) and the dead * `requireParentforSpans` code path (the SDK always passes `false`) + * - An orphan `http.client` span (no local parent) is created suppressed/non-recording outside of + * span streaming, so it isn't emitted as a standalone transaction. It is still created so trace + * propagation headers are injected. * - Dropped the `@opentelemetry/instrumentation` base (undici reports via `diagnostics_channel`, * so no module patching was needed) — now a plain class wired up directly by the integration */ @@ -20,7 +23,9 @@ import type { Span, SpanAttributes } from '@sentry/core'; import { debug, getClient, + getSpanStatusFromHttpCode, getTraceData, + hasSpanStreamingEnabled, LRUMap, shouldPropagateTraceForUrl, SPAN_KIND, @@ -242,10 +247,18 @@ export class UndiciInstrumentation { }); } + // Outside of span streaming, only record an `http.client` span when it has a parent. An orphan + // one (no local parent) is left to the server for the downstream sampling decision: `onlyIfParent` + // still creates a non-recording span so trace propagation headers are injected, but it isn't + // emitted as a standalone transaction. This rule also lives in `SentrySampler`, but that only runs + // when an OpenTelemetry SDK tracer provider is set up, so we enforce it here too, which covers + // SDKs that don't use an OpenTelemetry tracer provider at all. + const client = getClient(); const span = startInactiveSpan({ name: requestMethod === '_OTHER' ? 'HTTP' : requestMethod, kind: SPAN_KIND.CLIENT, attributes, + onlyIfParent: !client || !hasSpanStreamingEnabled(client), }); // Execute the request hook if defined @@ -344,10 +357,13 @@ export class UndiciInstrumentation { span.setAttributes(spanAttributes); - // The Sentry pipeline infers `ok` / `not_found` / etc. from `http.response.status_code` when the - // status is left unset, so we only need to flag erroneous responses explicitly. + // Resolve the HTTP status code to a Sentry span status here (like the raw http client/server + // instrumentation does) instead of setting a bare error and deferring to downstream inference. + // The SentryTracerProvider's status finalization reads the already-stringified span status, which + // can no longer be inferred back to `not_found` etc. the way the OpenTelemetry SDK exporter's + // `mapStatus` does from the raw `{ code, message }`. if (response.statusCode >= 400) { - span.setStatus({ code: SPAN_STATUS_ERROR }); + span.setStatus(getSpanStatusFromHttpCode(response.statusCode)); } } diff --git a/packages/node/src/sdk/initOtel.ts b/packages/node/src/sdk/initOtel.ts index e3794097b2b7..b6936ab1e269 100644 --- a/packages/node/src/sdk/initOtel.ts +++ b/packages/node/src/sdk/initOtel.ts @@ -1,7 +1,7 @@ import { context, propagation, trace } from '@opentelemetry/api'; import type { SpanProcessor } from '@opentelemetry/sdk-trace-base'; import { BasicTracerProvider } from '@opentelemetry/sdk-trace-base'; -import { debug as coreDebug } from '@sentry/core'; +import { debug as coreDebug, hasSpanStreamingEnabled } from '@sentry/core'; import { initializeEsmLoader, type NodeClient, @@ -9,11 +9,16 @@ import { setupOpenTelemetryLogger, } from '@sentry/node-core'; import { + applyOtelSpanData, type AsyncLocalStorageLookup, + backfillStreamedSpanDataFromOtel, getSentryResource, + type OpenTelemetryTracerProvider, SentryPropagator, SentrySampler, SentrySpanProcessor, + SentryTracerProvider, + setIsSetup, } from '@sentry/opentelemetry'; import { DEBUG_BUILD } from '../debug-build'; import { getOpenTelemetryInstrumentationToPreload } from '../integrations/tracing'; @@ -86,7 +91,18 @@ function getPreloadMethods(integrationNames?: string[]): ((() => void) & { id: s export function setupOtel( client: NodeClient, options: AdditionalOpenTelemetryOptions = {}, -): [BasicTracerProvider, AsyncLocalStorageLookup] { +): [OpenTelemetryTracerProvider | undefined, AsyncLocalStorageLookup | undefined] { + // Sentry's minimal tracer provider is the default. We fall back to the full OpenTelemetry SDK + // `BasicTracerProvider` when the user explicitly opts in via `openTelemetryBasicTracerProvider`, or + // when they provide custom `openTelemetrySpanProcessors` — those require the SDK span pipeline + // that the minimal provider does not run. + const shouldUseBasicTracerProvider = + client.getOptions().openTelemetryBasicTracerProvider || !!options.spanProcessors?.length; + + if (!shouldUseBasicTracerProvider) { + return setupSentryTracerProvider(client); + } + // Create and configure NodeTracerProvider const provider = new BasicTracerProvider({ sampler: new SentrySampler(client), @@ -111,6 +127,57 @@ export function setupOtel( return [provider, ctxManager.getAsyncLocalStorageLookup()]; } +function setupSentryTracerProvider( + client: NodeClient, +): [SentryTracerProvider | undefined, AsyncLocalStorageLookup | undefined] { + const provider = new SentryTracerProvider({ resource: getSentryResource('node') }); + + if (!trace.setGlobalTracerProvider(provider)) { + DEBUG_BUILD && + coreDebug.warn( + 'Could not register SentryTracerProvider because another OpenTelemetry tracer provider is already registered.', + ); + return [undefined, undefined]; + } + + // Only mark the provider as set up once it is actually the registered global + // tracer provider, so setup validation doesn't skip required checks when + // registration failed. + setIsSetup('SentryTracerProvider'); + + propagation.setGlobalPropagator(new SentryPropagator()); + + const ctxManager = new SentryContextManager(); + context.setGlobalContextManager(ctxManager); + + client.on('spanEnd', span => { + applyOtelSpanData(span, { finalizeStatus: true }); + }); + + if (hasSpanStreamingEnabled(client)) { + // Streamed spans skip the exporter, so per-span data inferred from OTel semantic conventions + // (notably `sentry.source` on child spans, which `applyOtelSpanData` only sets on segment roots) + // is backfilled here, reusing the exact inference the OTel SDK `SentrySpanProcessor` applies. + client.on('preprocessSpan', backfillStreamedSpanDataFromOtel); + } + + client.on('preprocessEvent', event => { + if (event.type !== 'transaction') { + return; + } + + event.contexts = { + ...event.contexts, + otel: { + resource: provider.resource?.attributes, + ...event.contexts?.otel, + }, + }; + }); + + return [provider, ctxManager.getAsyncLocalStorageLookup()]; +} + /** Just exported for tests. */ export function _clampSpanProcessorTimeout(maxSpanWaitDuration: number | undefined): number | undefined { if (maxSpanWaitDuration == null) { diff --git a/packages/node/test/helpers/mockSdkInit.ts b/packages/node/test/helpers/mockSdkInit.ts index 9163943bbeb5..b2f75c31632d 100644 --- a/packages/node/test/helpers/mockSdkInit.ts +++ b/packages/node/test/helpers/mockSdkInit.ts @@ -30,13 +30,14 @@ export function mockSdkInit(options?: Partial) { export function cleanupOtel(_provider?: BasicTracerProvider): void { const provider = getProvider(_provider); - if (!provider) { - return; + // `getProvider` only resolves the OpenTelemetry SDK `BasicTracerProvider`; the default + // `SentryTracerProvider` is not an instance of it. Flush/shutdown only apply to the SDK provider, + // but the global APIs must always be disabled so the next test can register its own provider. + if (provider) { + void provider.forceFlush(); + void provider.shutdown(); } - void provider.forceFlush(); - void provider.shutdown(); - // Disable all globally registered APIs trace.disable(); context.disable(); diff --git a/packages/node/test/integration/scope.test.ts b/packages/node/test/integration/scope.test.ts index 6f2acaf267ee..20b01d6fce47 100644 --- a/packages/node/test/integration/scope.test.ts +++ b/packages/node/test/integration/scope.test.ts @@ -41,7 +41,14 @@ describe('Integration | Scope', () => { scope2.setTag('tag3', 'val3'); Sentry.startSpan({ name: 'outer' }, span => { - expect(getCapturedScopesOnSpan(span).scope).toBe(tracingEnabled ? scope2 : undefined); + // The SentryTracerProvider captures a snapshot (clone) of the active scope at span + // start — for both sampled and non-recording spans — rather than the live instance, so + // assert the captured scope's data instead of instance identity. + expect(getCapturedScopesOnSpan(span).scope?.getScopeData().tags).toEqual({ + tag1: 'val1', + tag2: 'val2', + tag3: 'val3', + }); spanId = span.spanContext().spanId; traceId = span.spanContext().traceId; diff --git a/packages/node/test/integration/transactions.test.ts b/packages/node/test/integration/transactions.test.ts index 7b13a400dedb..e15ee6f89dac 100644 --- a/packages/node/test/integration/transactions.test.ts +++ b/packages/node/test/integration/transactions.test.ts @@ -97,7 +97,9 @@ describe('Integration | Transactions', () => { origin: 'auto.test', }); - expect(transaction.sdkProcessingMetadata?.sampleRate).toEqual(1); + // The sample rate is carried by the dynamic sampling context (asserted below). The + // `SentryTracerProvider` builds transactions via core's span capture, which does not write the + // (unused) `sdkProcessingMetadata.sampleRate` field the OpenTelemetry SDK exporter does. expect(transaction.sdkProcessingMetadata?.dynamicSamplingContext).toEqual({ environment: 'production', public_key: expect.any(String), @@ -558,7 +560,9 @@ describe('Integration | Transactions', () => { const logs: unknown[] = []; vi.spyOn(debug, 'log').mockImplementation(msg => logs.push(msg)); - mockSdkInit({ tracesSampleRate: 1, beforeSendTransaction }); + // This test inspects the `SentrySpanProcessor`/exporter buffering, which only exists on the + // OpenTelemetry SDK provider, so opt out of the default `SentryTracerProvider`. + mockSdkInit({ tracesSampleRate: 1, beforeSendTransaction, openTelemetryBasicTracerProvider: true }); const spanProcessor = getSpanProcessor(); @@ -630,10 +634,13 @@ describe('Integration | Transactions', () => { const logs: unknown[] = []; vi.spyOn(debug, 'log').mockImplementation(msg => logs.push(msg)); + // `maxSpanWaitDuration` configures the `SentrySpanProcessor` timeout, which only exists on the + // OpenTelemetry SDK provider, so opt out of the default `SentryTracerProvider`. mockSdkInit({ tracesSampleRate: 1, beforeSendTransaction, maxSpanWaitDuration: 100 * 60, + openTelemetryBasicTracerProvider: true, }); Sentry.startSpanManual({ name: 'test name' }, rootSpan => { diff --git a/packages/node/test/sdk/init.test.ts b/packages/node/test/sdk/init.test.ts index 26fe2d9933e6..1dd01361a2ab 100644 --- a/packages/node/test/sdk/init.test.ts +++ b/packages/node/test/sdk/init.test.ts @@ -1,3 +1,5 @@ +import { trace } from '@opentelemetry/api'; +import { BasicTracerProvider } from '@opentelemetry/sdk-trace-base'; import type { Integration } from '@sentry/core'; import { debug, SDK_VERSION } from '@sentry/core'; import * as SentryOpentelemetry from '@sentry/opentelemetry'; @@ -194,6 +196,58 @@ describe('init()', () => { expect(client?.traceProvider).not.toBeDefined(); }); + + it('uses the minimal Sentry trace provider by default', () => { + init({ dsn: PUBLIC_DSN }); + + const client = getClient(); + + expect(client?.traceProvider).toBeInstanceOf(SentryOpentelemetry.SentryTracerProvider); + }); + + it('uses the OpenTelemetry SDK tracer provider when opted in via `openTelemetryBasicTracerProvider`', () => { + init({ dsn: PUBLIC_DSN, openTelemetryBasicTracerProvider: true }); + + const client = getClient(); + + expect(client?.traceProvider).toBeInstanceOf(BasicTracerProvider); + }); + + it('uses the OpenTelemetry SDK tracer provider when custom span processors are provided', () => { + init({ + dsn: PUBLIC_DSN, + openTelemetrySpanProcessors: [ + { + forceFlush: () => Promise.resolve(), + onStart: () => undefined, + onEnd: () => undefined, + shutdown: () => Promise.resolve(), + }, + ], + }); + + const client = getClient(); + + expect(client?.traceProvider).toBeInstanceOf(BasicTracerProvider); + }); + + it('does not mark SentryTracerProvider as set up when global registration fails', () => { + // Simulate another OpenTelemetry tracer provider already being registered. + const setGlobalSpy = vi.spyOn(trace, 'setGlobalTracerProvider').mockReturnValue(false); + const setIsSetupSpy = vi.spyOn(SentryOpentelemetry, 'setIsSetup'); + const warnSpy = vi.spyOn(debug, 'warn').mockImplementation(() => {}); + + init({ dsn: PUBLIC_DSN }); + + expect(getClient()?.traceProvider).not.toBeDefined(); + expect(setIsSetupSpy).not.toHaveBeenCalledWith('SentryTracerProvider'); + expect(warnSpy).toHaveBeenCalledWith( + 'Could not register SentryTracerProvider because another OpenTelemetry tracer provider is already registered.', + ); + + setGlobalSpy.mockRestore(); + setIsSetupSpy.mockRestore(); + }); }); it('returns initialized client', () => { diff --git a/packages/opentelemetry/README.md b/packages/opentelemetry/README.md index 265a761c9a0b..3fc8413e6144 100644 --- a/packages/opentelemetry/README.md +++ b/packages/opentelemetry/README.md @@ -85,9 +85,9 @@ 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 +## Sentry Tracer Provider -`SentryTracerProvider` is an experimental minimal OpenTelemetry tracer provider which creates native Sentry spans directly. +`SentryTracerProvider` is a 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. @@ -101,19 +101,18 @@ const span = trace.getTracer('example').startSpan('work'); span.end(); ``` -In `@sentry/node`, this provider can be enabled with the experimental option: +In `@sentry/node`, this is the default tracer provider. To use the full OpenTelemetry SDK `BasicTracerProvider` +instead, opt out with: ```js Sentry.init({ dsn: 'xxx', - _experiments: { - useSentryTracerProvider: true, - }, + openTelemetryBasicTracerProvider: 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. +Providing `openTelemetrySpanProcessors` also falls back to the full OpenTelemetry SDK provider, since custom span +processors require the SDK span pipeline. The `SentryTracerProvider` does not handle OpenTelemetry logs and metrics. ## Links