initializeSdk.tsx 11 KB

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