@sentry/browser
Version:
Official Sentry SDK for browsers
220 lines (219 loc) • 10.9 kB
JavaScript
const require_helpers = require("../helpers.js");
const require_utils = require("./utils.js");
let _sentry_core = require("@sentry/core");
let _sentry_browser_utils = require("@sentry/browser-utils");
let _sentry_conventions_attributes = require("@sentry/conventions/attributes");
let _sentry_conventions_op = require("@sentry/conventions/op");
let _sentry_core_browser = require("@sentry/core/browser");
// src/tracing/request.ts
const defaultRequestInstrumentationOptions = {
traceFetch: true,
traceXHR: true,
enableHTTPTimings: true
};
/** Registers span creators for xhr and fetch requests */
function instrumentOutgoingRequests(client, _options) {
const options = {
...defaultRequestInstrumentationOptions,
..._options
};
if (options.traceFetch) instrumentFetchRequests(client, options);
if (options.traceXHR) instrumentXhrRequests(client, options);
}
/**
* Registers the span creator for fetch requests.
*/
function instrumentFetchRequests(client, options) {
const { enableHTTPTimings = true, onRequestSpanStart, onRequestSpanEnd } = options;
const { shouldCreateSpan, shouldAttachHeadersWithTargets, spans, propagateTraceparent } = getRequestSpanContext(client, options);
(0, _sentry_core.addFetchInstrumentationHandler)((handlerData) => {
const createdSpan = (0, _sentry_core.instrumentFetchRequest)(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans, {
propagateTraceparent,
onRequestSpanEnd,
urlBase: require_helpers.WINDOW.location?.href
});
if (createdSpan) {
const fullUrl = require_utils.getFullURL(handlerData.fetchData.url);
const host = fullUrl ? (0, _sentry_core.parseUrl)(fullUrl).host?.replace(/^.*@/, "") : void 0;
const sanitizedFullUrl = fullUrl ? (0, _sentry_core.stripDataUrlContent)(fullUrl) : void 0;
createdSpan.setAttributes({
[_sentry_conventions_attributes.URL_FULL]: (0, _sentry_core.filterCollectedUrl)(sanitizedFullUrl),
[_sentry_conventions_attributes.SERVER_ADDRESS]: host
});
if (enableHTTPTimings) addHTTPTimings(createdSpan, client);
onRequestSpanStart?.(createdSpan, { headers: handlerData.headers });
}
});
}
/**
* Registers the span creator for XHR requests.
*/
function instrumentXhrRequests(client, options) {
const { enableHTTPTimings = true, onRequestSpanStart, onRequestSpanEnd } = options;
const { shouldCreateSpan, shouldAttachHeadersWithTargets, spans, propagateTraceparent } = getRequestSpanContext(client, options);
(0, _sentry_browser_utils.addXhrInstrumentationHandler)((handlerData) => {
const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans, propagateTraceparent, onRequestSpanEnd);
if (createdSpan) {
if (enableHTTPTimings) addHTTPTimings(createdSpan, client);
onRequestSpanStart?.(createdSpan, { headers: require_utils.createHeadersSafely(handlerData.xhr.__sentry_xhr_v3__?.request_headers) });
}
});
}
function getRequestSpanContext(client, { shouldCreateSpanForRequest, tracePropagationTargets }) {
return {
shouldCreateSpan: typeof shouldCreateSpanForRequest === "function" ? shouldCreateSpanForRequest : () => true,
shouldAttachHeadersWithTargets: (url) => shouldAttachHeaders(url, tracePropagationTargets),
spans: {},
propagateTraceparent: client.getOptions().propagateTraceparent
};
}
/**
* The maximum time (ms) to wait for PerformanceResourceTiming data before ending the span.
* Same approach is used by OTel's browser fetch instrumentation:
* See {@link https://github.com/open-telemetry/opentelemetry-js/blob/30f94fe99339287b1e4d3c8bb90172c2523f06f4/experimental/packages/opentelemetry-instrumentation-fetch/src/fetch.ts#L352-L372}
*/
const HTTP_TIMING_WAIT_MS = 300;
/**
* Creates a temporary observer to listen to the next fetch/xhr resourcing timings,
* so that when timings hit their per-browser limit they don't need to be removed.
*
* @param span A span that has yet to be finished, must contain `url.full` on data.
*/
function addHTTPTimings(span, client) {
const url = (0, _sentry_core.spanToJSON)(span).attributes[_sentry_conventions_attributes.URL_FULL];
if (!url || typeof url !== "string") return;
let onEntryFound = () => void setTimeout(unsubscribePerformanceObsever);
if ((0, _sentry_core.hasSpanStreamingEnabled)(client)) {
const originalEnd = span.end.bind(span);
span.end = (endTimestamp) => {
const capturedEndTimestamp = endTimestamp ?? (0, _sentry_core.timestampInSeconds)();
let isEnded = false;
const endSpanAndCleanup = () => {
if (isEnded) return;
isEnded = true;
setTimeout(unsubscribePerformanceObsever);
originalEnd(capturedEndTimestamp);
clearTimeout(fallbackTimeout);
};
onEntryFound = endSpanAndCleanup;
const fallbackTimeout = setTimeout(endSpanAndCleanup, HTTP_TIMING_WAIT_MS);
};
}
const unsubscribePerformanceObsever = (0, _sentry_browser_utils.addPerformanceInstrumentationHandler)("resource", ({ entries }) => {
entries.forEach((entry) => {
if (require_utils.isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) {
span.setAttributes((0, _sentry_browser_utils.resourceTimingToSpanAttributes)(entry));
onEntryFound();
}
});
});
}
/**
* A function that determines whether to attach tracing headers to a request.
* We only export this function for testing purposes.
*/
function shouldAttachHeaders(targetUrl, tracePropagationTargets) {
const href = (0, _sentry_browser_utils.getLocationHref)();
if (!href) {
const isRelativeSameOriginRequest = !!targetUrl.match(/^\/(?!\/)/);
if (!tracePropagationTargets) return isRelativeSameOriginRequest;
else return (0, _sentry_core.matchesTracePropagationTargets)(targetUrl, tracePropagationTargets);
} else {
let resolvedUrl;
let currentOrigin;
try {
resolvedUrl = new URL(targetUrl, href);
currentOrigin = new URL(href).origin;
} catch {
return false;
}
const isSameOriginRequest = resolvedUrl.origin === currentOrigin;
if (!tracePropagationTargets) return isSameOriginRequest;
else return (0, _sentry_core.matchesTracePropagationTargets)(resolvedUrl.toString(), tracePropagationTargets) || isSameOriginRequest && (0, _sentry_core.matchesTracePropagationTargets)(resolvedUrl.pathname, tracePropagationTargets);
}
}
/**
* Create and track xhr request spans
*
* @returns Span if a span was created, otherwise void.
*/
function xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeaders, spans, propagateTraceparent, onRequestSpanEnd) {
const xhr = handlerData.xhr;
const sentryXhrData = xhr?.[_sentry_browser_utils.SENTRY_XHR_DATA_KEY];
if (!xhr || xhr.__sentry_own_request__ || !sentryXhrData) return;
const { url, method } = sentryXhrData;
const shouldCreateSpanResult = (0, _sentry_core.hasSpansEnabled)() && shouldCreateSpan(url);
if (handlerData.endTimestamp) {
const spanId = xhr.__sentry_xhr_span_id__;
if (!spanId) return;
const span = spans[spanId];
if (span) {
if (shouldCreateSpanResult && sentryXhrData.status_code !== void 0) {
(0, _sentry_core.setHttpStatus)(span, sentryXhrData.status_code);
span.end();
onRequestSpanEnd?.(span, {
headers: require_utils.createHeadersSafely((0, _sentry_browser_utils.parseXhrResponseHeaders)(xhr)),
error: handlerData.error
});
}
delete spans[spanId];
}
return;
}
const fullUrl = require_utils.getFullURL(url);
const parsedUrl = fullUrl ? (0, _sentry_core.parseUrl)(fullUrl) : (0, _sentry_core.parseUrl)(url);
const sanitizedFullUrl = fullUrl ? (0, _sentry_core.stripDataUrlContent)(fullUrl) : void 0;
const urlForSpanName = (0, _sentry_core.stripDataUrlContent)((0, _sentry_core.stripUrlQueryAndFragment)(url));
const client = (0, _sentry_core.getClient)();
const hasParent = !!(0, _sentry_core.getActiveSpan)();
const shouldEmitSpan = hasParent || !!client && (0, _sentry_core.hasSpanStreamingEnabled)(client);
const host = parsedUrl?.host?.replace(/^.*@/, "");
const domain = (0, _sentry_core.getUrlDomain)(fullUrl || url);
const streamedName = domain ? `${method} ${domain}` : method;
const span = shouldCreateSpanResult && shouldEmitSpan ? (0, _sentry_core_browser.startInactiveSpan)({
name: !!client && (0, _sentry_core.hasSpanStreamingEnabled)(client) ? streamedName : `${method} ${urlForSpanName}`,
attributes: {
type: "xhr",
[_sentry_conventions_attributes.HTTP_REQUEST_METHOD]: method,
[_sentry_conventions_attributes.URL_FULL]: (0, _sentry_core.filterCollectedUrl)(sanitizedFullUrl),
[_sentry_conventions_attributes.SERVER_ADDRESS]: host,
[_sentry_conventions_attributes.URL_DOMAIN]: domain,
[_sentry_conventions_attributes.SENTRY_ORIGIN]: "auto.http.browser",
[_sentry_conventions_attributes.SENTRY_OP]: _sentry_conventions_op.HTTP_CLIENT,
[_sentry_conventions_attributes.URL_QUERY]: (0, _sentry_core.filterCollectedUrlQuery)((0, _sentry_core.getUrlQuery)(parsedUrl?.search)),
[_sentry_conventions_attributes.URL_FRAGMENT]: (0, _sentry_core.getUrlFragment)(parsedUrl?.hash)
}
}) : new _sentry_core.SentryNonRecordingSpan();
const spanForTraceHeaders = (0, _sentry_core.spanIsIgnored)(span) && hasParent ? void 0 : span;
if (shouldCreateSpanResult && !shouldEmitSpan) client?.recordDroppedEvent("no_parent_span", "span");
xhr.__sentry_xhr_span_id__ = span.spanContext().spanId;
spans[xhr.__sentry_xhr_span_id__] = span;
if (shouldAttachHeaders(url)) addTracingHeadersToXhrRequest(xhr, (0, _sentry_core.hasSpansEnabled)() && shouldEmitSpan ? spanForTraceHeaders : void 0, propagateTraceparent);
if (client) client.emit("beforeOutgoingRequestSpan", span, handlerData);
return span;
}
function addTracingHeadersToXhrRequest(xhr, span, propagateTraceparent) {
const { "sentry-trace": sentryTrace, baggage, traceparent } = (0, _sentry_core.getTraceData)({
span,
propagateTraceparent
});
if (sentryTrace) setHeaderOnXhr(xhr, sentryTrace, baggage, traceparent);
}
function setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader, traceparentHeader) {
const originalHeaders = xhr.__sentry_xhr_v3__?.request_headers;
if (originalHeaders?.["sentry-trace"] || !xhr.setRequestHeader) return;
try {
xhr.setRequestHeader("sentry-trace", sentryTraceHeader);
if (traceparentHeader && !originalHeaders?.["traceparent"]) xhr.setRequestHeader("traceparent", traceparentHeader);
if (sentryBaggageHeader) {
const originalBaggageHeader = originalHeaders?.["baggage"];
if (!originalBaggageHeader || !require_utils.baggageHeaderHasSentryValues(originalBaggageHeader)) xhr.setRequestHeader("baggage", sentryBaggageHeader);
}
} catch {}
}
exports.defaultRequestInstrumentationOptions = defaultRequestInstrumentationOptions;
exports.instrumentFetchRequests = instrumentFetchRequests;
exports.instrumentOutgoingRequests = instrumentOutgoingRequests;
exports.instrumentXhrRequests = instrumentXhrRequests;
exports.shouldAttachHeaders = shouldAttachHeaders;
//# sourceMappingURL=request.js.map