initializeSdk.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // eslint-disable-next-line simple-import-sort/imports
  2. import {browserHistory, createRoutes, match} from 'react-router';
  3. import {ExtraErrorData} from '@sentry/integrations';
  4. import * as Sentry from '@sentry/react';
  5. import {BrowserTracing} from '@sentry/react';
  6. import {_browserPerformanceTimeOriginMode} from '@sentry/utils';
  7. import {Event} from '@sentry/types';
  8. import {SENTRY_RELEASE_VERSION, SPA_DSN} from 'sentry/constants';
  9. import {Config} from 'sentry/types';
  10. import {addExtraMeasurements, addUIElementTag} from 'sentry/utils/performanceForSentry';
  11. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  12. import {HTTPTimingIntegration} from 'sentry/utils/performanceForSentry/integrations';
  13. import {getErrorDebugIds} from 'sentry/utils/getErrorDebugIds';
  14. const SPA_MODE_ALLOW_URLS = [
  15. 'localhost',
  16. 'dev.getsentry.net',
  17. 'sentry.dev',
  18. 'webpack-internal://',
  19. ];
  20. const SPA_MODE_TRACE_PROPAGATION_TARGETS = [
  21. 'localhost',
  22. 'dev.getsentry.net',
  23. 'sentry.dev',
  24. ];
  25. // We don't care about recording breadcrumbs for these hosts. These typically
  26. // pollute our breadcrumbs since they may occur a LOT.
  27. //
  28. // XXX(epurkhiser): Note some of these hosts may only apply to sentry.io.
  29. const IGNORED_BREADCRUMB_FETCH_HOSTS = ['amplitude.com', 'reload.getsentry.net'];
  30. // Ignore analytics in spans as well
  31. const IGNORED_SPANS_BY_DESCRIPTION = ['amplitude.com', 'reload.getsentry.net'];
  32. // We check for `window.__initialData.user` property and only enable profiling
  33. // for Sentry employees. This is to prevent a Violation error being visible in
  34. // the browser console for our users.
  35. const shouldEnableBrowserProfiling = window?.__initialData?.user?.isSuperuser;
  36. /**
  37. * We accept a routes argument here because importing `static/routes`
  38. * is expensive in regards to bundle size. Some entrypoints may opt to forgo
  39. * having routing instrumentation in order to have a smaller bundle size.
  40. * (e.g. `static/views/integrationPipeline`)
  41. */
  42. function getSentryIntegrations(sentryConfig: Config['sentryConfig'], routes?: Function) {
  43. const extraTracePropagationTargets = SPA_DSN
  44. ? SPA_MODE_TRACE_PROPAGATION_TARGETS
  45. : [...sentryConfig?.tracePropagationTargets];
  46. const integrations = [
  47. new ExtraErrorData({
  48. // 6 is arbitrary, seems like a nice number
  49. depth: 6,
  50. }),
  51. new BrowserTracing({
  52. ...(typeof routes === 'function'
  53. ? {
  54. routingInstrumentation: Sentry.reactRouterV3Instrumentation(
  55. browserHistory as any,
  56. createRoutes(routes()),
  57. match
  58. ),
  59. }
  60. : {}),
  61. _experiments: {
  62. enableInteractions: true,
  63. onStartRouteTransaction: Sentry.onProfilingStartRouteTransaction,
  64. },
  65. tracePropagationTargets: ['localhost', /^\//, ...extraTracePropagationTargets],
  66. }),
  67. new Sentry.BrowserProfilingIntegration(),
  68. new HTTPTimingIntegration(),
  69. ];
  70. return integrations;
  71. }
  72. /**
  73. * Initialize the Sentry SDK
  74. *
  75. * If `routes` is passed, we will instrument react-router. Not all
  76. * entrypoints require this.
  77. */
  78. export function initializeSdk(config: Config, {routes}: {routes?: Function} = {}) {
  79. const {apmSampling, sentryConfig, userIdentity} = config;
  80. const tracesSampleRate = apmSampling ?? 0;
  81. Sentry.init({
  82. ...sentryConfig,
  83. /**
  84. * For SPA mode, we need a way to overwrite the default DSN from backend
  85. * as well as `allowUrls`
  86. */
  87. dsn: SPA_DSN || sentryConfig?.dsn,
  88. /**
  89. * Frontend can be built with a `SENTRY_RELEASE_VERSION` environment
  90. * variable for release string, useful if frontend is deployed separately
  91. * from backend.
  92. */
  93. release: SENTRY_RELEASE_VERSION ?? sentryConfig?.release,
  94. allowUrls: SPA_DSN ? SPA_MODE_ALLOW_URLS : sentryConfig?.allowUrls,
  95. integrations: getSentryIntegrations(sentryConfig, routes),
  96. tracesSampleRate,
  97. // @ts-expect-error not part of browser SDK types yet
  98. profilesSampleRate: shouldEnableBrowserProfiling ? 1 : 0,
  99. tracesSampler: context => {
  100. if (context.transactionContext.op?.startsWith('ui.action')) {
  101. return tracesSampleRate / 100;
  102. }
  103. return tracesSampleRate;
  104. },
  105. beforeSendTransaction(event) {
  106. addExtraMeasurements(event);
  107. addUIElementTag(event);
  108. event.spans = event.spans?.filter(span => {
  109. return IGNORED_SPANS_BY_DESCRIPTION.every(
  110. partialDesc => !span.description?.includes(partialDesc)
  111. );
  112. });
  113. if (event.transaction) {
  114. event.transaction = normalizeUrl(event.transaction, {forceCustomerDomain: true});
  115. }
  116. return event;
  117. },
  118. ignoreErrors: [
  119. /**
  120. * There is a bug in Safari, that causes `AbortError` when fetch is
  121. * aborted, and you are in the middle of reading the response. In Chrome
  122. * and other browsers, it is handled gracefully, where in Safari, it
  123. * produces additional error, that is jumping outside of the original
  124. * Promise chain and bubbles up to the `unhandledRejection` handler, that
  125. * we then captures as error.
  126. *
  127. * Ref: https://bugs.webkit.org/show_bug.cgi?id=215771
  128. */
  129. 'AbortError: Fetch is aborted',
  130. /**
  131. * Thrown when firefox prevents an add-on from refrencing a DOM element
  132. * that has been removed.
  133. */
  134. "TypeError: can't access dead object",
  135. /**
  136. * React internal error thrown when something outside react modifies the DOM
  137. * This is usually because of a browser extension or chrome translate page
  138. */
  139. "NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.",
  140. "NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.",
  141. ],
  142. beforeBreadcrumb(crumb) {
  143. const isFetch = crumb.category === 'fetch' || crumb.category === 'xhr';
  144. // Ignore
  145. if (
  146. isFetch &&
  147. IGNORED_BREADCRUMB_FETCH_HOSTS.some(host => crumb.data?.url?.includes(host))
  148. ) {
  149. return null;
  150. }
  151. return crumb;
  152. },
  153. beforeSend(event, _hint) {
  154. if (isFilteredRequestErrorEvent(event) || isEventWithFileUrl(event)) {
  155. return null;
  156. }
  157. handlePossibleUndefinedResponseBodyErrors(event);
  158. addEndpointTagToRequestError(event);
  159. return event;
  160. },
  161. });
  162. // Event processor to fill the debug_meta field with debug IDs based on the
  163. // files the error touched. (files inside the stacktrace)
  164. const debugIdPolyfillEventProcessor = async (event: Event, hint: Sentry.EventHint) => {
  165. if (!(hint.originalException instanceof Error)) {
  166. return event;
  167. }
  168. try {
  169. const debugIdMap = await getErrorDebugIds(hint.originalException);
  170. // Fill debug_meta information
  171. event.debug_meta = {};
  172. event.debug_meta.images = [];
  173. const images = event.debug_meta.images;
  174. Object.keys(debugIdMap).forEach(filename => {
  175. images.push({
  176. type: 'sourcemap',
  177. code_file: filename,
  178. debug_id: debugIdMap[filename],
  179. });
  180. });
  181. } catch (e) {
  182. event.extra = event.extra || {};
  183. event.extra.debug_id_fetch_error = String(e);
  184. }
  185. return event;
  186. };
  187. debugIdPolyfillEventProcessor.id = 'debugIdPolyfillEventProcessor';
  188. Sentry.addGlobalEventProcessor(debugIdPolyfillEventProcessor);
  189. // Track timeOrigin Selection by the SDK to see if it improves transaction durations
  190. Sentry.addGlobalEventProcessor((event: Sentry.Event, _hint?: Sentry.EventHint) => {
  191. event.tags = event.tags || {};
  192. event.tags['timeOrigin.mode'] = _browserPerformanceTimeOriginMode;
  193. return event;
  194. });
  195. if (userIdentity) {
  196. Sentry.setUser(userIdentity);
  197. }
  198. if (window.__SENTRY__VERSION) {
  199. Sentry.setTag('sentry_version', window.__SENTRY__VERSION);
  200. }
  201. const {customerDomain} = window.__initialData;
  202. if (customerDomain) {
  203. Sentry.setTag('isCustomerDomain', 'yes');
  204. Sentry.setTag('customerDomain.organizationUrl', customerDomain.organizationUrl);
  205. Sentry.setTag('customerDomain.sentryUrl', customerDomain.sentryUrl);
  206. Sentry.setTag('customerDomain.subdomain', customerDomain.subdomain);
  207. }
  208. }
  209. export function isFilteredRequestErrorEvent(event: Event): boolean {
  210. const exceptionValues = event.exception?.values;
  211. if (!exceptionValues) {
  212. return false;
  213. }
  214. // In case there's a chain, we take the last entry, because that's the one
  215. // passed to `captureException`, and the one right before that, since
  216. // `RequestError`s are used as the main error's `cause` value in
  217. // `handleXhrErrorResponse`
  218. const mainAndMaybeCauseErrors = exceptionValues.slice(-2);
  219. for (const error of mainAndMaybeCauseErrors) {
  220. const {type = '', value = ''} = error;
  221. const is200 =
  222. ['RequestError'].includes(type) && !!value.match('(GET|POST|PUT|DELETE) .* 200');
  223. const is401 =
  224. ['UnauthorizedError', 'RequestError'].includes(type) &&
  225. !!value.match('(GET|POST|PUT|DELETE) .* 401');
  226. const is403 =
  227. ['ForbiddenError', 'RequestError'].includes(type) &&
  228. !!value.match('(GET|POST|PUT|DELETE) .* 403');
  229. const is404 =
  230. ['NotFoundError', 'RequestError'].includes(type) &&
  231. !!value.match('(GET|POST|PUT|DELETE) .* 404');
  232. const is429 =
  233. ['TooManyRequestsError', 'RequestError'].includes(type) &&
  234. !!value.match('(GET|POST|PUT|DELETE) .* 429');
  235. if (is200 || is401 || is403 || is404 || is429) {
  236. return true;
  237. }
  238. }
  239. return false;
  240. }
  241. export function isEventWithFileUrl(event: Event): boolean {
  242. return !!event.request?.url?.startsWith('file://');
  243. }
  244. /** Tag and set fingerprint for UndefinedResponseBodyError events */
  245. function handlePossibleUndefinedResponseBodyErrors(event: Event): void {
  246. // One or both of these may be undefined, depending on the type of event
  247. const [mainError, causeError] = event.exception?.values?.slice(-2).reverse() || [];
  248. const mainErrorIsURBE = mainError?.type === 'UndefinedResponseBodyError';
  249. const causeErrorIsURBE = causeError?.type === 'UndefinedResponseBodyError';
  250. if (mainErrorIsURBE || causeErrorIsURBE) {
  251. mainError.type = 'UndefinedResponseBodyError';
  252. event.tags = {...event.tags, undefinedResponseBody: true};
  253. event.fingerprint = mainErrorIsURBE
  254. ? ['UndefinedResponseBodyError as main error']
  255. : ['UndefinedResponseBodyError as cause error'];
  256. }
  257. }
  258. export function addEndpointTagToRequestError(event: Event): void {
  259. const errorMessage = event.exception?.values?.[0].value || '';
  260. // The capturing group here turns `GET /dogs/are/great 500` into just `GET /dogs/are/great`
  261. const requestErrorRegex = new RegExp('^([A-Za-z]+ (/[^/]+)+/) \\d+$');
  262. const messageMatch = requestErrorRegex.exec(errorMessage);
  263. if (messageMatch) {
  264. event.tags = {...event.tags, endpoint: messageMatch[1]};
  265. }
  266. }