functionTrendsWidget.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. import {Fragment, ReactNode, useCallback, useEffect, useMemo, useState} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import {Theme, useTheme} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import partition from 'lodash/partition';
  6. import {Button} from 'sentry/components/button';
  7. import ChartZoom from 'sentry/components/charts/chartZoom';
  8. import {LineChart} from 'sentry/components/charts/lineChart';
  9. import Count from 'sentry/components/count';
  10. import EmptyStateWarning from 'sentry/components/emptyStateWarning';
  11. import IdBadge from 'sentry/components/idBadge';
  12. import Link from 'sentry/components/links/link';
  13. import LoadingIndicator from 'sentry/components/loadingIndicator';
  14. import Pagination, {CursorHandler} from 'sentry/components/pagination';
  15. import PerformanceDuration from 'sentry/components/performanceDuration';
  16. import TextOverflow from 'sentry/components/textOverflow';
  17. import {Tooltip} from 'sentry/components/tooltip';
  18. import {IconArrow, IconChevron, IconWarning} from 'sentry/icons';
  19. import {t, tct} from 'sentry/locale';
  20. import {space} from 'sentry/styles/space';
  21. import {Series} from 'sentry/types/echarts';
  22. import {trackAnalytics} from 'sentry/utils/analytics';
  23. import {axisLabelFormatter, tooltipFormatter} from 'sentry/utils/discover/charts';
  24. import type {TrendType} from 'sentry/utils/profiling/hooks/types';
  25. import {FunctionTrend} from 'sentry/utils/profiling/hooks/types';
  26. import {useProfileFunctionTrends} from 'sentry/utils/profiling/hooks/useProfileFunctionTrends';
  27. import {generateProfileFlamechartRouteWithQuery} from 'sentry/utils/profiling/routes';
  28. import {decodeScalar} from 'sentry/utils/queryString';
  29. import {useLocation} from 'sentry/utils/useLocation';
  30. import useOrganization from 'sentry/utils/useOrganization';
  31. import usePageFilters from 'sentry/utils/usePageFilters';
  32. import useProjects from 'sentry/utils/useProjects';
  33. import useRouter from 'sentry/utils/useRouter';
  34. import {
  35. Accordion,
  36. AccordionItem,
  37. ContentContainer,
  38. HeaderContainer,
  39. HeaderTitleLegend,
  40. StatusContainer,
  41. Subtitle,
  42. WidgetContainer,
  43. } from './styles';
  44. const MAX_FUNCTIONS = 3;
  45. const DEFAULT_CURSOR_NAME = 'fnTrendCursor';
  46. interface FunctionTrendsWidgetProps {
  47. trendFunction: 'p50()' | 'p75()' | 'p95()' | 'p99()';
  48. trendType: TrendType;
  49. cursorName?: string;
  50. header?: ReactNode;
  51. userQuery?: string;
  52. widgetHeight?: string;
  53. }
  54. export function FunctionTrendsWidget({
  55. cursorName = DEFAULT_CURSOR_NAME,
  56. header,
  57. trendFunction,
  58. trendType,
  59. widgetHeight,
  60. userQuery,
  61. }: FunctionTrendsWidgetProps) {
  62. const location = useLocation();
  63. const [expandedIndex, setExpandedIndex] = useState(0);
  64. const fnTrendCursor = useMemo(
  65. () => decodeScalar(location.query[cursorName]),
  66. [cursorName, location.query]
  67. );
  68. const handleCursor = useCallback(
  69. (cursor, pathname, query) => {
  70. browserHistory.push({
  71. pathname,
  72. query: {...query, [cursorName]: cursor},
  73. });
  74. },
  75. [cursorName]
  76. );
  77. const trendsQuery = useProfileFunctionTrends({
  78. trendFunction,
  79. trendType,
  80. query: userQuery,
  81. limit: MAX_FUNCTIONS,
  82. cursor: fnTrendCursor,
  83. });
  84. useEffect(() => {
  85. setExpandedIndex(0);
  86. }, [trendsQuery.data]);
  87. const hasTrends = (trendsQuery.data?.length || 0) > 0;
  88. const isLoading = trendsQuery.isLoading;
  89. const isError = trendsQuery.isError;
  90. return (
  91. <WidgetContainer height={widgetHeight}>
  92. <FunctionTrendsWidgetHeader
  93. header={header}
  94. handleCursor={handleCursor}
  95. pageLinks={trendsQuery.getResponseHeader?.('Link') ?? null}
  96. trendType={trendType}
  97. />
  98. <ContentContainer>
  99. {isLoading && (
  100. <StatusContainer>
  101. <LoadingIndicator />
  102. </StatusContainer>
  103. )}
  104. {isError && (
  105. <StatusContainer>
  106. <IconWarning data-test-id="error-indicator" color="gray300" size="lg" />
  107. </StatusContainer>
  108. )}
  109. {!isError && !isLoading && !hasTrends && (
  110. <EmptyStateWarning>
  111. {trendType === 'regression' ? (
  112. <p>{t('No regressed functions detected')}</p>
  113. ) : (
  114. <p>{t('No improved functions detected')}</p>
  115. )}
  116. </EmptyStateWarning>
  117. )}
  118. {hasTrends && (
  119. <Accordion>
  120. {(trendsQuery.data ?? []).map((f, i, l) => {
  121. return (
  122. <FunctionTrendsEntry
  123. key={`${f.project}-${f.function}-${f.package}`}
  124. trendFunction={trendFunction}
  125. trendType={trendType}
  126. isExpanded={i === expandedIndex}
  127. setExpanded={() => {
  128. const nextIndex = expandedIndex !== i ? i : (i + 1) % l.length;
  129. setExpandedIndex(nextIndex);
  130. }}
  131. func={f}
  132. />
  133. );
  134. })}
  135. </Accordion>
  136. )}
  137. </ContentContainer>
  138. </WidgetContainer>
  139. );
  140. }
  141. interface FunctionTrendsWidgetHeaderProps {
  142. handleCursor: CursorHandler;
  143. header: ReactNode;
  144. pageLinks: string | null;
  145. trendType: TrendType;
  146. }
  147. function FunctionTrendsWidgetHeader({
  148. handleCursor,
  149. header,
  150. pageLinks,
  151. trendType,
  152. }: FunctionTrendsWidgetHeaderProps) {
  153. switch (trendType) {
  154. case 'regression':
  155. return (
  156. <HeaderContainer>
  157. {header ?? (
  158. <HeaderTitleLegend>{t('Most Regressed Functions')}</HeaderTitleLegend>
  159. )}
  160. <Subtitle>{t('Functions by most regressed.')}</Subtitle>
  161. <StyledPagination pageLinks={pageLinks} size="xs" onCursor={handleCursor} />
  162. </HeaderContainer>
  163. );
  164. case 'improvement':
  165. return (
  166. <HeaderContainer>
  167. {header ?? (
  168. <HeaderTitleLegend>{t('Most Improved Functions')}</HeaderTitleLegend>
  169. )}
  170. <Subtitle>{t('Functions by most improved.')}</Subtitle>
  171. <StyledPagination pageLinks={pageLinks} size="xs" onCursor={handleCursor} />
  172. </HeaderContainer>
  173. );
  174. default:
  175. throw new Error(t('Unknown trend type'));
  176. }
  177. }
  178. interface FunctionTrendsEntryProps {
  179. func: FunctionTrend;
  180. isExpanded: boolean;
  181. setExpanded: () => void;
  182. trendFunction: string;
  183. trendType: TrendType;
  184. }
  185. function FunctionTrendsEntry({
  186. func,
  187. isExpanded,
  188. setExpanded,
  189. trendFunction,
  190. trendType,
  191. }: FunctionTrendsEntryProps) {
  192. const organization = useOrganization();
  193. const {projects} = useProjects();
  194. const project = projects.find(p => p.id === func.project);
  195. const [beforeExamples, afterExamples] = useMemo(() => {
  196. return partition(func.worst, ([ts, _example]) => ts <= func.breakpoint);
  197. }, [func]);
  198. let before = <PerformanceDuration nanoseconds={func.aggregate_range_1} abbreviation />;
  199. let after = <PerformanceDuration nanoseconds={func.aggregate_range_2} abbreviation />;
  200. function handleGoToProfile() {
  201. switch (trendType) {
  202. case 'improvement':
  203. trackAnalytics('profiling_views.go_to_flamegraph', {
  204. organization,
  205. source: 'profiling.function_trends.improvement',
  206. });
  207. break;
  208. case 'regression':
  209. trackAnalytics('profiling_views.go_to_flamegraph', {
  210. organization,
  211. source: 'profiling.function_trends.regression',
  212. });
  213. break;
  214. default:
  215. throw new Error('Unknown trend type');
  216. }
  217. }
  218. if (project && beforeExamples.length >= 2 && afterExamples.length >= 2) {
  219. // By choosing the 2nd most recent example in each period, we guarantee the example
  220. // occurred within the period and eliminate confusion with picking an example in
  221. // the same bucket as the breakpoint.
  222. const beforeTarget = generateProfileFlamechartRouteWithQuery({
  223. orgSlug: organization.slug,
  224. projectSlug: project.slug,
  225. profileId: beforeExamples[beforeExamples.length - 2][1],
  226. query: {
  227. frameName: func.function as string,
  228. framePackage: func.package as string,
  229. },
  230. });
  231. before = (
  232. <Link to={beforeTarget} onClick={handleGoToProfile}>
  233. {before}
  234. </Link>
  235. );
  236. const afterTarget = generateProfileFlamechartRouteWithQuery({
  237. orgSlug: organization.slug,
  238. projectSlug: project.slug,
  239. profileId: afterExamples[afterExamples.length - 2][1],
  240. query: {
  241. frameName: func.function as string,
  242. framePackage: func.package as string,
  243. },
  244. });
  245. after = (
  246. <Link to={afterTarget} onClick={handleGoToProfile}>
  247. {after}
  248. </Link>
  249. );
  250. }
  251. return (
  252. <Fragment>
  253. <StyledAccordionItem>
  254. {project && (
  255. <Tooltip title={project.name}>
  256. <IdBadge project={project} avatarSize={16} hideName />
  257. </Tooltip>
  258. )}
  259. <FunctionName>
  260. <Tooltip title={func.package}>{func.function}</Tooltip>
  261. </FunctionName>
  262. <Tooltip
  263. title={tct('Appeared [count] times.', {
  264. count: <Count value={func['count()']} />,
  265. })}
  266. >
  267. <DurationChange>
  268. {before}
  269. <IconArrow direction="right" size="xs" />
  270. {after}
  271. </DurationChange>
  272. </Tooltip>
  273. <Button
  274. icon={<IconChevron size="xs" direction={isExpanded ? 'up' : 'down'} />}
  275. aria-label={t('Expand')}
  276. aria-expanded={isExpanded}
  277. size="zero"
  278. borderless
  279. onClick={() => setExpanded()}
  280. />
  281. </StyledAccordionItem>
  282. {isExpanded && (
  283. <FunctionTrendsChartContainer>
  284. <FunctionTrendsChart func={func} trendFunction={trendFunction} />
  285. </FunctionTrendsChartContainer>
  286. )}
  287. </Fragment>
  288. );
  289. }
  290. interface FunctionTrendsChartProps {
  291. func: FunctionTrend;
  292. trendFunction: string;
  293. }
  294. function FunctionTrendsChart({func, trendFunction}: FunctionTrendsChartProps) {
  295. const {selection} = usePageFilters();
  296. const router = useRouter();
  297. const theme = useTheme();
  298. const series: Series[] = useMemo(() => {
  299. const trendSeries = {
  300. data: func.stats.data.map(([timestamp, data]) => {
  301. return {
  302. name: timestamp * 1e3,
  303. value: data[0].count / 1e6,
  304. };
  305. }),
  306. seriesName: trendFunction,
  307. color: getTrendLineColor(func.change, theme),
  308. };
  309. const seriesStart = func.stats.data[0][0] * 1e3;
  310. const seriesMid = func.breakpoint * 1e3;
  311. const seriesEnd = func.stats.data[func.stats.data.length - 1][0] * 1e3;
  312. const dividingLine = {
  313. data: [],
  314. color: theme.textColor,
  315. seriesName: 'dividing line',
  316. markLine: {},
  317. };
  318. dividingLine.markLine = {
  319. data: [{xAxis: seriesMid}],
  320. label: {show: false},
  321. lineStyle: {
  322. color: theme.textColor,
  323. type: 'solid',
  324. width: 2,
  325. },
  326. symbol: ['none', 'none'],
  327. tooltip: {
  328. show: false,
  329. },
  330. silent: true,
  331. };
  332. const beforeLine = {
  333. data: [],
  334. color: theme.textColor,
  335. seriesName: 'before line',
  336. markLine: {},
  337. };
  338. beforeLine.markLine = {
  339. data: [
  340. [
  341. {value: 'Past', coord: [seriesStart, func.aggregate_range_1 / 1e6]},
  342. {coord: [seriesMid, func.aggregate_range_1 / 1e6]},
  343. ],
  344. ],
  345. label: {
  346. fontSize: 11,
  347. show: true,
  348. color: theme.textColor,
  349. silent: true,
  350. formatter: 'Past',
  351. position: 'insideStartTop',
  352. },
  353. lineStyle: {
  354. color: theme.textColor,
  355. type: 'dashed',
  356. width: 1,
  357. },
  358. symbol: ['none', 'none'],
  359. tooltip: {
  360. formatter: getTooltipFormatter(t('Past Baseline'), func.aggregate_range_1),
  361. },
  362. };
  363. const afterLine = {
  364. data: [],
  365. color: theme.textColor,
  366. seriesName: 'after line',
  367. markLine: {},
  368. };
  369. afterLine.markLine = {
  370. data: [
  371. [
  372. {
  373. value: 'Present',
  374. coord: [seriesMid, func.aggregate_range_2 / 1e6],
  375. },
  376. {coord: [seriesEnd, func.aggregate_range_2 / 1e6]},
  377. ],
  378. ],
  379. label: {
  380. fontSize: 11,
  381. show: true,
  382. color: theme.textColor,
  383. silent: true,
  384. formatter: 'Present',
  385. position: 'insideEndBottom',
  386. },
  387. lineStyle: {
  388. color: theme.textColor,
  389. type: 'dashed',
  390. width: 1,
  391. },
  392. symbol: ['none', 'none'],
  393. tooltip: {
  394. formatter: getTooltipFormatter(t('Present Baseline'), func.aggregate_range_2),
  395. },
  396. };
  397. return [trendSeries, dividingLine, beforeLine, afterLine];
  398. }, [func, trendFunction, theme]);
  399. const chartOptions = useMemo(() => {
  400. return {
  401. height: 150,
  402. grid: {
  403. top: '10px',
  404. bottom: '10px',
  405. left: '10px',
  406. right: '10px',
  407. },
  408. yAxis: {
  409. axisLabel: {
  410. color: theme.chartLabel,
  411. formatter: (value: number) => axisLabelFormatter(value, 'duration'),
  412. },
  413. },
  414. xAxis: {
  415. type: 'time' as const,
  416. },
  417. tooltip: {
  418. valueFormatter: (value: number) => tooltipFormatter(value, 'duration'),
  419. },
  420. };
  421. }, [theme.chartLabel]);
  422. return (
  423. <ChartZoom router={router} {...selection.datetime}>
  424. {zoomRenderProps => (
  425. <LineChart {...zoomRenderProps} {...chartOptions} series={series} />
  426. )}
  427. </ChartZoom>
  428. );
  429. }
  430. function getTrendLineColor(trend: TrendType, theme: Theme) {
  431. switch (trend) {
  432. case 'improvement':
  433. return theme.green300;
  434. case 'regression':
  435. return theme.red300;
  436. default:
  437. throw new Error('Unknown trend type');
  438. }
  439. }
  440. function getTooltipFormatter(label: string, baseline: number) {
  441. return [
  442. '<div class="tooltip-series tooltip-series-solo">',
  443. '<div>',
  444. `<span class="tooltip-label"><strong>${label}</strong></span>`,
  445. tooltipFormatter(baseline / 1e6, 'duration'),
  446. '</div>',
  447. '</div>',
  448. '<div class="tooltip-arrow"></div>',
  449. ].join('');
  450. }
  451. const StyledPagination = styled(Pagination)`
  452. margin: 0;
  453. `;
  454. const StyledAccordionItem = styled(AccordionItem)`
  455. display: grid;
  456. grid-template-columns: auto 1fr auto auto;
  457. `;
  458. const FunctionName = styled(TextOverflow)`
  459. flex: 1 1 auto;
  460. `;
  461. const FunctionTrendsChartContainer = styled('div')`
  462. flex: 1 1 auto;
  463. `;
  464. const DurationChange = styled('span')`
  465. color: ${p => p.theme.gray300};
  466. display: flex;
  467. align-items: center;
  468. gap: ${space(1)};
  469. `;