initializeSdk.tsx 11 KB

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