UNPKG

@sentry/core

Version:
174 lines (173 loc) • 6.06 kB
import { getClient } from "../currentScopes.js"; import { isError, isObjectLike, isRequest } from "../utils/is.js"; import { isBrowser } from "../utils/isBrowser.js"; import { addNonEnumerableProperty, fill } from "../utils/object.js"; import { supportsNativeFetch } from "../utils/supports.js"; import { timestampInSeconds } from "../utils/time.js"; import { GLOBAL_OBJ } from "../utils/worldwide.js"; import { addHandler, maybeInstrument, triggerHandlers } from "./handlers.js"; // src/instrument/fetch.ts /** * Add an instrumentation handler for when a fetch request happens. * The handler function is called once when the request starts and once when it ends, * which can be identified by checking if it has an `endTimestamp`. * Returns a function to remove the handler. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */ function addFetchInstrumentationHandler(handler) { const type = "fetch"; const removeHandler = addHandler(type, handler); maybeInstrument(type, () => instrumentFetch()); return removeHandler; } /** * Add an instrumentation handler for long-lived fetch requests, like consuming server-sent events (SSE) via fetch. * The handler will resolve the request body and emit the actual `endTimestamp`, so that the * span can be updated accordingly. * Returns a function to remove the handler. * * Only used internally * @hidden */ function addFetchEndInstrumentationHandler(handler) { const type = "fetch-body-resolved"; const removeHandler = addHandler(type, handler); maybeInstrument(type, () => instrumentFetch(streamHandler)); return removeHandler; } function instrumentFetch(onFetchResolved) { if (isBrowser() && !supportsNativeFetch()) return; fill(GLOBAL_OBJ, "fetch", function(originalFetch) { return new Proxy(originalFetch, { apply(target, _thisArg, args) { const virtualError = /* @__PURE__ */ new Error(); const { method, url } = parseFetchArgs(args); const handlerData = { args, fetchData: { method, url }, startTimestamp: timestampInSeconds() * 1e3, virtualError, headers: getHeadersFromFetchArgs(args) }; if (!onFetchResolved) triggerHandlers("fetch", { ...handlerData }); return Reflect.apply(target, GLOBAL_OBJ, args).then(async (response) => { if (onFetchResolved) onFetchResolved(response); else triggerHandlers("fetch", { ...handlerData, endTimestamp: timestampInSeconds() * 1e3, response }); return response; }, (error) => { triggerHandlers("fetch", { ...handlerData, endTimestamp: timestampInSeconds() * 1e3, error }); if (isError(error) && error.stack === void 0) { error.stack = virtualError.stack; addNonEnumerableProperty(error, "framesToPop", 1); } const enhanceOption = getClient()?.getOptions().enhanceFetchErrorMessages ?? "always"; if (enhanceOption !== false && isError(error) && error.name === "TypeError" && (error.message === "Failed to fetch" || error.message === "Load failed" || error.message === "NetworkError when attempting to fetch resource.")) try { const hostname = new URL(handlerData.fetchData.url, GLOBAL_OBJ.location?.href).host; if (hostname) { if (enhanceOption === "always") error.message = `${error.message} (${hostname})`; else addNonEnumerableProperty(error, "__sentry_fetch_url_host__", hostname); } } catch {} throw error; }); } }); }); } async function resolveResponse(res, onFinishedResolving) { if (res?.body) { const body = res.body; const responseReader = body.getReader(); const maxFetchDurationTimeout = setTimeout(() => { body.cancel().then(null, () => {}); }, 9e4); let readingActive = true; while (readingActive) { let chunkTimeout; try { chunkTimeout = setTimeout(() => { body.cancel().then(null, () => {}); }, 5e3); const { done } = await responseReader.read(); clearTimeout(chunkTimeout); if (done) { onFinishedResolving(); readingActive = false; } } catch { readingActive = false; } finally { clearTimeout(chunkTimeout); } } clearTimeout(maxFetchDurationTimeout); responseReader.releaseLock(); body.cancel().then(null, () => {}); } } function streamHandler(response) { let clonedResponseForResolving; try { clonedResponseForResolving = response.clone(); } catch { return; } resolveResponse(clonedResponseForResolving, () => { triggerHandlers("fetch-body-resolved", { endTimestamp: timestampInSeconds() * 1e3, response }); }); } function hasProp(obj, prop) { return isObjectLike(obj) && !!obj[prop]; } function getUrlFromResource(resource) { if (typeof resource === "string") return resource; if (!resource) return ""; if (hasProp(resource, "url")) return resource.url; if (resource.toString) return resource.toString(); return ""; } /** * Parses the fetch arguments to find the used Http method and the url of the request. * Exported for tests only. */ function parseFetchArgs(fetchArgs) { if (fetchArgs.length === 0) return { method: "GET", url: "" }; if (fetchArgs.length === 2) { const [resource, options] = fetchArgs; return { url: getUrlFromResource(resource), method: hasProp(options, "method") ? String(options.method).toUpperCase() : isRequest(resource) && hasProp(resource, "method") ? String(resource.method).toUpperCase() : "GET" }; } const arg = fetchArgs[0]; return { url: getUrlFromResource(arg), method: hasProp(arg, "method") ? String(arg.method).toUpperCase() : "GET" }; } function getHeadersFromFetchArgs(fetchArgs) { const [requestArgument, optionsArgument] = fetchArgs; try { if (typeof optionsArgument === "object" && optionsArgument !== null && "headers" in optionsArgument && optionsArgument.headers) return new Headers(optionsArgument.headers); if (isRequest(requestArgument)) return new Headers(requestArgument.headers); } catch {} } export { addFetchEndInstrumentationHandler, addFetchInstrumentationHandler, parseFetchArgs }; //# sourceMappingURL=fetch.js.map