initializeSdk.tsx 11 KB

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