performanceForSentry.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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, TransactionEvent} 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 longTaskDuration = 0;
  101. private static lastTransaction: IdleTransaction | Transaction | undefined;
  102. static setLongTaskData(t: IdleTransaction | Transaction) {
  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. t.setMeasurement('longTaskCount', LongTaskObserver.longTaskCount, '');
  109. t.setMeasurement('longTaskDuration', LongTaskObserver.longTaskDuration, '');
  110. }
  111. static startPerformanceObserver(): PerformanceObserver | null {
  112. try {
  113. if (LongTaskObserver.observer) {
  114. LongTaskObserver.observer.disconnect();
  115. try {
  116. LongTaskObserver.observer.observe({entryTypes: ['longtask']});
  117. } catch (_) {
  118. // Safari doesn't support longtask, ignore this error.
  119. }
  120. return LongTaskObserver.observer;
  121. }
  122. if (!window.PerformanceObserver || !browserPerformanceTimeOrigin) {
  123. return null;
  124. }
  125. const observer = new PerformanceObserver(function () {
  126. try {
  127. const transaction = getPerformanceTransaction();
  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.setLongTaskData(LongTaskObserver.lastTransaction);
  135. }
  136. LongTaskObserver.longTaskCount = 0;
  137. LongTaskObserver.longTaskDuration = 0;
  138. LongTaskObserver.lastTransaction = transaction;
  139. }
  140. LongTaskObserver.setLongTaskData(transaction);
  141. } catch (_) {
  142. // Defensive catch.
  143. }
  144. });
  145. if (!observer || !observer.observe) {
  146. return null;
  147. }
  148. LongTaskObserver.observer = observer;
  149. try {
  150. LongTaskObserver.observer.observe({entryTypes: ['longtask']});
  151. } catch (_) {
  152. // Safari doesn't support longtask, ignore this error.
  153. }
  154. return LongTaskObserver.observer;
  155. } catch (e) {
  156. captureException(e);
  157. // Defensive try catch.
  158. }
  159. return null;
  160. }
  161. }
  162. export const CustomerProfiler = ({id, children}: {children: ReactNode; id: string}) => {
  163. return (
  164. <Profiler id={id} onRender={onRenderCallback}>
  165. {children}
  166. </Profiler>
  167. );
  168. };
  169. /**
  170. * This component wraps the main component on a page with a measurement checking for visual completedness.
  171. * It uses the data check to make sure endpoints have resolved and the component is meaningfully rendering
  172. * which sets it apart from simply checking LCP, which makes it a good back up check the LCP heuristic performance.
  173. *
  174. * Since this component is guaranteed to be part of the -real- critical path, it also wraps the component with the custom profiler.
  175. */
  176. export const VisuallyCompleteWithData = ({
  177. id,
  178. hasData,
  179. children,
  180. }: {
  181. children: ReactNode;
  182. hasData: boolean;
  183. id: string;
  184. }) => {
  185. const isDataCompleteSet = useRef(false);
  186. const longTaskCount = useRef(0);
  187. useEffect(() => {
  188. let observer;
  189. try {
  190. if (!window.PerformanceObserver || !browserPerformanceTimeOrigin) {
  191. return () => {};
  192. }
  193. observer = LongTaskObserver.startPerformanceObserver();
  194. } catch (_) {
  195. // Defensive since this is auxiliary code.
  196. }
  197. return () => {
  198. if (observer && observer.disconnect) {
  199. observer.disconnect();
  200. }
  201. };
  202. }, []);
  203. const num = useRef(1);
  204. const isVCDSet = useRef(false);
  205. if (isVCDSet && hasData && performance && performance.mark) {
  206. performance.mark(`${id}-vcsd-start`);
  207. isVCDSet.current = true;
  208. }
  209. useEffect(() => {
  210. try {
  211. const transaction: any = getCurrentSentryReactTransaction(); // Using any to override types for private api.
  212. if (!transaction) {
  213. return;
  214. }
  215. if (!isDataCompleteSet.current && hasData) {
  216. isDataCompleteSet.current = true;
  217. performance.mark(`${id}-vcsd-end-pre-timeout`);
  218. window.setTimeout(() => {
  219. if (!browserPerformanceTimeOrigin) {
  220. return;
  221. }
  222. performance.mark(`${id}-vcsd-end`);
  223. const measureName = `VCD [${id}] #${num.current}`;
  224. performance.measure(
  225. `VCD [${id}] #${num.current}`,
  226. `${id}-vcsd-start`,
  227. `${id}-vcsd-end`
  228. );
  229. num.current = num.current++;
  230. const [measureEntry] = performance.getEntriesByName(measureName);
  231. if (!measureEntry) {
  232. return;
  233. }
  234. transaction.registerBeforeFinishCallback((t: Transaction) => {
  235. if (!browserPerformanceTimeOrigin) {
  236. return;
  237. }
  238. // Should be called after performance entries finish callback.
  239. const lcp = (t as any)._measurements.lcp?.value;
  240. // Adjust to be relative to transaction.startTimestamp
  241. const entryStartSeconds =
  242. browserPerformanceTimeOrigin / 1000 + measureEntry.startTime / 1000;
  243. const time = (entryStartSeconds - transaction.startTimestamp) * 1000;
  244. if (lcp) {
  245. t.setMeasurement('lcpDiffVCD', lcp - time, 'millisecond');
  246. }
  247. t.setTag('longTaskCount', longTaskCount.current);
  248. t.setMeasurement('visuallyCompleteData', time, 'millisecond');
  249. });
  250. }, 0);
  251. }
  252. } catch (_) {
  253. // Defensive catch since this code is auxiliary.
  254. }
  255. }, [hasData, id]);
  256. return (
  257. <Profiler id={id} onRender={onRenderCallback}>
  258. <Fragment>{children}</Fragment>
  259. </Profiler>
  260. );
  261. };
  262. interface OpAssetMeasurementDefinition {
  263. key: string;
  264. }
  265. const OP_ASSET_MEASUREMENT_MAP: Record<string, OpAssetMeasurementDefinition> = {
  266. 'resource.script': {
  267. key: 'script',
  268. },
  269. };
  270. const ASSET_MEASUREMENT_ALL = 'allResources';
  271. const SENTRY_ASSET_DOMAINS = ['sentry-cdn.com'];
  272. const measureAssetsOnTransaction = (transaction: TransactionEvent) => {
  273. const spans = transaction.spans;
  274. if (!spans) {
  275. return;
  276. }
  277. let allTransfered = 0;
  278. let allEncoded = 0;
  279. let allCount = 0;
  280. let hasAssetTimings = false;
  281. for (const [op, _] of Object.entries(OP_ASSET_MEASUREMENT_MAP)) {
  282. const filtered = spans.filter(
  283. s =>
  284. s.op === op &&
  285. SENTRY_ASSET_DOMAINS.every(
  286. domain => !s.description || s.description.includes(domain)
  287. )
  288. );
  289. const count = filtered.length;
  290. const transfered = filtered.reduce(
  291. (acc, curr) => acc + (curr.data['Transfer Size'] ?? 0),
  292. 0
  293. );
  294. const encoded = filtered.reduce(
  295. (acc, curr) => acc + (curr.data['Encoded Body Size'] ?? 0),
  296. 0
  297. );
  298. if (encoded > 0) {
  299. hasAssetTimings = true;
  300. }
  301. allCount += count;
  302. allTransfered += transfered;
  303. allEncoded += encoded;
  304. }
  305. if (!transaction.measurements || !transaction.tags) {
  306. return;
  307. }
  308. transaction.measurements[`${ASSET_MEASUREMENT_ALL}.encoded`] = {
  309. value: allEncoded,
  310. unit: 'byte',
  311. };
  312. transaction.measurements[`${ASSET_MEASUREMENT_ALL}.transfer`] = {
  313. value: allTransfered,
  314. unit: 'byte',
  315. };
  316. transaction.measurements[`${ASSET_MEASUREMENT_ALL}.count`] = {
  317. value: allCount,
  318. unit: 'none',
  319. };
  320. transaction.tags.hasAnyAssetTimings = hasAssetTimings;
  321. };
  322. const additionalMeasurements = (transaction: TransactionEvent) => {
  323. if (
  324. !transaction.measurements ||
  325. !browserPerformanceTimeOrigin ||
  326. !transaction.start_timestamp
  327. ) {
  328. return;
  329. }
  330. const ttfb = Object.entries(transaction.measurements).find(([key]) =>
  331. key.toLowerCase().includes('ttfb')
  332. );
  333. if (!ttfb || !ttfb[1]) {
  334. return;
  335. }
  336. const headMark = performance.getEntriesByName('head-start')[0];
  337. if (!headMark) {
  338. return;
  339. }
  340. const ttfbValue = ttfb[1].value;
  341. const entryStartSeconds =
  342. browserPerformanceTimeOrigin / 1000 + headMark.startTime / 1000;
  343. const time = (entryStartSeconds - transaction.start_timestamp) * 1000 - ttfbValue;
  344. transaction.measurements.pre_bundle_load = {
  345. value: time,
  346. unit: 'millisecond',
  347. };
  348. };
  349. export const addExtraMeasurements = (transaction: TransactionEvent) => {
  350. try {
  351. measureAssetsOnTransaction(transaction);
  352. additionalMeasurements(transaction);
  353. } catch (_) {
  354. // Defensive catch since this code is auxiliary.
  355. }
  356. };