slowestFunctionsTable.tsx 15 KB

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