initializeSdk.tsx 11 KB

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