initializeSdk.tsx 12 KB

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