UNPKG

@sentry/core

Version:
210 lines (209 loc) • 8.88 kB
import { getClient, getCurrentScope, getIsolationScope } from "../currentScopes.js"; import { DEBUG_BUILD } from "../debug-build.js"; import { debug } from "../utils/debug-logger.js"; import { hasSpansEnabled } from "../utils/hasSpansEnabled.js"; import { shouldIgnoreSpan } from "../utils/should-ignore-span.js"; import { _setSpanForScope } from "../utils/spanOnScope.js"; import { getActiveSpan, getSpanDescendants, removeChildSpanFromSpan, spanTimeInputToSeconds, spanToJSON, spanToStaticSpanJSON } from "../utils/spanUtils.js"; import { timestampInSeconds } from "../utils/time.js"; import { _INTERNAL_ensureBrowserSpanStreaming } from "./browserSpanApi.js"; import { SentryNonRecordingSpan, spanIsNonRecordingSpan } from "./sentryNonRecordingSpan.js"; import { SentrySpan } from "./sentrySpan.js"; import "./spanstatus.js"; import { startInactiveSpan } from "./trace.js"; import { setCapturedScopesOnSpan } from "./utils.js"; import { SENTRY_IDLE_SPAN_FINISH_REASON } from "@sentry/conventions/attributes"; // src/tracing/idleSpan.ts const TRACING_DEFAULTS = { idleTimeout: 1e3, finalTimeout: 3e4, childSpanTimeout: 15e3 }; const FINISH_REASON_HEARTBEAT_FAILED = "heartbeatFailed"; const FINISH_REASON_IDLE_TIMEOUT = "idleTimeout"; const FINISH_REASON_FINAL_TIMEOUT = "finalTimeout"; const FINISH_REASON_EXTERNAL_FINISH = "externalFinish"; /** * An idle span is a span that automatically finishes. It does this by tracking child spans as activities. * An idle span is always the active span. */ function startIdleSpan(startSpanOptions, options = {}) { const client = getClient(); _INTERNAL_ensureBrowserSpanStreaming(client); const activities = /* @__PURE__ */ new Map(); let _finished = false; let _idleTimeoutID; let _childSpanTimeoutID; let _finishReason = FINISH_REASON_EXTERNAL_FINISH; let _autoFinishAllowed = !options.disableAutoFinish; const _cleanupHooks = []; const { idleTimeout = TRACING_DEFAULTS.idleTimeout, finalTimeout = TRACING_DEFAULTS.finalTimeout, childSpanTimeout = TRACING_DEFAULTS.childSpanTimeout, trimIdleSpanEndTimestamp = true } = options; const scope = getCurrentScope(); if (!client || !hasSpansEnabled()) { const span = new SentryNonRecordingSpan({ traceId: scope.getPropagationContext().traceId }); setCapturedScopesOnSpan(span, scope, getIsolationScope()); return span; } const previousActiveSpan = getActiveSpan(); const span = startInactiveSpan(startSpanOptions); _setSpanForScope(getCurrentScope(), span); DEBUG_BUILD && debug.log("[Tracing] Started span is an idle span"); span.end = new Proxy(span.end, { apply(target, thisArg, args) { client.emit("beforeIdleSpanEnd", span); if (spanIsNonRecordingSpan(thisArg)) return; const [definedEndTimestamp, ...rest] = args; const timestamp = definedEndTimestamp || timestampInSeconds(); const spanEndTimestamp = spanTimeInputToSeconds(timestamp); const spans = getSpanDescendants(span).filter((child) => child !== span); const spanJson = spanToStaticSpanJSON(span); if (!spans.length || !trimIdleSpanEndTimestamp) { onIdleSpanEnded(spanEndTimestamp); return Reflect.apply(target, thisArg, [spanEndTimestamp, ...rest]); } const ignoreSpans = client.getOptions().ignoreSpans; const latestSpanEndTimestamp = spans?.reduce((acc, current) => { const currentSpanJson = spanToStaticSpanJSON(current); if (!currentSpanJson.timestamp) return acc; if (ignoreSpans && shouldIgnoreSpan({ description: currentSpanJson.description, op: currentSpanJson.op, attributes: currentSpanJson.data }, ignoreSpans)) return acc; return acc ? Math.max(acc, currentSpanJson.timestamp) : currentSpanJson.timestamp; }, void 0); const spanStartTimestamp = spanJson.start_timestamp; const endTimestamp = Math.min(spanStartTimestamp ? spanStartTimestamp + finalTimeout / 1e3 : 1e400, Math.max(spanStartTimestamp || -1e400, Math.min(spanEndTimestamp, latestSpanEndTimestamp || 1e400))); onIdleSpanEnded(endTimestamp); return Reflect.apply(target, thisArg, [endTimestamp, ...rest]); } }); /** * Cancels the existing idle timeout, if there is one. */ function _cancelIdleTimeout() { if (_idleTimeoutID) { clearTimeout(_idleTimeoutID); _idleTimeoutID = void 0; } } /** * Cancels the existing child span timeout, if there is one. */ function _cancelChildSpanTimeout() { if (_childSpanTimeoutID) { clearTimeout(_childSpanTimeoutID); _childSpanTimeoutID = void 0; } } /** * Restarts idle timeout, if there is no running idle timeout it will start one. */ function _restartIdleTimeout(endTimestamp) { _cancelIdleTimeout(); _idleTimeoutID = setTimeout(() => { if (!_finished && activities.size === 0 && _autoFinishAllowed) { _finishReason = FINISH_REASON_IDLE_TIMEOUT; span.end(endTimestamp); } }, idleTimeout); } /** * Restarts child span timeout, if there is none running it will start one. */ function _restartChildSpanTimeout(endTimestamp) { _cancelChildSpanTimeout(); _childSpanTimeoutID = setTimeout(() => { if (!_finished && _autoFinishAllowed) { _finishReason = FINISH_REASON_HEARTBEAT_FAILED; span.end(endTimestamp); } }, childSpanTimeout); } /** * Start tracking a specific activity. * @param spanId The span id that represents the activity */ function _pushActivity(spanId) { _cancelIdleTimeout(); activities.set(spanId, true); _restartChildSpanTimeout(timestampInSeconds() + childSpanTimeout / 1e3); } /** * Remove an activity from usage * @param spanId The span id that represents the activity */ function _popActivity(spanId) { if (activities.has(spanId)) activities.delete(spanId); if (activities.size === 0) { _restartIdleTimeout(timestampInSeconds() + idleTimeout / 1e3); _cancelChildSpanTimeout(); } } function onIdleSpanEnded(endTimestamp) { _finished = true; activities.clear(); _cleanupHooks.forEach((cleanup) => cleanup()); _setSpanForScope(scope, previousActiveSpan); const spanJSON = spanToStaticSpanJSON(span); const { start_timestamp: startTimestamp } = spanJSON; if (!startTimestamp) return; if (!spanJSON.data[SENTRY_IDLE_SPAN_FINISH_REASON]) span.setAttribute(SENTRY_IDLE_SPAN_FINISH_REASON, _finishReason); const currentStatus = spanJSON.status; if (!currentStatus || currentStatus === "unknown") span.setStatus({ code: 1 }); debug.log(`[Tracing] Idle span "${spanJSON.op}" finished`); const childSpans = getSpanDescendants(span).filter((child) => child !== span); let discardedSpans = 0; childSpans.forEach((childSpan) => { if (childSpan.isRecording()) { childSpan.setStatus({ code: 2, message: "cancelled" }); childSpan.end(endTimestamp); DEBUG_BUILD && debug.log("[Tracing] Cancelling span since span ended early", JSON.stringify(childSpan, void 0, 2)); } const { timestamp: childEndTimestamp = 0, start_timestamp: childStartTimestamp = 0 } = spanToStaticSpanJSON(childSpan); const spanStartedBeforeIdleSpanEnd = childStartTimestamp <= endTimestamp; const timeoutWithMarginOfError = (finalTimeout + idleTimeout) / 1e3; const spanEndedBeforeFinalTimeout = childEndTimestamp - childStartTimestamp <= timeoutWithMarginOfError; if (DEBUG_BUILD) { const stringifiedSpan = JSON.stringify(childSpan, void 0, 2); if (!spanStartedBeforeIdleSpanEnd) debug.log("[Tracing] Discarding span since it happened after idle span was finished", stringifiedSpan); else if (!spanEndedBeforeFinalTimeout) debug.log("[Tracing] Discarding span since it finished after idle span final timeout", stringifiedSpan); } if (!spanEndedBeforeFinalTimeout || !spanStartedBeforeIdleSpanEnd) { removeChildSpanFromSpan(span, childSpan); discardedSpans++; } }); if (discardedSpans > 0) span.setAttribute("sentry.idle_span_discarded_spans", discardedSpans); } _cleanupHooks.push(client.on("spanStart", (startedSpan) => { if (_finished || startedSpan === span || !!spanToJSON(startedSpan).end_timestamp || startedSpan instanceof SentrySpan && startedSpan.isStandaloneSpan()) return; if (getSpanDescendants(span).includes(startedSpan)) _pushActivity(startedSpan.spanContext().spanId); })); _cleanupHooks.push(client.on("spanEnd", (endedSpan) => { if (_finished) return; _popActivity(endedSpan.spanContext().spanId); })); _cleanupHooks.push(client.on("idleSpanEnableAutoFinish", (spanToAllowAutoFinish) => { if (spanToAllowAutoFinish === span) { _autoFinishAllowed = true; _restartIdleTimeout(); if (activities.size) _restartChildSpanTimeout(); } })); if (!options.disableAutoFinish) _restartIdleTimeout(); setTimeout(() => { if (!_finished) { span.setStatus({ code: 2, message: "deadline_exceeded" }); _finishReason = FINISH_REASON_FINAL_TIMEOUT; span.end(); } }, finalTimeout); return span; } export { TRACING_DEFAULTS, startIdleSpan }; //# sourceMappingURL=idleSpan.js.map