regressedProfileFunctions.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. import {useCallback, useMemo, useState} from 'react';
  2. import {useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import type {SelectOption} from 'sentry/components/compactSelect';
  5. import {CompactSelect} from 'sentry/components/compactSelect';
  6. import Link from 'sentry/components/links/link';
  7. import LoadingIndicator from 'sentry/components/loadingIndicator';
  8. import Pagination from 'sentry/components/pagination';
  9. import PerformanceDuration from 'sentry/components/performanceDuration';
  10. import {TextTruncateOverflow} from 'sentry/components/profiling/textTruncateOverflow';
  11. import {t} from 'sentry/locale';
  12. import {space} from 'sentry/styles/space';
  13. import type {Organization} from 'sentry/types/organization';
  14. import type {Project} from 'sentry/types/project';
  15. import {defined} from 'sentry/utils';
  16. import {trackAnalytics} from 'sentry/utils/analytics';
  17. import {browserHistory} from 'sentry/utils/browserHistory';
  18. import {formatPercentage} from 'sentry/utils/number/formatPercentage';
  19. import type {FunctionTrend, TrendType} from 'sentry/utils/profiling/hooks/types';
  20. import {useCurrentProjectFromRouteParam} from 'sentry/utils/profiling/hooks/useCurrentProjectFromRouteParam';
  21. import {useProfileFunctionTrends} from 'sentry/utils/profiling/hooks/useProfileFunctionTrends';
  22. import {
  23. generateProfileDifferentialFlamegraphRouteWithQuery,
  24. generateProfileFlamechartRouteWithQuery,
  25. } from 'sentry/utils/profiling/routes';
  26. import {relativeChange} from 'sentry/utils/profiling/units/units';
  27. import {decodeScalar} from 'sentry/utils/queryString';
  28. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  29. import {useLocation} from 'sentry/utils/useLocation';
  30. import useOrganization from 'sentry/utils/useOrganization';
  31. import {ProfilingSparklineChart} from './profilingSparklineChart';
  32. const REGRESSED_FUNCTIONS_LIMIT = 5;
  33. const REGRESSED_FUNCTIONS_CURSOR = 'functionRegressionCursor';
  34. function trendToPoints(trend: FunctionTrend): {timestamp: number; value: number}[] {
  35. if (!trend.stats.data.length) {
  36. return [];
  37. }
  38. return trend.stats.data.map(p => {
  39. return {
  40. timestamp: p[0],
  41. value: p[1][0].count,
  42. };
  43. });
  44. }
  45. function findBreakPointIndex(
  46. breakpoint: number,
  47. worst: FunctionTrend['worst']
  48. ): number | undefined {
  49. let low = 0;
  50. let high = worst.length - 1;
  51. let mid = 0;
  52. let bestMatch: number | undefined;
  53. // eslint-disable-next-line
  54. while (low <= high) {
  55. mid = Math.floor((low + high) / 2);
  56. const value = worst[mid][0];
  57. if (breakpoint === value) {
  58. return mid;
  59. }
  60. if (breakpoint > value) {
  61. low = mid + 1;
  62. bestMatch = mid;
  63. } else if (breakpoint < value) {
  64. high = mid - 1;
  65. }
  66. }
  67. // We dont need an exact match as the breakpoint is not guaranteed to be
  68. // in the worst array, so we return the closest index
  69. return bestMatch;
  70. }
  71. function findWorstProfileIDBeforeAndAfter(trend: FunctionTrend): {
  72. after: string;
  73. before: string;
  74. } {
  75. const breakPointIndex = findBreakPointIndex(trend.breakpoint, trend.worst);
  76. if (breakPointIndex === undefined) {
  77. throw new Error('Could not find breakpoint index');
  78. }
  79. let beforeProfileID = '';
  80. let afterProfileID = '';
  81. const STABILITY_WINDOW = 2 * 60 * 1000;
  82. for (let i = breakPointIndex; i >= 0; i--) {
  83. if (trend.worst[i][0] < trend.breakpoint - STABILITY_WINDOW) {
  84. break;
  85. }
  86. beforeProfileID = trend.worst[i][1];
  87. }
  88. for (let i = breakPointIndex; i < trend.worst.length; i++) {
  89. if (trend.worst[i][0] > trend.breakpoint + STABILITY_WINDOW) {
  90. break;
  91. }
  92. afterProfileID = trend.worst[i][1];
  93. }
  94. return {
  95. before: beforeProfileID,
  96. after: afterProfileID,
  97. };
  98. }
  99. interface MostRegressedProfileFunctionsProps {
  100. transaction: string;
  101. }
  102. export function MostRegressedProfileFunctions(props: MostRegressedProfileFunctionsProps) {
  103. const organization = useOrganization();
  104. const project = useCurrentProjectFromRouteParam();
  105. const location = useLocation();
  106. const theme = useTheme();
  107. const fnTrendCursor = useMemo(
  108. () => decodeScalar(location.query[REGRESSED_FUNCTIONS_CURSOR]),
  109. [location.query]
  110. );
  111. const handleRegressedFunctionsCursor = useCallback((cursor, pathname, query) => {
  112. browserHistory.push({
  113. pathname,
  114. query: {...query, [REGRESSED_FUNCTIONS_CURSOR]: cursor},
  115. });
  116. }, []);
  117. const functionQuery = useMemo(() => {
  118. const conditions = new MutableSearch('');
  119. conditions.setFilterValues('is_application', ['1']);
  120. conditions.setFilterValues('transaction', [props.transaction]);
  121. return conditions.formatString();
  122. }, [props.transaction]);
  123. const [trendType, setTrendType] = useState<TrendType>('regression');
  124. const trendsQuery = useProfileFunctionTrends({
  125. trendFunction: 'p95()',
  126. trendType,
  127. query: functionQuery,
  128. limit: REGRESSED_FUNCTIONS_LIMIT,
  129. cursor: fnTrendCursor,
  130. });
  131. const trends = trendsQuery?.data ?? [];
  132. const onChangeTrendType = useCallback(v => setTrendType(v.value), []);
  133. const hasDifferentialFlamegraphPageFeature = organization.features.includes(
  134. 'profiling-differential-flamegraph-page'
  135. );
  136. return (
  137. <RegressedFunctionsContainer>
  138. <RegressedFunctionsTitleContainer>
  139. <RegressedFunctionsTypeSelect
  140. value={trendType}
  141. options={TREND_FUNCTION_OPTIONS}
  142. onChange={onChangeTrendType}
  143. triggerProps={TRIGGER_PROPS}
  144. offset={4}
  145. />
  146. <RegressedFunctionsPagination
  147. pageLinks={trendsQuery.getResponseHeader?.('Link')}
  148. onCursor={handleRegressedFunctionsCursor}
  149. size="xs"
  150. />
  151. </RegressedFunctionsTitleContainer>
  152. {trendsQuery.isLoading ? (
  153. <RegressedFunctionsQueryState>
  154. <LoadingIndicator size={36} />
  155. </RegressedFunctionsQueryState>
  156. ) : trendsQuery.isError ? (
  157. <RegressedFunctionsQueryState>
  158. {t('Failed to fetch regressed functions')}
  159. </RegressedFunctionsQueryState>
  160. ) : !trends.length ? (
  161. <RegressedFunctionsQueryState>
  162. {trendType === 'regression' ? (
  163. <p>{t('No regressed functions detected')}</p>
  164. ) : (
  165. <p>{t('No improved functions detected')}</p>
  166. )}
  167. </RegressedFunctionsQueryState>
  168. ) : (
  169. trends.map((fn, i) => {
  170. const {before, after} = findWorstProfileIDBeforeAndAfter(fn);
  171. return (
  172. <RegressedFunctionRow key={i}>
  173. {hasDifferentialFlamegraphPageFeature ? (
  174. <RegressedFunctionDifferentialFlamegraph
  175. transaction={props.transaction}
  176. organization={organization}
  177. project={project}
  178. fn={fn}
  179. />
  180. ) : (
  181. <RegressedFunctionBeforeAfterFlamechart
  182. organization={organization}
  183. project={project}
  184. before={before}
  185. after={after}
  186. fn={fn}
  187. />
  188. )}
  189. <RegressedFunctionMetricsRow>
  190. <div>
  191. <TextTruncateOverflow>{fn.package}</TextTruncateOverflow>
  192. </div>
  193. <div>
  194. {/* We dont handle improvements as formatPercentage and relativeChange
  195. on lines below dont return absolute values, else we end up with a double sign */}
  196. {trendType === 'regression'
  197. ? fn.aggregate_range_1 < fn.aggregate_range_2
  198. ? '+'
  199. : '-'
  200. : null}
  201. {formatPercentage(
  202. relativeChange(fn.aggregate_range_2, fn.aggregate_range_1)
  203. )}
  204. </div>
  205. </RegressedFunctionMetricsRow>
  206. <RegressedFunctionSparklineContainer>
  207. <ProfilingSparklineChart
  208. name="p95(function.duration)"
  209. points={trendToPoints(fn)}
  210. color={trendType === 'improvement' ? theme.green300 : theme.red300}
  211. aggregate_range_1={fn.aggregate_range_1}
  212. aggregate_range_2={fn.aggregate_range_2}
  213. breakpoint={fn.breakpoint}
  214. start={fn.stats.data[0][0]}
  215. end={fn.stats.data[fn.stats.data.length - 1][0]}
  216. />
  217. </RegressedFunctionSparklineContainer>
  218. </RegressedFunctionRow>
  219. );
  220. })
  221. )}
  222. </RegressedFunctionsContainer>
  223. );
  224. }
  225. interface RegressedFunctionDifferentialFlamegraphProps {
  226. fn: FunctionTrend;
  227. organization: Organization;
  228. project: Project | null;
  229. transaction: string;
  230. }
  231. function RegressedFunctionDifferentialFlamegraph(
  232. props: RegressedFunctionDifferentialFlamegraphProps
  233. ) {
  234. const onRegressedFunctionClick = useCallback(() => {
  235. trackAnalytics('profiling_views.go_to_differential_flamegraph', {
  236. organization: props.organization,
  237. source: `profiling_transaction.regressed_functions_table`,
  238. });
  239. }, [props.organization]);
  240. const differentialFlamegraphLink = generateProfileDifferentialFlamegraphRouteWithQuery({
  241. orgSlug: props.organization.slug,
  242. projectSlug: props.project?.slug ?? '',
  243. transaction: props.transaction,
  244. fingerprint: props.fn.fingerprint,
  245. breakpoint: props.fn.breakpoint,
  246. query: {
  247. // specify the frame to focus, the flamegraph will switch
  248. // to the appropriate thread when these are specified
  249. frameName: props.fn.function as string,
  250. framePackage: props.fn.package as string,
  251. },
  252. });
  253. return (
  254. <RegressedFunctionMainRow>
  255. <div>
  256. <Link onClick={onRegressedFunctionClick} to={differentialFlamegraphLink}>
  257. <TextTruncateOverflow>{props.fn.function}</TextTruncateOverflow>
  258. </Link>
  259. </div>
  260. <div>
  261. <Link onClick={onRegressedFunctionClick} to={differentialFlamegraphLink}>
  262. <PerformanceDuration
  263. abbreviation
  264. nanoseconds={props.fn.aggregate_range_1 as number}
  265. />
  266. <ChangeArrow>{' \u2192 '}</ChangeArrow>
  267. <PerformanceDuration
  268. abbreviation
  269. nanoseconds={props.fn.aggregate_range_2 as number}
  270. />
  271. </Link>
  272. </div>
  273. </RegressedFunctionMainRow>
  274. );
  275. }
  276. interface RegressedFunctionBeforeAfterProps {
  277. after: string;
  278. before: string;
  279. fn: FunctionTrend;
  280. organization: Organization;
  281. project: Project | null;
  282. }
  283. function RegressedFunctionBeforeAfterFlamechart(
  284. props: RegressedFunctionBeforeAfterProps
  285. ) {
  286. const onRegressedFunctionClick = useCallback(() => {
  287. trackAnalytics('profiling_views.go_to_flamegraph', {
  288. organization: props.organization,
  289. source: `profiling_transaction.regressed_functions_table`,
  290. });
  291. }, [props.organization]);
  292. let rendered = <TextTruncateOverflow>{props.fn.function}</TextTruncateOverflow>;
  293. if (defined(props.fn['examples()']?.[0])) {
  294. rendered = (
  295. <Link
  296. onClick={onRegressedFunctionClick}
  297. to={generateProfileFlamechartRouteWithQuery({
  298. orgSlug: props.organization.slug,
  299. projectSlug: props.project?.slug ?? '',
  300. profileId: (props.fn['examples()']?.[0] as string) ?? '',
  301. query: {
  302. // specify the frame to focus, the flamegraph will switch
  303. // to the appropriate thread when these are specified
  304. frameName: props.fn.function as string,
  305. framePackage: props.fn.package as string,
  306. },
  307. })}
  308. >
  309. {rendered}
  310. </Link>
  311. );
  312. }
  313. return (
  314. <RegressedFunctionMainRow>
  315. <div>{rendered}</div>
  316. <div>
  317. <Link
  318. onClick={onRegressedFunctionClick}
  319. to={generateProfileFlamechartRouteWithQuery({
  320. orgSlug: props.organization.slug,
  321. projectSlug: props.project?.slug ?? '',
  322. profileId: props.before,
  323. query: {
  324. // specify the frame to focus, the flamegraph will switch
  325. // to the appropriate thread when these are specified
  326. frameName: props.fn.function as string,
  327. framePackage: props.fn.package as string,
  328. },
  329. })}
  330. >
  331. <PerformanceDuration
  332. abbreviation
  333. nanoseconds={props.fn.aggregate_range_1 as number}
  334. />
  335. </Link>
  336. <ChangeArrow>{' \u2192 '}</ChangeArrow>
  337. <Link
  338. onClick={onRegressedFunctionClick}
  339. to={generateProfileFlamechartRouteWithQuery({
  340. orgSlug: props.organization.slug,
  341. projectSlug: props.project?.slug ?? '',
  342. profileId: props.after,
  343. query: {
  344. // specify the frame to focus, the flamegraph will switch
  345. // to the appropriate thread when these are specified
  346. frameName: props.fn.function as string,
  347. framePackage: props.fn.package as string,
  348. },
  349. })}
  350. >
  351. <PerformanceDuration
  352. abbreviation
  353. nanoseconds={props.fn.aggregate_range_2 as number}
  354. />
  355. </Link>
  356. </div>
  357. </RegressedFunctionMainRow>
  358. );
  359. }
  360. const ChangeArrow = styled('span')`
  361. color: ${p => p.theme.subText};
  362. `;
  363. const RegressedFunctionsTypeSelect = styled(CompactSelect)`
  364. button {
  365. margin: 0;
  366. padding: 0;
  367. }
  368. `;
  369. const RegressedFunctionSparklineContainer = styled('div')``;
  370. const RegressedFunctionRow = styled('div')`
  371. position: relative;
  372. margin-bottom: ${space(1)};
  373. `;
  374. const RegressedFunctionMainRow = styled('div')`
  375. display: flex;
  376. align-items: center;
  377. justify-content: space-between;
  378. > div:first-child {
  379. min-width: 0;
  380. }
  381. > div:last-child {
  382. white-space: nowrap;
  383. }
  384. `;
  385. const RegressedFunctionMetricsRow = styled('div')`
  386. display: flex;
  387. align-items: center;
  388. justify-content: space-between;
  389. font-size: ${p => p.theme.fontSizeSmall};
  390. color: ${p => p.theme.subText};
  391. margin-top: ${space(0.25)};
  392. `;
  393. const RegressedFunctionsContainer = styled('div')`
  394. flex-basis: 80px;
  395. padding: 0 ${space(1)};
  396. border-bottom: 1px solid ${p => p.theme.border};
  397. `;
  398. const RegressedFunctionsPagination = styled(Pagination)`
  399. margin: 0;
  400. button {
  401. height: 16px;
  402. width: 16px;
  403. min-width: 16px;
  404. min-height: 16px;
  405. svg {
  406. width: 10px;
  407. height: 10px;
  408. }
  409. }
  410. `;
  411. const RegressedFunctionsTitleContainer = styled('div')`
  412. display: flex;
  413. align-items: center;
  414. justify-content: space-between;
  415. margin-bottom: ${space(0.5)};
  416. margin-top: ${space(0.5)};
  417. `;
  418. const RegressedFunctionsQueryState = styled('div')`
  419. text-align: center;
  420. padding: ${space(2)} ${space(0.5)};
  421. color: ${p => p.theme.subText};
  422. `;
  423. const TRIGGER_PROPS = {borderless: true, size: 'zero' as const};
  424. const TREND_FUNCTION_OPTIONS: SelectOption<TrendType>[] = [
  425. {
  426. label: t('Most Regressed Functions'),
  427. value: 'regression' as const,
  428. },
  429. {
  430. label: t('Most Improved Functions'),
  431. value: 'improvement' as const,
  432. },
  433. ];