functionTrendsWidget.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. <p>{t('No functions found')}</p>
  112. </EmptyStateWarning>
  113. )}
  114. {hasTrends && (
  115. <Accordion>
  116. {(trendsQuery.data ?? []).map((f, i) => {
  117. return (
  118. <FunctionTrendsEntry
  119. key={`${f.project}-${f.function}-${f.package}`}
  120. trendFunction={trendFunction}
  121. trendType={trendType}
  122. isExpanded={i === expandedIndex}
  123. setExpanded={() => setExpandedIndex(i)}
  124. func={f}
  125. />
  126. );
  127. })}
  128. </Accordion>
  129. )}
  130. </ContentContainer>
  131. </WidgetContainer>
  132. );
  133. }
  134. interface FunctionTrendsWidgetHeaderProps {
  135. handleCursor: CursorHandler;
  136. header: ReactNode;
  137. pageLinks: string | null;
  138. trendType: TrendType;
  139. }
  140. function FunctionTrendsWidgetHeader({
  141. handleCursor,
  142. header,
  143. pageLinks,
  144. trendType,
  145. }: FunctionTrendsWidgetHeaderProps) {
  146. switch (trendType) {
  147. case 'regression':
  148. return (
  149. <HeaderContainer>
  150. {header ?? (
  151. <HeaderTitleLegend>{t('Most Regressed Functions')}</HeaderTitleLegend>
  152. )}
  153. <Subtitle>{t('Functions by most regressed.')}</Subtitle>
  154. <StyledPagination pageLinks={pageLinks} size="xs" onCursor={handleCursor} />
  155. </HeaderContainer>
  156. );
  157. case 'improvement':
  158. return (
  159. <HeaderContainer>
  160. {header ?? (
  161. <HeaderTitleLegend>{t('Most Improved Functions')}</HeaderTitleLegend>
  162. )}
  163. <Subtitle>{t('Functions by most improved.')}</Subtitle>
  164. <StyledPagination pageLinks={pageLinks} size="xs" onCursor={handleCursor} />
  165. </HeaderContainer>
  166. );
  167. default:
  168. throw new Error(t('Unknown trend type'));
  169. }
  170. }
  171. interface FunctionTrendsEntryProps {
  172. func: FunctionTrend;
  173. isExpanded: boolean;
  174. setExpanded: () => void;
  175. trendFunction: string;
  176. trendType: TrendType;
  177. }
  178. function FunctionTrendsEntry({
  179. func,
  180. isExpanded,
  181. setExpanded,
  182. trendFunction,
  183. trendType,
  184. }: FunctionTrendsEntryProps) {
  185. const organization = useOrganization();
  186. const {projects} = useProjects();
  187. const project = projects.find(p => p.id === func.project);
  188. const [beforeExamples, afterExamples] = useMemo(() => {
  189. return partition(func.worst, ([ts, _example]) => ts <= func.breakpoint);
  190. }, [func]);
  191. let before = <PerformanceDuration nanoseconds={func.aggregate_range_1} abbreviation />;
  192. let after = <PerformanceDuration nanoseconds={func.aggregate_range_2} abbreviation />;
  193. function handleGoToProfile() {
  194. switch (trendType) {
  195. case 'improvement':
  196. trackAnalytics('profiling_views.go_to_flamegraph', {
  197. organization,
  198. source: 'profiling.function_trends.improvement',
  199. });
  200. break;
  201. case 'regression':
  202. trackAnalytics('profiling_views.go_to_flamegraph', {
  203. organization,
  204. source: 'profiling.function_trends.regression',
  205. });
  206. break;
  207. default:
  208. throw new Error('Unknown trend type');
  209. }
  210. }
  211. if (project && beforeExamples.length >= 2 && afterExamples.length >= 2) {
  212. // By choosing the 2nd most recent example in each period, we guarantee the example
  213. // occurred within the period and eliminate confusion with picking an example in
  214. // the same bucket as the breakpoint.
  215. const beforeTarget = generateProfileFlamechartRouteWithQuery({
  216. orgSlug: organization.slug,
  217. projectSlug: project.slug,
  218. profileId: beforeExamples[beforeExamples.length - 2][1],
  219. query: {
  220. frameName: func.function as string,
  221. framePackage: func.package as string,
  222. },
  223. });
  224. before = (
  225. <Link to={beforeTarget} onClick={handleGoToProfile}>
  226. {before}
  227. </Link>
  228. );
  229. const afterTarget = generateProfileFlamechartRouteWithQuery({
  230. orgSlug: organization.slug,
  231. projectSlug: project.slug,
  232. profileId: afterExamples[afterExamples.length - 2][1],
  233. query: {
  234. frameName: func.function as string,
  235. framePackage: func.package as string,
  236. },
  237. });
  238. after = (
  239. <Link to={afterTarget} onClick={handleGoToProfile}>
  240. {after}
  241. </Link>
  242. );
  243. }
  244. return (
  245. <Fragment>
  246. <StyledAccordionItem>
  247. {project && (
  248. <Tooltip title={project.name}>
  249. <IdBadge project={project} avatarSize={16} hideName />
  250. </Tooltip>
  251. )}
  252. <FunctionName>
  253. <Tooltip title={func.package}>{func.function}</Tooltip>
  254. </FunctionName>
  255. <Tooltip
  256. title={tct('Appeared [count] times.', {
  257. count: <Count value={func['count()']} />,
  258. })}
  259. >
  260. <DurationChange>
  261. {before}
  262. <IconArrow direction="right" size="xs" />
  263. {after}
  264. </DurationChange>
  265. </Tooltip>
  266. <Button
  267. icon={<IconChevron size="xs" direction={isExpanded ? 'up' : 'down'} />}
  268. aria-label={t('Expand')}
  269. aria-expanded={isExpanded}
  270. size="zero"
  271. borderless
  272. onClick={() => setExpanded()}
  273. />
  274. </StyledAccordionItem>
  275. {isExpanded && (
  276. <FunctionTrendsChartContainer>
  277. <FunctionTrendsChart func={func} trendFunction={trendFunction} />
  278. </FunctionTrendsChartContainer>
  279. )}
  280. </Fragment>
  281. );
  282. }
  283. interface FunctionTrendsChartProps {
  284. func: FunctionTrend;
  285. trendFunction: string;
  286. }
  287. function FunctionTrendsChart({func, trendFunction}: FunctionTrendsChartProps) {
  288. const {selection} = usePageFilters();
  289. const router = useRouter();
  290. const theme = useTheme();
  291. const series: Series[] = useMemo(() => {
  292. const trendSeries = {
  293. data: func.stats.data.map(([timestamp, data]) => {
  294. return {
  295. name: timestamp * 1e3,
  296. value: data[0].count / 1e6,
  297. };
  298. }),
  299. seriesName: trendFunction,
  300. color: getTrendLineColor(func.change, theme),
  301. };
  302. const seriesStart = func.stats.data[0][0] * 1e3;
  303. const seriesMid = func.breakpoint * 1e3;
  304. const seriesEnd = func.stats.data[func.stats.data.length - 1][0] * 1e3;
  305. const dividingLine = {
  306. data: [],
  307. color: theme.textColor,
  308. seriesName: 'dividing line',
  309. markLine: {},
  310. };
  311. dividingLine.markLine = {
  312. data: [{xAxis: seriesMid}],
  313. label: {show: false},
  314. lineStyle: {
  315. color: theme.textColor,
  316. type: 'solid',
  317. width: 2,
  318. },
  319. symbol: ['none', 'none'],
  320. tooltip: {
  321. show: false,
  322. },
  323. silent: true,
  324. };
  325. const beforeLine = {
  326. data: [],
  327. color: theme.textColor,
  328. seriesName: 'before line',
  329. markLine: {},
  330. };
  331. beforeLine.markLine = {
  332. data: [
  333. [
  334. {value: 'Past', coord: [seriesStart, func.aggregate_range_1 / 1e6]},
  335. {coord: [seriesMid, func.aggregate_range_1 / 1e6]},
  336. ],
  337. ],
  338. label: {
  339. fontSize: 11,
  340. show: true,
  341. color: theme.textColor,
  342. silent: true,
  343. formatter: 'Past',
  344. position: 'insideStartTop',
  345. },
  346. lineStyle: {
  347. color: theme.textColor,
  348. type: 'dashed',
  349. width: 1,
  350. },
  351. symbol: ['none', 'none'],
  352. tooltip: {
  353. formatter: getTooltipFormatter(t('Past Baseline'), func.aggregate_range_1),
  354. },
  355. };
  356. const afterLine = {
  357. data: [],
  358. color: theme.textColor,
  359. seriesName: 'after line',
  360. markLine: {},
  361. };
  362. afterLine.markLine = {
  363. data: [
  364. [
  365. {
  366. value: 'Present',
  367. coord: [seriesMid, func.aggregate_range_2 / 1e6],
  368. },
  369. {coord: [seriesEnd, func.aggregate_range_2 / 1e6]},
  370. ],
  371. ],
  372. label: {
  373. fontSize: 11,
  374. show: true,
  375. color: theme.textColor,
  376. silent: true,
  377. formatter: 'Present',
  378. position: 'insideEndBottom',
  379. },
  380. lineStyle: {
  381. color: theme.textColor,
  382. type: 'dashed',
  383. width: 1,
  384. },
  385. symbol: ['none', 'none'],
  386. tooltip: {
  387. formatter: getTooltipFormatter(t('Present Baseline'), func.aggregate_range_2),
  388. },
  389. };
  390. return [trendSeries, dividingLine, beforeLine, afterLine];
  391. }, [func, trendFunction, theme]);
  392. const chartOptions = useMemo(() => {
  393. return {
  394. height: 150,
  395. grid: {
  396. top: '10px',
  397. bottom: '0px',
  398. left: '10px',
  399. right: '10px',
  400. },
  401. yAxis: {
  402. axisLabel: {
  403. color: theme.chartLabel,
  404. formatter: (value: number) => axisLabelFormatter(value, 'duration'),
  405. },
  406. },
  407. xAxis: {
  408. show: false,
  409. },
  410. tooltip: {
  411. valueFormatter: (value: number) => tooltipFormatter(value, 'duration'),
  412. },
  413. };
  414. }, [theme.chartLabel]);
  415. return (
  416. <ChartZoom router={router} {...selection.datetime}>
  417. {zoomRenderProps => (
  418. <LineChart {...zoomRenderProps} {...chartOptions} series={series} />
  419. )}
  420. </ChartZoom>
  421. );
  422. }
  423. function getTrendLineColor(trend: TrendType, theme: Theme) {
  424. switch (trend) {
  425. case 'improvement':
  426. return theme.green300;
  427. case 'regression':
  428. return theme.red300;
  429. default:
  430. throw new Error('Unknown trend type');
  431. }
  432. }
  433. function getTooltipFormatter(label: string, baseline: number) {
  434. return [
  435. '<div class="tooltip-series tooltip-series-solo">',
  436. '<div>',
  437. `<span class="tooltip-label"><strong>${label}</strong></span>`,
  438. tooltipFormatter(baseline / 1e6, 'duration'),
  439. '</div>',
  440. '</div>',
  441. '<div class="tooltip-arrow"></div>',
  442. ].join('');
  443. }
  444. const StyledPagination = styled(Pagination)`
  445. margin: 0;
  446. `;
  447. const StyledAccordionItem = styled(AccordionItem)`
  448. display: grid;
  449. grid-template-columns: auto 1fr auto auto;
  450. `;
  451. const FunctionName = styled(TextOverflow)`
  452. flex: 1 1 auto;
  453. `;
  454. const FunctionTrendsChartContainer = styled('div')`
  455. flex: 1 1 auto;
  456. `;
  457. const DurationChange = styled('span')`
  458. color: ${p => p.theme.gray300};
  459. display: flex;
  460. align-items: center;
  461. gap: ${space(1)};
  462. `;