initializeSdk.tsx 11 KB

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