@sentry/opentelemetry 10.49.0 → 10.50.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,68 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ const node_diagnostics_channel = require('node:diagnostics_channel');
4
+ const api = require('@opentelemetry/api');
5
+ const core = require('@sentry/core');
6
+ const debugBuild = require('./debug-build-ntZrglYX.js');
7
+
8
+ /**
9
+ * Transform function that creates a span from the channel data.
10
+ */
11
+
12
+ /**
13
+ * Creates a new tracing channel with proper OTel context propagation.
14
+ *
15
+ * When the channel's `tracePromise` / `traceSync` / `traceCallback` is called,
16
+ * the `transformStart` function runs inside `bindStore` so that:
17
+ * 1. A new span is created from the channel data.
18
+ * 2. The span is set on the OTel context stored in AsyncLocalStorage.
19
+ * 3. Downstream code (including Sentry's span processor) sees the correct parent.
20
+ *
21
+ * @param channelNameOrInstance - Either a channel name string or an existing TracingChannel instance.
22
+ * @param transformStart - Function that creates an OpenTelemetry span from the channel data.
23
+ * @returns The tracing channel with OTel context bound.
24
+ */
25
+ function tracingChannel(
26
+ channelNameOrInstance,
27
+ transformStart,
28
+ ) {
29
+ const channel = node_diagnostics_channel.tracingChannel(
30
+ channelNameOrInstance,
31
+ ) ;
32
+
33
+ let lookup;
34
+ try {
35
+ const contextManager = (api.context )._getContextManager();
36
+ lookup = contextManager.getAsyncLocalStorageLookup();
37
+ } catch {
38
+ // getAsyncLocalStorageLookup may not exist if using a non-Sentry context manager
39
+ }
40
+
41
+ if (!lookup) {
42
+ debugBuild.DEBUG_BUILD &&
43
+ core.logger.warn(
44
+ '[TracingChannel] Could not access OpenTelemetry AsyncLocalStorage, context propagation will not work.',
45
+ );
46
+ return channel;
47
+ }
48
+
49
+ const otelStorage = lookup.asyncLocalStorage;
50
+
51
+ // Bind the start channel so that each trace invocation runs the transform
52
+ // and stores the resulting context (with span) in AsyncLocalStorage.
53
+ // @ts-expect-error bindStore types don't account for AsyncLocalStorage of a different generic type
54
+ channel.start.bindStore(otelStorage, (data) => {
55
+ const span = transformStart(data);
56
+
57
+ // Store the span on data so downstream event handlers (asyncEnd, error, etc.) can access it.
58
+ data._sentrySpan = span;
59
+
60
+ // Return the context with the span set — this is what gets stored in AsyncLocalStorage.
61
+ return api.trace.setSpan(api.context.active(), span);
62
+ });
63
+
64
+ return channel;
65
+ }
66
+
67
+ exports.tracingChannel = tracingChannel;
68
+ //# sourceMappingURL=tracingChannel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracingChannel.js","sources":["../../src/tracingChannel.ts"],"sourcesContent":["/**\n * Vendored and adapted from https://github.com/logaretm/otel-tracing-channel\n *\n * Creates a TracingChannel with proper OpenTelemetry context propagation\n * using Node.js diagnostic_channel's `bindStore` mechanism.\n */\nimport type { TracingChannel, TracingChannelSubscribers } from 'node:diagnostics_channel';\nimport { tracingChannel as nativeTracingChannel } from 'node:diagnostics_channel';\nimport type { Span } from '@opentelemetry/api';\nimport { context, trace } from '@opentelemetry/api';\nimport { logger } from '@sentry/core';\nimport type { SentryAsyncLocalStorageContextManager } from './asyncLocalStorageContextManager';\nimport type { AsyncLocalStorageLookup } from './contextManager';\nimport { DEBUG_BUILD } from './debug-build';\n\n/**\n * Transform function that creates a span from the channel data.\n */\nexport type OtelTracingChannelTransform<TData = object> = (data: TData) => Span;\n\ntype WithSpan<TData = object> = TData & { _sentrySpan?: Span };\n\n/**\n * A TracingChannel whose `subscribe` / `unsubscribe` accept partial subscriber\n * objects — you only need to provide handlers for the events you care about.\n */\nexport interface OtelTracingChannel<\n TData extends object = object,\n TDataWithSpan extends object = WithSpan<TData>,\n> extends Omit<TracingChannel<TData, TDataWithSpan>, 'subscribe' | 'unsubscribe'> {\n subscribe(subscribers: Partial<TracingChannelSubscribers<TDataWithSpan>>): void;\n unsubscribe(subscribers: Partial<TracingChannelSubscribers<TDataWithSpan>>): void;\n}\n\ninterface ContextApi {\n _getContextManager(): SentryAsyncLocalStorageContextManager;\n}\n\n/**\n * Creates a new tracing channel with proper OTel context propagation.\n *\n * When the channel's `tracePromise` / `traceSync` / `traceCallback` is called,\n * the `transformStart` function runs inside `bindStore` so that:\n * 1. A new span is created from the channel data.\n * 2. The span is set on the OTel context stored in AsyncLocalStorage.\n * 3. Downstream code (including Sentry's span processor) sees the correct parent.\n *\n * @param channelNameOrInstance - Either a channel name string or an existing TracingChannel instance.\n * @param transformStart - Function that creates an OpenTelemetry span from the channel data.\n * @returns The tracing channel with OTel context bound.\n */\nexport function tracingChannel<TData extends object = object>(\n channelNameOrInstance: string,\n transformStart: OtelTracingChannelTransform<TData>,\n): OtelTracingChannel<TData, WithSpan<TData>> {\n const channel = nativeTracingChannel<WithSpan<TData>, WithSpan<TData>>(\n channelNameOrInstance,\n ) as unknown as OtelTracingChannel<TData, WithSpan<TData>>;\n\n let lookup: AsyncLocalStorageLookup | undefined;\n try {\n const contextManager = (context as unknown as ContextApi)._getContextManager();\n lookup = contextManager.getAsyncLocalStorageLookup();\n } catch {\n // getAsyncLocalStorageLookup may not exist if using a non-Sentry context manager\n }\n\n if (!lookup) {\n DEBUG_BUILD &&\n logger.warn(\n '[TracingChannel] Could not access OpenTelemetry AsyncLocalStorage, context propagation will not work.',\n );\n return channel;\n }\n\n const otelStorage = lookup.asyncLocalStorage;\n\n // Bind the start channel so that each trace invocation runs the transform\n // and stores the resulting context (with span) in AsyncLocalStorage.\n // @ts-expect-error bindStore types don't account for AsyncLocalStorage of a different generic type\n channel.start.bindStore(otelStorage, (data: WithSpan<TData>) => {\n const span = transformStart(data);\n\n // Store the span on data so downstream event handlers (asyncEnd, error, etc.) can access it.\n data._sentrySpan = span;\n\n // Return the context with the span set — this is what gets stored in AsyncLocalStorage.\n return trace.setSpan(context.active(), span);\n });\n\n return channel;\n}\n"],"names":["nativeTracingChannel","context","DEBUG_BUILD","logger","trace"],"mappings":";;;;;;;AAeA;AACA;AACA;;AAqBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,cAAc;AAC9B,EAAE,qBAAqB;AACvB,EAAE,cAAc;AAChB,EAA8C;AAC9C,EAAE,MAAM,OAAA,GAAUA,uCAAoB;AACtC,IAAI,qBAAqB;AACzB,GAAE;;AAEF,EAAE,IAAI,MAAM;AACZ,EAAE,IAAI;AACN,IAAI,MAAM,iBAAiB,CAACC,cAAkC,kBAAkB,EAAE;AAClF,IAAI,SAAS,cAAc,CAAC,0BAA0B,EAAE;AACxD,EAAE,EAAE,MAAM;AACV;AACA,EAAE;;AAEF,EAAE,IAAI,CAAC,MAAM,EAAE;AACf,IAAIC,sBAAA;AACJ,MAAMC,WAAM,CAAC,IAAI;AACjB,QAAQ,uGAAuG;AAC/G,OAAO;AACP,IAAI,OAAO,OAAO;AAClB,EAAE;;AAEF,EAAE,MAAM,WAAA,GAAc,MAAM,CAAC,iBAAiB;;AAE9C;AACA;AACA;AACA,EAAE,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC,IAAI,KAAsB;AAClE,IAAI,MAAM,IAAA,GAAO,cAAc,CAAC,IAAI,CAAC;;AAErC;AACA,IAAI,IAAI,CAAC,WAAA,GAAc,IAAI;;AAE3B;AACA,IAAI,OAAOC,SAAK,CAAC,OAAO,CAACH,WAAO,CAAC,MAAM,EAAE,EAAE,IAAI,CAAC;AAChD,EAAE,CAAC,CAAC;;AAEJ,EAAE,OAAO,OAAO;AAChB;;;;"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
3
+ *
4
+ * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
5
+ */
6
+ const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
7
+
8
+ export { DEBUG_BUILD as D };
9
+ //# sourceMappingURL=debug-build-DcLzdrV_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debug-build-DcLzdrV_.js","sources":["../../src/debug-build.ts"],"sourcesContent":["declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n"],"names":[],"mappings":"AAEA;AACA;AACA;AACA;AACA;AACO,MAAM,WAAA,IAAc,OAAA,gBAAA,KAAA,WAAA,IAAA,gBAAA;;;;"}
@@ -4,6 +4,7 @@ export { getClient, getDynamicSamplingContextFromSpan, shouldPropagateTraceForUr
4
4
  import * as api from '@opentelemetry/api';
5
5
  import { trace, SpanKind, createContextKey, TraceFlags, propagation, INVALID_TRACEID, context, SpanStatusCode, ROOT_CONTEXT, isSpanContextValid } from '@opentelemetry/api';
6
6
  import { TraceState, W3CBaggagePropagator, isTracingSuppressed, suppressTracing as suppressTracing$1, SDK_INFO } from '@opentelemetry/core';
7
+ import { D as DEBUG_BUILD } from './debug-build-DcLzdrV_.js';
7
8
  import { AsyncLocalStorage } from 'node:async_hooks';
8
9
  import { EventEmitter } from 'node:events';
9
10
  import { SamplingDecision } from '@opentelemetry/sdk-trace-base';
@@ -654,13 +655,6 @@ function getActiveSpan() {
654
655
  return trace.getActiveSpan();
655
656
  }
656
657
 
657
- /**
658
- * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
659
- *
660
- * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
661
- */
662
- const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
663
-
664
658
  /**
665
659
  * Generate a TraceState for the given data.
666
660
  */
@@ -991,8 +985,12 @@ function _startSpan(options, callback, autoEnd) {
991
985
 
992
986
  return wrapper(() => {
993
987
  const activeCtx = getContext(options.scope, options.forceTransaction);
994
- const shouldSkipSpan = options.onlyIfParent && !trace.getSpan(activeCtx);
995
- const ctx = shouldSkipSpan ? suppressTracing$1(activeCtx) : activeCtx;
988
+ const missingRequiredParent = options.onlyIfParent && !trace.getSpan(activeCtx);
989
+ const ctx = missingRequiredParent ? suppressTracing$1(activeCtx) : activeCtx;
990
+
991
+ if (missingRequiredParent) {
992
+ getClient()?.recordDroppedEvent('no_parent_span', 'span');
993
+ }
996
994
 
997
995
  const spanOptions = getSpanOptions(options);
998
996
 
@@ -1094,8 +1092,12 @@ function startInactiveSpan(options) {
1094
1092
 
1095
1093
  return wrapper(() => {
1096
1094
  const activeCtx = getContext(options.scope, options.forceTransaction);
1097
- const shouldSkipSpan = options.onlyIfParent && !trace.getSpan(activeCtx);
1098
- let ctx = shouldSkipSpan ? suppressTracing$1(activeCtx) : activeCtx;
1095
+ const missingRequiredParent = options.onlyIfParent && !trace.getSpan(activeCtx);
1096
+ let ctx = missingRequiredParent ? suppressTracing$1(activeCtx) : activeCtx;
1097
+
1098
+ if (missingRequiredParent) {
1099
+ getClient()?.recordDroppedEvent('no_parent_span', 'span');
1100
+ }
1099
1101
 
1100
1102
  const spanOptions = getSpanOptions(options);
1101
1103
 
@@ -2053,8 +2055,11 @@ class SentrySpanExporter {
2053
2055
  // We'll recursively add all the child spans to this array
2054
2056
  const spans = transactionEvent.spans || [];
2055
2057
 
2058
+ let hasGenAiSpans = false;
2056
2059
  for (const child of root.children) {
2057
- createAndFinishSpanForOtelSpan(child, spans, sentSpans);
2060
+ if (createAndFinishSpanForOtelSpan(child, spans, sentSpans)) {
2061
+ hasGenAiSpans = true;
2062
+ }
2058
2063
  }
2059
2064
 
2060
2065
  // spans.sort() mutates the array, but we do not use this anymore after this point
@@ -2064,6 +2069,13 @@ class SentrySpanExporter {
2064
2069
  ? spans.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT)
2065
2070
  : spans;
2066
2071
 
2072
+ if (hasGenAiSpans) {
2073
+ transactionEvent.sdkProcessingMetadata = {
2074
+ ...transactionEvent.sdkProcessingMetadata,
2075
+ hasGenAiSpans: true,
2076
+ };
2077
+ }
2078
+
2067
2079
  const measurements = timedEventsToMeasurements(span.events);
2068
2080
  if (measurements) {
2069
2081
  transactionEvent.measurements = measurements;
@@ -2180,6 +2192,9 @@ function createTransactionForOtelSpan(span) {
2180
2192
  return transactionEvent;
2181
2193
  }
2182
2194
 
2195
+ /**
2196
+ * Returns `true` if this span or any descendant is a gen_ai span.
2197
+ */
2183
2198
  function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
2184
2199
  const span = node.span;
2185
2200
 
@@ -2191,10 +2206,13 @@ function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
2191
2206
 
2192
2207
  // If this span should be dropped, we still want to create spans for the children of this
2193
2208
  if (shouldDrop) {
2209
+ let hasGenAiSpans = false;
2194
2210
  node.children.forEach(child => {
2195
- createAndFinishSpanForOtelSpan(child, spans, sentSpans);
2211
+ if (createAndFinishSpanForOtelSpan(child, spans, sentSpans)) {
2212
+ hasGenAiSpans = true;
2213
+ }
2196
2214
  });
2197
- return;
2215
+ return hasGenAiSpans;
2198
2216
  }
2199
2217
 
2200
2218
  const span_id = span.spanContext().spanId;
@@ -2231,9 +2249,13 @@ function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
2231
2249
 
2232
2250
  spans.push(spanJSON);
2233
2251
 
2252
+ let hasGenAiSpans = !!op?.startsWith('gen_ai.');
2234
2253
  node.children.forEach(child => {
2235
- createAndFinishSpanForOtelSpan(child, spans, sentSpans);
2254
+ if (createAndFinishSpanForOtelSpan(child, spans, sentSpans)) {
2255
+ hasGenAiSpans = true;
2256
+ }
2236
2257
  });
2258
+ return hasGenAiSpans;
2237
2259
  }
2238
2260
 
2239
2261
  function getSpanData(span)
@@ -2418,6 +2440,7 @@ class SentrySampler {
2418
2440
  // If we have a http.client span that has no local parent, we never want to sample it
2419
2441
  // but we want to leave downstream sampling decisions up to the server
2420
2442
  if (spanKind === SpanKind.CLIENT && maybeSpanHttpMethod && (!parentSpan || parentContext?.isRemote)) {
2443
+ this._client.recordDroppedEvent('no_parent_span', 'span');
2421
2444
  return wrapSamplingDecision({ decision: undefined, context, spanAttributes });
2422
2445
  }
2423
2446