initializeSdk.tsx 12 KB

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