UNPKG

@sentry/core

Version:
418 lines (417 loc) • 18.7 kB
import { getAsyncContextStrategy } from "../asyncContext/index.js"; import { getMainCarrier } from "../carrier.js"; import { getClient, getCurrentScope, getIsolationScope, withScope } from "../currentScopes.js"; import { DEBUG_BUILD } from "../debug-build.js"; import { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE } from "../semanticAttributes.js"; import { baggageHeaderToDynamicSamplingContext } from "../utils/baggage.js"; import { debug } from "../utils/debug-logger.js"; import { handleCallbackErrors } from "../utils/handleCallbackErrors.js"; import { recordEscapedErrorSpan } from "../utils/errorSpanAttribution.js"; import { hasSpansEnabled } from "../utils/hasSpansEnabled.js"; import { shouldIgnoreSpan } from "../utils/should-ignore-span.js"; import { hasSpanStreamingEnabled } from "./spans/hasSpanStreamingEnabled.js"; import { parseSampleRate } from "../utils/parseSampleRate.js"; import { generateTraceId } from "../utils/propagationContext.js"; import { safeMathRandom } from "../utils/randomSafeContext.js"; import { _setSpanForScope } from "../utils/spanOnScope.js"; import { addChildSpanToSpan, getActiveSpan, getRootSpan, spanIsSampled, spanTimeInputToSeconds, spanToStaticSpanJSON } from "../utils/spanUtils.js"; import { propagationContextFromHeaders, shouldContinueTrace } from "../utils/tracing.js"; import { freezeDscOnSpan, getDynamicSamplingContextFromSpan } from "./dynamicSamplingContext.js"; import { logSpanStart } from "./logSpans.js"; import { sampleSpan } from "./sampling.js"; import { SentryNonRecordingSpan, spanIsNonRecordingSpan } from "./sentryNonRecordingSpan.js"; import { SentrySpan } from "./sentrySpan.js"; import "./spanstatus.js"; import { getCapturedScopesOnSpan, setCapturedScopesOnSpan } from "./utils.js"; import { SUPPRESS_TRACING_KEY } from "./constants.js"; import { SENTRY_OP, SENTRY_SEGMENT_NAME_SOURCE } from "@sentry/conventions/attributes"; // src/tracing/trace.ts /** * Wraps a function with a transaction/span and finishes the span after the function is done. * The created span is the active span and will be used as parent by other spans created inside the function * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active. * * If you want to create a span that is not set as active, use {@link startInactiveSpan}. * * You'll always get a span passed to the callback, * it may just be a non-recording span if the span is not sampled or if tracing is disabled. */ function startSpan(options, callback) { const spanArguments = parseSentrySpanArguments(options); const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options; const customForkedScope = customScope?.clone(); return withScope(customForkedScope, () => { return getActiveSpanWrapper(customParentSpan)(() => { const scope = getCurrentScope(); const parentSpan = getParentSpan(customScope ?? scope, customParentSpan); const client = getClient(); const activeSpan = options.onlyIfParent && !parentSpan ? startMissingRequiredParentSpan(scope, client) : createChildOrRootSpan({ parentSpan, spanArguments, forceTransaction, scope }); return runCallback(activeSpan, !spanIsIgnored(activeSpan) || !parentSpan, () => callback(activeSpan), () => activeSpan.end()); }); }); } /** * Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span * after the function is done automatically. Use `span.end()` to end the span. * * The created span is the active span and will be used as parent by other spans created inside the function * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active. * * You'll always get a span passed to the callback, * it may just be a non-recording span if the span is not sampled or if tracing is disabled. */ function startSpanManual(options, callback) { const spanArguments = parseSentrySpanArguments(options); const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options; const customForkedScope = customScope?.clone(); return withScope(customForkedScope, () => { return getActiveSpanWrapper(customParentSpan)(() => { const scope = getCurrentScope(); const parentSpan = getParentSpan(customScope ?? scope, customParentSpan); const activeSpan = options.onlyIfParent && !parentSpan ? startMissingRequiredParentSpan(scope, getClient()) : createChildOrRootSpan({ parentSpan, spanArguments, forceTransaction, scope }); return runCallback(activeSpan, !spanIsIgnored(activeSpan) || !parentSpan, () => callback(activeSpan, () => activeSpan.end())); }); }); } /** * Creates a span. This span is not set as active, so will not get automatic instrumentation spans * as children or be able to be accessed via `Sentry.getActiveSpan()`. * * If you want to create a span that is set as active, use {@link startSpan}. * * This function will always return a span, * it may just be a non-recording span if the span is not sampled or if tracing is disabled. */ function startInactiveSpan(options) { const spanArguments = parseSentrySpanArguments(options); const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options; return (customScope ? (callback) => withScope(customScope, callback) : customParentSpan !== void 0 ? (callback) => withActiveSpan(customParentSpan, callback) : (callback) => callback())(() => { const scope = getCurrentScope(); const parentSpan = getParentSpan(customScope ?? scope, customParentSpan); const client = getClient(); if (options.onlyIfParent && !parentSpan) return startMissingRequiredParentSpan(scope, client); return createChildOrRootSpan({ parentSpan, spanArguments, forceTransaction, scope }); }); } /** * Continue a trace from `sentry-trace` and `baggage` values. * These values can be obtained from incoming request headers, or in the browser from `<meta name="sentry-trace">` * and `<meta name="baggage">` HTML tags. * * Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically * be attached to the incoming trace. */ const continueTrace = (options, callback) => { const carrier = getMainCarrier(); const acs = getAsyncContextStrategy(carrier); if (acs.continueTrace) return acs.continueTrace(options, callback); const { sentryTrace, baggage } = options; const client = getClient(); const incomingDsc = baggageHeaderToDynamicSamplingContext(baggage); if (client && !shouldContinueTrace(client, incomingDsc?.org_id)) return startNewTrace(callback); return withScope((scope) => { const propagationContext = propagationContextFromHeaders(sentryTrace, baggage); scope.setPropagationContext(propagationContext); return withActiveSpan(null, callback); }); }; /** * Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be * passed `null` to start an entirely new span tree. * * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed, * spans started within the callback will not be attached to a parent span. * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope. * @returns the value returned from the provided callback function. */ function withActiveSpan(span, callback) { const acs = getAcs(); if (acs.withActiveSpan) return acs.withActiveSpan(span, callback); return withScope((scope) => { _setSpanForScope(scope, span || void 0); return callback(scope); }); } /** Suppress tracing in the given callback, ensuring no spans are generated inside of it. */ function suppressTracing(callback) { const acs = getAcs(); if (acs.suppressTracing) return acs.suppressTracing(callback); return withScope((scope) => { scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true }); return callback(); }); } /** Check if tracing is suppressed. */ function isTracingSuppressed(scope = getCurrentScope()) { const acs = getAcs(); if (acs.isTracingSuppressed) return acs.isTracingSuppressed(scope); return scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] === true; } /** * Starts a new trace for the duration of the provided callback. Spans started within the * callback will be part of the new trace instead of a potentially previously started trace. * * Important: Only use this function if you want to override the default trace lifetime and * propagation mechanism of the SDK for the duration and scope of the provided callback. * The newly created trace will also be the root of a new distributed trace, for example if * you make http requests within the callback. * This function might be useful if the operation you want to instrument should not be part * of a potentially ongoing trace. * * Default behavior: * - Server-side: A new trace is started for each incoming request. * - Browser: A new trace is started for each page our route. Navigating to a new route * or page will automatically create a new trace. */ function startNewTrace(callback) { const acs = getAcs(); if (acs.startNewTrace) return acs.startNewTrace(callback); return withActiveSpan(null, () => { return withScope((scope) => { scope.setPropagationContext({ traceId: generateTraceId(), sampleRand: safeMathRandom() }); DEBUG_BUILD && debug.log(`Starting a new trace with id ${scope.getPropagationContext().traceId}`); return callback(); }); }); } /** * The placeholder returned from `startSpan*` when `onlyIfParent` is set but there is no parent span. * It carries the current trace id and captured scopes so the trace data it propagates (and any nested * span that resolves it as its root via `getRootSpan`) reads its DSC from the scope, preserving a * continued trace's DSC instead of fabricating a fresh client one. Also records the dropped-span outcome. */ function startMissingRequiredParentSpan(scope, client) { client?.recordDroppedEvent("no_parent_span", "span"); const span = new SentryNonRecordingSpan({ dropReason: "no_parent_span", traceId: scope.getPropagationContext().traceId }); setCapturedScopesOnSpan(span, scope, getIsolationScope()); return span; } function createChildOrRootSpan({ parentSpan: resolvedParentSpan, spanArguments, forceTransaction, scope: currentScope }) { const isolationScope = getIsolationScope(); const spanScope = { scope: currentScope, parentSpan: resolvedParentSpan }; getClient()?.emit("prepareSpanScope", spanScope); const { scope, parentSpan } = spanScope; if (!hasSpansEnabled()) { const scopePropagationContext = scope.getPropagationContext(); const traceId = parentSpan ? parentSpan.spanContext().traceId : scopePropagationContext.traceId; const span = new SentryNonRecordingSpan({ traceId }); if (parentSpan && !forceTransaction) addChildSpanToSpan(parentSpan, span); setCapturedScopesOnSpan(span, scope, isolationScope); return span; } const client = getClient(); if (_shouldIgnoreStreamedSpan(client, spanArguments)) { if (!isTracingSuppressed(scope)) client?.recordDroppedEvent("ignored", "span"); const ignoredSpan = new SentryNonRecordingSpan({ dropReason: "ignored", traceId: parentSpan?.spanContext().traceId ?? scope.getPropagationContext().traceId }); if (parentSpan && !forceTransaction) addChildSpanToSpan(parentSpan, ignoredSpan); setCapturedScopesOnSpan(ignoredSpan, scope, isolationScope); return ignoredSpan; } let span; if (parentSpan && !forceTransaction) { span = _startChildSpan(parentSpan, scope, spanArguments, isolationScope); addChildSpanToSpan(parentSpan, span); } else if (parentSpan) { const dsc = getDynamicSamplingContextFromSpan(parentSpan); const { traceId, spanId: parentSpanId } = parentSpan.spanContext(); const parentSampled = spanIsSampled(parentSpan); span = _startRootSpan({ traceId, parentSpanId, ...spanArguments }, scope, isolationScope, parentSampled); freezeDscOnSpan(span, dsc); } else { const { traceId, dsc, parentSpanId, sampled: parentSampled, sampleRand } = scope.getPropagationContext(); span = _startRootSpan({ traceId, parentSpanId, ...spanArguments }, scope, isolationScope, parentSampled); if (dsc) { const dscWithSampleRand = Object.keys(dsc).length === 0 && sampleRand !== void 0 ? { sample_rand: sampleRand.toString() } : dsc; freezeDscOnSpan(span, dscWithSampleRand); } } logSpanStart(span); return span; } /** * This converts StartSpanOptions to SentrySpanArguments. * For the most part (for now) we accept the same options, * but some of them need to be transformed. */ function parseSentrySpanArguments(options) { const initialCtx = { isStandalone: options.experimental?.standalone, ...options }; if (options.op) initialCtx.attributes = { [SENTRY_OP]: options.op, ...options.attributes }; if (options.startTime) { const ctx = { ...initialCtx }; ctx.startTimestamp = spanTimeInputToSeconds(options.startTime); delete ctx.startTime; return ctx; } return initialCtx; } function getAcs() { const carrier = getMainCarrier(); return getAsyncContextStrategy(carrier); } /** * Runs the callback with the span active. When the async context strategy bridges to an ambient * context (OTel), activation must go through it so the span lands on that context and * instrumentation-created child spans nest under it; the scope alone is not consulted there. */ function _startRootSpan(spanArguments, scope, isolationScope, parentSampled) { const client = getClient(); const options = client?.getOptions() || {}; const { name = "" } = spanArguments; const mutableSpanSamplingData = { spanAttributes: { ...spanArguments.attributes }, spanName: name, parentSampled }; client?.emit("beforeSampling", mutableSpanSamplingData, { decision: false }); const finalParentSampled = mutableSpanSamplingData.parentSampled ?? parentSampled; const finalAttributes = mutableSpanSamplingData.spanAttributes; const currentPropagationContext = scope.getPropagationContext(); const _isTracingSuppressed = isTracingSuppressed(scope); const [sampled, sampleRate, localSampleRateWasApplied, dropReason] = _isTracingSuppressed ? [false] : sampleSpan(options, { name, parentSampled: finalParentSampled, attributes: finalAttributes, normalizedRequest: isolationScope.getScopeData().sdkProcessingMetadata.normalizedRequest, parentSampleRate: parseSampleRate(currentPropagationContext.dsc?.sample_rate) }, currentPropagationContext.sampleRand); const rootSpan = new SentrySpan({ ...spanArguments, attributes: { [SENTRY_SEGMENT_NAME_SOURCE]: "custom", [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate !== void 0 && localSampleRateWasApplied ? sampleRate : void 0, ...finalAttributes }, sampled }); if (!sampled && client && !_isTracingSuppressed) { DEBUG_BUILD && debug.log("[Tracing] Discarding root span because its trace was not chosen to be sampled."); const outcomeReason = dropReason || "sample_rate"; if (!hasSpanStreamingEnabled(client) && !spanArguments.isStandalone) client.recordDroppedEvent(outcomeReason, "transaction"); client.recordDroppedEvent(outcomeReason, "span"); } setCapturedScopesOnSpan(rootSpan, scope, isolationScope); if (client) client.emit("spanStart", rootSpan); return rootSpan; } /** * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`. * This inherits the sampling decision from the parent span. */ function _startChildSpan(parentSpan, scope, spanArguments, isolationScope) { const { spanId, traceId } = parentSpan.spanContext(); const _isTracingSuppressed = isTracingSuppressed(scope); const sampled = _isTracingSuppressed ? false : spanIsSampled(parentSpan); const childSpan = sampled ? new SentrySpan({ ...spanArguments, parentSpanId: spanId, traceId, sampled }) : new SentryNonRecordingSpan({ traceId }); addChildSpanToSpan(parentSpan, childSpan); setCapturedScopesOnSpan(childSpan, scope, isolationScope); const client = getClient(); if (!client) return childSpan; if (spanIsNonRecordingSpan(childSpan)) { if (spanIsNonRecordingSpan(parentSpan) && parentSpan.dropReason) { childSpan.dropReason = parentSpan.dropReason; client.recordDroppedEvent(parentSpan.dropReason, "span"); } else if (!_isTracingSuppressed) { childSpan.dropReason = "sample_rate"; client.recordDroppedEvent("sample_rate", "span"); } } client.emit("spanStart", childSpan); return childSpan; } function getParentSpan(scope, customParentSpan) { if (customParentSpan) return customParentSpan; if (customParentSpan === null) return; const span = getActiveSpan(scope); if (!span) return; const client = getClient(); if ((client ? client.getOptions() : {}).parentSpanIsAlwaysRootSpan) return getRootSpan(span); return span; } function getActiveSpanWrapper(parentSpan) { return parentSpan !== void 0 ? (callback) => { return withActiveSpan(parentSpan, callback); } : (callback) => callback(); } function _shouldIgnoreStreamedSpan(client, spanArguments) { const ignoreSpans = client?.getOptions().ignoreSpans; if (!client || !hasSpanStreamingEnabled(client) || !ignoreSpans?.length) return false; return shouldIgnoreSpan({ description: spanArguments.name || "", op: spanArguments.attributes?.[SENTRY_OP] || spanArguments.op, attributes: spanArguments.attributes }, ignoreSpans); } /** * Whether a span is an ignored (`ignoreSpans`) placeholder. Such a span must not be set as the active * span when it has a parent, so its children attach to that parent and get re-parented rather than * dropped with it. Shared with the OTel-based provider so both span pipelines apply the same rule. */ function spanIsIgnored(span) { return spanIsNonRecordingSpan(span) && span.dropReason === "ignored"; } function runCallback(span, makeSpanActive, callback, finallyCallback) { return (makeSpanActive ? (callback) => { return withActiveSpan(span, () => { const scope = getCurrentScope(); const creationScope = getCapturedScopesOnSpan(span).scope; if (creationScope) scope.setPropagationContext(creationScope.getPropagationContext()); setCapturedScopesOnSpan(span, scope, getIsolationScope()); return callback(); }); } : (callback) => callback())(() => handleCallbackErrors(() => callback(), (error) => { recordEscapedErrorSpan(error, span); const { status } = spanToStaticSpanJSON(span); if (span.isRecording() && status === "ok") span.setStatus({ code: 2, message: "internal_error" }); }, finallyCallback)); } export { continueTrace, isTracingSuppressed, spanIsIgnored, startInactiveSpan, startNewTrace, startSpan, startSpanManual, suppressTracing, withActiveSpan }; //# sourceMappingURL=trace.js.map