slowestFunctionsTable.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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, 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: '', value: '', width: 62},
  118. {label: t('Function'), value: 'function'},
  119. {label: t('Project'), value: 'project'},
  120. {label: t('Package'), value: 'package'},
  121. {label: t('p75()'), value: 'p75', width: 'min-content' as const},
  122. {label: t('p95()'), value: 'p95', width: 'min-content' as const},
  123. {label: t('p99()'), value: 'p99', width: 'min-content' as const},
  124. ];
  125. const {tableStyles} = useTableStyles({items: columns});
  126. return (
  127. <Fragment>
  128. <TableHeader>
  129. <TableHeaderTitle>{t('Slowest Functions')}</TableHeaderTitle>
  130. <TableHeaderActions>
  131. <SlowestFunctionsPaginationContainer>
  132. <ButtonBar merged>
  133. <Button
  134. icon={<IconChevron direction="left" />}
  135. aria-label={t('Previous')}
  136. size={'sm'}
  137. {...pagination.previousButtonProps}
  138. />
  139. <Button
  140. icon={<IconChevron direction="right" />}
  141. aria-label={t('Next')}
  142. size={'sm'}
  143. {...pagination.nextButtonProps}
  144. />
  145. </ButtonBar>
  146. </SlowestFunctionsPaginationContainer>
  147. </TableHeaderActions>
  148. </TableHeader>
  149. <Table style={tableStyles}>
  150. <TableHead>
  151. <TableRow>
  152. {columns.map((column, i) => (
  153. <TableHeadCell key={column.value} isFirst={i === 0}>
  154. {column.label}
  155. </TableHeadCell>
  156. ))}
  157. </TableRow>
  158. </TableHead>
  159. <TableBody>
  160. {query.isPending && (
  161. <TableStatus>
  162. <LoadingIndicator size={36} />
  163. </TableStatus>
  164. )}
  165. {query.isError && (
  166. <TableStatus>
  167. <IconWarning data-test-id="error-indicator" color="gray300" size="lg" />
  168. </TableStatus>
  169. )}
  170. {!query.isError && !query.isPending && !hasFunctions && (
  171. <TableStatus>
  172. <EmptyStateWarning>
  173. <p>{t('No functions found')}</p>
  174. </EmptyStateWarning>
  175. </TableStatus>
  176. )}
  177. {hasFunctions &&
  178. query.isFetched &&
  179. sortedMetrics.slice(pagination.start, pagination.end).map((f, i) => {
  180. return (
  181. <SlowestFunction
  182. key={i}
  183. function={f}
  184. projectsLookupTable={projectsLookupTable}
  185. />
  186. );
  187. })}
  188. </TableBody>
  189. </Table>
  190. </Fragment>
  191. );
  192. }
  193. interface SlowestFunctionProps {
  194. function: NonNullable<Profiling.Schema['metrics']>[0];
  195. projectsLookupTable: Record<string, Project>;
  196. }
  197. function SlowestFunction(props: SlowestFunctionProps) {
  198. const [expanded, setExpanded] = useState(false);
  199. const organization = useOrganization();
  200. const exampleLink = makeProfileLinkFromExample(
  201. organization,
  202. props.function,
  203. props.function.examples[0],
  204. props.projectsLookupTable
  205. );
  206. return (
  207. <Fragment>
  208. <TableRow>
  209. <TableBodyCell>
  210. <div>
  211. <Button
  212. icon={<IconChevron direction={expanded ? 'up' : 'down'} />}
  213. aria-label={t('View Function Metrics')}
  214. onClick={() => setExpanded(!expanded)}
  215. size="xs"
  216. borderless
  217. />
  218. </div>
  219. </TableBodyCell>
  220. <TableBodyCell>
  221. <Tooltip title={props.function.name}>
  222. <TextOverflow>
  223. {exampleLink ? (
  224. <Link to={exampleLink}>
  225. {props.function.name || t('<unknown function>')}
  226. </Link>
  227. ) : (
  228. props.function.name || t('<unknown function>')
  229. )}
  230. </TextOverflow>
  231. </Tooltip>
  232. </TableBodyCell>
  233. <TableBodyCell>
  234. <SlowestFunctionsProjectBadge
  235. examples={props.function.examples}
  236. projectsLookupTable={props.projectsLookupTable}
  237. />{' '}
  238. </TableBodyCell>
  239. <TableBodyCell>
  240. <TextOverflow>
  241. <Tooltip title={props.function.package || t('<unknown package>')}>
  242. {props.function.package}
  243. </Tooltip>
  244. </TextOverflow>
  245. </TableBodyCell>
  246. <TableBodyCell>{getPerformanceDuration(props.function.p75 / 1e6)}</TableBodyCell>
  247. <TableBodyCell>{getPerformanceDuration(props.function.p95 / 1e6)}</TableBodyCell>
  248. <TableBodyCell>{getPerformanceDuration(props.function.p99 / 1e6)}</TableBodyCell>
  249. </TableRow>
  250. {expanded ? (
  251. <SlowestFunctionTimeSeries
  252. function={props.function}
  253. projectsLookupTable={props.projectsLookupTable}
  254. />
  255. ) : null}
  256. </Fragment>
  257. );
  258. }
  259. interface SlowestFunctionsProjectBadgeProps {
  260. examples: Profiling.FunctionMetric['examples'];
  261. projectsLookupTable: Record<string, Project>;
  262. }
  263. function SlowestFunctionsProjectBadge(props: SlowestFunctionsProjectBadgeProps) {
  264. const resolvedProjects = useMemo(() => {
  265. const projects: Project[] = [];
  266. for (const example of props.examples) {
  267. if ('project_id' in example) {
  268. const project = props.projectsLookupTable[example.project_id];
  269. if (project) {
  270. projects.push(project);
  271. }
  272. }
  273. }
  274. return projects;
  275. }, [props.examples, props.projectsLookupTable]);
  276. return resolvedProjects[0] ? (
  277. <ProjectBadge avatarSize={16} project={resolvedProjects[0]} />
  278. ) : null;
  279. }
  280. const METRICS_CHART_OPTIONS: Partial<LineChartProps> = {
  281. tooltip: {
  282. valueFormatter: (value: number) => tooltipFormatter(value, 'number'),
  283. },
  284. xAxis: {
  285. show: true,
  286. type: 'time' as const,
  287. },
  288. yAxis: {
  289. axisLabel: {
  290. formatter(value: number) {
  291. return axisLabelFormatter(value, 'integer');
  292. },
  293. },
  294. },
  295. };
  296. interface SlowestFunctionTimeSeriesProps {
  297. function: Profiling.FunctionMetric;
  298. projectsLookupTable: Record<string, Project>;
  299. }
  300. function SlowestFunctionTimeSeries(props: SlowestFunctionTimeSeriesProps) {
  301. const organization = useOrganization();
  302. const projects = useMemo(() => {
  303. const projectsMap = props.function.examples.reduce<Record<string, number>>(
  304. (acc, f) => {
  305. if (typeof f !== 'string' && 'project_id' in f) {
  306. acc[f.project_id] = f.project_id;
  307. }
  308. return acc;
  309. },
  310. {}
  311. );
  312. return Object.values(projectsMap);
  313. }, [props.function]);
  314. const metrics = useProfilingFunctionMetrics({
  315. fingerprint: props.function.fingerprint,
  316. projects,
  317. });
  318. const series: Series[] = useMemo(() => {
  319. if (!metrics.isFetched) {
  320. return [];
  321. }
  322. const serie: Series = {
  323. seriesName: props.function.name,
  324. data:
  325. metrics.data?.data?.map?.(entry => {
  326. return {
  327. name: entry[0] * 1000,
  328. value: entry[1][0].count,
  329. };
  330. }) ?? [],
  331. };
  332. return [serie];
  333. }, [metrics, props.function]);
  334. const examples = useMemo(() => {
  335. const uniqueExamples: Profiling.FunctionMetric['examples'] = [];
  336. const profileIds = new Set<string>();
  337. const transactionIds = new Set<string>();
  338. for (const example of props.function.examples) {
  339. if ('profile_id' in example) {
  340. if (!profileIds.has(example.profile_id)) {
  341. profileIds.add(example.profile_id);
  342. uniqueExamples.push(example);
  343. }
  344. } else {
  345. if (
  346. defined(example.transaction_id) &&
  347. !transactionIds.has(example.transaction_id)
  348. ) {
  349. transactionIds.add(example.transaction_id);
  350. uniqueExamples.push(example);
  351. }
  352. }
  353. }
  354. return uniqueExamples;
  355. }, [props.function.examples]);
  356. return (
  357. <TableRow>
  358. <SlowestFunctionsTimeSeriesContainer>
  359. <SlowestFunctionsHeader>
  360. <SlowestFunctionsHeaderCell />
  361. <SlowestFunctionsHeaderCell>{t('Examples')}</SlowestFunctionsHeaderCell>
  362. <SlowestFunctionsHeaderCell>{t('Occurrences')}</SlowestFunctionsHeaderCell>
  363. </SlowestFunctionsHeader>
  364. <SlowestFunctionsExamplesContainer>
  365. {examples.slice(0, 5).map((example, i) => {
  366. const exampleLink = makeProfileLinkFromExample(
  367. organization,
  368. props.function,
  369. example,
  370. props.projectsLookupTable
  371. );
  372. const eventId =
  373. 'profile_id' in example ? example.profile_id : example.transaction_id;
  374. return (
  375. <SlowestFunctionsExamplesContainerRow key={i}>
  376. <SlowestFunctionsExamplesContainerRowInner>
  377. {defined(exampleLink) && defined(eventId) && (
  378. <Link to={exampleLink}>{getShortEventId(eventId)}</Link>
  379. )}
  380. </SlowestFunctionsExamplesContainerRowInner>
  381. </SlowestFunctionsExamplesContainerRow>
  382. );
  383. })}
  384. </SlowestFunctionsExamplesContainer>
  385. <SlowestFunctionsChartContainer>
  386. {metrics.isPending && (
  387. <TableStatusContainer>
  388. <LoadingIndicator size={36} />
  389. </TableStatusContainer>
  390. )}
  391. {metrics.isError && (
  392. <TableStatusContainer>
  393. <IconWarning data-test-id="error-indicator" color="gray300" size="lg" />
  394. </TableStatusContainer>
  395. )}
  396. {!metrics.isError && !metrics.isPending && !series.length && (
  397. <TableStatusContainer>
  398. <EmptyStateWarning>
  399. <p>{t('No function metrics found')}</p>
  400. </EmptyStateWarning>
  401. </TableStatusContainer>
  402. )}
  403. {metrics.isFetched && series.length > 0 ? (
  404. <LineChart
  405. {...METRICS_CHART_OPTIONS}
  406. isGroupedByDate
  407. showTimeInTooltip
  408. series={series}
  409. />
  410. ) : null}
  411. </SlowestFunctionsChartContainer>
  412. <SlowestFunctionsRowSpacer>
  413. <SlowestFunctionsRowSpacerCell />
  414. <SlowestFunctionsRowSpacerCell />
  415. </SlowestFunctionsRowSpacer>
  416. </SlowestFunctionsTimeSeriesContainer>
  417. </TableRow>
  418. );
  419. }
  420. const TableStatusContainer = styled('div')`
  421. display: flex;
  422. justify-content: center;
  423. align-items: center;
  424. text-align: center;
  425. height: 100px;
  426. grid-column: 1 / -1;
  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 SlowestFunctionsRowSpacer = styled('div')`
  453. display: grid;
  454. grid-template-columns: subgrid;
  455. grid-column: 1 / -1;
  456. background-color: ${p => p.theme.backgroundSecondary};
  457. border-top: 1px solid ${p => p.theme.border};
  458. `;
  459. const SlowestFunctionsRowSpacerCell = styled('div')`
  460. height: ${space(2)};
  461. `;
  462. const SlowestFunctionsTimeSeriesContainer = styled(TableBodyCell)`
  463. display: grid;
  464. grid-column: 1 / -1;
  465. grid-template-columns: subgrid;
  466. border-top: 1px solid ${p => p.theme.border};
  467. padding: 0 !important;
  468. `;
  469. const SlowestFunctionsChartContainer = styled('div')`
  470. grid-column: 3 / -1;
  471. padding: ${space(3)} ${space(2)} ${space(1)} ${space(2)};
  472. height: 214px;
  473. `;
  474. const SlowestFunctionsExamplesContainer = styled('div')`
  475. grid-column: 1 / 3;
  476. border-right: 1px solid ${p => p.theme.border};
  477. display: grid;
  478. grid-template-columns: subgrid;
  479. `;
  480. const SlowestFunctionsExamplesContainerRowInner = styled('div')`
  481. grid-column: 2 / 3;
  482. display: flex;
  483. justify-content: space-between;
  484. align-items: center;
  485. padding: ${space(1)} ${space(2)};
  486. `;
  487. const SlowestFunctionsExamplesContainerRow = styled('div')`
  488. display: grid;
  489. grid-template-columns: subgrid;
  490. grid-column: 1 / 3;
  491. &:not(:last-child) {
  492. border-bottom: 1px solid ${p => p.theme.border};
  493. }
  494. `;
  495. const SlowestFunctionsPaginationContainer = styled('div')`
  496. display: flex;
  497. justify-content: flex-end;
  498. `;