All Downloads are FREE. Search and download functionalities are using the official Maven repository.

package.build.cjs.utils.spanUtils.js.map Maven / Gradle / Ivy

There is a newer version: 8.39.0
Show newest version
{"version":3,"file":"spanUtils.js","sources":["../../../src/utils/spanUtils.ts"],"sourcesContent":["import type {\n  MeasurementUnit,\n  Primitive,\n  Span,\n  SpanAttributes,\n  SpanJSON,\n  SpanOrigin,\n  SpanStatus,\n  SpanTimeInput,\n  TraceContext,\n} from '@sentry/types';\nimport {\n  addNonEnumerableProperty,\n  dropUndefinedKeys,\n  generateSentryTraceHeader,\n  timestampInSeconds,\n} from '@sentry/utils';\nimport { getAsyncContextStrategy } from '../asyncContext';\nimport { getMainCarrier } from '../carrier';\nimport { getCurrentScope } from '../currentScopes';\nimport { getMetricSummaryJsonForSpan, updateMetricSummaryOnSpan } from '../metrics/metric-summary';\nimport type { MetricType } from '../metrics/types';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../semanticAttributes';\nimport type { SentrySpan } from '../tracing/sentrySpan';\nimport { SPAN_STATUS_OK, SPAN_STATUS_UNSET } from '../tracing/spanstatus';\nimport { _getSpanForScope } from './spanOnScope';\n\n// These are aligned with OpenTelemetry trace flags\nexport const TRACE_FLAG_NONE = 0x0;\nexport const TRACE_FLAG_SAMPLED = 0x1;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n * By default, this will only include trace_id, span_id & parent_span_id.\n * If `includeAllData` is true, it will also include data, op, status & origin.\n */\nexport function spanToTransactionTraceContext(span: Span): TraceContext {\n  const { spanId: span_id, traceId: trace_id } = span.spanContext();\n  const { data, op, parent_span_id, status, origin } = spanToJSON(span);\n\n  return dropUndefinedKeys({\n    parent_span_id,\n    span_id,\n    trace_id,\n    data,\n    op,\n    status,\n    origin,\n  });\n}\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in a non-transaction event.\n */\nexport function spanToTraceContext(span: Span): TraceContext {\n  const { spanId: span_id, traceId: trace_id } = span.spanContext();\n  const { parent_span_id } = spanToJSON(span);\n\n  return dropUndefinedKeys({ parent_span_id, span_id, trace_id });\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nexport function spanToTraceHeader(span: Span): string {\n  const { traceId, spanId } = span.spanContext();\n  const sampled = spanIsSampled(span);\n  return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a span time input into a timestamp in seconds.\n */\nexport function spanTimeInputToSeconds(input: SpanTimeInput | undefined): number {\n  if (typeof input === 'number') {\n    return ensureTimestampInSeconds(input);\n  }\n\n  if (Array.isArray(input)) {\n    // See {@link HrTime} for the array-based time format\n    return input[0] + input[1] / 1e9;\n  }\n\n  if (input instanceof Date) {\n    return ensureTimestampInSeconds(input.getTime());\n  }\n\n  return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp: number): number {\n  const isMs = timestamp > 9999999999;\n  return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n */\n// Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n// This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n// And `spanToJSON` needs the Span class from `span.ts` to check here.\nexport function spanToJSON(span: Span): Partial {\n  if (spanIsSentrySpan(span)) {\n    return span.getSpanJSON();\n  }\n\n  try {\n    const { spanId: span_id, traceId: trace_id } = span.spanContext();\n\n    // Handle a span from @opentelemetry/sdk-base-trace's `Span` class\n    if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {\n      const { attributes, startTime, name, endTime, parentSpanId, status } = span;\n\n      return dropUndefinedKeys({\n        span_id,\n        trace_id,\n        data: attributes,\n        description: name,\n        parent_span_id: parentSpanId,\n        start_timestamp: spanTimeInputToSeconds(startTime),\n        // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time\n        timestamp: spanTimeInputToSeconds(endTime) || undefined,\n        status: getStatusMessage(status),\n        op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],\n        origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined,\n        _metrics_summary: getMetricSummaryJsonForSpan(span),\n      });\n    }\n\n    // Finally, at least we have `spanContext()`....\n    return {\n      span_id,\n      trace_id,\n    };\n  } catch {\n    return {};\n  }\n}\n\nfunction spanIsOpenTelemetrySdkTraceBaseSpan(span: Span): span is OpenTelemetrySdkTraceBaseSpan {\n  const castSpan = span as OpenTelemetrySdkTraceBaseSpan;\n  return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status;\n}\n\n/** Exported only for tests. */\nexport interface OpenTelemetrySdkTraceBaseSpan extends Span {\n  attributes: SpanAttributes;\n  startTime: SpanTimeInput;\n  name: string;\n  status: SpanStatus;\n  endTime: SpanTimeInput;\n  parentSpanId?: string;\n}\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSentrySpan(span: Span): span is SentrySpan {\n  return typeof (span as SentrySpan).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nexport function spanIsSampled(span: Span): boolean {\n  // We align our trace flags with the ones OpenTelemetry use\n  // So we also check for sampled the same way they do.\n  const { traceFlags } = span.spanContext();\n  return traceFlags === TRACE_FLAG_SAMPLED;\n}\n\n/** Get the status message to use for a JSON representation of a span. */\nexport function getStatusMessage(status: SpanStatus | undefined): string | undefined {\n  if (!status || status.code === SPAN_STATUS_UNSET) {\n    return undefined;\n  }\n\n  if (status.code === SPAN_STATUS_OK) {\n    return 'ok';\n  }\n\n  return status.message || 'unknown_error';\n}\n\nconst CHILD_SPANS_FIELD = '_sentryChildSpans';\nconst ROOT_SPAN_FIELD = '_sentryRootSpan';\n\ntype SpanWithPotentialChildren = Span & {\n  [CHILD_SPANS_FIELD]?: Set;\n  [ROOT_SPAN_FIELD]?: Span;\n};\n\n/**\n * Adds an opaque child span reference to a span.\n */\nexport function addChildSpanToSpan(span: SpanWithPotentialChildren, childSpan: Span): void {\n  // We store the root span reference on the child span\n  // We need this for `getRootSpan()` to work\n  const rootSpan = span[ROOT_SPAN_FIELD] || span;\n  addNonEnumerableProperty(childSpan as SpanWithPotentialChildren, ROOT_SPAN_FIELD, rootSpan);\n\n  // We store a list of child spans on the parent span\n  // We need this for `getSpanDescendants()` to work\n  if (span[CHILD_SPANS_FIELD]) {\n    span[CHILD_SPANS_FIELD].add(childSpan);\n  } else {\n    addNonEnumerableProperty(span, CHILD_SPANS_FIELD, new Set([childSpan]));\n  }\n}\n\n/** This is only used internally by Idle Spans. */\nexport function removeChildSpanFromSpan(span: SpanWithPotentialChildren, childSpan: Span): void {\n  if (span[CHILD_SPANS_FIELD]) {\n    span[CHILD_SPANS_FIELD].delete(childSpan);\n  }\n}\n\n/**\n * Returns an array of the given span and all of its descendants.\n */\nexport function getSpanDescendants(span: SpanWithPotentialChildren): Span[] {\n  const resultSet = new Set();\n\n  function addSpanChildren(span: SpanWithPotentialChildren): void {\n    // This exit condition is required to not infinitely loop in case of a circular dependency.\n    if (resultSet.has(span)) {\n      return;\n      // We want to ignore unsampled spans (e.g. non recording spans)\n    } else if (spanIsSampled(span)) {\n      resultSet.add(span);\n      const childSpans = span[CHILD_SPANS_FIELD] ? Array.from(span[CHILD_SPANS_FIELD]) : [];\n      for (const childSpan of childSpans) {\n        addSpanChildren(childSpan);\n      }\n    }\n  }\n\n  addSpanChildren(span);\n\n  return Array.from(resultSet);\n}\n\n/**\n * Returns the root span of a given span.\n */\nexport function getRootSpan(span: SpanWithPotentialChildren): Span {\n  return span[ROOT_SPAN_FIELD] || span;\n}\n\n/**\n * Returns the currently active span.\n */\nexport function getActiveSpan(): Span | undefined {\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n  if (acs.getActiveSpan) {\n    return acs.getActiveSpan();\n  }\n\n  return _getSpanForScope(getCurrentScope());\n}\n\n/**\n * Updates the metric summary on the currently active span\n */\nexport function updateMetricSummaryOnActiveSpan(\n  metricType: MetricType,\n  sanitizedName: string,\n  value: number,\n  unit: MeasurementUnit,\n  tags: Record,\n  bucketKey: string,\n): void {\n  const span = getActiveSpan();\n  if (span) {\n    updateMetricSummaryOnSpan(span, metricType, sanitizedName, value, unit, tags, bucketKey);\n  }\n}\n"],"names":["dropUndefinedKeys","generateSentryTraceHeader","timestampInSeconds","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","getMetricSummaryJsonForSpan","SPAN_STATUS_UNSET","SPAN_STATUS_OK","addNonEnumerableProperty","carrier","getMainCarrier","getAsyncContextStrategy","_getSpanForScope","getCurrentScope","updateMetricSummaryOnSpan"],"mappings":";;;;;;;;;;;AA2BA;AACO,MAAM,eAAgB,GAAE,IAAG;AAC3B,MAAM,kBAAmB,GAAE,IAAG;AACrC;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,6BAA6B,CAAC,IAAI,EAAsB;AACxE,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,QAAA,KAAa,IAAI,CAAC,WAAW,EAAE,CAAA;AACnE,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,cAAc,EAAE,MAAM,EAAE,QAAS,GAAE,UAAU,CAAC,IAAI,CAAC,CAAA;AACvE;AACA,EAAE,OAAOA,uBAAiB,CAAC;AAC3B,IAAI,cAAc;AAClB,IAAI,OAAO;AACX,IAAI,QAAQ;AACZ,IAAI,IAAI;AACR,IAAI,EAAE;AACN,IAAI,MAAM;AACV,IAAI,MAAM;AACV,GAAG,CAAC,CAAA;AACJ,CAAA;AACA;AACA;AACA;AACA;AACO,SAAS,kBAAkB,C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