initializeSdk.tsx 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. const SPA_MODE_ALLOW_URLS = [
  13. 'localhost',
  14. 'dev.getsentry.net',
  15. 'sentry.dev',
  16. 'webpack-internal://',
  17. ];
  18. // We check for `window.__initialData.user` property and only enable profiling
  19. // for Sentry employees. This is to prevent a Violation error being visible in
  20. // the browser console for our users.
  21. const shouldEnableBrowserProfiling = window?.__initialData?.user?.isSuperuser;
  22. /**
  23. * We accept a routes argument here because importing `static/routes`
  24. * is expensive in regards to bundle size. Some entrypoints may opt to forgo
  25. * having routing instrumentation in order to have a smaller bundle size.
  26. * (e.g. `static/views/integrationPipeline`)
  27. */
  28. function getSentryIntegrations(sentryConfig: Config['sentryConfig'], routes?: Function) {
  29. const extraTracingOrigins = SPA_DSN
  30. ? SPA_MODE_ALLOW_URLS
  31. : [...sentryConfig?.whitelistUrls];
  32. const partialTracingOptions: Partial<BrowserTracing['options']> = {
  33. tracingOrigins: ['localhost', /^\//, ...extraTracingOrigins],
  34. };
  35. const integrations = [
  36. new ExtraErrorData({
  37. // 6 is arbitrary, seems like a nice number
  38. depth: 6,
  39. }),
  40. new BrowserTracing({
  41. ...(typeof routes === 'function'
  42. ? {
  43. routingInstrumentation: Sentry.reactRouterV3Instrumentation(
  44. browserHistory as any,
  45. createRoutes(routes()),
  46. match
  47. ),
  48. }
  49. : {}),
  50. _experiments: {
  51. enableInteractions: true,
  52. onStartRouteTransaction: Sentry.onProfilingStartRouteTransaction,
  53. },
  54. ...partialTracingOptions,
  55. }),
  56. new Sentry.BrowserProfilingIntegration(),
  57. ];
  58. return integrations;
  59. }
  60. /**
  61. * Initialize the Sentry SDK
  62. *
  63. * If `routes` is passed, we will instrument react-router. Not all
  64. * entrypoints require this.
  65. */
  66. export function initializeSdk(config: Config, {routes}: {routes?: Function} = {}) {
  67. const {apmSampling, sentryConfig, userIdentity} = config;
  68. const tracesSampleRate = apmSampling ?? 0;
  69. Sentry.init({
  70. ...sentryConfig,
  71. /**
  72. * For SPA mode, we need a way to overwrite the default DSN from backend
  73. * as well as `whitelistUrls`
  74. */
  75. dsn: SPA_DSN || sentryConfig?.dsn,
  76. /**
  77. * Frontend can be built with a `SENTRY_RELEASE_VERSION` environment
  78. * variable for release string, useful if frontend is deployed separately
  79. * from backend.
  80. */
  81. release: SENTRY_RELEASE_VERSION ?? sentryConfig?.release,
  82. allowUrls: SPA_DSN ? SPA_MODE_ALLOW_URLS : sentryConfig?.whitelistUrls,
  83. denyUrls: [/^file:\/\//],
  84. integrations: getSentryIntegrations(sentryConfig, routes),
  85. tracesSampleRate,
  86. // @ts-ignore not part of browser SDK types yet
  87. profilesSampleRate: shouldEnableBrowserProfiling ? 1 : 0,
  88. tracesSampler: context => {
  89. if (context.transactionContext.op?.startsWith('ui.action')) {
  90. return tracesSampleRate / 100;
  91. }
  92. return tracesSampleRate;
  93. },
  94. beforeSendTransaction(event) {
  95. addExtraMeasurements(event);
  96. addUIElementTag(event);
  97. event.spans = event.spans?.filter(span => {
  98. // Filter analytic timeout spans.
  99. return ['reload.getsentry.net', 'amplitude.com'].every(
  100. partialDesc => !span.description?.includes(partialDesc)
  101. );
  102. });
  103. if (event.transaction) {
  104. event.transaction = normalizeUrl(event.transaction, {forceCustomerDomain: true});
  105. }
  106. return event;
  107. },
  108. ignoreErrors: [
  109. /**
  110. * There is a bug in Safari, that causes `AbortError` when fetch is
  111. * aborted, and you are in the middle of reading the response. In Chrome
  112. * and other browsers, it is handled gracefully, where in Safari, it
  113. * produces additional error, that is jumping outside of the original
  114. * Promise chain and bubbles up to the `unhandledRejection` handler, that
  115. * we then captures as error.
  116. *
  117. * Ref: https://bugs.webkit.org/show_bug.cgi?id=215771
  118. */
  119. 'AbortError: Fetch is aborted',
  120. /**
  121. * Thrown when firefox prevents an add-on from refrencing a DOM element
  122. * that has been removed.
  123. */
  124. "TypeError: can't access dead object",
  125. /**
  126. * React internal error thrown when something outside react modifies the DOM
  127. * This is usually because of a browser extension or chrome translate page
  128. */
  129. "NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.",
  130. "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.",
  131. ],
  132. // Temporary fix while `ignoreErrors` bug is fixed and request error handling is cleaned up
  133. beforeSend(event, _hint) {
  134. return isFilteredRequestErrorEvent(event) ? null : event;
  135. },
  136. });
  137. // Track timeOrigin Selection by the SDK to see if it improves transaction durations
  138. Sentry.addGlobalEventProcessor((event: Sentry.Event, _hint?: Sentry.EventHint) => {
  139. event.tags = event.tags || {};
  140. event.tags['timeOrigin.mode'] = _browserPerformanceTimeOriginMode;
  141. return event;
  142. });
  143. if (userIdentity) {
  144. Sentry.setUser(userIdentity);
  145. }
  146. if (window.__SENTRY__VERSION) {
  147. Sentry.setTag('sentry_version', window.__SENTRY__VERSION);
  148. }
  149. const {customerDomain} = window.__initialData;
  150. if (customerDomain) {
  151. Sentry.setTag('isCustomerDomain', 'yes');
  152. Sentry.setTag('customerDomain.organizationUrl', customerDomain.organizationUrl);
  153. Sentry.setTag('customerDomain.sentryUrl', customerDomain.sentryUrl);
  154. Sentry.setTag('customerDomain.subdomain', customerDomain.subdomain);
  155. }
  156. }
  157. export function isFilteredRequestErrorEvent(event: Event): boolean {
  158. const exceptionValues = event.exception?.values;
  159. if (!exceptionValues) {
  160. return false;
  161. }
  162. // In case there's a chain, we take the last entry, because that's the one
  163. // passed to `captureException`
  164. const mainError = exceptionValues[exceptionValues.length - 1];
  165. const {type = '', value = ''} = mainError;
  166. const is200 =
  167. ['RequestError'].includes(type) && !!value.match('(GET|POST|PUT|DELETE) .* 200');
  168. const is401 =
  169. ['UnauthorizedError', 'RequestError'].includes(type) &&
  170. !!value.match('(GET|POST|PUT|DELETE) .* 401');
  171. const is403 =
  172. ['ForbiddenError', 'RequestError'].includes(type) &&
  173. !!value.match('(GET|POST|PUT|DELETE) .* 403');
  174. const is404 =
  175. ['NotFoundError', 'RequestError'].includes(type) &&
  176. !!value.match('(GET|POST|PUT|DELETE) .* 404');
  177. return is200 || is401 || is403 || is404;
  178. }