initializeSdk.tsx 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import {browserHistory, createRoutes, match} from 'react-router';
  2. import {ExtraErrorData} from '@sentry/integrations';
  3. import * as Sentry from '@sentry/react';
  4. import {Integrations} from '@sentry/tracing';
  5. import {_browserPerformanceTimeOriginMode} from '@sentry/utils';
  6. import {SENTRY_RELEASE_VERSION, SPA_DSN} from 'sentry/constants';
  7. import {Config} from 'sentry/types';
  8. import {addExtraMeasurements, LongTaskObserver} from 'sentry/utils/performanceForSentry';
  9. const SPA_MODE_ALLOW_URLS = [
  10. 'localhost',
  11. 'dev.getsentry.net',
  12. 'sentry.dev',
  13. 'webpack-internal://',
  14. ];
  15. /**
  16. * We accept a routes argument here because importing `static/routes`
  17. * is expensive in regards to bundle size. Some entrypoints may opt to forgo
  18. * having routing instrumentation in order to have a smaller bundle size.
  19. * (e.g. `static/views/integrationPipeline`)
  20. */
  21. function getSentryIntegrations(sentryConfig: Config['sentryConfig'], routes?: Function) {
  22. const extraTracingOrigins = SPA_DSN
  23. ? SPA_MODE_ALLOW_URLS
  24. : [...sentryConfig?.whitelistUrls];
  25. const partialTracingOptions: Partial<Integrations.BrowserTracing['options']> = {
  26. tracingOrigins: ['localhost', /^\//, ...extraTracingOrigins],
  27. };
  28. const integrations = [
  29. new ExtraErrorData({
  30. // 6 is arbitrary, seems like a nice number
  31. depth: 6,
  32. }),
  33. new Integrations.BrowserTracing({
  34. ...(typeof routes === 'function'
  35. ? {
  36. routingInstrumentation: Sentry.reactRouterV3Instrumentation(
  37. browserHistory as any,
  38. createRoutes(routes()),
  39. match
  40. ),
  41. }
  42. : {}),
  43. idleTimeout: 5000,
  44. _metricOptions: {
  45. _reportAllChanges: false,
  46. },
  47. _experiments: {
  48. enableInteractions: true,
  49. },
  50. ...partialTracingOptions,
  51. }),
  52. ];
  53. return integrations;
  54. }
  55. /**
  56. * Initialize the Sentry SDK
  57. *
  58. * If `routes` is passed, we will instrument react-router. Not all
  59. * entrypoints require this.
  60. */
  61. export function initializeSdk(config: Config, {routes}: {routes?: Function} = {}) {
  62. const {apmSampling, sentryConfig, userIdentity} = config;
  63. const tracesSampleRate = apmSampling ?? 0;
  64. Sentry.init({
  65. ...sentryConfig,
  66. /**
  67. * For SPA mode, we need a way to overwrite the default DSN from backend
  68. * as well as `whitelistUrls`
  69. */
  70. dsn: SPA_DSN || sentryConfig?.dsn,
  71. /**
  72. * Frontend can be built with a `SENTRY_RELEASE_VERSION` environment
  73. * variable for release string, useful if frontend is deployed separately
  74. * from backend.
  75. */
  76. release: SENTRY_RELEASE_VERSION ?? sentryConfig?.release,
  77. allowUrls: SPA_DSN ? SPA_MODE_ALLOW_URLS : sentryConfig?.whitelistUrls,
  78. integrations: getSentryIntegrations(sentryConfig, routes),
  79. tracesSampleRate,
  80. tracesSampler: context => {
  81. if (context.transactionContext.op?.startsWith('ui.action')) {
  82. return tracesSampleRate / 100;
  83. }
  84. return tracesSampleRate;
  85. },
  86. beforeSendTransaction(event) {
  87. addExtraMeasurements(event);
  88. event.spans = event.spans?.filter(span => {
  89. // Filter analytic timeout spans.
  90. return ['reload.getsentry.net', 'amplitude.com'].every(
  91. partialDesc => !span.description?.includes(partialDesc)
  92. );
  93. });
  94. return event;
  95. },
  96. /**
  97. * There is a bug in Safari, that causes `AbortError` when fetch is
  98. * aborted, and you are in the middle of reading the response. In Chrome
  99. * and other browsers, it is handled gracefully, where in Safari, it
  100. * produces additional error, that is jumping outside of the original
  101. * Promise chain and bubbles up to the `unhandledRejection` handler, that
  102. * we then captures as error.
  103. *
  104. * Ref: https://bugs.webkit.org/show_bug.cgi?id=215771
  105. */
  106. ignoreErrors: ['AbortError: Fetch is aborted'],
  107. });
  108. // Track timeOrigin Selection by the SDK to see if it improves transaction durations
  109. Sentry.addGlobalEventProcessor((event: Sentry.Event, _hint?: Sentry.EventHint) => {
  110. event.tags = event.tags || {};
  111. event.tags['timeOrigin.mode'] = _browserPerformanceTimeOriginMode;
  112. return event;
  113. });
  114. if (userIdentity) {
  115. Sentry.setUser(userIdentity);
  116. }
  117. if (window.__SENTRY__VERSION) {
  118. Sentry.setTag('sentry_version', window.__SENTRY__VERSION);
  119. }
  120. const {customerDomain} = window.__initialData;
  121. if (customerDomain) {
  122. Sentry.setTag('isCustomerDomain', 'yes');
  123. Sentry.setTag('customerDomain.organizationUrl', customerDomain.organizationUrl);
  124. Sentry.setTag('customerDomain.sentryUrl', customerDomain.sentryUrl);
  125. Sentry.setTag('customerDomain.subdomain', customerDomain.subdomain);
  126. }
  127. LongTaskObserver.startPerformanceObserver();
  128. }