initializeSdk.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. import FeatureObserver from 'sentry/utils/featureObserver';
  17. const SPA_MODE_ALLOW_URLS = [
  18. 'localhost',
  19. 'dev.getsentry.net',
  20. 'sentry.dev',
  21. 'webpack-internal://',
  22. ];
  23. const SPA_MODE_TRACE_PROPAGATION_TARGETS = [
  24. 'localhost',
  25. 'dev.getsentry.net',
  26. 'sentry.dev',
  27. ];
  28. let lastEventId: string | undefined;
  29. export function getLastEventId(): string | undefined {
  30. return lastEventId;
  31. }
  32. // We don't care about recording breadcrumbs for these hosts. These typically
  33. // pollute our breadcrumbs since they may occur a LOT.
  34. //
  35. // XXX(epurkhiser): Note some of these hosts may only apply to sentry.io.
  36. const IGNORED_BREADCRUMB_FETCH_HOSTS = ['amplitude.com', 'reload.getsentry.net'];
  37. // Ignore analytics in spans as well
  38. const IGNORED_SPANS_BY_DESCRIPTION = ['amplitude.com', 'reload.getsentry.net'];
  39. // We check for `window.__initialData.user` property and only enable profiling
  40. // for Sentry employees. This is to prevent a Violation error being visible in
  41. // the browser console for our users.
  42. const shouldOverrideBrowserProfiling = window?.__initialData?.user?.isSuperuser;
  43. /**
  44. * We accept a routes argument here because importing `static/routes`
  45. * is expensive in regards to bundle size. Some entrypoints may opt to forgo
  46. * having routing instrumentation in order to have a smaller bundle size.
  47. * (e.g. `static/views/integrationPipeline`)
  48. */
  49. function getSentryIntegrations() {
  50. const integrations = [
  51. Sentry.extraErrorDataIntegration({
  52. // 6 is arbitrary, seems like a nice number
  53. depth: 6,
  54. }),
  55. Sentry.reactRouterV6BrowserTracingIntegration({
  56. useEffect: useEffect,
  57. useLocation: useLocation,
  58. useNavigationType: useNavigationType,
  59. createRoutesFromChildren: createRoutesFromChildren,
  60. matchRoutes: matchRoutes,
  61. }),
  62. Sentry.browserProfilingIntegration(),
  63. Sentry.thirdPartyErrorFilterIntegration({
  64. filterKeys: ['sentry-spa'],
  65. behaviour: 'apply-tag-if-contains-third-party-frames',
  66. }),
  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. // attach feature flags to the event context
  164. if (event.contexts) {
  165. const flags = FeatureObserver.singleton({}).getFeatureFlags();
  166. event.contexts.flags = flags;
  167. }
  168. return event;
  169. },
  170. });
  171. if (process.env.NODE_ENV !== 'production') {
  172. if (
  173. sentryConfig.environment === 'development' &&
  174. process.env.SENTRY_SPOTLIGHT &&
  175. !['false', 'f', 'n', 'no', 'off', '0'].includes(process.env.SENTRY_SPOTLIGHT)
  176. ) {
  177. import('@spotlightjs/spotlight').then(Spotlight => {
  178. // TODO: use the value of `process.env.SENTRY_SPOTLIGHT` for the `sidecarUrl` below when it is not "truthy"
  179. // Truthy is defined in https://github.com/getsentry/sentry-javascript/pull/13325/files#diff-a139d0f6c10ca33f2b0264da406662f90061cd7e8f707c197a02460a7f666e87R2
  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. }