initializeSdk.tsx 11 KB

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