performanceForSentry.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 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 isVisuallyCompleteSet = useRef(false);
  186. const isDataCompleteSet = useRef(false);
  187. const longTaskCount = useRef(0);
  188. useEffect(() => {
  189. let observer;
  190. try {
  191. if (!window.PerformanceObserver || !browserPerformanceTimeOrigin) {
  192. return () => {};
  193. }
  194. observer = LongTaskObserver.startPerformanceObserver();
  195. } catch (_) {
  196. // Defensive since this is auxiliary code.
  197. }
  198. return () => {
  199. if (observer && observer.disconnect) {
  200. observer.disconnect();
  201. }
  202. };
  203. }, []);
  204. const num = useRef(1);
  205. const isVCDSet = useRef(false);
  206. if (isVCDSet && hasData && performance && performance.mark) {
  207. performance.mark(`${id}-vcsd-start`);
  208. isVCDSet.current = true;
  209. }
  210. useEffect(() => {
  211. try {
  212. const transaction: any = getCurrentSentryReactTransaction(); // Using any to override types for private api.
  213. if (!transaction) {
  214. return;
  215. }
  216. if (!isVisuallyCompleteSet.current) {
  217. const time = performance.now();
  218. transaction.registerBeforeFinishCallback((t: Transaction, _) => {
  219. // Should be called after performance entries finish callback.
  220. t.setMeasurement('visuallyComplete', time, 'ms');
  221. });
  222. isVisuallyCompleteSet.current = true;
  223. }
  224. if (!isDataCompleteSet.current && hasData) {
  225. isDataCompleteSet.current = true;
  226. performance.mark(`${id}-vcsd-end-pre-timeout`);
  227. window.setTimeout(() => {
  228. if (!browserPerformanceTimeOrigin) {
  229. return;
  230. }
  231. performance.mark(`${id}-vcsd-end`);
  232. const measureName = `VCD [${id}] #${num.current}`;
  233. performance.measure(
  234. `VCD [${id}] #${num.current}`,
  235. `${id}-vcsd-start`,
  236. `${id}-vcsd-end`
  237. );
  238. num.current = num.current++;
  239. const [measureEntry] = performance.getEntriesByName(measureName);
  240. if (!measureEntry) {
  241. return;
  242. }
  243. transaction.registerBeforeFinishCallback((t: Transaction) => {
  244. if (!browserPerformanceTimeOrigin) {
  245. return;
  246. }
  247. // Should be called after performance entries finish callback.
  248. const lcp = (t as any)._measurements.lcp?.value;
  249. // Adjust to be relative to transaction.startTimestamp
  250. const entryStartSeconds =
  251. browserPerformanceTimeOrigin / 1000 + measureEntry.startTime / 1000;
  252. const time = (entryStartSeconds - transaction.startTimestamp) * 1000;
  253. if (lcp) {
  254. t.setMeasurement('lcpDiffVCD', lcp - time, 'ms');
  255. }
  256. t.setTag('longTaskCount', longTaskCount.current);
  257. t.setMeasurement('visuallyCompleteData', time, 'ms');
  258. });
  259. }, 0);
  260. }
  261. } catch (_) {
  262. // Defensive catch since this code is auxiliary.
  263. }
  264. }, [hasData, id]);
  265. return (
  266. <Profiler id={id} onRender={onRenderCallback}>
  267. <Fragment>{children}</Fragment>
  268. </Profiler>
  269. );
  270. };
  271. interface OpAssetMeasurementDefinition {
  272. key: string;
  273. }
  274. const OP_ASSET_MEASUREMENT_MAP: Record<string, OpAssetMeasurementDefinition> = {
  275. 'resource.script': {
  276. key: 'script',
  277. },
  278. 'resource.css': {
  279. key: 'css',
  280. },
  281. 'resource.link': {
  282. key: 'link',
  283. },
  284. 'resource.img': {
  285. key: 'img',
  286. },
  287. };
  288. const ASSET_MEASUREMENT_ALL = 'allResources';
  289. const measureAssetsOnTransaction = () => {
  290. try {
  291. const transaction: any = getCurrentSentryReactTransaction(); // Using any to override types for private api.
  292. if (!transaction) {
  293. return;
  294. }
  295. transaction.registerBeforeFinishCallback((t: Transaction) => {
  296. const spans: any[] = (t as any).spanRecorder?.spans;
  297. const measurements = (t as any)._measurements;
  298. if (!spans) {
  299. return;
  300. }
  301. if (measurements[ASSET_MEASUREMENT_ALL]) {
  302. return;
  303. }
  304. let allTransfered = 0;
  305. let allEncoded = 0;
  306. let allCount = 0;
  307. for (const [op, definition] of Object.entries(OP_ASSET_MEASUREMENT_MAP)) {
  308. const filtered = spans.filter(s => s.op === op);
  309. const count = filtered.length;
  310. const transfered = filtered.reduce(
  311. (acc, curr) => acc + (curr.data['Transfer Size'] ?? 0),
  312. 0
  313. );
  314. const encoded = filtered.reduce(
  315. (acc, curr) => acc + (curr.data['Encoded Body Size'] ?? 0),
  316. 0
  317. );
  318. if (op === 'resource.script') {
  319. t.setMeasurement(`assets.${definition.key}.encoded`, encoded, '');
  320. t.setMeasurement(`assets.${definition.key}.transfer`, transfered, '');
  321. t.setMeasurement(`assets.${definition.key}.count`, count, '');
  322. }
  323. allCount += count;
  324. allTransfered += transfered;
  325. allEncoded += encoded;
  326. }
  327. t.setMeasurement(`${ASSET_MEASUREMENT_ALL}.encoded`, allEncoded, '');
  328. t.setMeasurement(`${ASSET_MEASUREMENT_ALL}.transfer`, allTransfered, '');
  329. t.setMeasurement(`${ASSET_MEASUREMENT_ALL}.count`, allCount, '');
  330. });
  331. } catch (_) {
  332. // Defensive catch since this code is auxiliary.
  333. }
  334. };
  335. /**
  336. * This will add asset-measurement code to the transaction after a timeout.
  337. * Meant to be called from the sdk without pushing too many perf concerns into our initializeSdk code,
  338. * it's fine if not every transaction gets recorded.
  339. */
  340. export const initializeMeasureAssetsTimeout = () => {
  341. setTimeout(measureAssetsOnTransaction, 1000);
  342. };