regressedProfileFunctions.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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(breakpoint: number, worst: FunctionTrend['worst']): number {
  46. let low = 0;
  47. let high = worst.length - 1;
  48. let mid = 0;
  49. let bestMatch: number = worst.length;
  50. // eslint-disable-next-line
  51. while (low <= high) {
  52. mid = Math.floor((low + high) / 2);
  53. const value = worst[mid][0];
  54. if (breakpoint === value) {
  55. return mid;
  56. }
  57. if (breakpoint > value) {
  58. low = mid + 1;
  59. bestMatch = mid + 1;
  60. } else if (breakpoint < value) {
  61. high = mid - 1;
  62. bestMatch = mid;
  63. }
  64. }
  65. // We dont need an exact match as the breakpoint is not guaranteed to be
  66. // in the worst array, so we return the closest index
  67. return bestMatch;
  68. }
  69. function findWorstProfileIDBeforeAndAfter(trend: FunctionTrend): {
  70. after: string | null;
  71. before: string | null;
  72. } {
  73. const breakPointIndex = findBreakPointIndex(trend.breakpoint, trend.worst);
  74. let beforeProfileID: string | null = null;
  75. let afterProfileID: string | null = null;
  76. const STABILITY_WINDOW = 2 * 60 * 1000;
  77. for (let i = breakPointIndex; i >= 0; i--) {
  78. if (!defined(trend.worst[i])) {
  79. continue;
  80. }
  81. if (trend.worst[i][0] < trend.breakpoint - STABILITY_WINDOW) {
  82. break;
  83. }
  84. beforeProfileID = trend.worst[i][1];
  85. }
  86. for (let i = breakPointIndex; i < trend.worst.length; i++) {
  87. if (!defined(trend.worst[i])) {
  88. continue;
  89. }
  90. if (trend.worst[i][0] > trend.breakpoint + STABILITY_WINDOW) {
  91. break;
  92. }
  93. afterProfileID = trend.worst[i][1];
  94. }
  95. return {
  96. before: beforeProfileID,
  97. after: afterProfileID,
  98. };
  99. }
  100. interface MostRegressedProfileFunctionsProps {
  101. transaction: string;
  102. }
  103. export function MostRegressedProfileFunctions(props: MostRegressedProfileFunctionsProps) {
  104. const organization = useOrganization();
  105. const project = useCurrentProjectFromRouteParam();
  106. const location = useLocation();
  107. const theme = useTheme();
  108. const fnTrendCursor = useMemo(
  109. () => decodeScalar(location.query[REGRESSED_FUNCTIONS_CURSOR]),
  110. [location.query]
  111. );
  112. const handleRegressedFunctionsCursor = useCallback((cursor, pathname, query) => {
  113. browserHistory.push({
  114. pathname,
  115. query: {...query, [REGRESSED_FUNCTIONS_CURSOR]: cursor},
  116. });
  117. }, []);
  118. const functionQuery = useMemo(() => {
  119. const conditions = new MutableSearch('');
  120. conditions.setFilterValues('is_application', ['1']);
  121. conditions.setFilterValues('transaction', [props.transaction]);
  122. return conditions.formatString();
  123. }, [props.transaction]);
  124. const [trendType, setTrendType] = useState<TrendType>('regression');
  125. const trendsQuery = useProfileFunctionTrends({
  126. trendFunction: 'p95()',
  127. trendType,
  128. query: functionQuery,
  129. limit: REGRESSED_FUNCTIONS_LIMIT,
  130. cursor: fnTrendCursor,
  131. });
  132. const trends = trendsQuery?.data ?? [];
  133. const onChangeTrendType = useCallback(v => setTrendType(v.value), []);
  134. const hasDifferentialFlamegraphPageFeature =
  135. false && organization.features.includes('profiling-differential-flamegraph-page');
  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.isPending ? (
  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 | null;
  278. before: string | null;
  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. let before = (
  314. <PerformanceDuration
  315. abbreviation
  316. nanoseconds={props.fn.aggregate_range_1 as number}
  317. />
  318. );
  319. if (props.before) {
  320. before = (
  321. <Link
  322. onClick={onRegressedFunctionClick}
  323. to={generateProfileFlamechartRouteWithQuery({
  324. orgSlug: props.organization.slug,
  325. projectSlug: props.project?.slug ?? '',
  326. profileId: props.before,
  327. query: {
  328. // specify the frame to focus, the flamegraph will switch
  329. // to the appropriate thread when these are specified
  330. frameName: props.fn.function as string,
  331. framePackage: props.fn.package as string,
  332. },
  333. })}
  334. >
  335. {before}
  336. </Link>
  337. );
  338. }
  339. let after = (
  340. <PerformanceDuration
  341. abbreviation
  342. nanoseconds={props.fn.aggregate_range_2 as number}
  343. />
  344. );
  345. if (props.after) {
  346. after = (
  347. <Link
  348. onClick={onRegressedFunctionClick}
  349. to={generateProfileFlamechartRouteWithQuery({
  350. orgSlug: props.organization.slug,
  351. projectSlug: props.project?.slug ?? '',
  352. profileId: props.after,
  353. query: {
  354. // specify the frame to focus, the flamegraph will switch
  355. // to the appropriate thread when these are specified
  356. frameName: props.fn.function as string,
  357. framePackage: props.fn.package as string,
  358. },
  359. })}
  360. >
  361. {after}
  362. </Link>
  363. );
  364. }
  365. return (
  366. <RegressedFunctionMainRow>
  367. <div>{rendered}</div>
  368. <div>
  369. {before}
  370. <ChangeArrow>{' \u2192 '}</ChangeArrow>
  371. {after}
  372. </div>
  373. </RegressedFunctionMainRow>
  374. );
  375. }
  376. const ChangeArrow = styled('span')`
  377. color: ${p => p.theme.subText};
  378. `;
  379. const RegressedFunctionsTypeSelect = styled(CompactSelect)`
  380. button {
  381. margin: 0;
  382. padding: 0;
  383. }
  384. `;
  385. const RegressedFunctionSparklineContainer = styled('div')``;
  386. const RegressedFunctionRow = styled('div')`
  387. position: relative;
  388. margin-bottom: ${space(1)};
  389. `;
  390. const RegressedFunctionMainRow = styled('div')`
  391. display: flex;
  392. align-items: center;
  393. justify-content: space-between;
  394. > div:first-child {
  395. min-width: 0;
  396. }
  397. > div:last-child {
  398. white-space: nowrap;
  399. }
  400. `;
  401. const RegressedFunctionMetricsRow = styled('div')`
  402. display: flex;
  403. align-items: center;
  404. justify-content: space-between;
  405. font-size: ${p => p.theme.fontSizeSmall};
  406. color: ${p => p.theme.subText};
  407. margin-top: ${space(0.25)};
  408. `;
  409. const RegressedFunctionsContainer = styled('div')`
  410. flex-basis: 80px;
  411. padding: 0 ${space(1)};
  412. border-bottom: 1px solid ${p => p.theme.border};
  413. `;
  414. const RegressedFunctionsPagination = styled(Pagination)`
  415. margin: 0;
  416. button {
  417. height: 16px;
  418. width: 16px;
  419. min-width: 16px;
  420. min-height: 16px;
  421. svg {
  422. width: 10px;
  423. height: 10px;
  424. }
  425. }
  426. `;
  427. const RegressedFunctionsTitleContainer = styled('div')`
  428. display: flex;
  429. align-items: center;
  430. justify-content: space-between;
  431. margin-bottom: ${space(0.5)};
  432. margin-top: ${space(0.5)};
  433. `;
  434. const RegressedFunctionsQueryState = styled('div')`
  435. text-align: center;
  436. padding: ${space(2)} ${space(0.5)};
  437. color: ${p => p.theme.subText};
  438. `;
  439. const TRIGGER_PROPS = {borderless: true, size: 'zero' as const};
  440. const TREND_FUNCTION_OPTIONS: SelectOption<TrendType>[] = [
  441. {
  442. label: t('Most Regressed Functions'),
  443. value: 'regression' as const,
  444. },
  445. {
  446. label: t('Most Improved Functions'),
  447. value: 'improvement' as const,
  448. },
  449. ];