slowestFunctionsTable.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. import {Fragment, useCallback, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import clamp from 'lodash/clamp';
  4. import {Button} from 'sentry/components/button';
  5. import ButtonBar from 'sentry/components/buttonBar';
  6. import {LineChart, type LineChartProps} from 'sentry/components/charts/lineChart';
  7. import EmptyStateWarning from 'sentry/components/emptyStateWarning';
  8. import ProjectBadge from 'sentry/components/idBadge/projectBadge';
  9. import Link from 'sentry/components/links/link';
  10. import LoadingIndicator from 'sentry/components/loadingIndicator';
  11. import TextOverflow from 'sentry/components/textOverflow';
  12. import {Tooltip} from 'sentry/components/tooltip';
  13. import {IconChevron, IconOpen, IconWarning} from 'sentry/icons';
  14. import {t} from 'sentry/locale';
  15. import {space} from 'sentry/styles/space';
  16. import type {Series} from 'sentry/types/echarts';
  17. import type {Organization} from 'sentry/types/organization';
  18. import type {Project} from 'sentry/types/project';
  19. import {defined} from 'sentry/utils';
  20. import {axisLabelFormatter, tooltipFormatter} from 'sentry/utils/discover/charts';
  21. import {getShortEventId} from 'sentry/utils/events';
  22. import {useAggregateFlamegraphQuery} from 'sentry/utils/profiling/hooks/useAggregateFlamegraphQuery';
  23. import {useProfilingFunctionMetrics} from 'sentry/utils/profiling/hooks/useProfilingFunctionMetrics';
  24. import {generateProfileRouteFromProfileReference} from 'sentry/utils/profiling/routes';
  25. import useOrganization from 'sentry/utils/useOrganization';
  26. import useProjects from 'sentry/utils/useProjects';
  27. import {
  28. Table,
  29. TableBody,
  30. TableBodyCell,
  31. TableHead,
  32. TableHeadCell,
  33. TableHeader,
  34. TableHeaderActions,
  35. TableHeaderTitle,
  36. TableRow,
  37. TableStatus,
  38. useTableStyles,
  39. } from 'sentry/views/explore/components/table';
  40. import {getPerformanceDuration} from 'sentry/views/performance/utils/getPerformanceDuration';
  41. function sortFunctions(a: Profiling.FunctionMetric, b: Profiling.FunctionMetric) {
  42. return b.sum - a.sum;
  43. }
  44. function makeProfileLinkFromExample(
  45. organization: Organization,
  46. f: Profiling.FunctionMetric,
  47. example: Profiling.FunctionMetric['examples'][0],
  48. projectsLookupTable: Record<string, Project>
  49. ) {
  50. if ('project_id' in example) {
  51. return generateProfileRouteFromProfileReference({
  52. frameName: f.name,
  53. framePackage: f.package,
  54. orgSlug: organization.slug,
  55. projectSlug: projectsLookupTable[example.project_id]?.slug,
  56. reference: example,
  57. });
  58. }
  59. return null;
  60. }
  61. function useMemoryPagination(items: any[], size: number) {
  62. const [pagination, setPagination] = useState({
  63. start: 0,
  64. end: size,
  65. });
  66. const page = Math.floor(pagination.start / size);
  67. const toPage = useCallback(
  68. (p: number) => {
  69. const next = clamp(p, 0, Math.floor(items.length / size));
  70. setPagination({
  71. start: clamp(next * size, 0, items.length - size),
  72. end: Math.min(next * size + size, items.length),
  73. });
  74. },
  75. [size, items]
  76. );
  77. return {
  78. page,
  79. start: pagination.start,
  80. end: pagination.end,
  81. nextButtonProps: {
  82. disabled: pagination.end >= items.length,
  83. onClick: () => toPage(page + 1),
  84. },
  85. previousButtonProps: {
  86. disabled: pagination.start <= 0,
  87. onClick: () => toPage(page - 1),
  88. },
  89. };
  90. }
  91. export function SlowestFunctionsTable({userQuery}: {userQuery?: string}) {
  92. const {projects} = useProjects();
  93. const query = useAggregateFlamegraphQuery({
  94. // User query is only permitted when using transactions.
  95. // If this is to be reused for strictly continuous profiling,
  96. // it'll need to be swapped to use the `profiles` data source
  97. // with no user query.
  98. dataSource: 'transactions',
  99. query: userQuery ?? '',
  100. metrics: true,
  101. });
  102. const sortedMetrics = useMemo(() => {
  103. return query.data?.metrics?.sort(sortFunctions) ?? [];
  104. }, [query.data?.metrics]);
  105. const pagination = useMemoryPagination(sortedMetrics, 5);
  106. const projectsLookupTable = useMemo(() => {
  107. return projects.reduce(
  108. (acc, project) => {
  109. acc[project.id] = project;
  110. return acc;
  111. },
  112. {} as Record<string, Project>
  113. );
  114. }, [projects]);
  115. const hasFunctions = query.data?.metrics && query.data.metrics.length > 0;
  116. const columns = [
  117. {label: t('Function'), value: 'function'},
  118. {label: t('Package'), value: 'package'},
  119. {label: t('Project'), value: 'project'},
  120. {label: t('p75()'), value: 'p75', width: 'min-content' as const},
  121. {label: t('p95()'), value: 'p95', width: 'min-content' as const},
  122. {label: t('p99()'), value: 'p99', width: 'min-content' as const},
  123. ];
  124. const {tableStyles} = useTableStyles({items: columns});
  125. return (
  126. <Fragment>
  127. <TableHeader>
  128. <TableHeaderTitle>{t('Slowest Functions')}</TableHeaderTitle>
  129. <TableHeaderActions>
  130. <SlowestFunctionsPaginationContainer>
  131. <ButtonBar merged>
  132. <Button
  133. icon={<IconChevron direction="left" />}
  134. aria-label={t('Previous')}
  135. size={'sm'}
  136. {...pagination.previousButtonProps}
  137. />
  138. <Button
  139. icon={<IconChevron direction="right" />}
  140. aria-label={t('Next')}
  141. size={'sm'}
  142. {...pagination.nextButtonProps}
  143. />
  144. </ButtonBar>
  145. </SlowestFunctionsPaginationContainer>
  146. </TableHeaderActions>
  147. </TableHeader>
  148. <Table style={tableStyles}>
  149. <TableHead>
  150. <TableRow>
  151. {columns.map((column, i) => (
  152. <TableHeadCell key={column.value} isFirst={i === 0}>
  153. {column.label}
  154. </TableHeadCell>
  155. ))}
  156. </TableRow>
  157. </TableHead>
  158. <TableBody>
  159. {query.isPending && (
  160. <TableStatus>
  161. <LoadingIndicator size={36} />
  162. </TableStatus>
  163. )}
  164. {query.isError && (
  165. <TableStatus>
  166. <IconWarning data-test-id="error-indicator" color="gray300" size="lg" />
  167. </TableStatus>
  168. )}
  169. {!query.isError && !query.isPending && !hasFunctions && (
  170. <TableStatus>
  171. <EmptyStateWarning>
  172. <p>{t('No functions found')}</p>
  173. </EmptyStateWarning>
  174. </TableStatus>
  175. )}
  176. {hasFunctions &&
  177. query.isFetched &&
  178. sortedMetrics.slice(pagination.start, pagination.end).map((f, i) => {
  179. return (
  180. <SlowestFunction
  181. key={i}
  182. function={f}
  183. projectsLookupTable={projectsLookupTable}
  184. />
  185. );
  186. })}
  187. </TableBody>
  188. </Table>
  189. </Fragment>
  190. );
  191. }
  192. interface SlowestFunctionProps {
  193. function: NonNullable<Profiling.Schema['metrics']>[0];
  194. projectsLookupTable: Record<string, Project>;
  195. }
  196. function SlowestFunction(props: SlowestFunctionProps) {
  197. const [expanded, setExpanded] = useState(false);
  198. const organization = useOrganization();
  199. const exampleLink = makeProfileLinkFromExample(
  200. organization,
  201. props.function,
  202. props.function.examples[0],
  203. props.projectsLookupTable
  204. );
  205. return (
  206. <Fragment>
  207. <TableRow>
  208. <TableBodyCell>
  209. <TableButtonWrapper>
  210. <Button
  211. icon={<IconChevron direction={expanded ? 'up' : 'down'} />}
  212. aria-label={t('View Function Metrics')}
  213. onClick={() => setExpanded(!expanded)}
  214. size="xs"
  215. borderless
  216. />
  217. <Tooltip title={props.function.name}>
  218. <TextOverflow>
  219. {exampleLink ? (
  220. <Link to={exampleLink}>
  221. {props.function.name || t('<unknown function>')}
  222. </Link>
  223. ) : (
  224. props.function.name || t('<unknown function>')
  225. )}
  226. </TextOverflow>
  227. </Tooltip>
  228. </TableButtonWrapper>
  229. </TableBodyCell>
  230. <TableBodyCell>
  231. <TextOverflow>
  232. <Tooltip title={props.function.package || t('<unknown package>')}>
  233. {props.function.package}
  234. </Tooltip>
  235. </TextOverflow>
  236. </TableBodyCell>
  237. <TableBodyCell>
  238. <SlowestFunctionsProjectBadge
  239. examples={props.function.examples}
  240. projectsLookupTable={props.projectsLookupTable}
  241. />{' '}
  242. </TableBodyCell>
  243. <TableBodyCell>{getPerformanceDuration(props.function.p75 / 1e6)}</TableBodyCell>
  244. <TableBodyCell>{getPerformanceDuration(props.function.p95 / 1e6)}</TableBodyCell>
  245. <TableBodyCell>{getPerformanceDuration(props.function.p99 / 1e6)}</TableBodyCell>
  246. </TableRow>
  247. {expanded ? (
  248. <SlowestFunctionTimeSeries
  249. function={props.function}
  250. projectsLookupTable={props.projectsLookupTable}
  251. />
  252. ) : null}
  253. </Fragment>
  254. );
  255. }
  256. interface SlowestFunctionsProjectBadgeProps {
  257. examples: Profiling.FunctionMetric['examples'];
  258. projectsLookupTable: Record<string, Project>;
  259. }
  260. function SlowestFunctionsProjectBadge(props: SlowestFunctionsProjectBadgeProps) {
  261. const resolvedProjects = useMemo(() => {
  262. const projects: Project[] = [];
  263. for (const example of props.examples) {
  264. if ('project_id' in example) {
  265. const project = props.projectsLookupTable[example.project_id];
  266. if (project) {
  267. projects.push(project);
  268. }
  269. }
  270. }
  271. return projects;
  272. }, [props.examples, props.projectsLookupTable]);
  273. return resolvedProjects[0] ? (
  274. <ProjectBadge avatarSize={16} project={resolvedProjects[0]} />
  275. ) : null;
  276. }
  277. const METRICS_CHART_OPTIONS: Partial<LineChartProps> = {
  278. tooltip: {
  279. valueFormatter: (value: number) => tooltipFormatter(value, 'number'),
  280. },
  281. xAxis: {
  282. show: true,
  283. type: 'time' as const,
  284. },
  285. yAxis: {
  286. axisLabel: {
  287. formatter(value: number) {
  288. return axisLabelFormatter(value, 'integer');
  289. },
  290. },
  291. },
  292. };
  293. interface SlowestFunctionTimeSeriesProps {
  294. function: Profiling.FunctionMetric;
  295. projectsLookupTable: Record<string, Project>;
  296. }
  297. function SlowestFunctionTimeSeries(props: SlowestFunctionTimeSeriesProps) {
  298. const organization = useOrganization();
  299. const projects = useMemo(() => {
  300. const projectsMap = props.function.examples.reduce<Record<string, number>>(
  301. (acc, f) => {
  302. if (typeof f !== 'string' && 'project_id' in f) {
  303. acc[f.project_id] = f.project_id;
  304. }
  305. return acc;
  306. },
  307. {}
  308. );
  309. return Object.values(projectsMap);
  310. }, [props.function]);
  311. const metrics = useProfilingFunctionMetrics({
  312. fingerprint: props.function.fingerprint,
  313. projects,
  314. });
  315. const series: Series[] = useMemo(() => {
  316. if (!metrics.isFetched) {
  317. return [];
  318. }
  319. const serie: Series = {
  320. seriesName: props.function.name,
  321. data:
  322. metrics.data?.data?.map?.(entry => {
  323. return {
  324. name: entry[0] * 1000,
  325. value: entry[1][0].count,
  326. };
  327. }) ?? [],
  328. };
  329. return [serie];
  330. }, [metrics, props.function]);
  331. const examples = useMemo(() => {
  332. const uniqueExamples: Profiling.FunctionMetric['examples'] = [];
  333. const profileIds = new Set<string>();
  334. const transactionIds = new Set<string>();
  335. for (const example of props.function.examples) {
  336. if ('profile_id' in example) {
  337. if (!profileIds.has(example.profile_id)) {
  338. profileIds.add(example.profile_id);
  339. uniqueExamples.push(example);
  340. }
  341. } else {
  342. if (
  343. defined(example.transaction_id) &&
  344. !transactionIds.has(example.transaction_id)
  345. ) {
  346. transactionIds.add(example.transaction_id);
  347. uniqueExamples.push(example);
  348. }
  349. }
  350. }
  351. return uniqueExamples;
  352. }, [props.function.examples]);
  353. return (
  354. <TableRow>
  355. <SlowestFunctionsTimeSeriesContainer>
  356. <SlowestFunctionsHeader>
  357. <SlowestFunctionsHeaderCell>{t('Examples')}</SlowestFunctionsHeaderCell>
  358. <SlowestFunctionsHeaderCell>{t('Occurrences')}</SlowestFunctionsHeaderCell>
  359. </SlowestFunctionsHeader>
  360. <SlowestFunctionsExamplesContainer>
  361. {examples.slice(0, 5).map((example, i) => {
  362. const exampleLink = makeProfileLinkFromExample(
  363. organization,
  364. props.function,
  365. example,
  366. props.projectsLookupTable
  367. );
  368. const eventId =
  369. 'profile_id' in example ? example.profile_id : example.transaction_id;
  370. return (
  371. <SlowestFunctionsExamplesContainerRow key={i}>
  372. <SlowestFunctionsExamplesContainerRowInner>
  373. {defined(exampleLink) && defined(eventId) && (
  374. <SlowestFunctionExampleLink to={exampleLink}>
  375. <IconOpen size="xs" /> {getShortEventId(eventId)}
  376. </SlowestFunctionExampleLink>
  377. )}
  378. </SlowestFunctionsExamplesContainerRowInner>
  379. </SlowestFunctionsExamplesContainerRow>
  380. );
  381. })}
  382. </SlowestFunctionsExamplesContainer>
  383. <SlowestFunctionsChartContainer>
  384. {metrics.isPending && (
  385. <TableStatusContainer>
  386. <LoadingIndicator size={36} />
  387. </TableStatusContainer>
  388. )}
  389. {metrics.isError && (
  390. <TableStatusContainer>
  391. <IconWarning data-test-id="error-indicator" color="gray300" size="lg" />
  392. </TableStatusContainer>
  393. )}
  394. {!metrics.isError && !metrics.isPending && !series.length && (
  395. <TableStatusContainer>
  396. <EmptyStateWarning>
  397. <p>{t('No function metrics found')}</p>
  398. </EmptyStateWarning>
  399. </TableStatusContainer>
  400. )}
  401. {metrics.isFetched && series.length > 0 ? (
  402. <LineChart
  403. {...METRICS_CHART_OPTIONS}
  404. isGroupedByDate
  405. showTimeInTooltip
  406. series={series}
  407. />
  408. ) : null}
  409. </SlowestFunctionsChartContainer>
  410. </SlowestFunctionsTimeSeriesContainer>
  411. </TableRow>
  412. );
  413. }
  414. const TableStatusContainer = styled('div')`
  415. display: flex;
  416. justify-content: center;
  417. align-items: center;
  418. text-align: center;
  419. height: 100px;
  420. grid-column: 1 / -1;
  421. `;
  422. const TableButtonWrapper = styled('div')`
  423. display: flex;
  424. align-items: center;
  425. gap: ${space(1)};
  426. min-width: 0;
  427. `;
  428. const SlowestFunctionsHeader = styled('div')`
  429. display: grid;
  430. grid-template-columns: subgrid;
  431. grid-column: 1 / -1;
  432. background-color: ${p => p.theme.backgroundSecondary};
  433. border-bottom: 1px solid ${p => p.theme.border};
  434. color: ${p => p.theme.subText};
  435. text-transform: uppercase;
  436. font-size: ${p => p.theme.fontSizeSmall};
  437. font-weight: 600;
  438. text-align: left;
  439. > div:nth-child(n + 4) {
  440. text-align: right;
  441. }
  442. `;
  443. const SlowestFunctionsHeaderCell = styled('div')`
  444. padding: ${space(1)} ${space(2)};
  445. overflow: hidden;
  446. text-overflow: ellipsis;
  447. white-space: nowrap;
  448. &:last-child {
  449. grid-column: 3 / -1;
  450. }
  451. `;
  452. const SlowestFunctionsTimeSeriesContainer = styled(TableBodyCell)`
  453. display: grid;
  454. grid-column: 1 / -1;
  455. grid-template-columns: 160px 1fr;
  456. padding: 0 !important;
  457. `;
  458. const SlowestFunctionExampleLink = styled(Link)`
  459. display: flex;
  460. align-items: center;
  461. gap: ${space(1)};
  462. `;
  463. const SlowestFunctionsChartContainer = styled('div')`
  464. grid-column: 2 / -1;
  465. padding: ${space(3)} ${space(2)} ${space(1)} ${space(2)};
  466. height: 214px;
  467. `;
  468. const SlowestFunctionsExamplesContainer = styled('div')`
  469. grid-column: 1;
  470. border-right: 1px solid ${p => p.theme.border};
  471. display: grid;
  472. grid-template-columns: subgrid;
  473. `;
  474. const SlowestFunctionsExamplesContainerRowInner = styled('div')`
  475. grid-column: 2 / 3;
  476. display: flex;
  477. align-items: center;
  478. padding: ${space(1)} ${space(2)};
  479. `;
  480. const SlowestFunctionsExamplesContainerRow = styled('div')`
  481. display: grid;
  482. grid-template-columns: subgrid;
  483. grid-column: 1 / 3;
  484. &:not(:last-child) {
  485. border-bottom: 1px solid ${p => p.theme.border};
  486. }
  487. `;
  488. const SlowestFunctionsPaginationContainer = styled('div')`
  489. display: flex;
  490. justify-content: flex-end;
  491. `;