UNPKG

@sentry/core

Version:
358 lines (357 loc) • 13.5 kB
import { getClient, getCurrentScope } from "../currentScopes.js"; import { DEBUG_BUILD } from "../debug-build.js"; import { SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME } from "../semanticAttributes.js"; import { debug } from "../utils/debug-logger.js"; import { generateSpanId, generateTraceId } from "../utils/propagationContext.js"; import { INTERNAL_setSegmentNameSourceIfSegment, addStatusMessageAttribute, convertSpanLinksForEnvelope, getRootSpan, getSimpleStatus, getSpanDescendants, getStatusMessage, getStreamedSpanLinks, otelTimeInputToSeconds, spanIsSegment, spanTimeInputToSeconds, spanToStaticSpanJSON, spanToTransactionTraceContext } from "../utils/spanUtils.js"; import { safePerformanceNow, timestampInSeconds } from "../utils/time.js"; import { getDynamicSamplingContextFromSpan } from "./dynamicSamplingContext.js"; import { logSpanEnd } from "./logSpans.js"; import { timedEventsToMeasurements } from "./measurement.js"; import { getSegmentSpanCaptureStrategy } from "./segmentSpanCaptureStrategy.js"; import { isStaticBeforeSendSpanCallback } from "./spans/beforeSendSpan.js"; import { captureSpan, captureStandaloneSpanWithStaticCallback } from "./spans/captureSpan.js"; import { createStreamedSpanEnvelope } from "./spans/envelope.js"; import { hasSpanStreamingEnabled } from "./spans/hasSpanStreamingEnabled.js"; import { getCapturedScopesOnSpan, spanIsTracerProviderSpan } from "./utils.js"; import { SENTRY_EXCLUSIVE_TIME, SENTRY_OP, SENTRY_ORIGIN, SENTRY_PROFILE_ID, SENTRY_SEGMENT_NAME_SOURCE } from "@sentry/conventions/attributes"; // src/tracing/sentrySpan.ts const MAX_SPAN_COUNT = 1e3; /** * Span contains all data about a span */ var SentrySpan = class { /** * You should never call the constructor manually, always use `Sentry.startSpan()` * or other span methods. * @internal * @hideconstructor * @hidden */ constructor(spanContext = {}) { this._traceId = spanContext.traceId || generateTraceId(); this._spanId = spanContext.spanId || generateSpanId(); if (spanContext.startTimestamp) this._startTime = spanContext.startTimestamp; else { this._startTime = timestampInSeconds(); this._startPerformanceNow = safePerformanceNow(); } this._links = spanContext.links; this._attributes = {}; this.setAttributes({ [SENTRY_ORIGIN]: "manual", [SENTRY_OP]: spanContext.op, ...spanContext.attributes }); this._name = spanContext.name; if (spanContext.parentSpanId) this._parentSpanId = spanContext.parentSpanId; if ("sampled" in spanContext) this._sampled = spanContext.sampled; this._events = []; this._isStandaloneSpan = spanContext.isStandalone; } /** @inheritDoc */ addLink(link) { if (this._frozen) return this; if (this._links) this._links.push(link); else this._links = [link]; return this; } /** @inheritDoc */ addLinks(links) { if (this._frozen) return this; if (this._links) this._links.push(...links); else this._links = links; return this; } /** * This should generally not be used, * but it is needed for being compliant with the OTEL Span interface. * * @hidden * @internal */ recordException(_exception, _time) {} /** @inheritdoc */ spanContext() { const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this; return { spanId, traceId, traceFlags: sampled ? 1 : 0 }; } /** @inheritdoc */ setAttribute(key, value) { if (this._frozen) return this; if (key === SENTRY_SEGMENT_NAME_SOURCE && value !== void 0 && !spanIsSegment(this)) { DEBUG_BUILD && debug.warn("[Tracing] Ignoring name source on a child span: this attribute is only valid on the root span."); return this; } if (value === void 0) delete this._attributes[key]; else this._attributes[key] = value; return this; } /** @inheritdoc */ setAttributes(attributes) { Object.keys(attributes).forEach((key) => this.setAttribute(key, attributes[key])); return this; } /** * This should generally not be used, * but we need it for browser tracing where we want to adjust the start time afterwards. * USE THIS WITH CAUTION! * * @hidden * @internal */ updateStartTime(timeInput) { if (this._frozen) return; this._startTime = timeInputToSeconds(this, timeInput); this._startPerformanceNow = void 0; } /** * @inheritDoc */ setStatus(value) { if (this._frozen) return this; this._status = value; return this; } /** * @inheritDoc */ updateName(name) { if (this._frozen) return this; this._name = name; INTERNAL_setSegmentNameSourceIfSegment(this, "custom"); return this; } /** @inheritdoc */ end(endTimestamp) { if (this._endTime) return; this._endTime = endTimestamp == null ? this._getEndTimeFromDuration() : timeInputToSeconds(this, endTimestamp); logSpanEnd(this); this._onSpanEnded(); this._frozen = spanIsTracerProviderSpan(this); } /** * Get JSON representation of this span. * * @hidden * @internal This method is purely for internal purposes and should not be used outside * of SDK code. If you need to get a JSON representation of a span, * use `spanToJSON(span)` instead. */ getStaticSpanJSON() { return { data: this._attributes, description: this._name, op: this._attributes[SENTRY_OP], parent_span_id: this._parentSpanId, span_id: this._spanId, start_timestamp: this._startTime, status: getStatusMessage(this._status), timestamp: this._endTime, trace_id: this._traceId, origin: this._attributes[SENTRY_ORIGIN], profile_id: this._attributes[SENTRY_PROFILE_ID], exclusive_time: this._attributes[SENTRY_EXCLUSIVE_TIME], measurements: timedEventsToMeasurements(this._events), links: convertSpanLinksForEnvelope(this._links) }; } /** * Get {@link StreamedSpanJSON} representation of this span. * * @hidden * @internal This method is purely for internal purposes and should not be used outside * of SDK code. If you need to get a JSON representation of a span, * use `spanToJSON(span)` instead. */ getSpanJSON() { return { name: this._name ?? "", span_id: this._spanId, trace_id: this._traceId, parent_span_id: this._parentSpanId, start_timestamp: this._startTime, end_timestamp: this._endTime, is_segment: spanIsSegment(this), status: getSimpleStatus(this._status), attributes: addStatusMessageAttribute(this._attributes, this._status), links: getStreamedSpanLinks(this._links) }; } /** @inheritdoc */ isRecording() { return !this._endTime && !!this._sampled; } /** * @inheritdoc */ addEvent(name, attributesOrStartTime, startTime) { if (this._frozen) return this; DEBUG_BUILD && debug.log("[Tracing] Adding an event to span:", name); const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || void 0; const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {}; const event = { name, time: timeInputToSeconds(this, time), attributes }; this._events.push(event); return this; } /** * Whether this span is sent on its own (as a v2 streamed span) rather than as part of a * transaction. Used internally; see `_isStandaloneSpan`. * @internal */ isStandaloneSpan() { return !!this._isStandaloneSpan; } /** * Returns the start time plus the `performance.now()` time since the span started. * * This way, the duration is correct even if the time origin was corrected while the span was running (e.g. after the * device slept), and it can never be negative. */ _getEndTimeFromDuration() { const performanceNow = safePerformanceNow(); if (this._startPerformanceNow == null || performanceNow == null) return timestampInSeconds(); return this._startTime + (performanceNow - this._startPerformanceNow) / 1e3; } /** Emit `spanEnd` when the span is ended. */ _onSpanEnded() { const client = getClient(); client?.emit("spanEnd", this); if (this._isStandaloneSpan) { if (!client) return; if (this._sampled) { sendStandaloneSpan(this, client); return; } DEBUG_BUILD && debug.log("[Tracing] Discarding standalone span because its trace was not chosen to be sampled."); return; } client?.emit("afterSpanEnd", this); const rootSpan = getRootSpan(this); if (rootSpan !== this) { const strategy = getSegmentSpanCaptureStrategy(); if (strategy) { const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope(); strategy.onChildSpanEnded(this, rootSpan, (options) => this._convertSpanToTransaction(options), scope); } return; } if (client && hasSpanStreamingEnabled(client)) { client.emit("afterSegmentSpanEnd", this); return; } const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope(); const strategy = getSegmentSpanCaptureStrategy(); if (strategy) strategy.onSegmentSpanEnded((options) => this._convertSpanToTransaction(options), scope); else { const transactionEvent = this._convertSpanToTransaction(); if (transactionEvent) scope.captureEvent(transactionEvent); } } /** * Finish the transaction & prepare the event to send to Sentry. */ _convertSpanToTransaction(options = {}) { if (!isFullFinishedSpan(spanToStaticSpanJSON(this))) return; if (!this._name) { DEBUG_BUILD && debug.warn("Transaction has no name, falling back to `<unlabeled transaction>`."); this._name = "<unlabeled transaction>"; } const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this); const normalizedRequest = capturedSpanScope?.getScopeData().sdkProcessingMetadata?.normalizedRequest; if (this._sampled !== true) return; options.onSpanCaptured?.(this); const spans = []; let droppedUnfinishedSpanCount = 0; for (const descendant of getSpanDescendants(this)) { if (descendant === this || isStandaloneSpan(descendant) || options.isSpanAlreadyCaptured?.(descendant)) continue; const spanJSON = spanToStaticSpanJSON(descendant); if (!isFullFinishedSpan(spanJSON)) { if (!options.onSpanCaptured) droppedUnfinishedSpanCount++; continue; } options.onSpanCaptured?.(descendant); spans.push(spanJSON); } const client = capturedSpanScope?.getClient() || getClient(); if (droppedUnfinishedSpanCount) client?.recordDroppedEvent("invalid", "span", droppedUnfinishedSpanCount); if (spans.length > MAX_SPAN_COUNT) client?.recordDroppedEvent("buffer_overflow", "span", spans.length - MAX_SPAN_COUNT); const source = this._attributes[SENTRY_SEGMENT_NAME_SOURCE]; delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]; let hasGenAiSpans = false; spans.forEach((span) => { delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]; if (span.op?.startsWith("gen_ai.")) hasGenAiSpans = true; }); const transaction = { contexts: { trace: spanToTransactionTraceContext(this) }, spans: spans.length > MAX_SPAN_COUNT ? spans.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT) : spans, start_timestamp: this._startTime, timestamp: this._endTime, transaction: this._name, type: "transaction", sdkProcessingMetadata: { capturedSpanScope, capturedSpanIsolationScope, dynamicSamplingContext: getDynamicSamplingContextFromSpan(this), hasGenAiSpans }, request: normalizedRequest, ...source && { transaction_info: { source } } }; const measurements = timedEventsToMeasurements(this._events); if (measurements && Object.keys(measurements).length) { DEBUG_BUILD && debug.log("[Measurements] Adding measurements to transaction event", JSON.stringify(measurements, void 0, 2)); transaction.measurements = measurements; } return transaction; } }; function timeInputToSeconds(span, input) { return spanIsTracerProviderSpan(span) ? otelTimeInputToSeconds(input) : spanTimeInputToSeconds(input); } function isSpanTimeInput(value) { return value && typeof value === "number" || value instanceof Date || Array.isArray(value); } function isFullFinishedSpan(input) { return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id; } /** * `SentrySpan`s can be sent on their own (as a v2 streamed span) rather than as part of a transaction. * * TODO(standalone): remove once the static (transaction) trace lifecycle is dropped. */ function isStandaloneSpan(span) { return span instanceof SentrySpan && span.isStandaloneSpan(); } /** * Sends a single span on its own, as a v2 streamed span envelope. * * Used for standalone spans (e.g. a late INP web vital when span streaming is disabled): they are * not part of a transaction and are not handled by the span streaming buffer, so we serialize and * send them here directly. * * TODO(standalone): remove once the static (transaction) trace lifecycle is dropped. */ function sendStandaloneSpan(span, client) { const { beforeSendSpan, traceLifecycle } = client.getOptions(); if (traceLifecycle === "static" && isStaticBeforeSendSpanCallback(beforeSendSpan)) { const serializedSpan = captureStandaloneSpanWithStaticCallback(span, client, beforeSendSpan); const dsc = getDynamicSamplingContextFromSpan(span); client.sendEnvelope(createStreamedSpanEnvelope([serializedSpan], dsc, client)); return; } const { _segmentSpan, _segmentNameAtCapture, ...serializedSpan } = captureSpan(span, client); const dsc = getDynamicSamplingContextFromSpan(_segmentSpan); client.sendEnvelope(createStreamedSpanEnvelope([serializedSpan], dsc, client)); } export { SentrySpan }; //# sourceMappingURL=sentrySpan.js.map