regressedProfileFunctions.tsx 15 KB

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