initializeSdk.tsx 11 KB

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