UNPKG

@sentry/core

Version:
338 lines (337 loc) • 12.7 kB
import { getAsyncContextStrategy } from "../asyncContext/index.js"; import { serializeAttributes } from "../attributes.js"; import { getMainCarrier } from "../carrier.js"; import { getCurrentScope } from "../currentScopes.js"; import { SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME } from "../semanticAttributes.js"; import { isStatusErrorMessageValid } from "../tracing/spanstatus.js"; import { getCapturedScopesOnSpan } from "../tracing/utils.js"; import { addNonEnumerableProperty } from "./object.js"; import { generateSpanId } from "./propagationContext.js"; import { performanceTimeToSeconds, timestampInSeconds } from "./time.js"; import { generateSentryTraceHeader, generateTraceparentHeader } from "./tracing.js"; import { _getSpanForScope } from "./spanOnScope.js"; import { SENTRY_OP, SENTRY_ORIGIN, SENTRY_SEGMENT_NAME_SOURCE, SENTRY_STATUS_MESSAGE } from "@sentry/conventions/attributes"; /** * Convert a span to a trace context, which can be sent as the `trace` context in an event. * By default, this will only include trace_id, span_id & parent_span_id. * If `includeAllData` is true, it will also include data, op, status & origin. */ function spanToTransactionTraceContext(span) { const { spanId: span_id, traceId: trace_id } = span.spanContext(); const { data, op, parent_span_id, status, origin, links } = spanToStaticSpanJSON(span); return { parent_span_id, span_id, trace_id, data, op, status, origin, links }; } /** * Convert a span to a trace context, which can be sent as the `trace` context in a non-transaction event. */ function spanToTraceContext(span) { const { spanId, traceId: trace_id, isRemote } = span.spanContext(); const parent_span_id = isRemote ? spanId : spanToStaticSpanJSON(span).parent_span_id; const scope = getCapturedScopesOnSpan(span).scope; return { parent_span_id, span_id: isRemote ? scope?.getPropagationContext().propagationSpanId || generateSpanId() : spanId, trace_id }; } /** * Convert a Span to a Sentry trace header. */ function spanToTraceHeader(span) { const { traceId, spanId } = span.spanContext(); const sampled = spanIsSampled(span); return generateSentryTraceHeader(traceId, spanId, sampled); } /** * Convert a Span to a W3C traceparent header. */ function spanToTraceparentHeader(span) { const { traceId, spanId } = span.spanContext(); const sampled = spanIsSampled(span); return generateTraceparentHeader(traceId, spanId, sampled); } /** * Converts the span links array to a flattened version to be sent within an envelope. * * If the links array is empty, it returns `undefined` so the empty value can be dropped before it's sent. */ function convertSpanLinksForEnvelope(links) { if (links && links.length > 0) return links.map(({ context: { spanId, traceId, traceFlags, ...restContext }, attributes }) => ({ span_id: spanId, trace_id: traceId, sampled: traceFlags === 1, attributes, ...restContext })); else return; } /** * Converts the span links array to a flattened version with serialized attributes for V2 spans. * * If the links array is empty, it returns `undefined` so the empty value can be dropped before it's sent. */ function getStreamedSpanLinks(links) { if (links?.length) return links.map(({ context: { spanId, traceId, traceFlags }, attributes }) => ({ span_id: spanId, trace_id: traceId, sampled: traceFlags === 1, attributes })); else return; } /** * Convert a span time input into a timestamp in seconds. */ function spanTimeInputToSeconds(input) { if (typeof input === "number") return ensureTimestampInSeconds(input); if (Array.isArray(input)) return input[0] + input[1] / 1e9; if (input instanceof Date) return ensureTimestampInSeconds(input.getTime()); return timestampInSeconds(); } /** * Converts a timestamp to second, if it was in milliseconds, or keeps it as second. */ function ensureTimestampInSeconds(timestamp) { return timestamp > 9999999999 ? timestamp / 1e3 : timestamp; } /** * Convert an OpenTelemetry time input into a timestamp in seconds. * * OpenTelemetry numbers are always milliseconds, either since the epoch or since the performance time origin * (`performance.now()`). */ function otelTimeInputToSeconds(input) { if (typeof input !== "number") return spanTimeInputToSeconds(input); if (input < 0xe8d4a51000) return performanceTimeToSeconds(input) ?? timestampInSeconds(); return input / 1e3; } /** * Convert a span to a static JSON representation. */ function spanToStaticSpanJSON(span) { if (spanIsSentrySpan(span)) return span.getStaticSpanJSON(); const { spanId: span_id, traceId: trace_id } = span.spanContext(); if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) { const { attributes, startTime, name, endTime, status, links } = span; return { span_id, trace_id, data: attributes, description: name, parent_span_id: getOtelParentSpanId(span), start_timestamp: spanTimeInputToSeconds(startTime), timestamp: spanTimeInputToSeconds(endTime) || void 0, status: getStatusMessage(status), op: attributes[SENTRY_OP], origin: attributes[SENTRY_ORIGIN], links: convertSpanLinksForEnvelope(links) }; } return { span_id, trace_id, start_timestamp: 0, status: "ok", data: {} }; } /** * Convert a span to a JSON representation. */ function spanToJSON(span) { if (spanIsSentrySpan(span)) return span.getSpanJSON(); const { spanId: span_id, traceId: trace_id } = span.spanContext(); if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) { const { attributes, startTime, name, endTime, status, links } = span; return { name, span_id, trace_id, parent_span_id: getOtelParentSpanId(span), start_timestamp: spanTimeInputToSeconds(startTime), end_timestamp: spanTimeInputToSeconds(endTime) || void 0, is_segment: spanIsSegment(span), status: getSimpleStatus(status), attributes: addStatusMessageAttribute(attributes, status), links: getStreamedSpanLinks(links) }; } return { span_id, trace_id, start_timestamp: 0, name: "", status: "ok", is_segment: spanIsSegment(span), attributes: {} }; } /** * In preparation for the next major of OpenTelemetry, we want to support * looking up the parent span id according to the new API * In OTel v1, the parent span id is accessed as `parentSpanId` * In OTel v2, the parent span id is accessed as `spanId` on the `parentSpanContext` */ function getOtelParentSpanId(span) { return "parentSpanId" in span ? span.parentSpanId : "parentSpanContext" in span ? span.parentSpanContext?.spanId : void 0; } /** * Converts a {@link StreamedSpanJSON} to a {@link SerializedSpan}. * This is the final serialized span format that is sent to Sentry. * The returned serilaized spans must not be consumed by users or SDK integrations. */ function streamedSpanJsonToSerializedSpan(spanJson) { return { ...spanJson, end_timestamp: spanJson.end_timestamp ?? spanJson.start_timestamp, attributes: serializeAttributes(spanJson.attributes), links: spanJson.links?.map((link) => ({ ...link, attributes: serializeAttributes(link.attributes) })) }; } function spanIsOpenTelemetrySdkTraceBaseSpan(span) { const castSpan = span; return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status; } /** * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof. * :( So instead we approximate this by checking if it has the `getSpanJSON` method. */ function spanIsSentrySpan(span) { return typeof span.getSpanJSON === "function"; } /** * Returns true if a span is sampled. * In most cases, you should just use `span.isRecording()` instead. * However, this has a slightly different semantic, as it also returns false if the span is finished. * So in the case where this distinction is important, use this method. */ function spanIsSampled(span) { const { traceFlags } = span.spanContext(); return traceFlags === 1; } /** Get the status message to use for a JSON representation of a span. */ function getStatusMessage(status) { if (!status || status.code === 0) return "ok"; if (status.code === 1) return "ok"; return status.message && isStatusErrorMessageValid(status.message) ? status.message : "internal_error"; } /** * Convert the various statuses to the simple ones expected by Sentry for streamed spans ('ok' is default). */ function getSimpleStatus(status) { return !status || status.code === 1 || status.code === 0 || status.message === "cancelled" ? "ok" : "error"; } /** * Returns the span's attributes with the SENTRY_STATUS_MESSAGE attribute added * if the span has an error status message worth preserving. * * An explicitly set attribute is never overwritten. */ function addStatusMessageAttribute(attributes, status) { const statusMessage = getSimpleStatus(status) === "error" ? status?.message : void 0; return { ...statusMessage && { [SENTRY_STATUS_MESSAGE]: statusMessage }, ...attributes }; } const CHILD_SPANS_FIELD = "_sentryChildSpans"; const ROOT_SPAN_FIELD = "_sentryRootSpan"; /** * Adds an opaque child span reference to a span. */ function addChildSpanToSpan(span, childSpan) { const rootSpan = span[ROOT_SPAN_FIELD] || span; addNonEnumerableProperty(childSpan, ROOT_SPAN_FIELD, rootSpan); childSpan.setAttribute(SENTRY_SEGMENT_NAME_SOURCE, void 0); if (!spanIsSampled(span)) return; if (!span.isRecording() && !rootSpan.isRecording()) return; if (span[CHILD_SPANS_FIELD]) span[CHILD_SPANS_FIELD].add(childSpan); else addNonEnumerableProperty(span, CHILD_SPANS_FIELD, /* @__PURE__ */ new Set([childSpan])); } /** This is only used internally by Idle Spans. */ function removeChildSpanFromSpan(span, childSpan) { if (span[CHILD_SPANS_FIELD]) span[CHILD_SPANS_FIELD].delete(childSpan); } /** * Returns an array of the given span and all of its descendants. */ function getSpanDescendants(span) { const resultSet = /* @__PURE__ */ new Set(); function addSpanChildren(span) { if (resultSet.has(span)) return; else if (spanIsSampled(span)) { resultSet.add(span); const childSpans = span[CHILD_SPANS_FIELD] ? Array.from(span[CHILD_SPANS_FIELD]) : []; for (const childSpan of childSpans) addSpanChildren(childSpan); } } addSpanChildren(span); return Array.from(resultSet); } /** * Returns the root span of a given span. */ const getRootSpan = INTERNAL_getSegmentSpan; /** * Returns the segment span of a given span. */ function INTERNAL_getSegmentSpan(span) { return span[ROOT_SPAN_FIELD] || span; } /** * Whether the given span is the segment span, i.e. it has no parent within its trace. */ function spanIsSegment(span) { return span === INTERNAL_getSegmentSpan(span); } /** * Returns the currently active span. */ function getActiveSpan(scope) { const carrier = getMainCarrier(); const acs = getAsyncContextStrategy(carrier); if (acs.getActiveSpan) return acs.getActiveSpan(scope); return _getSpanForScope(scope || getCurrentScope()); } /** * Updates the name of the given span and ensures that the span name is not * overwritten by the Sentry SDK. * * Use this function instead of `span.updateName()` if you want to make sure that * your name is kept. For some spans, for example root `http.server` spans the * Sentry SDK would otherwise overwrite the span name with a high-quality name * it infers when the span ends. * * Use this function in server code or when your span is started on the server * and on the client (browser). If you only update a span name on the client, * you can also use `span.updateName()` the SDK does not overwrite the name. * * @param span - The span to update the name of. * @param name - The name to set on the span. */ function updateSpanName(span, name) { span.updateName(name); span.setAttributes({ [SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]: name }); INTERNAL_setSegmentNameSourceIfSegment(span, "custom"); } /** * Sets `sentry.segment.name.source` only when `span` is the segment span. * No-op for child spans — the attribute must exclusively live on the segment. */ function INTERNAL_setSegmentNameSourceIfSegment(span, source) { if (spanIsSegment(span)) span.setAttribute(SENTRY_SEGMENT_NAME_SOURCE, source); } export { INTERNAL_getSegmentSpan, INTERNAL_setSegmentNameSourceIfSegment, addChildSpanToSpan, addStatusMessageAttribute, convertSpanLinksForEnvelope, getActiveSpan, getRootSpan, getSimpleStatus, getSpanDescendants, getStatusMessage, getStreamedSpanLinks, otelTimeInputToSeconds, removeChildSpanFromSpan, spanIsSampled, spanIsSegment, spanIsSentrySpan, spanTimeInputToSeconds, spanToJSON, spanToStaticSpanJSON, spanToTraceContext, spanToTraceHeader, spanToTraceparentHeader, spanToTransactionTraceContext, streamedSpanJsonToSerializedSpan, updateSpanName }; //# sourceMappingURL=spanUtils.js.map