performanceForSentry.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import {Fragment, Profiler, ReactNode, useEffect, useRef} from 'react';
  2. import {captureException, captureMessage} from '@sentry/react';
  3. import * as Sentry from '@sentry/react';
  4. import {IdleTransaction} from '@sentry/tracing';
  5. import {Transaction} from '@sentry/types';
  6. import {browserPerformanceTimeOrigin, timestampWithMs} from '@sentry/utils';
  7. import getCurrentSentryReactTransaction from './getCurrentSentryReactTransaction';
  8. const MIN_UPDATE_SPAN_TIME = 16; // Frame boundary @ 60fps
  9. const WAIT_POST_INTERACTION = 50; // Leave a small amount of time for observers and onRenderCallback to log since they come in after they occur and not during.
  10. const INTERACTION_TIMEOUT = 2 * 60_000; // 2min. Wrap interactions up after this time since we don't want transactions sticking around forever.
  11. /**
  12. * It depends on where it is called but the way we fetch transactions can be empty despite an ongoing transaction existing.
  13. * This will return an interaction-type transaction held onto by a class static if one exists.
  14. */
  15. export function getPerformanceTransaction(): IdleTransaction | Transaction | undefined {
  16. return PerformanceInteraction.getTransaction() ?? getCurrentSentryReactTransaction();
  17. }
  18. /**
  19. * Callback for React Profiler https://reactjs.org/docs/profiler.html
  20. */
  21. export function onRenderCallback(
  22. id: string,
  23. phase: 'mount' | 'update',
  24. actualDuration: number
  25. ) {
  26. try {
  27. const transaction: Transaction | undefined = getPerformanceTransaction();
  28. if (transaction && actualDuration > MIN_UPDATE_SPAN_TIME) {
  29. const now = timestampWithMs();
  30. transaction.startChild({
  31. description: `<${id}>`,
  32. op: `ui.react.${phase}`,
  33. startTimestamp: now - actualDuration / 1000,
  34. endTimestamp: now,
  35. });
  36. }
  37. } catch (_) {
  38. // Add defensive catch since this wraps all of App
  39. }
  40. }
  41. export class PerformanceInteraction {
  42. private static interactionTransaction: Transaction | null = null;
  43. private static interactionTimeoutId: number | undefined = undefined;
  44. static getTransaction() {
  45. return PerformanceInteraction.interactionTransaction;
  46. }
  47. static startInteraction(name: string, timeout = INTERACTION_TIMEOUT, immediate = true) {
  48. try {
  49. const currentIdleTransaction = getCurrentSentryReactTransaction();
  50. if (currentIdleTransaction) {
  51. // If interaction is started while idle still exists.
  52. currentIdleTransaction.setTag('finishReason', 'sentry.interactionStarted'); // Override finish reason so we can capture if this has effects on idle timeout.
  53. currentIdleTransaction.finish();
  54. }
  55. PerformanceInteraction.finishInteraction(immediate);
  56. const txn = Sentry?.startTransaction({
  57. name: `ui.${name}`,
  58. op: 'interaction',
  59. });
  60. PerformanceInteraction.interactionTransaction = txn;
  61. // Auto interaction timeout
  62. PerformanceInteraction.interactionTimeoutId = window.setTimeout(() => {
  63. if (!PerformanceInteraction.interactionTransaction) {
  64. return;
  65. }
  66. PerformanceInteraction.interactionTransaction.setTag(
  67. 'ui.interaction.finish',
  68. 'timeout'
  69. );
  70. PerformanceInteraction.finishInteraction(true);
  71. }, timeout);
  72. } catch (e) {
  73. captureMessage(e);
  74. }
  75. }
  76. static async finishInteraction(immediate = false) {
  77. try {
  78. if (!PerformanceInteraction.interactionTransaction) {
  79. return;
  80. }
  81. clearTimeout(PerformanceInteraction.interactionTimeoutId);
  82. if (immediate) {
  83. PerformanceInteraction.interactionTransaction?.finish();
  84. PerformanceInteraction.interactionTransaction = null;
  85. return;
  86. }
  87. // Add a slight wait if this isn't called as the result of another transaction starting.
  88. await new Promise(resolve => setTimeout(resolve, WAIT_POST_INTERACTION));
  89. PerformanceInteraction.interactionTransaction?.finish();
  90. PerformanceInteraction.interactionTransaction = null;
  91. return;
  92. } catch (e) {
  93. captureMessage(e);
  94. }
  95. }
  96. }
  97. export class LongTaskObserver {
  98. private static observer: PerformanceObserver;
  99. private static longTaskCount = 0;
  100. private static lastTransaction: IdleTransaction | Transaction | undefined;
  101. static setLongTaskTags(t: IdleTransaction | Transaction) {
  102. t.setTag('ui.longTaskCount', LongTaskObserver.longTaskCount);
  103. const group =
  104. [
  105. 1, 2, 5, 10, 25, 50, 100, 150, 200, 250, 300, 400, 500, 600, 700, 800, 900, 1001,
  106. ].find(n => LongTaskObserver.longTaskCount <= n) || -1;
  107. t.setTag('ui.longTaskCount.grouped', group < 1001 ? `<=${group}` : `>1000`);
  108. }
  109. static startPerformanceObserver(): PerformanceObserver | null {
  110. try {
  111. if (LongTaskObserver.observer) {
  112. LongTaskObserver.observer.disconnect();
  113. try {
  114. LongTaskObserver.observer.observe({entryTypes: ['longtask']});
  115. } catch (_) {
  116. // Safari doesn't support longtask, ignore this error.
  117. }
  118. return LongTaskObserver.observer;
  119. }
  120. if (!window.PerformanceObserver || !browserPerformanceTimeOrigin) {
  121. return null;
  122. }
  123. const timeOrigin = browserPerformanceTimeOrigin / 1000;
  124. const observer = new PerformanceObserver(function (list) {
  125. try {
  126. const transaction = getPerformanceTransaction();
  127. const perfEntries = list.getEntries();
  128. if (!transaction) {
  129. return;
  130. }
  131. if (transaction !== LongTaskObserver.lastTransaction) {
  132. // If long tasks observer is active and is called while the transaction has changed.
  133. if (LongTaskObserver.lastTransaction) {
  134. LongTaskObserver.setLongTaskTags(LongTaskObserver.lastTransaction);
  135. }
  136. LongTaskObserver.longTaskCount = 0;
  137. LongTaskObserver.lastTransaction = transaction;
  138. }
  139. perfEntries.forEach(entry => {
  140. const startSeconds = timeOrigin + entry.startTime / 1000;
  141. LongTaskObserver.longTaskCount++;
  142. transaction.startChild({
  143. description: `Long Task`,
  144. op: `ui.sentry.long-task`,
  145. startTimestamp: startSeconds,
  146. endTimestamp: startSeconds + entry.duration / 1000,
  147. });
  148. });
  149. LongTaskObserver.setLongTaskTags(transaction);
  150. } catch (_) {
  151. // Defensive catch.
  152. }
  153. });
  154. if (!observer || !observer.observe) {
  155. return null;
  156. }
  157. LongTaskObserver.observer = observer;
  158. try {
  159. LongTaskObserver.observer.observe({entryTypes: ['longtask']});
  160. } catch (_) {
  161. // Safari doesn't support longtask, ignore this error.
  162. }
  163. return LongTaskObserver.observer;
  164. } catch (e) {
  165. captureException(e);
  166. // Defensive try catch.
  167. }
  168. return null;
  169. }
  170. }
  171. export const CustomerProfiler = ({id, children}: {children: ReactNode; id: string}) => {
  172. return (
  173. <Profiler id={id} onRender={onRenderCallback}>
  174. {children}
  175. </Profiler>
  176. );
  177. };
  178. export const VisuallyCompleteWithData = ({
  179. id,
  180. hasData,
  181. children,
  182. }: {
  183. children: ReactNode;
  184. hasData: boolean;
  185. id: string;
  186. }) => {
  187. const isVisuallyCompleteSet = useRef(false);
  188. const isDataCompleteSet = useRef(false);
  189. const longTaskCount = useRef(0);
  190. useEffect(() => {
  191. let observer;
  192. try {
  193. if (!window.PerformanceObserver || !browserPerformanceTimeOrigin) {
  194. return () => {};
  195. }
  196. observer = LongTaskObserver.startPerformanceObserver();
  197. } catch (_) {
  198. // Defensive since this is auxiliary code.
  199. }
  200. return () => {
  201. if (observer && observer.disconnect) {
  202. observer.disconnect();
  203. }
  204. };
  205. }, []);
  206. const num = useRef(1);
  207. const isVCDSet = useRef(false);
  208. if (isVCDSet && hasData && performance && performance.mark) {
  209. performance.mark(`${id}-vcsd-start`);
  210. isVCDSet.current = true;
  211. }
  212. useEffect(() => {
  213. try {
  214. const transaction: any = getCurrentSentryReactTransaction(); // Using any to override types for private api.
  215. if (!transaction) {
  216. return;
  217. }
  218. if (!isVisuallyCompleteSet.current) {
  219. const time = performance.now();
  220. transaction.registerBeforeFinishCallback((t: Transaction, _) => {
  221. // Should be called after performance entries finish callback.
  222. t.setMeasurement('visuallyComplete', time, 'ms');
  223. });
  224. isVisuallyCompleteSet.current = true;
  225. }
  226. if (!isDataCompleteSet.current && hasData) {
  227. isDataCompleteSet.current = true;
  228. performance.mark(`${id}-vcsd-end-pre-timeout`);
  229. window.setTimeout(() => {
  230. if (!browserPerformanceTimeOrigin) {
  231. return;
  232. }
  233. performance.mark(`${id}-vcsd-end`);
  234. const measureName = `VCD [${id}] #${num.current}`;
  235. performance.measure(
  236. `VCD [${id}] #${num.current}`,
  237. `${id}-vcsd-start`,
  238. `${id}-vcsd-end`
  239. );
  240. num.current = num.current++;
  241. const [measureEntry] = performance.getEntriesByName(measureName);
  242. if (!measureEntry) {
  243. return;
  244. }
  245. transaction.registerBeforeFinishCallback((t: Transaction) => {
  246. if (!browserPerformanceTimeOrigin) {
  247. return;
  248. }
  249. // Should be called after performance entries finish callback.
  250. const lcp = (t as any)._measurements.lcp?.value;
  251. // Adjust to be relative to transaction.startTimestamp
  252. const entryStartSeconds =
  253. browserPerformanceTimeOrigin / 1000 + measureEntry.startTime / 1000;
  254. const time = (entryStartSeconds - transaction.startTimestamp) * 1000;
  255. if (lcp) {
  256. t.setMeasurement('lcpDiffVCD', lcp - time, 'ms');
  257. }
  258. t.setTag('longTaskCount', longTaskCount.current);
  259. t.setMeasurement('visuallyCompleteData', time, 'ms');
  260. });
  261. }, 0);
  262. }
  263. } catch (_) {
  264. // Defensive catch since this code is auxiliary.
  265. }
  266. }, [hasData, id]);
  267. return (
  268. <Profiler id={id} onRender={onRenderCallback}>
  269. <Fragment>{children}</Fragment>
  270. </Profiler>
  271. );
  272. };